Krita Source Code Documentation
Loading...
Searching...
No Matches
KisDocument Class Reference

#include <KisDocument.h>

+ Inheritance diagram for KisDocument:

Public Types

enum  OpenFlag { None = 0 , DontAddToRecent = 0x1 , RecoveryFile = 0x2 }
 

Signals

void canceled (const QString &)
 
void clearStatusBarMessage ()
 
void completed ()
 
void modified (bool)
 
void sigAssistantsChanged ()
 
void sigAudioLevelChanged (qreal level)
 
void sigAudioTracksChanged ()
 
void sigBackgroundSavingFinished (KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
 
void sigCompleteBackgroundSaving (const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
 
void sigGridConfigChanged (const KisGridConfig &config)
 
void sigGuidesConfigChanged (const KisGuidesConfig &config)
 
void sigLoadingFinished ()
 
void sigMirrorAxisConfigChanged ()
 
void sigPaletteListChanged (const QList< KoColorSetSP > &oldPaletteList, const QList< KoColorSetSP > &newPaletteList)
 
void sigPathChanged (const QString &path)
 
void sigReadWriteChanged (bool value)
 
void sigRecoveredChanged (bool value)
 
void sigReferenceImagesChanged ()
 
void sigReferenceImagesLayerChanged (KisSharedPtr< KisReferenceImagesLayer > layer)
 
void sigSavingFinished (const QString &filePath)
 
void sigStoryboardCommentListChanged ()
 
void sigStoryboardItemListChanged ()
 
void statusBarMessage (const QString &text, int timeout=0)
 
void unitChanged (const KoUnit &unit)
 

Public Member Functions

QList< KisPaintingAssistantSP > assistants () const
 
QColor assistantsGlobalColor ()
 
void autoSaveOnPause ()
 Start saving when android activity is pushed to the background.
 
QString caption () const
 
void clearUndoHistory ()
 
KisDocument * clone (bool addStorage=false)
 creates a clone of the document and returns it. Please make sure that you hold all the necessary locks on the image before asking for a clone!
 
bool closePath (bool promptToSave=true)
 
QList< KoColor > colorHistoryColors () const
 
KisUniqueColorSet * colorHistoryModel ()
 
void copyFrom (const Private &rhs, KisDocument *q)
 
void copyFromDocument (const KisDocument &rhs)
 
void copyFromImpl (const Private &rhs, KisDocument *q, KisDocument::CopyPolicy policy)
 
KoDocumentInfoDlg * createDocumentInfoDialog (QWidget *parent, KoDocumentInfo *docInfo) const
 
QDomDocument createDomDocument (const QString &tagName, const QString &version) const
 
KisUndoStore * createUndoStore ()
 
QRectF documentBounds () const
 
KoDocumentInfo * documentInfo () const
 
QString embeddedResourcesStorageId () const
 
QString errorMessage () const
 
bool exportDocument (const QString &path, const QByteArray &mimeType, bool isAdvancedExporting=false, bool showWarnings=false, KisPropertiesConfigurationSP exportConfiguration=0)
 
bool exportDocumentSync (const QString &path, const QByteArray &mimeType, KisPropertiesConfigurationSP exportConfiguration=0)
 
bool fileBatchMode () const
 
QPixmap generatePreview (const QSize &size)
 Generates a preview picture of the document.
 
qreal getAudioLevel ()
 
QVector< QFileInfo > getAudioTracks () const
 
QVector< StoryboardComment > getStoryboardCommentsList ()
 returns the list of comments for the storyboard docker in the document
 
StoryboardItemList getStoryboardItemList ()
 returns the list of pointers to storyboard Items for the document
 
KisGridConfig gridConfig () const
 
const KisGuidesConfig & guidesConfig () const
 returns the guides data for this document.
 
void hackPreliminarySetImage (KisImageSP image)
 
KisImageWSP image () const
 
bool importDocument (const QString &path)
 
KisImportExportManager * importExportManager () const
 importExportManager gives access to the internal import/export manager
 
bool isAutoSaveActive ()
 
bool isAutosaving () const
 
bool isInSaving () const
 isInSaving shown if the document has any (background) saving process or not
 
bool isModified () const
 
bool isNativeFormat (const QByteArray &mimeType) const
 Checks whether a given mimeType can be handled natively.
 
bool isReadWrite () const
 
bool isRecovered () const
 
bool isSaving () const
 
QList< KoResourceLoadResult > linkedDocumentResources ()
 linkedDocumentResources List returns all the resources linked to the document, such as palettes
 
QString linkedResourcesStorageId () const
 
bool loadNativeFormat (const QString &file)
 
QString localFilePath () const
 
KisDocument * lockAndCloneForSaving ()
 try to clone the image. This method handles all the locking for you. If locking has failed, no cloning happens
 
KisDocument * lockAndCloneImpl (bool fetchResourcesFromLayers)
 
KisDocument * lockAndCreateSnapshot ()
 
QByteArray mimeType () const
 
const KisMirrorAxisConfig & mirrorAxisConfig () const
 
bool newImage (const QString &name, qint32 width, qint32 height, const KoColorSpace *cs, const KoColor &bgColor, KisConfig::BackgroundStyle bgStyle, int numberOfLayers, const QString &imageDescription, const double imageResolution)
 
bool openPath (const QString &path, OpenFlags flags=None)
 openPath Open a Path
 
QString path () const
 
KisNodeSP preActivatedNode () const
 
 Private (const Private &rhs, KisDocument *_q)
 
 Private (KisDocument *_q)
 
KisSharedPtr< KisReferenceImagesLayer > referenceImagesLayer () const
 
void removeAutoSaveFiles (const QString &autosaveBaseName, bool wasRecovered)
 
void resetPath ()
 
bool save (bool showWarnings, KisPropertiesConfigurationSP exportConfiguration)
 
bool saveAs (const QString &path, const QByteArray &mimeType, bool showWarnings, KisPropertiesConfigurationSP exportConfiguration=0)
 
KisImageSP savingImage () const
 savingImage provides a detached, shallow copy of the original image that must be used when saving. Any strokes in progress will not be applied to this image, so the result might be missing some data. On the other hand, it won't block.
 
QByteArray serializeToNativeByteArray ()
 serializeToNativeByteArray daves the document into a .kra file written to a memory-based byte-array
 
void setAssistants (const QList< KisPaintingAssistantSP > &value)
 @replace the current list of assistants with
 
void setAssistantsGlobalColor (QColor color)
 
void setAudioTracks (QVector< QFileInfo > f)
 
void setAudioVolume (qreal level)
 
void setAutoSaveActive (bool autoSaveIsActive)
 
void setColorHistoryColors (const QList< KoColor > &colors)
 
void setCurrentImage (KisImageSP image, bool forceInitialUpdate=true, KisNodeSP preActivatedNode=nullptr)
 
void setEmergencyAutoSaveInterval ()
 
void setEmpty (bool empty=true)
 Sets the document to empty.
 
void setErrorMessage (const QString &errMsg)
 
void setFileBatchMode (const bool batchMode)
 
void setGridConfig (const KisGridConfig &config)
 
void setGuidesConfig (const KisGuidesConfig &data)
 
void setImageAndInitIdleWatcher (KisImageSP _image)
 
void setInfiniteAutoSaveInterval ()
 
void setLocalFilePath (const QString &localFilePath)
 
void setMimeType (const QByteArray &mimeType)
 Sets the mime type for the document.
 
void setMimeTypeAfterLoading (const QString &mimeType)
 
void setMirrorAxisConfig (const KisMirrorAxisConfig &config)
 
void setModified (bool _mod)
 
void setNormalAutoSaveInterval ()
 
void setPaletteList (const QList< KoColorSetSP > &paletteList, bool emitSignal=false)
 setPaletteList replaces the palettes in the document's local resource storage with the list of palettes passed to this function. It will then Q_EMIT sigPaletteListChanged with both the old and the new list, if emitSignal is true.
 
void setPath (const QString &path)
 
void setPreActivatedNode (KisNodeSP activatedNode)
 
void setReadWrite (bool readwrite=true)
 Sets whether the document can be edited or is read only.
 
void setRecovered (bool value)
 
void setReferenceImagesLayer (KisSharedPtr< KisReferenceImagesLayer > layer, bool updateImage)
 
void setStoryboardCommentList (const QVector< StoryboardComment > &storyboardCommentList, bool emitSignal=false)
 sets the list of comments for the storyboard docker in the document, emits empty signal if emitSignal is true.
 
void setStoryboardItemList (const StoryboardItemList &storyboardItemList, bool emitSignal=false)
 sets the storyboardItemList in the document, emits empty signal if emitSignal is true.
 
void setUnit (const KoUnit &unit)
 
void setWarningMessage (const QString &warningMsg)
 
KoShapeControllerBase * shapeController () const
 
KoShapeLayer * shapeForNode (KisNodeSP layer) const
 
void syncDecorationsWrapperLayerState ()
 
KUndo2Stack * undoStack ()
 
KoUnit unit () const
 
void updateDocumentMetadataOnSaving (const QString &filePath, const QByteArray &mimeType)
 
void updateEditingTime (bool forceStoreElapsed)
 
void uploadLinkedResourcesFromLayersToStorage ()
 
void waitForSavingToComplete ()
 
QString warningMessage () const
 
 ~KisDocument ()
 
 ~Private ()
 

Static Public Member Functions

static QDomDocument createDomDocument (const QString &appName, const QString &tagName, const QString &version)
 
static QStringList extraNativeMimeTypes ()
 
static QByteArray nativeFormatMimeType ()
 

Public Attributes

QList< KisPaintingAssistantSP > assistants
 
qreal audioLevel = 1.0
 
QVector< QFileInfo > audioTracks
 
bool autoSaveActive = true
 
int autoSaveDelay = 300
 
int autoSaveFailureCount = 0
 
QTimer * autoSaveTimer
 
std::unique_ptr< KisDocument > backgroundSaveDocument
 
KritaUtils::ExportFileJob backgroundSaveJob
 
bool batchMode { false }
 
QFuture< KisImportExportErrorCode > childSavingFuture
 
KisUniqueColorSet colorHistoryModel
 
QMetaObject::Connection completeSavingConnection
 
bool decorationsSyncingDisabled = false
 
bool disregardAutosaveFailure = false
 
KoDocumentInfo * docInfo = 0
 
bool documentIsClosing = false
 
QString embeddedResourcesStorageID
 
KisResourceStorageSP embeddedResourceStorage
 
QDateTime firstMod
 
QColor globalAssistantsColor
 
KisGridConfig gridConfig
 
KisGuidesConfig guidesConfig
 
KisImageSP image
 
QScopedPointer< KisSignalAutoConnection > imageIdleConnection
 
KisIdleWatcher imageIdleWatcher
 
bool imageModifiedWithoutUndo = false
 
KisImportExportManager * importExportManager = 0
 
bool isAutosaving = false
 
bool isRecovered = false
 
KoShapeController * koShapeController = 0
 
QString lastErrorMessage
 
QDateTime lastMod
 
QString lastWarningMessage
 
QString linkedResourcesStorageID
 
KisResourceStorageSP linkedResourceStorage
 
bool m_bAutoDetectedMime = false
 
QString m_file
 
QString m_path
 
QVector< StoryboardComment > m_storyboardCommentList
 
StoryboardItemList m_storyboardItemList
 
QByteArray mimeType
 
KisMirrorAxisConfig mirrorAxisConfig
 
bool modified = false
 
bool modifiedAfterAutosave = false
 
bool modifiedWhileSaving = false
 
KisNameServer * nserver
 
QByteArray outputMimeType
 
KisNodeWSP preActivatedNode
 
KisDocument * q = 0
 
bool readwrite = false
 
KisSignalAutoConnectionsStore referenceLayerConnections
 
KisImageSP savingImage
 
QMutex savingMutex
 
QPointer< KoUpdater > savingUpdater
 
KisShapeController * shapeController = 0
 
KUndo2Stack * undoStack = 0
 
KoUnit unit
 
bool wasStorageAdded = false
 

Protected Member Functions

 KisDocument (bool addStorage=true)
 
 KisDocument (const KisDocument &rhs, bool addStorage)
 KisDocument makes a deep copy of the document rhs. The caller must ensure that the image is properly locked and is in consistent state before asking for cloning.
 

Private Types

enum  CopyPolicy { CONSTRUCT = 0 , REPLACE }
 

Private Slots

void finishExportInBackground ()
 
void setImageModified ()
 
void setImageModifiedWithoutUndo ()
 
void slotAutoSave ()
 
void slotChildCompletedSavingInBackground (KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
 
void slotCompleteAutoSaving (const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
 
void slotCompleteSavingDocument (const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
 
void slotConfigChanged ()
 
void slotDocumentCloningCancelled ()
 
void slotImageRootChanged ()
 
void slotInitiateAsyncAutosaving (KisDocument *clonedDocument)
 
void slotPerformIdleRoutines ()
 
void slotUndoStackCleanChanged (bool value)
 

Private Member Functions

void copyFromDocumentImpl (const KisDocument &rhs, CopyPolicy policy)
 
bool exportDocumentImpl (const KritaUtils::ExportFileJob &job, KisPropertiesConfigurationSP exportConfiguration, bool isAdvancedExporting=false)
 
QString exportErrorToUserMessage (KisImportExportErrorCode status, const QString &errorMessage)
 
QString generateAutoSaveFileName (const QString &path) const
 
KritaUtils::BackgroudSavingStartResult initiateSavingInBackground (const QString actionName, const QObject *receiverObject, const char *receiverMethod, const KritaUtils::ExportFileJob &job, KisPropertiesConfigurationSP exportConfiguration, bool isAdvancedExporting=false)
 
KritaUtils::BackgroudSavingStartResult initiateSavingInBackground (const QString actionName, const QObject *receiverObject, const char *receiverMethod, const KritaUtils::ExportFileJob &job, KisPropertiesConfigurationSP exportConfiguration, std::unique_ptr< KisDocument > &&optionalClonedDocument, bool isAdvancedExporting=false)
 
QString newObjectName ()
 
bool openFile ()
 
bool openPathInternal (const QString &path)
 
QString prettyPath () const
 
bool resourceSavingFilter (const QString &path, const QByteArray &mimeType, KisPropertiesConfigurationSP exportConfiguration)
 
void setAutoSaveDelay (int delay)
 
void slotAutoSaveImpl (std::unique_ptr< KisDocument > &&optionalClonedDocument)
 
KisImportExportErrorCode startExportInBackground (const QString &actionName, const QString &location, const QString &realLocation, const QByteArray &mimeType, bool showWarnings, KisPropertiesConfigurationSP exportConfiguration, bool isAdvancedExporting=false)
 
- Private Member Functions inherited from Private
 Private (KisCanvas2 *c)
 

Private Attributes

Private *const d
 
- Private Attributes inherited from Private
KisCanvas2 * canvas
 
int displayedFrame
 
int intendedFrame
 

Friends

class KisPart
 
class SafeSavingLocker
 

Detailed Description

KisDocument contains the image and keeps track of loading, modification, undo stack and saving.

Definition at line 296 of file KisDocument.cpp.

Member Enumeration Documentation

◆ CopyPolicy

Enumerator
CONSTRUCT 

we are copy-constructing a new KisDocument

REPLACE 

we are replacing the current KisDocument with another

Definition at line 744 of file KisDocument.h.

744 {
745 CONSTRUCT = 0,
746 REPLACE
747 };
@ CONSTRUCT
we are copy-constructing a new KisDocument
@ REPLACE
we are replacing the current KisDocument with another

◆ OpenFlag

Enumerator
None 
DontAddToRecent 
RecoveryFile 

Definition at line 80 of file KisDocument.h.

80 {
81 None = 0,
82 DontAddToRecent = 0x1,
83 RecoveryFile = 0x2
84 };

Constructor & Destructor Documentation

◆ ~Private()

KisDocument::~Private ( )
inline

Definition at line 339 of file KisDocument.cpp.

339 {
340 // Don't delete m_d->shapeController because it's in a QObject hierarchy.
341 delete nserver;
342 }
KisNameServer * nserver

◆ KisDocument() [1/2]

KisDocument::KisDocument ( bool addStorage = true)
explicitprotected

Definition at line 606 of file KisDocument.cpp.

607 : d(new Private(this))
608{
609 connect(KisConfigNotifier::instance(), SIGNAL(configChanged()), SLOT(slotConfigChanged()));
610 connect(d->undoStack, SIGNAL(cleanChanged(bool)), this, SLOT(slotUndoStackCleanChanged(bool)));
611 connect(d->autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
612 setObjectName(newObjectName());
613
614#ifdef Q_OS_MACOS
616 if (bookmarkmngr->isSandboxed()) {
617 connect(this, SIGNAL(sigSavingFinished(const QString&)), bookmarkmngr, SLOT(slotCreateBookmark(const QString&)));
618 }
619#endif
620
621
622 if (addStorage) {
623 d->linkedResourcesStorageID = QUuid::createUuid().toString();
624 d->linkedResourceStorage.reset(new KisResourceStorage(d->linkedResourcesStorageID));
625 KisResourceLocator::instance()->addStorage(d->linkedResourcesStorageID, d->linkedResourceStorage);
626
627 d->embeddedResourcesStorageID = QUuid::createUuid().toString();
628 d->embeddedResourceStorage.reset(new KisResourceStorage(d->embeddedResourcesStorageID));
629 KisResourceLocator::instance()->addStorage(d->embeddedResourcesStorageID, d->embeddedResourceStorage);
630
631 d->wasStorageAdded = true;
632 }
633
634 // preload the krita resources
636
637 d->shapeController = new KisShapeController(d->nserver, d->undoStack, this);
638 d->koShapeController = new KoShapeController(0, d->shapeController);
639
641}
static KisConfigNotifier * instance()
void slotUndoStackCleanChanged(bool value)
void slotAutoSave()
Private *const d
void sigSavingFinished(const QString &filePath)
QString newObjectName()
void slotConfigChanged()
static KisMacosSecurityBookmarkManager * instance()
bool addStorage(const QString &storageLocation, KisResourceStorageSP storage)
addStorage Adds a new resource storage to the database. The storage is will be marked as not pre-inst...
static KisResourceLocator * instance()
static KisResourceServerProvider * instance()

References KisResourceLocator::addStorage(), KisConfigNotifier::instance(), KisMacosSecurityBookmarkManager::instance(), KisResourceLocator::instance(), KisResourceServerProvider::instance(), and KisMacosSecurityBookmarkManager::isSandboxed().

◆ KisDocument() [2/2]

KisDocument::KisDocument ( const KisDocument & rhs,
bool addStorage )
explicitprotected

KisDocument makes a deep copy of the document rhs. The caller must ensure that the image is properly locked and is in consistent state before asking for cloning.

Parameters
rhsthe source document to copy from

Definition at line 643 of file KisDocument.cpp.

644 : QObject(),
645 d(new Private(*rhs.d, this))
646{
648
649 if (addStorage) {
650 KisResourceLocator::instance()->addStorage(d->linkedResourcesStorageID, d->linkedResourceStorage);
651 KisResourceLocator::instance()->addStorage(d->embeddedResourcesStorageID, d->embeddedResourceStorage);
652 d->wasStorageAdded = true;
653 }
654}
void copyFromDocumentImpl(const KisDocument &rhs, CopyPolicy policy)

References KisResourceLocator::addStorage(), CONSTRUCT, copyFromDocumentImpl(), d, and KisResourceLocator::instance().

◆ ~KisDocument()

KisDocument::~KisDocument ( )

Destructor.

The destructor does not delete any attached KisView objects and it does not delete the attached widget as returned by widget().

Push a timebomb, which will try to release the memory after the document has been deleted

WARNING: We should wait for all the internal image jobs to finish before entering KisImage's destructor. The problem is, while execution of KisImage::~KisImage, all the weak shared pointers pointing to the image enter an inconsistent state(!). The shared counter is already zero and destruction has started, but the weak reference doesn't know about it, because KisShared::~KisShared hasn't been executed yet. So all the threads running in background and having weak pointers will enter the KisImage's destructor as well.

Definition at line 656 of file KisDocument.cpp.

657{
658 d->documentIsClosing = true;
659
660 // wait until all the pending operations are in progress
662 d->imageIdleWatcher.setTrackedImage(0);
663
669
670 d->autoSaveTimer->disconnect(this);
671 d->autoSaveTimer->stop();
672
673 delete d->importExportManager;
674
675 // Despite being QObject they needs to be deleted before the image
676 delete d->shapeController;
677
678 delete d->koShapeController;
679
680 if (d->image) {
681 d->image->animationInterface()->blockBackgroundFrameGeneration();
682
683 d->image->notifyAboutToBeDeleted();
684
697 d->image->requestStrokeCancellation();
698 d->image->waitForDone();
699
700 // clear undo commands that can still point to the image
701 d->undoStack->clear();
702 d->image->waitForDone();
703
704 KisImageWSP sanityCheckPointer = d->image;
705 Q_UNUSED(sanityCheckPointer);
706
707 // The following line trigger the deletion of the image
708 d->image.clear();
709
710 // check if the image has actually been deleted
711 KIS_SAFE_ASSERT_RECOVER_NOOP(!sanityCheckPointer.isValid());
712 }
713
714 if (d->wasStorageAdded) {
715 if (KisResourceLocator::instance()->hasStorage(d->linkedResourcesStorageID)) {
716 KisResourceLocator::instance()->removeStorage(d->linkedResourcesStorageID);
717 }
718 if (KisResourceLocator::instance()->hasStorage(d->embeddedResourcesStorageID)) {
719 KisResourceLocator::instance()->removeStorage(d->embeddedResourcesStorageID);
720 }
721 }
722
723 delete d;
724}
void waitForSavingToComplete()
static MemoryReleaseObject * createMemoryReleaseObject()
bool removeStorage(const QString &storageLocation)
removeStorage removes the temporary storage from the database
bool isValid() const
#define KIS_SAFE_ASSERT_RECOVER_NOOP(cond)
Definition kis_assert.h:130

References KisPaintDevice::createMemoryReleaseObject(), d, KisResourceLocator::instance(), KisWeakSharedPtr< T >::isValid(), KIS_SAFE_ASSERT_RECOVER_NOOP, KisResourceLocator::removeStorage(), and waitForSavingToComplete().

Member Function Documentation

◆ assistants()

QList< KisPaintingAssistantSP > KisDocument::assistants ( ) const
Returns
the list of assistants associated with this document

◆ assistantsGlobalColor()

QColor KisDocument::assistantsGlobalColor ( )

Definition at line 2940 of file KisDocument.cpp.

2941{
2942 return d->globalAssistantsColor;
2943}

References d.

◆ autoSaveOnPause()

void KisDocument::autoSaveOnPause ( )

Start saving when android activity is pushed to the background.

Definition at line 2113 of file KisDocument.cpp.

2114{
2115 if (!d->modified || !d->modifiedAfterAutosave)
2116 return;
2117
2118 const QString autoSaveFileName = generateAutoSaveFileName(localFilePath());
2119
2120 bool started = exportDocumentSync(autoSaveFileName, nativeFormatMimeType());
2121
2122 if (started)
2123 {
2124 d->modifiedAfterAutosave = false;
2125 dbgAndroid << "autoSaveOnPause successful";
2126 }
2127 else
2128 {
2129 qWarning() << "Could not auto-save when paused";
2130 }
2131}
QString localFilePath() const
static QByteArray nativeFormatMimeType()
QString generateAutoSaveFileName(const QString &path) const
bool exportDocumentSync(const QString &path, const QByteArray &mimeType, KisPropertiesConfigurationSP exportConfiguration=0)
#define dbgAndroid
Definition kis_debug.h:65

References d, dbgAndroid, exportDocumentSync(), generateAutoSaveFileName(), localFilePath(), and nativeFormatMimeType().

◆ canceled

void KisDocument::canceled ( const QString & )
signal

◆ caption()

QString KisDocument::caption ( ) const
Returns
caption of the document

Caption is of the form "[title] - [path]", built out of the document info (title) and pretty-printed document Path. If the title is not present, only the Path it returned.

Definition at line 2228 of file KisDocument.cpp.

2229{
2230 QString c;
2231 const QString _url(QFileInfo(path()).fileName());
2232
2233 // if URL is empty...it is probably an unsaved file
2234 if (_url.isEmpty()) {
2235 c = " [" + i18n("Not Saved") + "] ";
2236 } else {
2237 c = _url; // Fall back to document URL
2238 }
2239
2240 return c;
2241}
QString path() const

References path().

◆ clearStatusBarMessage

void KisDocument::clearStatusBarMessage ( )
signal

Emitted e.g. at the end of a save operation This is emitted by KisDocument and used by KisView to clear the statusbar message

◆ clearUndoHistory()

void KisDocument::clearUndoHistory ( )

Definition at line 2376 of file KisDocument.cpp.

2377{
2378 d->undoStack->clear();
2379}

References d.

◆ clone()

KisDocument * KisDocument::clone ( bool addStorage = false)

creates a clone of the document and returns it. Please make sure that you hold all the necessary locks on the image before asking for a clone!

Definition at line 736 of file KisDocument.cpp.

737{
738 return new KisDocument(*this, addStorage);
739}
KisDocument(bool addStorage=true)

References KisDocument().

◆ closePath()

bool KisDocument::closePath ( bool promptToSave = true)

Definition at line 2574 of file KisDocument.cpp.

2575{
2576 if (promptToSave) {
2577 if ( isReadWrite() && isModified()) {
2578 Q_FOREACH (KisView *view, KisPart::instance()->views()) {
2579 if (view && view->document() == this) {
2580 if (!view->queryClose()) {
2581 return false;
2582 }
2583 }
2584 }
2585 }
2586 }
2587 // Not modified => ok and delete temp file.
2588 d->mimeType = QByteArray();
2589
2590 // It always succeeds for a read-only part,
2591 // but the return value exists for reimplementations
2592 // (e.g. pressing cancel for a modified read-write part)
2593 return true;
2594}
bool isReadWrite() const
bool isModified() const
static KisPart * instance()
Definition KisPart.cpp:131
QPointer< KisDocument > document
Definition KisView.cpp:121
bool queryClose()
Definition KisView.cpp:1161

References d, KisView::document, KisPart::instance(), isModified(), isReadWrite(), and KisView::queryClose().

◆ colorHistoryColors()

QList< KoColor > KisDocument::colorHistoryColors ( ) const

Return the per-document history of the last-used colors, from the newest to oldest.

The actual values are stored in the model returned by colorHistoryModel()

Definition at line 2963 of file KisDocument.cpp.

2964{
2965 return d->colorHistoryModel.colorList();
2966}

References d.

◆ colorHistoryModel()

KisUniqueColorSet * KisDocument::colorHistoryModel ( )

Return an internal model for managing the last used colors of the document. The model can be used to manipulate the colors and subscribe to updates.

◆ completed

void KisDocument::completed ( )
signal

◆ copyFrom()

void KisDocument::copyFrom ( const Private & rhs,
KisDocument * q )

◆ copyFromDocument()

void KisDocument::copyFromDocument ( const KisDocument & rhs)

Definition at line 1253 of file KisDocument.cpp.

1254{
1256}

References copyFromDocumentImpl(), and REPLACE.

◆ copyFromDocumentImpl()

void KisDocument::copyFromDocumentImpl ( const KisDocument & rhs,
CopyPolicy policy )
private

Definition at line 1258 of file KisDocument.cpp.

1259{
1260 if (policy == REPLACE) {
1261 d->decorationsSyncingDisabled = true;
1262 d->copyFrom(*(rhs.d), this);
1263 d->decorationsSyncingDisabled = false;
1264
1265 d->undoStack->clear();
1266 } else {
1267 // in CONSTRUCT mode, d should be already initialized
1268 connect(KisConfigNotifier::instance(), SIGNAL(configChanged()), SLOT(slotConfigChanged()));
1269 connect(d->undoStack, SIGNAL(cleanChanged(bool)), this, SLOT(slotUndoStackCleanChanged(bool)));
1270 connect(d->autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
1271
1272 d->shapeController = new KisShapeController(d->nserver, d->undoStack, this);
1273 d->koShapeController = new KoShapeController(0, d->shapeController);
1274 }
1275
1276 setObjectName(rhs.objectName());
1277
1279
1280 if (rhs.d->image) {
1281 if (policy == REPLACE) {
1282 d->image->barrierLock(/* readOnly = */ false);
1283 rhs.d->image->barrierLock(/* readOnly = */ true);
1284 d->image->copyFromImage(*(rhs.d->image));
1285 d->image->unlock();
1286 rhs.d->image->unlock();
1287
1288 setCurrentImage(d->image, /* forceInitialUpdate = */ true);
1289 } else {
1290 // clone the image with keeping the GUIDs of the layers intact
1291 // NOTE: we expect the image to be locked!
1292 setCurrentImage(rhs.image()->clone(/* exactCopy = */ true), /* forceInitialUpdate = */ false);
1293 }
1294 }
1295
1296 if (policy == REPLACE) {
1297 d->syncDecorationsWrapperLayerState();
1298 }
1299
1300 if (rhs.d->preActivatedNode) {
1301 QQueue<KisNodeSP> linearizedNodes;
1302 KisLayerUtils::recursiveApplyNodes(rhs.d->image->root(),
1303 [&linearizedNodes](KisNodeSP node) {
1304 linearizedNodes.enqueue(node);
1305 });
1307 [&linearizedNodes, &rhs, this](KisNodeSP node) {
1308 KisNodeSP refNode = linearizedNodes.dequeue();
1309 if (rhs.d->preActivatedNode.data() == refNode.data()) {
1310 d->preActivatedNode = node;
1311 }
1312 });
1313 }
1314
1315 // reinitialize references' signal connection
1316 KisReferenceImagesLayerSP referencesLayer = this->referenceImagesLayer();
1317 if (referencesLayer) {
1318 d->referenceLayerConnections.clear();
1319 d->referenceLayerConnections.addConnection(
1320 referencesLayer, SIGNAL(sigUpdateCanvas(QRectF)),
1321 this, SIGNAL(sigReferenceImagesChanged()));
1322
1323 Q_EMIT sigReferenceImagesLayerChanged(referencesLayer);
1325 }
1326
1327 KisDecorationsWrapperLayerSP decorationsLayer =
1328 KisLayerUtils::findNodeByType<KisDecorationsWrapperLayer>(d->image->root());
1329 if (decorationsLayer) {
1330 decorationsLayer->setDocument(this);
1331 }
1332
1333
1334 if (policy == REPLACE) {
1335 setModified(true);
1336 }
1337}
KisSharedPtr< KisReferenceImagesLayer > referenceImagesLayer() const
KisImageSP image
void setModified(bool _mod)
void sigReferenceImagesLayerChanged(KisSharedPtr< KisReferenceImagesLayer > layer)
void setCurrentImage(KisImageSP image, bool forceInitialUpdate=true, KisNodeSP preActivatedNode=nullptr)
void sigReferenceImagesChanged()
KisImage * clone(bool exactCopy=false)
Definition kis_image.cc:427
void recursiveApplyNodes(NodePointer node, Functor func)

References KisImage::clone(), d, image, KisConfigNotifier::instance(), KisLayerUtils::recursiveApplyNodes(), REPLACE, setCurrentImage(), slotAutoSave(), slotConfigChanged(), and slotUndoStackCleanChanged().

◆ copyFromImpl()

void KisDocument::copyFromImpl ( const Private & rhs,
KisDocument * q,
KisDocument::CopyPolicy policy )

◆ createDocumentInfoDialog()

KoDocumentInfoDlg * KisDocument::createDocumentInfoDialog ( QWidget * parent,
KoDocumentInfo * docInfo ) const

Definition at line 2559 of file KisDocument.cpp.

2560{
2561 return new KoDocumentInfoDlg(parent, docInfo);
2562}
KoDocumentInfo * docInfo
The dialog that shows information about the document.

References docInfo.

◆ createDomDocument() [1/2]

QDomDocument KisDocument::createDomDocument ( const QString & appName,
const QString & tagName,
const QString & version )
static

Return a correctly created QDomDocument for an old (1.3-style) Krita document, including processing instruction, complete DOCTYPE tag (with systemId and publicId), and root element. This static method can be used e.g. by filters.

Parameters
appNamethe app's instance name, e.g. words, kspread, kpresenter etc.
tagNamethe name of the tag for the root element, e.g. DOC for words/kpresenter.
versionthe DTD version (usually the application's version).

Definition at line 2249 of file KisDocument.cpp.

2250{
2251 QDomImplementation impl;
2252 QString url = QString("http://www.calligra.org/DTD/%1-%2.dtd").arg(appName).arg(version);
2253 QDomDocumentType dtype = impl.createDocumentType(tagName,
2254 QString("-//KDE//DTD %1 %2//EN").arg(appName).arg(version),
2255 url);
2256 // The namespace URN doesn't need to include the version number.
2257 QString namespaceURN = QString("http://www.calligra.org/DTD/%1").arg(appName);
2258 QDomDocument doc = impl.createDocument(namespaceURN, tagName, dtype);
2259 doc.insertBefore(doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""), doc.documentElement());
2260 return doc;
2261}

◆ createDomDocument() [2/2]

QDomDocument KisDocument::createDomDocument ( const QString & tagName,
const QString & version ) const

Return a correctly created QDomDocument for this KisDocument, including processing instruction, complete DOCTYPE tag (with systemId and publicId), and root element.

Parameters
tagNamethe name of the tag for the root element
versionthe DTD version (usually the application's version).

Definition at line 2243 of file KisDocument.cpp.

2244{
2245 return createDomDocument("krita", tagName, version);
2246}
QDomDocument createDomDocument(const QString &tagName, const QString &version) const

References createDomDocument().

◆ createUndoStore()

KisUndoStore * KisDocument::createUndoStore ( )

Definition at line 2920 of file KisDocument.cpp.

2921{
2922 return new KisDocumentUndoStore(this);
2923}

◆ documentBounds()

QRectF KisDocument::documentBounds ( ) const

Return the bounding box of the image and associated elements (e.g. reference images)

Definition at line 2945 of file KisDocument.cpp.

2946{
2947 QRectF bounds = d->image->bounds();
2948
2950
2951 if (referenceImagesLayer) {
2953 }
2954
2955 return bounds;
2956}
#define bounds(x, a, b)

References KisReferenceImagesLayer::boundingImageRect(), bounds, d, and referenceImagesLayer().

◆ documentInfo()

KoDocumentInfo * KisDocument::documentInfo ( ) const
Returns
the information concerning this document.
See also
KoDocumentInfo

Definition at line 1847 of file KisDocument.cpp.

1848{
1849 return d->docInfo;
1850}

References d.

◆ embeddedResourcesStorageId()

QString KisDocument::embeddedResourcesStorageId ( ) const

Temporary storage for the resources that are embedded into other resources used by the document. E.g. patterns embedded into layer styles.

Definition at line 726 of file KisDocument.cpp.

727{
728 return d->embeddedResourcesStorageID;
729}

References d.

◆ errorMessage()

QString KisDocument::errorMessage ( ) const

Return the last error message. Usually KisDocument takes care of showing it; this method is mostly provided for non-interactive use.

Definition at line 2275 of file KisDocument.cpp.

2276{
2277 return d->lastErrorMessage;
2278}

References d.

◆ exportDocument()

bool KisDocument::exportDocument ( const QString & path,
const QByteArray & mimeType,
bool isAdvancedExporting = false,
bool showWarnings = false,
KisPropertiesConfigurationSP exportConfiguration = 0 )

Saves the document as path without changing the state of the KisDocument (Path, modified flag etc.). Call this instead of saveAs() to implement KisMainWindow's File --> Export feature. Make sure to provide two separate bool parameters otherwise it will mix them

Definition at line 931 of file KisDocument.cpp.

932{
933 using namespace KritaUtils;
934
935 SaveFlags flags = SaveIsExporting;
936 if (showWarnings) {
937 flags |= SaveShowWarnings;
938 }
939
940 KisUsageLogger::log(QString("Exporting Document: %1 as %2. %3 * %4 pixels, %5 layers, %6 frames, %7 "
941 "framerate. Export configuration: %8")
942 .arg(path, QString::fromLatin1(mimeType), QString::number(d->image->width()),
943 QString::number(d->image->height()), QString::number(d->image->nlayers()),
944 QString::number(d->image->animationInterface()->totalLength()),
945 QString::number(d->image->animationInterface()->framerate()),
946 (exportConfiguration ? exportConfiguration->toXML() : "No configuration")));
947
949 mimeType,
950 flags),
951 exportConfiguration, isAdvancedExporting);
952}
QByteArray mimeType
bool exportDocumentImpl(const KritaUtils::ExportFileJob &job, KisPropertiesConfigurationSP exportConfiguration, bool isAdvancedExporting=false)
static void log(const QString &message)
Logs with date/time.

References d, exportDocumentImpl(), KisUsageLogger::log(), and mimeType.

◆ exportDocumentImpl()

bool KisDocument::exportDocumentImpl ( const KritaUtils::ExportFileJob & job,
KisPropertiesConfigurationSP exportConfiguration,
bool isAdvancedExporting = false )
private

Definition at line 741 of file KisDocument.cpp.

742{
743 // ANDROID NOTES (other comments in this file reference this one!)
744 //
745 // The Android file system doesn't work like on a real operating system.
746 // Instead of normal file paths, we get to deal with "content URIs", which
747 // can have various kinds of storage providers behind them. For example,
748 // there's a "normal" storage provider, a slightly less normal documents
749 // provider, a Google Drive provider and various kinds of third-party
750 // providers that are mostly just good at losing the data you give them.
751 // For example, we have reports of compression programs that provide a
752 // storage provider to write to ZIP or RAR archives or something. Except
753 // that they don't seem to work at all, they just accept the data with no
754 // error and throw it on the floor.
755 //
756 // The providers are particularly unreliable with regards to permissions,
757 // so calling "isWritable" will just always return false on some of them.
758 // This includes the default provider on some devices, which means checking
759 // whether a file is writable will mean that the user can't save anything!
760 // So, all the Android code skips over the writability check and assumes the
761 // files are writable. If they're not, we'll notice later anyway, by the
762 // fact that writing to them fails.
763 //
764 // Another issue is that it's only possible to overwrite files using File >
765 // Save. Using File > Save As or File > Export can't replace existing
766 // files. The reason for this is that we have to go through the operating
767 // system to request access to a file and the only things you can ask for
768 // is to open an existing file or to create a new file. Out of necessity,
769 // Save As and Export use the latter. If the user selects an existing file,
770 // the operating system "helpfully" appends a number to the path, *after*
771 // the file extension of course, because it hates the living. So that's
772 // another reason we can't go with the "safer" option of assuming that files
773 // aren't writable in some cases, since that would prevent the user from
774 // saving them normally and end up with a lot of "kiki.kra (2)".
775 //
776 // Also, when you request a file from the operating system, it always
777 // creates an empty file. That means checking whether a file exists will
778 // pretty much always succeed, so to know whether a file actually exists
779 // you have to check whether it isn't empty. Of course providers may fail to
780 // implement this correctly, but I'm not aware of any of them botching it
781 // that hard. Well, at least none of the ones that actually save files, as
782 // mentioned above some of them just seem to lose whatever you give them.
783
784 QFileInfo filePathInfo(job.filePath);
785 bool fileExists = filePathInfo.exists();
786#ifdef Q_OS_ANDROID
787 if (fileExists) {
788 fileExists = filePathInfo.size() > 0;
789 }
790#else
791 if (fileExists && !filePathInfo.isWritable()) {
793 i18n("%1 cannot be written to. Please save under a different name.", job.filePath),
794 "");
795 return false;
796 }
797#endif
798
799 KisConfig cfg(true);
800 if (cfg.backupFile() && fileExists) {
801
802 QString backupDir;
803
804 switch(cfg.readEntry<int>("backupfilelocation", 0)) {
805 case 1:
806 backupDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
807 break;
808 case 2:
809 backupDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
810 break;
811 default:
812#ifdef Q_OS_ANDROID
813 // We deal with URIs, there may or may not be a "directory"
815 QDir().mkpath(backupDir);
816#endif
817
818#ifdef Q_OS_MACOS
820 if (bookmarkmngr->isSandboxed()) {
821 // If the user does not have directory permission force backup
822 // files to be inside Container tmp
823 QUrl fileUrl = QUrl::fromLocalFile(job.filePath);
824 if( !bookmarkmngr->parentDirHasPermissions(fileUrl.path()) ) {
825 backupDir = QDir::tempPath();
826 }
827 }
828#endif
829
830 // Do nothing: the empty string is user file location
831 break;
832 }
833
834 int numOfBackupsKept = cfg.readEntry<int>("numberofbackupfiles", 1);
835 QString suffix = cfg.readEntry<QString>("backupfilesuffix", "~");
836
837 if (numOfBackupsKept == 1) {
838 if (!KisBackup::simpleBackupFile(job.filePath, backupDir, suffix)) {
839 qWarning() << "Failed to create simple backup file!" << job.filePath << backupDir << suffix;
840 KisUsageLogger::log(QString("Failed to create a simple backup for %1 in %2.")
841 .arg(job.filePath, backupDir.isEmpty()
842 ? "the same location as the file"
843 : backupDir));
844 slotCompleteSavingDocument(job, ImportExportCodes::ErrorWhileWriting, i18nc("Saving error message", "Failed to create a backup file"), "");
845 return false;
846 }
847 else {
848 KisUsageLogger::log(QString("Create a simple backup for %1 in %2.")
849 .arg(job.filePath, backupDir.isEmpty()
850 ? "the same location as the file"
851 : backupDir));
852 }
853 }
854 else if (numOfBackupsKept > 1) {
855 if (!KisBackup::numberedBackupFile(job.filePath, backupDir, suffix, numOfBackupsKept)) {
856 qWarning() << "Failed to create numbered backup file!" << job.filePath << backupDir << suffix;
857 KisUsageLogger::log(QString("Failed to create a numbered backup for %2.")
858 .arg(job.filePath, backupDir.isEmpty()
859 ? "the same location as the file"
860 : backupDir));
861 slotCompleteSavingDocument(job, ImportExportCodes::ErrorWhileWriting, i18nc("Saving error message", "Failed to create a numbered backup file"), "");
862 return false;
863 }
864 else {
865 KisUsageLogger::log(QString("Create a simple backup for %1 in %2.")
866 .arg(job.filePath, backupDir.isEmpty()
867 ? "the same location as the file"
868 : backupDir));
869 }
870 }
871 }
872
873 //KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(!job.mimeType.isEmpty(), false);
874 if (job.mimeType.isEmpty()) {
876 slotCompleteSavingDocument(job, error, error.errorMessage(), "");
877 return false;
878
879 }
880
881 const QString actionName =
883 i18n("Exporting Document...") :
884 i18n("Saving Document...");
885
889 job, exportConfiguration, isAdvancedExporting);
890
892 QString errorShortLog;
893 QString errorMessage;
895
896 switch (result) {
898 errorShortLog = "another save operation is in progress";
899 errorMessage = i18n("Could not start saving %1. Wait until the current save operation has finished.", job.filePath);
900 errorCode = ImportExportCodes::Failure;
901 break;
903 errorShortLog = "failed to lock and clone the image";
904 errorMessage = i18n("Could not start saving %1. Image is busy", job.filePath);
905 errorCode = ImportExportCodes::Busy;
906 break;
908 errorShortLog = "failed to start background saving";
909 errorMessage = i18n("Could not start saving %1. Unknown failure has happened", job.filePath);
910 errorCode = ImportExportCodes::Failure;
911 break;
914 break;
916 // noop, not possible
917 break;
918 }
919
920 KisUsageLogger::log(QString("Failed to initiate saving %1 in background: %2").arg(job.filePath).arg(errorShortLog));
921
922 slotCompleteSavingDocument(job, errorCode,
924 "");
925 return false;
926 }
927
929}
static bool simpleBackupFile(const QString &filename, const QString &backupDir=QString(), const QString &backupExtension=QStringLiteral("~"))
Definition KisBackup.cpp:24
static bool numberedBackupFile(const QString &filename, const QString &backupDir=QString(), const QString &backupExtension=QStringLiteral("~"), const uint maxBackups=10)
Definition KisBackup.cpp:38
KritaUtils::BackgroudSavingStartResult initiateSavingInBackground(const QString actionName, const QObject *receiverObject, const char *receiverMethod, const KritaUtils::ExportFileJob &job, KisPropertiesConfigurationSP exportConfiguration, std::unique_ptr< KisDocument > &&optionalClonedDocument, bool isAdvancedExporting=false)
QString errorMessage() const
void slotCompleteSavingDocument(const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)

References KritaUtils::AnotherSavingInProgress, KisAutoSaveRecoveryDialog::autoSaveLocation(), KisConfig::backupFile(), ImportExportCodes::Busy, ImportExportCodes::Cancelled, KritaUtils::Cancelled, errorMessage(), KisImportExportErrorCode::errorMessage(), ImportExportCodes::ErrorWhileWriting, ImportExportCodes::Failure, KritaUtils::Failure, ImportExportCodes::FileFormatNotSupported, KritaUtils::ExportFileJob::filePath, KritaUtils::ExportFileJob::flags, KritaUtils::ImageLockFailure, initiateSavingInBackground(), KisMacosSecurityBookmarkManager::instance(), KisMacosSecurityBookmarkManager::isSandboxed(), KisUsageLogger::log(), KritaUtils::ExportFileJob::mimeType, ImportExportCodes::NoAccessToWrite, KisBackup::numberedBackupFile(), KisMacosSecurityBookmarkManager::parentDirHasPermissions(), KisConfig::readEntry(), KritaUtils::SaveIsExporting, KisBackup::simpleBackupFile(), slotCompleteSavingDocument(), and KritaUtils::Success.

◆ exportDocumentSync()

bool KisDocument::exportDocumentSync ( const QString & path,
const QByteArray & mimeType,
KisPropertiesConfigurationSP exportConfiguration = 0 )

Exports he document is a synchronous way. The caller must ensure that the image is not accessed by any other actors, because the exporting happens without holding the image lock.

The caller guarantees that no one else uses the document (usually, it is a temporary document created specifically for exporting), so we don't need to copy or lock the document. Instead we should just ensure the barrier lock is synced and then released.

Definition at line 1339 of file KisDocument.cpp.

1340{
1341 {
1348 Private::StrippedSafeSavingLocker locker(&d->savingMutex, d->image);
1349 if (!locker.successfullyLocked()) {
1350 return false;
1351 }
1352 }
1353
1354 d->savingImage = d->image;
1355
1357 d->importExportManager->
1358 exportDocument(path, path, mimeType, false, exportConfiguration);
1359
1360 d->savingImage = 0;
1361
1362 return status.isOk();
1363}
bool exportDocument(const QString &path, const QByteArray &mimeType, bool isAdvancedExporting=false, bool showWarnings=false, KisPropertiesConfigurationSP exportConfiguration=0)

References d, exportDocument(), KisImportExportErrorCode::isOk(), and mimeType.

◆ exportErrorToUserMessage()

QString KisDocument::exportErrorToUserMessage ( KisImportExportErrorCode status,
const QString & errorMessage )
private

Definition at line 2930 of file KisDocument.cpp.

2931{
2932 return errorMessage.isEmpty() ? status.errorMessage() : errorMessage;
2933}

References errorMessage(), and KisImportExportErrorCode::errorMessage().

◆ extraNativeMimeTypes()

static QStringList KisDocument::extraNativeMimeTypes ( )
inlinestatic

Returns a list of the mimeTypes considered "native", i.e. which can be saved by KisDocument without a filter, in addition to the main one

Definition at line 178 of file KisDocument.h.

178{ return QStringList() << KIS_MIME_TYPE; }
#define KIS_MIME_TYPE
Definition KisDocument.h:57
QList< QString > QStringList

References KIS_MIME_TYPE.

◆ fileBatchMode()

bool KisDocument::fileBatchMode ( ) const
Returns
true if file operations should inhibit the option dialog

Definition at line 1148 of file KisDocument.cpp.

1149{
1150 return d->batchMode;
1151}

References d.

◆ finishExportInBackground

void KisDocument::finishExportInBackground ( )
privateslot

Definition at line 1763 of file KisDocument.cpp.

1764{
1765 KIS_SAFE_ASSERT_RECOVER(d->childSavingFuture.isFinished()) {
1767 return;
1768 }
1769
1770 KisImportExportErrorCode status = d->childSavingFuture.result();
1771 QString errorMessage = status.errorMessage();
1772 QString warningMessage = d->lastWarningMessage;
1773
1774 if (!d->lastErrorMessage.isEmpty()) {
1776 errorMessage = d->lastErrorMessage;
1777 } else {
1778 errorMessage += "\n" + d->lastErrorMessage;
1779 }
1780 }
1781
1782 d->savingImage.clear();
1783 d->childSavingFuture = QFuture<KisImportExportErrorCode>();
1784 d->lastErrorMessage.clear();
1785 d->lastWarningMessage.clear();
1786
1787 if (d->savingUpdater) {
1788 d->savingUpdater->setProgress(100);
1789 }
1790
1792}
QString warningMessage() const
void sigBackgroundSavingFinished(KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
#define KIS_SAFE_ASSERT_RECOVER(cond)
Definition kis_assert.h:126

References d, errorMessage(), KisImportExportErrorCode::errorMessage(), ImportExportCodes::Failure, ImportExportCodes::InternalError, KIS_SAFE_ASSERT_RECOVER, sigBackgroundSavingFinished(), and warningMessage().

◆ generateAutoSaveFileName()

QString KisDocument::generateAutoSaveFileName ( const QString & path) const
private

Definition at line 1900 of file KisDocument.cpp.

1901{
1902 QString retval;
1903
1904 // Using the extension allows to avoid relying on the mime magic when opening
1905 const QString extension (".kra");
1906 QString prefix = KisConfig(true).readEntry<bool>("autosavefileshidden") ? QString(".") : QString();
1907 QRegularExpression autosavePattern1("^\\..+-autosave.kra$");
1908 QRegularExpression autosavePattern2("^.+-autosave.kra$");
1909
1910 QFileInfo fi(path);
1911 QString dir = fi.absolutePath();
1912
1913#ifdef Q_OS_ANDROID
1914 // URIs may or may not have a directory backing them, so we save to our default autosave location
1915 if (path.startsWith("content://")) {
1917 QDir().mkpath(dir);
1918 }
1919#endif
1920
1921 QString filename = fi.fileName();
1922
1923 if (path.isEmpty() || autosavePattern1.match(filename).hasMatch() || autosavePattern2.match(filename).hasMatch() || !fi.isWritable()) {
1924 // Never saved?
1925 retval = QString("%1%2%3%4-%5-%6-autosave%7")
1927 .arg('/')
1928 .arg(prefix)
1929 .arg("krita")
1930 .arg(qApp->applicationPid())
1931 .arg(objectName())
1932 .arg(extension);
1933 } else {
1934 // Beware: don't reorder arguments
1935 // otherwise in case of filename = '1-file.kra' it will become '.-file.kra-autosave.kra' instead of '.1-file.kra-autosave.kra'
1936 retval = QString("%1%2%3%4-autosave%5").arg(dir).arg('/').arg(prefix).arg(filename).arg(extension);
1937 }
1938
1939 //qDebug() << "generateAutoSaveFileName() for path" << path << ":" << retval;
1940 return retval;
1941}
T readEntry(const QString &name, const T &defaultValue=T())
Definition kis_config.h:914

References KisAutoSaveRecoveryDialog::autoSaveLocation(), and KisConfig::readEntry().

◆ generatePreview()

QPixmap KisDocument::generatePreview ( const QSize & size)

Generates a preview picture of the document.

Note
The preview is used in the File Dialog and also to create the Thumbnail

Definition at line 1857 of file KisDocument.cpp.

1858{
1859 KisImageSP image = d->image;
1860 if (d->savingImage) image = d->savingImage;
1861
1862 if (image) {
1863 QRect bounds = image->bounds();
1864 QSize originalSize = bounds.size();
1865 // QSize may round down one dimension to zero on extreme aspect rations, so ensure 1px minimum
1866 QSize newSize = originalSize.scaled(size, Qt::KeepAspectRatio).expandedTo({1, 1});
1867
1868 bool pixelArt = false;
1869 // determine if the image is pixel art or not
1870 if (originalSize.width() < size.width() && originalSize.height() < size.height()) {
1871 // the image must be smaller than the requested preview
1872 // the scale must be integer
1873 if (newSize.height()%originalSize.height() == 0 && newSize.width()%originalSize.width() == 0) {
1874 pixelArt = true;
1875 }
1876 }
1877
1878 QPixmap px;
1879 if (pixelArt) {
1880 // do not scale while converting (because it uses Bicubic)
1881 QImage original = image->convertToQImage(originalSize, 0);
1882 // scale using FastTransformation, which is probably Nearest neighbour, suitable for pixel art
1883 QImage scaled = original.scaled(newSize, Qt::KeepAspectRatio, Qt::FastTransformation);
1884 px = QPixmap::fromImage(scaled);
1885 } else {
1886 px = QPixmap::fromImage(image->convertToQImage(newSize, 0));
1887 }
1888 if (px.size() == QSize(0,0)) {
1889 px = QPixmap(newSize);
1890 QPainter gc(&px);
1891 QBrush checkBrush = QBrush(KisCanvasWidgetBase::createCheckersImage(newSize.width() / 5));
1892 gc.fillRect(px.rect(), checkBrush);
1893 gc.end();
1894 }
1895 return px;
1896 }
1897 return QPixmap(size);
1898}
static QImage createCheckersImage(qint32 checkSize=-1)
QImage convertToQImage(qint32 x1, qint32 y1, qint32 width, qint32 height, const KoColorProfile *profile)
QRect bounds() const override
int size(const Forest< T > &forest)
Definition KisForest.h:1232

References KisImage::bounds(), bounds, KisImage::convertToQImage(), KisCanvasWidgetBase::createCheckersImage(), d, and image.

◆ getAudioLevel()

qreal KisDocument::getAudioLevel ( )

Definition at line 2513 of file KisDocument.cpp.

2514{
2515 return d->audioLevel;
2516}

References d.

◆ getAudioTracks()

QVector< QFileInfo > KisDocument::getAudioTracks ( ) const

Definition at line 2497 of file KisDocument.cpp.

2497 {
2498 return d->audioTracks;
2499}

References d.

◆ getStoryboardCommentsList()

QVector< StoryboardComment > KisDocument::getStoryboardCommentsList ( )

returns the list of comments for the storyboard docker in the document

Definition at line 2484 of file KisDocument.cpp.

2485{
2486 return d->m_storyboardCommentList;
2487}

References d.

◆ getStoryboardItemList()

StoryboardItemList KisDocument::getStoryboardItemList ( )

returns the list of pointers to storyboard Items for the document

Definition at line 2471 of file KisDocument.cpp.

2472{
2473 return d->m_storyboardItemList;
2474}

References d.

◆ gridConfig()

KisGridConfig KisDocument::gridConfig ( ) const

◆ guidesConfig()

const KisGuidesConfig & KisDocument::guidesConfig ( ) const

returns the guides data for this document.

◆ hackPreliminarySetImage()

void KisDocument::hackPreliminarySetImage ( KisImageSP image)

Set the image of the document preliminary, before the document has completed loading. Some of the document items (shapes) may want to access image properties (bounds and resolution), so we should provide it to them even before the entire image is loaded.

Right now, the only use by KoShapeRegistry::createShapeFromOdf(), remove after it is deprecated.

Definition at line 2897 of file KisDocument.cpp.

2898{
2900
2901 // we set image without connecting idle-watcher, because loading
2902 // hasn't been finished yet
2903 d->image = image;
2904 d->shapeController->setImage(image);
2905}
#define KIS_SAFE_ASSERT_RECOVER_RETURN(cond)
Definition kis_assert.h:128

References d, image, and KIS_SAFE_ASSERT_RECOVER_RETURN.

◆ image()

KisImageWSP KisDocument::image ( ) const

◆ importDocument()

bool KisDocument::importDocument ( const QString & path)

Opens the document given by path, without storing the Path in the KisDocument. Call this instead of openPath() to implement KisMainWindow's File --> Import feature.

Note
This will call openPath(). To differentiate this from an ordinary Open operation (in any reimplementation of openPath() or openFile()) call isImporting().

Definition at line 1943 of file KisDocument.cpp.

1944{
1945 bool ret;
1946
1947 dbgUI << "path=" << _path;
1948
1949 // open...
1950 ret = openPath(_path);
1951
1952 // reset url & m_file (kindly? set by KisParts::openUrl()) to simulate a
1953 // File --> Import
1954 if (ret) {
1955 dbgUI << "success, resetting url";
1956 resetPath();
1957 }
1958
1959 return ret;
1960}
bool openPath(const QString &path, OpenFlags flags=None)
openPath Open a Path
#define dbgUI
Definition kis_debug.h:56

References dbgUI, openPath(), and resetPath().

◆ importExportManager()

KisImportExportManager * KisDocument::importExportManager ( ) const

importExportManager gives access to the internal import/export manager

Returns
the document's import/export manager

◆ initiateSavingInBackground() [1/2]

KritaUtils::BackgroudSavingStartResult KisDocument::initiateSavingInBackground ( const QString actionName,
const QObject * receiverObject,
const char * receiverMethod,
const KritaUtils::ExportFileJob & job,
KisPropertiesConfigurationSP exportConfiguration,
bool isAdvancedExporting = false )
private

Definition at line 1366 of file KisDocument.cpp.

1370{
1371 return initiateSavingInBackground(actionName, receiverObject, receiverMethod,
1372 job, exportConfiguration, std::unique_ptr<KisDocument>(), isAdvancedExporting);
1373}

References initiateSavingInBackground().

◆ initiateSavingInBackground() [2/2]

KritaUtils::BackgroudSavingStartResult KisDocument::initiateSavingInBackground ( const QString actionName,
const QObject * receiverObject,
const char * receiverMethod,
const KritaUtils::ExportFileJob & job,
KisPropertiesConfigurationSP exportConfiguration,
std::unique_ptr< KisDocument > && optionalClonedDocument,
bool isAdvancedExporting = false )
private

This lock will later release() when we start the background thread, it means that the ownership is transferred to the background thread

From now on no return statements are allowed, even inside asserts, since the ownership over the saving mutex has already been passed to the background thread.

The cancellation process should go through slotChildCompletedSavingInBackground(), which will unlock the mutex itself.

Definition at line 1375 of file KisDocument.cpp.

1380{
1382
1383 std::unique_ptr<KisDocument> clonedDocument;
1384
1385 if (!optionalClonedDocument) {
1386 clonedDocument.reset(lockAndCloneForSaving());
1387 } else {
1388 clonedDocument.reset(optionalClonedDocument.release());
1389 }
1390
1391 if (!d->savingMutex.tryLock()){
1393 }
1394
1399 std::unique_lock<QMutex> savingMutexLock(d->savingMutex, std::adopt_lock);
1400
1401 if (!clonedDocument) {
1403 }
1404
1405 auto waitForImage = [] (KisImageSP image) {
1407 if (window) {
1408 if (window->viewManager()) {
1410 }
1411 }
1412 };
1413
1414 {
1415 KisNodeSP newRoot = clonedDocument->image()->root();
1418 waitForImage(clonedDocument->image());
1419 }
1420 }
1421
1422 if (clonedDocument->image()->hasOverlaySelectionMask()) {
1423 clonedDocument->image()->setOverlaySelectionMask(0);
1424 waitForImage(clonedDocument->image());
1425 }
1426
1427 KisConfig cfg(true);
1428 if (cfg.trimKra()) {
1429 clonedDocument->image()->cropImage(clonedDocument->image()->bounds());
1430 clonedDocument->image()->purgeUnusedData(false);
1431 waitForImage(clonedDocument->image());
1432 }
1433
1434 KIS_SAFE_ASSERT_RECOVER(clonedDocument->image()->isIdle()) {
1435 waitForImage(clonedDocument->image());
1436 }
1437
1440
1450 savingMutexLock.release();
1451
1452 d->backgroundSaveDocument.reset(clonedDocument.release());
1453 d->backgroundSaveJob = job;
1454 d->modifiedWhileSaving = false;
1455
1456 if (d->backgroundSaveJob.flags & KritaUtils::SaveInAutosaveMode) {
1457 d->backgroundSaveDocument->d->isAutosaving = true;
1458 }
1459
1460 connect(d->backgroundSaveDocument.get(),
1461 SIGNAL(sigBackgroundSavingFinished(KisImportExportErrorCode, QString, QString)),
1462 this,
1464
1465
1466 if (d->completeSavingConnection) {
1467 disconnect(d->completeSavingConnection);
1468 }
1469 d->completeSavingConnection = connect(
1471 receiverObject, receiverMethod);
1472
1474 d->backgroundSaveDocument->startExportInBackground(actionName,
1475 job.filePath,
1476 job.filePath,
1477 job.mimeType,
1479 exportConfiguration, isAdvancedExporting);
1480 if (!error.isOk()) {
1481 // the state should have been deinitialized in slotChildCompletedSavingInBackground()
1482 KIS_SAFE_ASSERT_RECOVER (!d->backgroundSaveDocument && !d->backgroundSaveJob.isValid()) {
1483 d->backgroundSaveDocument.release()->deleteLater();
1484 d->savingMutex.unlock();
1485 d->backgroundSaveJob = KritaUtils::ExportFileJob();
1486 }
1487 if (error.isCancelled()) {
1489 }
1491 }
1492
1494}
KisDocument * lockAndCloneForSaving()
try to clone the image. This method handles all the locking for you. If locking has failed,...
void slotChildCompletedSavingInBackground(KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
void sigCompleteBackgroundSaving(const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
Main window for Krita.
KisViewManager * viewManager
KisMainWindow * currentMainwindow() const
Definition KisPart.cpp:458
void blockUntilOperationsFinishedForced(KisImageSP image)
blockUntilOperationsFinished blocks the GUI of the application until execution of actions on image is...
#define KIS_ASSERT_RECOVER_RETURN_VALUE(cond, val)
Definition kis_assert.h:85
bool hasDelayedNodeWithUpdates(KisNodeSP root)
void forceAllDelayedNodesUpdate(KisNodeSP root)
KisImageWSP image

References KritaUtils::AnotherSavingInProgress, KisViewManager::blockUntilOperationsFinishedForced(), KritaUtils::Cancelled, KisPart::currentMainwindow(), d, KritaUtils::Failure, KritaUtils::ExportFileJob::filePath, KritaUtils::ExportFileJob::flags, KisLayerUtils::forceAllDelayedNodesUpdate(), KisLayerUtils::hasDelayedNodeWithUpdates(), KisBaseNode::image, image, KritaUtils::ImageLockFailure, KisPart::instance(), KisImportExportErrorCode::isCancelled(), KisImportExportErrorCode::isOk(), KritaUtils::ExportFileJob::isValid(), KIS_ASSERT_RECOVER_RETURN_VALUE, KIS_SAFE_ASSERT_RECOVER, lockAndCloneForSaving(), KritaUtils::ExportFileJob::mimeType, KisNodeFacade::root, KritaUtils::SaveInAutosaveMode, KritaUtils::SaveShowWarnings, sigBackgroundSavingFinished(), sigCompleteBackgroundSaving(), slotChildCompletedSavingInBackground(), KritaUtils::Success, KisConfig::trimKra(), and KisMainWindow::viewManager.

◆ isAutoSaveActive()

bool KisDocument::isAutoSaveActive ( )

Indicate if autosave is active or inactive

the value is independent of auto save delay

Definition at line 1842 of file KisDocument.cpp.

1843{
1844 return d->autoSaveActive;
1845}

References d.

◆ isAutosaving()

bool KisDocument::isAutosaving ( ) const

◆ isInSaving()

bool KisDocument::isInSaving ( ) const

isInSaving shown if the document has any (background) saving process or not

Returns
true if there is some saving in action

◆ isModified()

bool KisDocument::isModified ( ) const

Returns true if this document or any of its internal child documents are modified.

Definition at line 1852 of file KisDocument.cpp.

1853{
1854 return d->modified;
1855}

References d.

◆ isNativeFormat()

bool KisDocument::isNativeFormat ( const QByteArray & mimeType) const

Checks whether a given mimeType can be handled natively.

Definition at line 2263 of file KisDocument.cpp.

2264{
2266 return true;
2267 return extraNativeMimeTypes().contains(mimeType);
2268}
static QStringList extraNativeMimeTypes()

References extraNativeMimeTypes(), mimeType, and nativeFormatMimeType().

◆ isReadWrite()

bool KisDocument::isReadWrite ( ) const

Definition at line 2564 of file KisDocument.cpp.

2565{
2566 return d->readwrite;
2567}

References d.

◆ isRecovered()

bool KisDocument::isRecovered ( ) const

◆ isSaving()

bool KisDocument::isSaving ( ) const

Definition at line 2761 of file KisDocument.cpp.

2762{
2763 const bool result = d->savingMutex.tryLock();
2764 if (result) {
2765 d->savingMutex.unlock();
2766 }
2767 return !result;
2768}

References d.

◆ linkedDocumentResources()

QList< KoResourceLoadResult > KisDocument::linkedDocumentResources ( )

linkedDocumentResources List returns all the resources linked to the document, such as palettes

In some cases (e.g. when the document is temporary), the underlying document storage will not be registered in the resource system, so we cannot get fully initialized resources from it (resourceId(), active(), md5() and storageLocation() fields will be uninitialized). Therefore we just return KoEmbeddedResource which is suitable for saving this data into hard drive.

The returned KoResourceLoadResult object can either be in EmbeddedResource or FailedLink state. The former means the resource has been prepared for embedding, the latter means there was some issue with serializing the resource. In the latter case the called should check result.signature() to find out which resource has failed.

NOTE: the returned result can NOT have ExistingResource state!

Definition at line 2399 of file KisDocument.cpp.

2400{
2402 if (!d->linkedResourceStorage) {
2403 return result;
2404 }
2405
2406 Q_FOREACH(const QString &resourceType, KisResourceLoaderRegistry::instance()->resourceTypes()) {
2407 QSharedPointer<KisResourceStorage::ResourceIterator> iter = d->linkedResourceStorage->resources(resourceType);
2408 while (iter->hasNext()) {
2409 iter->next();
2410
2411 QBuffer buf;
2412 buf.open(QBuffer::WriteOnly);
2413 bool exportSuccessful =
2414 d->linkedResourceStorage->exportResource(iter->url(), &buf);
2415
2416 KoResourceSP resource = d->linkedResourceStorage->resource(iter->url());
2417 exportSuccessful &= bool(resource);
2418
2419 const QString name = resource ? resource->name() : QString();
2420 const QString fileName = QFileInfo(iter->url()).fileName();
2421 const KoResourceSignature signature(resourceType,
2422 KoMD5Generator::generateHash(buf.data()),
2423 fileName, name);
2424
2425 if (exportSuccessful) {
2426 result << KoEmbeddedResource(signature, buf.data());
2427 } else {
2428 result << signature;
2429 }
2430 }
2431 }
2432
2433 return result;
2434}
static KisResourceLoaderRegistry * instance()
static QString generateHash(const QString &filename)
generateHash reads the given file and generates a hex-encoded md5sum for the file.
A simple wrapper object for the main information about the resource.
const char * name(StandardAction id)

References d, KoMD5Generator::generateHash(), and KisResourceLoaderRegistry::instance().

◆ linkedResourcesStorageId()

QString KisDocument::linkedResourcesStorageId ( ) const

Persistent storage for the resources that are linked but the resources embedded in the document. These resources are not embedded into their own container resource, so they should be stored by the document

All these resources are saved into the document itself and loaded alongside the document.

Definition at line 731 of file KisDocument.cpp.

732{
733 return d->linkedResourcesStorageID;
734}

References d.

◆ loadNativeFormat()

bool KisDocument::loadNativeFormat ( const QString & file)

Loads a document in the native format from a given Path. Reimplement if your native format isn't XML.

Parameters
filethe file to load - usually KReadOnlyPart::m_file or the result of a filter

Definition at line 2141 of file KisDocument.cpp.

2142{
2143 return openPath(file_);
2144}

References openPath().

◆ localFilePath()

QString KisDocument::localFilePath ( ) const

Definition at line 2609 of file KisDocument.cpp.

2610{
2611 return d->m_file;
2612}

References d.

◆ lockAndCloneForSaving()

KisDocument * KisDocument::lockAndCloneForSaving ( )

try to clone the image. This method handles all the locking for you. If locking has failed, no cloning happens

Returns
cloned document on success, null otherwise

Definition at line 1243 of file KisDocument.cpp.

1244{
1245 return d->lockAndCloneImpl(true);
1246}

References d.

◆ lockAndCloneImpl()

KisDocument * KisDocument::lockAndCloneImpl ( bool fetchResourcesFromLayers)

◆ lockAndCreateSnapshot()

KisDocument * KisDocument::lockAndCreateSnapshot ( )

Definition at line 1248 of file KisDocument.cpp.

1249{
1250 return d->lockAndCloneImpl(false);
1251}

References d.

◆ mimeType()

QByteArray KisDocument::mimeType ( ) const

Returns the actual mimeType of the document

◆ mirrorAxisConfig()

const KisMirrorAxisConfig & KisDocument::mirrorAxisConfig ( ) const

◆ modified

void KisDocument::modified ( bool )
signal

Emitted when the document is modified

◆ nativeFormatMimeType()

static QByteArray KisDocument::nativeFormatMimeType ( )
inlinestatic

To be preferred when a document exists. It is fast when calling it multiple times since it caches the result that readNativeFormatMimeType() delivers. This comes from the X-KDE-NativeMimeType key in the .desktop file.

Definition at line 171 of file KisDocument.h.

171{ return KIS_MIME_TYPE; }

References KIS_MIME_TYPE.

◆ newImage()

bool KisDocument::newImage ( const QString & name,
qint32 width,
qint32 height,
const KoColorSpace * cs,
const KoColor & bgColor,
KisConfig::BackgroundStyle bgStyle,
int numberOfLayers,
const QString & imageDescription,
const double imageResolution )

Create a new image that has this document as a parent and replace the current image with this image.

Preinitialize color history for new documents when possible

Definition at line 2666 of file KisDocument.cpp.

2672{
2673 Q_ASSERT(cs);
2674
2676
2677 if (!cs) return false;
2678
2679 KisCursorOverrideLock cursorLock(Qt::BusyCursor);
2680
2681 image = new KisImage(createUndoStore(), width, height, cs, name);
2682
2683 Q_CHECK_PTR(image);
2684
2685 connect(image, SIGNAL(sigImageModified()), this, SLOT(setImageModified()), Qt::UniqueConnection);
2686 connect(image, SIGNAL(sigImageModifiedWithoutUndo()), this, SLOT(setImageModifiedWithoutUndo()), Qt::UniqueConnection);
2687 image->setResolution(imageResolution, imageResolution);
2688
2690 image->waitForDone();
2691
2692 documentInfo()->setAboutInfo("title", name);
2693 documentInfo()->setAboutInfo("abstract", description);
2694
2695 KisConfig cfg(false);
2696 const bool autopin = cfg.autoPinLayersToTimeline();
2697
2698 KisLayerSP bgLayer;
2699 if (bgStyle == KisConfig::RASTER_LAYER || bgStyle == KisConfig::FILL_LAYER) {
2700 KoColor strippedAlpha = bgColor;
2701 strippedAlpha.setOpacity(OPACITY_OPAQUE_U8);
2702
2703 if (bgStyle == KisConfig::RASTER_LAYER) {
2704 bgLayer = new KisPaintLayer(image.data(), i18nc("Name for the bottom-most layer in the layerstack", "Background"), OPACITY_OPAQUE_U8, cs);
2705 bgLayer->paintDevice()->setDefaultPixel(strippedAlpha);
2706 bgLayer->setPinnedToTimeline(autopin);
2707 } else if (bgStyle == KisConfig::FILL_LAYER) {
2709 filter_config->setProperty("color", strippedAlpha.toQColor());
2710 filter_config->createLocalResourcesSnapshot();
2711 bgLayer = new KisGeneratorLayer(image.data(), i18nc("Name of automatically created background color fill layer", "Background Fill"), filter_config, image->globalSelection());
2712 }
2713
2714 bgLayer->setOpacity(bgColor.opacityU8());
2715
2716 if (numberOfLayers > 1) {
2717 //Lock bg layer if others are present.
2718 bgLayer->setUserLocked(true);
2719 }
2720 }
2721 else { // KisConfig::CANVAS_COLOR (needs an unlocked starting layer).
2723 bgLayer = new KisPaintLayer(image.data(), image->nextLayerName(), OPACITY_OPAQUE_U8, cs);
2724 }
2725
2726 Q_CHECK_PTR(bgLayer);
2727 image->addNode(bgLayer.data(), image->rootLayer().data());
2728 bgLayer->setDirty(QRect(0, 0, width, height));
2729
2730 // reset mirror axis to default:
2731 d->mirrorAxisConfig.setAxisPosition(QRectF(image->bounds()).center());
2733
2734 for(int i = 1; i < numberOfLayers; ++i) {
2736 layer->setPinnedToTimeline(autopin);
2737 image->addNode(layer, image->root(), i);
2738 layer->setDirty(QRect(0, 0, width, height));
2739 }
2740
2741 {
2743 if (window) {
2748 }
2749 }
2750
2752 QString("Created image \"%1\", %2 * %3 pixels, %4 dpi. Color model: %6 %5 (%7). Layers: %8")
2753 .arg(name, QString::number(width), QString::number(height),
2754 QString::number(imageResolution * 72.0), image->colorSpace()->colorModelId().name(),
2756 QString::number(numberOfLayers)));
2757
2758 return true;
2759}
const quint8 OPACITY_OPAQUE_U8
QList< KoColor > colorHistoryColors() const
KisUndoStore * createUndoStore()
KoDocumentInfo * documentInfo() const
void setImageModified()
void setImageModifiedWithoutUndo()
void setColorHistoryColors(const QList< KoColor > &colors)
static KisGeneratorRegistry * instance()
static KisResourcesInterfaceSP instance()
void waitForDone()
KisGroupLayerSP rootLayer() const
const KoColorSpace * colorSpace() const
QString nextLayerName(const QString &baseName="") const
Definition kis_image.cc:741
bool assignImageProfile(const KoColorProfile *profile, bool blockAllUpdates=false)
void setDefaultProjectionColor(const KoColor &color)
KisSelectionSP globalSelection() const
Definition kis_image.cc:721
void setResolution(double xres, double yres)
void setDefaultPixel(const KoColor &defPixel)
KisCanvasResourceProvider * canvasResourceProvider()
virtual KoID colorModelId() const =0
virtual KoID colorDepthId() const =0
virtual const KoColorProfile * profile() const =0
void setOpacity(quint8 alpha)
Definition KoColor.cpp:333
quint8 opacityU8() const
Definition KoColor.cpp:341
void toQColor(QColor *c) const
a convenience method for the above.
Definition KoColor.cpp:198
void setAboutInfo(const QString &info, const QString &data)
T get(const QString &id) const
QString name() const
Definition KoID.cpp:68
void setPinnedToTimeline(bool pinned)
virtual void setUserLocked(bool l)
void setOpacity(quint8 val)
virtual KisPaintDeviceSP paintDevice() const =0
virtual KisFilterConfigurationSP defaultConfiguration(KisResourcesInterfaceSP resourcesInterface) const
bool addNode(KisNodeSP node, KisNodeSP parent=KisNodeSP(), KisNodeAdditionFlags flags=KisNodeAdditionFlag::None)
virtual void setDirty()
Definition kis_node.cpp:577

References KisNodeFacade::addNode(), KisImage::assignImageProfile(), KisConfig::autoPinLayersToTimeline(), KisImage::bounds(), KisViewManager::canvasResourceProvider(), KoColorSpace::colorDepthId(), KisCanvasResourceProvider::colorHistoryColors(), KoColorSpace::colorModelId(), KisImage::colorSpace(), createUndoStore(), KisPart::currentMainwindow(), d, KisSharedPtr< T >::data(), KisBaseProcessor::defaultConfiguration(), documentInfo(), KisConfig::FILL_LAYER, KoGenericRegistry< T >::get(), KisImage::globalSelection(), image, KisGeneratorRegistry::instance(), KisGlobalResourcesInterface::instance(), KisPart::instance(), KisUsageLogger::log(), KoID::name(), KoColorProfile::name, KisImage::nextLayerName(), OPACITY_OPAQUE_U8, KoColor::opacityU8(), KisBaseNode::paintDevice(), KoColorSpace::profile(), KisConfig::RASTER_LAYER, KisNodeFacade::root, KisImage::rootLayer(), KoDocumentInfo::setAboutInfo(), setColorHistoryColors(), setCurrentImage(), KisPaintDevice::setDefaultPixel(), KisImage::setDefaultProjectionColor(), KisNode::setDirty(), setImageModified(), setImageModifiedWithoutUndo(), KoColor::setOpacity(), KisBaseNode::setOpacity(), KisBaseNode::setPinnedToTimeline(), KisImage::setResolution(), KisBaseNode::setUserLocked(), KoColor::toQColor(), KisMainWindow::viewManager, and KisImage::waitForDone().

◆ newObjectName()

QString KisDocument::newObjectName ( )
private

Generate a name for the document.

Definition at line 161 of file KisDocument.cpp.

162{
163 static int s_docIFNumber = 0;
164 QString name; name.setNum(s_docIFNumber++); name.prepend("document_");
165 return name;
166}

◆ openFile()

bool KisDocument::openFile ( )
private

Loads a document

Applies a filter if necessary, and calls loadNativeFormat in any case You should not have to reimplement, except for very special cases.

NOTE: this method also creates a new KisView instance!

This method is called from the KReadOnlyPart::openPath method.

Definition at line 2038 of file KisDocument.cpp.

2039{
2040 //dbgUI <<"for" << localFilePath();
2041 if (!QFile::exists(localFilePath()) && !fileBatchMode()) {
2042 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"), i18n("File %1 does not exist.", localFilePath()));
2043 return false;
2044 }
2045
2046 QString filename = localFilePath();
2047 QString typeName = mimeType();
2048
2049 if (typeName.isEmpty()) {
2050 typeName = KisMimeDatabase::mimeTypeForFile(filename);
2051 }
2052
2053 // Allow to open backup files, don't keep the mimeType application/x-trash.
2054 if (typeName == "application/x-trash") {
2055 QString path = filename;
2056 while (path.length() > 0) {
2057 path.chop(1);
2058 typeName = KisMimeDatabase::mimeTypeForFile(path);
2059 //qDebug() << "\t" << path << typeName;
2060 if (!typeName.isEmpty()) {
2061 break;
2062 }
2063 }
2064 //qDebug() << "chopped" << filename << "to" << path << "Was trash, is" << typeName;
2065 }
2066 dbgUI << localFilePath() << "type:" << typeName;
2067
2069 KoUpdaterPtr updater;
2070 if (window && window->viewManager()) {
2071 updater = window->viewManager()->createUnthreadedUpdater(i18n("Opening document"));
2072 d->importExportManager->setUpdater(updater);
2073 }
2074
2075 KisImportExportErrorCode status = d->importExportManager->importDocument(localFilePath(), typeName);
2076
2077 if (!status.isOk()) {
2078 if (window && window->viewManager()) {
2079 updater->cancel();
2080 }
2081 QString msg = status.errorMessage();
2082 KisUsageLogger::log(QString("Loading %1 failed: %2").arg(prettyPath(), msg));
2083
2084 if (!msg.isEmpty() && !fileBatchMode()) {
2085 DlgLoadMessages dlg(i18nc("@title:window", "Krita"),
2086 i18n("Could not open %1.", prettyPath()),
2087 errorMessage().split("\n", Qt::SkipEmptyParts)
2088 + warningMessage().split("\n", Qt::SkipEmptyParts),
2089 msg);
2090
2091 dlg.exec();
2092 }
2093 return false;
2094 }
2095 else if (!warningMessage().isEmpty() && !fileBatchMode()) {
2096 DlgLoadMessages dlg(i18nc("@title:window", "Krita"),
2097 i18n("There were problems opening %1.", prettyPath()),
2098 warningMessage().split("\n", Qt::SkipEmptyParts));
2099
2100 dlg.exec();
2101 setPath(QString());
2102 }
2103
2104 setMimeTypeAfterLoading(typeName);
2105 d->syncDecorationsWrapperLayerState();
2106 Q_EMIT sigLoadingFinished();
2107
2108 undoStack()->clear();
2109
2110 return true;
2111}
KUndo2Stack * undoStack
void sigLoadingFinished()
void setPath(const QString &path)
bool fileBatchMode() const
void setMimeTypeAfterLoading(const QString &mimeType)
QString prettyPath() const
static QString mimeTypeForFile(const QString &file, bool checkExistingFiles=true)
Find the mimetype for the given filename. The filename must include a suffix.
QPointer< KoUpdater > createUnthreadedUpdater(const QString &name)
create a new progress updater
QList< KoSubpath * > split(const KoPathShape &path)

References KUndo2QStack::clear(), KisViewManager::createUnthreadedUpdater(), KisPart::currentMainwindow(), d, dbgUI, errorMessage(), KisImportExportErrorCode::errorMessage(), fileBatchMode(), KisPart::instance(), KisImportExportErrorCode::isOk(), localFilePath(), KisUsageLogger::log(), mimeType, KisMimeDatabase::mimeTypeForFile(), prettyPath(), setMimeTypeAfterLoading(), setPath(), sigLoadingFinished(), undoStack, KisMainWindow::viewManager, and warningMessage().

◆ openPath()

bool KisDocument::openPath ( const QString & path,
OpenFlags flags = None )

openPath Open a Path

Parameters
pathPath to file
flagsControl specific behavior
Returns
success status

Definition at line 1963 of file KisDocument.cpp.

1964{
1965 dbgUI << "path=" << _path;
1966 d->lastErrorMessage.clear();
1967
1968 // Reimplemented, to add a check for autosave files and to improve error reporting
1969 if (_path.isEmpty()) {
1970 d->lastErrorMessage = i18n("Malformed Path\n%1", _path); // ## used anywhere ?
1971 return false;
1972 }
1973
1974 QString path = _path;
1975 QString original = "";
1976 bool autosaveOpened = false;
1977 if (!fileBatchMode()) {
1978 QString file = path;
1979 QString asf = generateAutoSaveFileName(file);
1980 if (QFile::exists(asf)) {
1981 KisApplication *kisApp = static_cast<KisApplication*>(qApp);
1982 kisApp->hideSplashScreen();
1983 //qDebug() <<"asf=" << asf;
1984 // ## TODO compare timestamps ?
1985 KisRecoverNamedAutosaveDialog dlg(0, file, asf);
1986 dlg.exec();
1987 int res = dlg.result();
1988
1989 switch (res) {
1991 original = file;
1992 path = asf;
1993 autosaveOpened = true;
1994 break;
1996 KisUsageLogger::log(QString("Removing autosave file: %1").arg(asf));
1997 QFile::remove(asf);
1998 break;
1999 default: // Cancel
2000 return false;
2001 }
2002 }
2003 }
2004
2005 bool ret = openPathInternal(path);
2006
2007 if (autosaveOpened || flags & RecoveryFile) {
2008 setReadWrite(true); // enable save button
2009 setModified(true);
2010 setRecovered(true);
2011
2012 setPath(original); // since it was an autosave, it will be a local file
2013 setLocalFilePath(original);
2014 }
2015 else {
2016 if (ret) {
2017
2018 if (!(flags & DontAddToRecent)) {
2019 KisPart::instance()->addRecentURLToAllMainWindows(QUrl::fromLocalFile(_path));
2020 }
2021
2022#ifdef Q_OS_ANDROID
2023 // See the comment titled "ANDROID NOTES" in this file for an
2024 // explanation of what this is about. (This is not that comment.)
2025 setReadWrite(true);
2026#else
2027 QFileInfo fi(_path);
2028 setReadWrite(fi.isWritable());
2029#endif
2030 }
2031
2032 setRecovered(false);
2033 }
2034
2035 return ret;
2036}
Base class for the Krita app.
void setLocalFilePath(const QString &localFilePath)
void setRecovered(bool value)
void setReadWrite(bool readwrite=true)
Sets whether the document can be edited or is read only.
bool openPathInternal(const QString &path)
void addRecentURLToAllMainWindows(QUrl url, QUrl oldUrl=QUrl())
Definition KisPart.cpp:573
The KisRecoverNamedAutosaveDialog class is a dialog to recover already existing files from autosave.

References KisPart::addRecentURLToAllMainWindows(), d, dbgUI, DontAddToRecent, fileBatchMode(), generateAutoSaveFileName(), KisApplication::hideSplashScreen(), KisPart::instance(), KisUsageLogger::log(), KisRecoverNamedAutosaveDialog::OpenAutosave, KisRecoverNamedAutosaveDialog::OpenMainFile, openPathInternal(), path(), RecoveryFile, setLocalFilePath(), setModified(), setPath(), setReadWrite(), and setRecovered().

◆ openPathInternal()

bool KisDocument::openPathInternal ( const QString & path)
private

Definition at line 2620 of file KisDocument.cpp.

2621{
2622 if ( path.isEmpty() ) {
2623 return false;
2624 }
2625
2626 if (d->m_bAutoDetectedMime) {
2627 d->mimeType = QByteArray();
2628 d->m_bAutoDetectedMime = false;
2629 }
2630
2631 QByteArray mimeType = d->mimeType;
2632
2633 if ( !closePath() ) {
2634 return false;
2635 }
2636
2637 d->mimeType = mimeType;
2638 setPath(path);
2639
2640 d->m_file.clear();
2641
2642 d->m_file = d->m_path;
2643
2644 bool ret = false;
2645 // set the mimeType only if it was not already set (for example, by the host application)
2646 if (d->mimeType.isEmpty()) {
2647 // get the mimeType of the file
2648 // using findByUrl() to avoid another string -> url conversion
2649 QString mime = KisMimeDatabase::mimeTypeForFile(d->m_path);
2650 d->mimeType = mime.toLocal8Bit();
2651 d->m_bAutoDetectedMime = true;
2652 }
2653
2654 setPath(d->m_path);
2655 ret = openFile();
2656
2657 if (ret) {
2658 Q_EMIT completed();
2659 }
2660 else {
2661 Q_EMIT canceled(QString());
2662 }
2663 return ret;
2664}
void completed()
void canceled(const QString &)
bool closePath(bool promptToSave=true)

References canceled(), closePath(), completed(), d, mimeType, KisMimeDatabase::mimeTypeForFile(), openFile(), and setPath().

◆ path()

QString KisDocument::path ( ) const

Definition at line 2569 of file KisDocument.cpp.

2570{
2571 return d->m_path;
2572}

References d.

◆ preActivatedNode()

KisNodeSP KisDocument::preActivatedNode ( ) const
Returns
the node that was set as active during loading. Used only for saving loading. Never use it for tools or processing.

◆ prettyPath()

QString KisDocument::prettyPath ( ) const
private

Definition at line 2218 of file KisDocument.cpp.

2219{
2220 QString _url(path());
2221#ifdef Q_OS_WIN
2222 _url = QDir::toNativeSeparators(_url);
2223#endif
2224 return _url;
2225}

References path().

◆ Private() [1/2]

KisDocument::Private ( const Private & rhs,
KisDocument * _q )
inline

Definition at line 324 of file KisDocument.cpp.

325 : q(_q)
326 , docInfo(new KoDocumentInfo(*rhs.docInfo, _q))
328 , autoSaveTimer(new QTimer(_q))
329 , undoStack(new UndoStack(_q))
330 , nserver(new KisNameServer(*rhs.nserver))
331 , preActivatedNode(0) // the node is from another hierarchy!
332 , imageIdleWatcher(2000 /*ms*/)
333 , colorHistoryModel(rhs.colorHistoryModel)
334 {
335 copyFromImpl(rhs, _q, CONSTRUCT);
336 connect(&imageIdleWatcher, SIGNAL(startedIdleMode()), q, SLOT(slotPerformIdleRoutines()));
337 }
QTimer * autoSaveTimer
void copyFromImpl(const Private &rhs, KisDocument *q, KisDocument::CopyPolicy policy)
KisImportExportManager * importExportManager
KisDocument * q
KisNodeWSP preActivatedNode
KisIdleWatcher imageIdleWatcher
void slotPerformIdleRoutines()
KisUniqueColorSet colorHistoryModel
The class managing all the filters.
The class containing all meta information about a document.

◆ Private() [2/2]

KisDocument::Private ( KisDocument * _q)
inline

Definition at line 299 of file KisDocument.cpp.

300 : q(_q)
301 , docInfo(new KoDocumentInfo(_q)) // deleted by QObject
302 , importExportManager(new KisImportExportManager(_q)) // deleted manually
303 , autoSaveTimer(new QTimer(_q))
304 , undoStack(new UndoStack(_q)) // deleted by QObject
305 , m_bAutoDetectedMime(false)
306 , modified(false)
307 , readwrite(true)
308 , autoSaveActive(true)
309 , firstMod(QDateTime::currentDateTime())
311 , nserver(new KisNameServer(1))
312 , imageIdleWatcher(2000 /*ms*/)
313 , globalAssistantsColor(KisConfig(true).defaultAssistantsColor())
314 , batchMode(false)
315 {
316 if (QLocale().measurementSystem() == QLocale::ImperialSystem) {
318 } else {
320 }
321 connect(&imageIdleWatcher, SIGNAL(startedIdleMode()), q, SLOT(slotPerformIdleRoutines()));
322 }
bool m_bAutoDetectedMime
QDateTime lastMod
QDateTime firstMod
QColor globalAssistantsColor
@ Centimeter
Definition KoUnit.h:78
@ Inch
Definition KoUnit.h:77

References KoUnit::Centimeter, and KoUnit::Inch.

◆ referenceImagesLayer()

KisReferenceImagesLayerSP KisDocument::referenceImagesLayer ( ) const

Get existing reference images layer or null if none exists.

Definition at line 2802 of file KisDocument.cpp.

2803{
2804 if (!d->image) return KisReferenceImagesLayerSP();
2805
2806 KisReferenceImagesLayerSP referencesLayer =
2807 KisLayerUtils::findNodeByType<KisReferenceImagesLayer>(d->image->root());
2808
2809 return referencesLayer;
2810}
KisSharedPtr< KisReferenceImagesLayer > KisReferenceImagesLayerSP

References d.

◆ removeAutoSaveFiles()

void KisDocument::removeAutoSaveFiles ( const QString & autosaveBaseName,
bool wasRecovered )

Performs a cleanup of unneeded backup files

Definition at line 2291 of file KisDocument.cpp.

2292{
2293 // Eliminate any auto-save file
2294 QString asf = generateAutoSaveFileName(autosaveBaseName); // the one in the current dir
2295 if (QFile::exists(asf)) {
2296 KisUsageLogger::log(QString("Removing autosave file: %1").arg(asf));
2297 QFile::remove(asf);
2298 }
2299 asf = generateAutoSaveFileName(QString()); // and the one in $HOME
2300
2301 if (QFile::exists(asf)) {
2302 KisUsageLogger::log(QString("Removing autosave file: %1").arg(asf));
2303 QFile::remove(asf);
2304 }
2305
2306 QList<QRegularExpression> expressions;
2307
2308 expressions << QRegularExpression("^\\..+-autosave.kra$")
2309 << QRegularExpression("^.+-autosave.kra$");
2310
2311 Q_FOREACH(const QRegularExpression &rex, expressions) {
2312 if (wasRecovered &&
2313 !autosaveBaseName.isEmpty() &&
2314 rex.match(QFileInfo(autosaveBaseName).fileName()).hasMatch() &&
2315 QFile::exists(autosaveBaseName)) {
2316
2317 KisUsageLogger::log(QString("Removing autosave file: %1").arg(autosaveBaseName));
2318 QFile::remove(autosaveBaseName);
2319 }
2320 }
2321}

References generateAutoSaveFileName(), and KisUsageLogger::log().

◆ resetPath()

void KisDocument::resetPath ( )

Sets the document Path to empty Path After using loadNativeFormat on a template, one wants to set the path to QString()

Definition at line 2554 of file KisDocument.cpp.

2554 {
2555 setPath(QString());
2556 setLocalFilePath(QString());
2557}

References setLocalFilePath(), and setPath().

◆ resourceSavingFilter()

bool KisDocument::resourceSavingFilter ( const QString & path,
const QByteArray & mimeType,
KisPropertiesConfigurationSP exportConfiguration )
private

Checks whether we are saving a resource we've been editing, and if so, uses the resource server to update the resource.

Returns
true if this was a resource, false if the document needs to be saved

Definition at line 1580 of file KisDocument.cpp.

1581{
1582 if (QFileInfo(path).absolutePath().startsWith(KisResourceLocator::instance()->resourceLocationBase())) {
1583
1584 QStringList pathParts = QFileInfo(path).absolutePath().split('/');
1585 if (pathParts.size() > 0) {
1586 QString resourceType = pathParts.last();
1587 if (KisResourceLoaderRegistry::instance()->resourceTypes().contains(resourceType)) {
1588
1589 KisResourceModel model(resourceType);
1590 model.setResourceFilter(KisResourceModel::ShowAllResources);
1591
1592 QString tempFileName = QDir::tempPath() + "/" + QFileInfo(path).fileName();
1593
1594 if (QFileInfo(path).exists()) {
1595
1596 int outResourceId;
1597 KoResourceSP res;
1598 if (KisResourceCacheDb::getResourceIdFromVersionedFilename(QFileInfo(path).fileName(), resourceType, "", outResourceId)) {
1599 res = model.resourceForId(outResourceId);
1600 }
1601
1602 if (res) {
1603 d->modifiedWhileSaving = false;
1604
1605 if (!exportConfiguration) {
1606 QScopedPointer<KisImportExportFilter> filter(
1608 if (filter) {
1609 exportConfiguration = filter->defaultConfiguration(nativeFormatMimeType(), mimeType);
1610 }
1611 }
1612
1613 if (exportConfiguration) {
1614 // make sure the name of the resource doesn't change
1615 exportConfiguration->setProperty("name", res->name());
1616 }
1617
1618 if (exportDocumentSync(tempFileName, mimeType, exportConfiguration)) {
1619 QFile f2(tempFileName);
1620 KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(f2.open(QFile::ReadOnly), false);
1621
1622 QByteArray ba = f2.readAll();
1623
1624 QBuffer buf(&ba);
1625 buf.open(QBuffer::ReadOnly);
1626
1627
1628
1629 if (res->loadFromDevice(&buf, KisGlobalResourcesInterface::instance())) {
1630 if (model.updateResource(res)) {
1631 const QString filePath =
1633
1634 d->updateDocumentMetadataOnSaving(filePath, mimeType);
1635
1636 return true;
1637 }
1638 }
1639 }
1640 }
1641 }
1642 else {
1643 d->modifiedWhileSaving = false;
1644 if (exportDocumentSync(tempFileName, mimeType, exportConfiguration)) {
1645 KoResourceSP res = model.importResourceFile(tempFileName, false);
1646 if (res) {
1647 const QString filePath =
1649
1650 d->updateDocumentMetadataOnSaving(filePath, mimeType);
1651
1652 return true;
1653 }
1654 }
1655 }
1656 }
1657 }
1658 }
1659 return false;
1660}
static KisImportExportFilter * filterForMimeType(const QString &mimetype, Direction direction)
filterForMimeType loads the relevant import/export plugin and returns it. The caller is responsible f...
static bool getResourceIdFromVersionedFilename(QString filename, QString resourceType, QString storageLocation, int &outResourceId)
Note that here you can put even the original filename - any filename from the versioned_resources - a...
QString filePathForResource(KoResourceSP resource)
The KisResourceModel class provides the main access to resources. It is possible to filter the resour...
#define KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(cond, val)
Definition kis_assert.h:129

References d, KisImportExportManager::Export, exportDocumentSync(), KisResourceLocator::filePathForResource(), KisImportExportManager::filterForMimeType(), KisResourceCacheDb::getResourceIdFromVersionedFilename(), KisResourceModel::importResourceFile(), KisGlobalResourcesInterface::instance(), KisResourceLoaderRegistry::instance(), KisResourceLocator::instance(), KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE, mimeType, nativeFormatMimeType(), KisResourceModel::resourceForId(), KisResourceModel::setResourceFilter(), KisAbstractResourceFilterInterface::ShowAllResources, and KisResourceModel::updateResource().

◆ save()

bool KisDocument::save ( bool showWarnings,
KisPropertiesConfigurationSP exportConfiguration )

Definition at line 978 of file KisDocument.cpp.

979{
980 return saveAs(path(), mimeType(), showWarnings, exportConfiguration);
981}
bool saveAs(const QString &path, const QByteArray &mimeType, bool showWarnings, KisPropertiesConfigurationSP exportConfiguration=0)

References mimeType, path(), and saveAs().

◆ saveAs()

bool KisDocument::saveAs ( const QString & path,
const QByteArray & mimeType,
bool showWarnings,
KisPropertiesConfigurationSP exportConfiguration = 0 )

Definition at line 954 of file KisDocument.cpp.

955{
956 using namespace KritaUtils;
957
958 KisUsageLogger::log(QString("Saving Document %9 as %1 (mime: %2). %3 * %4 pixels, %5 layers. %6 frames, "
959 "%7 framerate. Export configuration: %8")
960 .arg(_path, QString::fromLatin1(mimeType), QString::number(d->image->width()),
961 QString::number(d->image->height()), QString::number(d->image->nlayers()),
962 QString::number(d->image->animationInterface()->totalLength()),
963 QString::number(d->image->animationInterface()->framerate()),
964 (exportConfiguration ? exportConfiguration->toXML() : "No configuration"),
965 path()));
966
967 // Check whether it's an existing resource were are saving to
968 if (resourceSavingFilter(_path, mimeType, exportConfiguration)) {
969 return true;
970 }
971
973 mimeType,
974 showWarnings ? SaveShowWarnings : SaveNone),
975 exportConfiguration);
976}
bool resourceSavingFilter(const QString &path, const QByteArray &mimeType, KisPropertiesConfigurationSP exportConfiguration)

References d, exportDocumentImpl(), KisUsageLogger::log(), mimeType, path(), and resourceSavingFilter().

◆ savingImage()

KisImageSP KisDocument::savingImage ( ) const

savingImage provides a detached, shallow copy of the original image that must be used when saving. Any strokes in progress will not be applied to this image, so the result might be missing some data. On the other hand, it won't block.

Returns
a shallow copy of the original image, or 0 is saving is not in progress

◆ serializeToNativeByteArray()

QByteArray KisDocument::serializeToNativeByteArray ( )

serializeToNativeByteArray daves the document into a .kra file written to a memory-based byte-array

Returns
a byte array containing the .kra file

Definition at line 983 of file KisDocument.cpp.

984{
985 QBuffer buffer;
986
988 filter->setBatchMode(true);
989 filter->setMimeType(nativeFormatMimeType());
990
991 Private::StrippedSafeSavingLocker locker(&d->savingMutex, d->image);
992 if (!locker.successfullyLocked()) {
993 return buffer.data();
994 }
995
996 // temporary set the saving image to avoid shared pointer
997 // leaking (see bug 528540)
998 QScopedValueRollback<KisImageSP> rollback(d->savingImage, d->image);
999
1000 if (!filter->convert(this, &buffer).isOk()) {
1001 qWarning() << "serializeToByteArray():: Could not export to our native format";
1002 }
1003
1004 return buffer.data();
1005}

References d, KisImportExportManager::Export, KisImportExportManager::filterForMimeType(), and nativeFormatMimeType().

◆ setAssistants()

void KisDocument::setAssistants ( const QList< KisPaintingAssistantSP > & value)

@replace the current list of assistants with

Parameters
value

Definition at line 2793 of file KisDocument.cpp.

2794{
2795 if (d->assistants != value) {
2796 d->assistants = value;
2797 d->syncDecorationsWrapperLayerState();
2798 Q_EMIT sigAssistantsChanged();
2799 }
2800}
float value(const T *src, size_t ch)
void sigAssistantsChanged()

References d, sigAssistantsChanged(), and value().

◆ setAssistantsGlobalColor()

void KisDocument::setAssistantsGlobalColor ( QColor color)

Definition at line 2935 of file KisDocument.cpp.

2936{
2937 d->globalAssistantsColor = color;
2938}

References d.

◆ setAudioTracks()

void KisDocument::setAudioTracks ( QVector< QFileInfo > f)

Definition at line 2501 of file KisDocument.cpp.

2502{
2503 d->audioTracks = f;
2504 Q_EMIT sigAudioTracksChanged();
2505}
void sigAudioTracksChanged()

References d, and sigAudioTracksChanged().

◆ setAudioVolume()

void KisDocument::setAudioVolume ( qreal level)

Definition at line 2507 of file KisDocument.cpp.

2508{
2509 d->audioLevel = level;
2510 Q_EMIT sigAudioLevelChanged(level);
2511}
void sigAudioLevelChanged(qreal level)

References d, and sigAudioLevelChanged().

◆ setAutoSaveActive()

void KisDocument::setAutoSaveActive ( bool autoSaveIsActive)

Allow to activate or deactivate autosave on document, independently of auto save delay

the value is independent of auto save delay

Definition at line 1805 of file KisDocument.cpp.

1806{
1807 const bool changed = autoSaveActive != d->autoSaveActive;
1808
1809 if (changed) {
1810 d->autoSaveActive = autoSaveActive;
1812 }
1813}
void setNormalAutoSaveInterval()

References autoSaveActive, d, and setNormalAutoSaveInterval().

◆ setAutoSaveDelay()

void KisDocument::setAutoSaveDelay ( int delay)
private

Activate/deactivate/configure the autosave feature.

Parameters
delayin seconds, 0 to disable

Definition at line 1815 of file KisDocument.cpp.

1816{
1817 if (isReadWrite() && delay > 0 && d->autoSaveActive) {
1818 d->autoSaveTimer->start(delay * 1000);
1819 } else {
1820 d->autoSaveTimer->stop();
1821 }
1822}

References d, and isReadWrite().

◆ setColorHistoryColors()

void KisDocument::setColorHistoryColors ( const QList< KoColor > & colors)

Replaces the per-document history of the last-used colors, from the newest to oldest.

The actual values are stored in the model returned by colorHistoryModel()

Definition at line 2958 of file KisDocument.cpp.

2959{
2960 d->colorHistoryModel.setColorList(colors);
2961}

References d.

◆ setCurrentImage()

void KisDocument::setCurrentImage ( KisImageSP image,
bool forceInitialUpdate = true,
KisNodeSP preActivatedNode = nullptr )

Set the current image to the specified image and turn undo on.

Definition at line 2867 of file KisDocument.cpp.

2868{
2869 if (d->image) {
2870 // Disconnect existing sig/slot connections
2871 d->image->setUndoStore(new KisDumbUndoStore());
2872 d->image->disconnect(this);
2873 d->shapeController->setImage(0);
2874 d->image = 0;
2875 }
2876
2877 if (!image) return;
2878
2879 if (d->linkedResourceStorage){
2880 d->linkedResourceStorage->setMetaData(KisResourceStorage::s_meta_name, image->objectName());
2881 }
2882
2883 d->setImageAndInitIdleWatcher(image);
2884 d->image->setUndoStore(new KisDocumentUndoStore(this));
2885 d->shapeController->setImage(image, preActivatedNode);
2886 d->image->setMirrorAxesCenter(KisAlgebra2D::absoluteToRelative(d->mirrorAxisConfig.axisPosition(), image->bounds()));
2887 setModified(false);
2888 connect(d->image, SIGNAL(sigImageModified()), this, SLOT(setImageModified()), Qt::UniqueConnection);
2889 connect(d->image, SIGNAL(sigImageModifiedWithoutUndo()), this, SLOT(setImageModifiedWithoutUndo()), Qt::UniqueConnection);
2890 connect(d->image, SIGNAL(sigLayersChangedAsync()), this, SLOT(slotImageRootChanged()));
2891
2892 if (forceInitialUpdate) {
2893 d->image->initialRefreshGraph();
2894 }
2895}
void slotImageRootChanged()
The KisDumbUndoStore class doesn't actually save commands, so you cannot undo or redo!
static const QString s_meta_name
QPointF absoluteToRelative(const QPointF &pt, const QRectF &rc)

References KisAlgebra2D::absoluteToRelative(), KisImage::bounds(), d, image, preActivatedNode, KisResourceStorage::s_meta_name, setImageModified(), setImageModifiedWithoutUndo(), setModified(), and slotImageRootChanged().

◆ setEmergencyAutoSaveInterval()

void KisDocument::setEmergencyAutoSaveInterval ( )

Set emergency interval that autosave uses when the image is busy, by default it is 10 sec

Definition at line 1830 of file KisDocument.cpp.

1831{
1832 const int emergencyAutoSaveInterval = 10; /* sec */
1833 setAutoSaveDelay(emergencyAutoSaveInterval);
1834 d->autoSaveFailureCount++;
1835}
void setAutoSaveDelay(int delay)

References d, and setAutoSaveDelay().

◆ setEmpty()

void KisDocument::setEmpty ( bool empty = true)

Sets the document to empty.

Used after loading a template (which is not empty, but not the user's input).

See also
isEmpty()

◆ setErrorMessage()

void KisDocument::setErrorMessage ( const QString & errMsg)

Sets the error message to be shown to the user (use i18n()!) when loading or saving fails. If you asked the user about something and they chose "Cancel",

Definition at line 2270 of file KisDocument.cpp.

2271{
2272 d->lastErrorMessage = errMsg;
2273}

References d.

◆ setFileBatchMode()

void KisDocument::setFileBatchMode ( const bool batchMode)
Parameters
batchModeif true, do not show the option dialog for file operations.

Definition at line 1153 of file KisDocument.cpp.

1154{
1155 d->batchMode = batchMode;
1156}

References batchMode, and d.

◆ setGridConfig()

void KisDocument::setGridConfig ( const KisGridConfig & config)

Definition at line 2386 of file KisDocument.cpp.

2387{
2388 if (d->gridConfig != config) {
2389 d->gridConfig = config;
2390 d->syncDecorationsWrapperLayerState();
2391 Q_EMIT sigGridConfigChanged(config);
2392
2393 // Store last assigned value as future default...
2394 KisConfig cfg(false);
2395 cfg.setDefaultGridSpacing(config.spacing());
2396 }
2397}
void sigGridConfigChanged(const KisGridConfig &config)
QPoint spacing() const

References d, KisConfig::setDefaultGridSpacing(), sigGridConfigChanged(), and KisGridConfig::spacing().

◆ setGuidesConfig()

void KisDocument::setGuidesConfig ( const KisGuidesConfig & data)

Definition at line 2523 of file KisDocument.cpp.

2524{
2525 if (d->guidesConfig == data) return;
2526
2527 d->guidesConfig = data;
2528 d->syncDecorationsWrapperLayerState();
2529 Q_EMIT sigGuidesConfigChanged(d->guidesConfig);
2530}
void sigGuidesConfigChanged(const KisGuidesConfig &config)

References d, and sigGuidesConfigChanged().

◆ setImageAndInitIdleWatcher()

void KisDocument::setImageAndInitIdleWatcher ( KisImageSP _image)
inline

Definition at line 432 of file KisDocument.cpp.

432 {
433 image = _image;
434
436 }
void setTrackedImage(KisImageSP image)

References KisIdleWatcher::setTrackedImage().

◆ setImageModified

void KisDocument::setImageModified ( )
privateslot

Definition at line 2907 of file KisDocument.cpp.

2908{
2909 // we only set as modified if undo stack is not at clean state
2910 setModified(d->imageModifiedWithoutUndo || !d->undoStack->isClean());
2911}

References d, and setModified().

◆ setImageModifiedWithoutUndo

void KisDocument::setImageModifiedWithoutUndo ( )
privateslot

Definition at line 2913 of file KisDocument.cpp.

2914{
2915 d->imageModifiedWithoutUndo = true;
2917}

References d, and setImageModified().

◆ setInfiniteAutoSaveInterval()

void KisDocument::setInfiniteAutoSaveInterval ( )

Disable autosave

Definition at line 1837 of file KisDocument.cpp.

1838{
1839 setAutoSaveDelay(-1);
1840}

References setAutoSaveDelay().

◆ setLocalFilePath()

void KisDocument::setLocalFilePath ( const QString & localFilePath)

Definition at line 2615 of file KisDocument.cpp.

2616{
2617 d->m_file = localFilePath;
2618}

References d, and localFilePath().

◆ setMimeType()

void KisDocument::setMimeType ( const QByteArray & mimeType)

Sets the mime type for the document.

When choosing "save as" this is also the mime type selected by default.

Definition at line 1143 of file KisDocument.cpp.

1144{
1145 d->mimeType = mimeType;
1146}

References d, and mimeType.

◆ setMimeTypeAfterLoading()

void KisDocument::setMimeTypeAfterLoading ( const QString & mimeType)

Definition at line 2134 of file KisDocument.cpp.

2135{
2136 d->mimeType = mimeType.toLatin1();
2137 d->outputMimeType = d->mimeType;
2138}

References d, and mimeType.

◆ setMirrorAxisConfig()

void KisDocument::setMirrorAxisConfig ( const KisMirrorAxisConfig & config)

Definition at line 2538 of file KisDocument.cpp.

2539{
2540 if (d->mirrorAxisConfig == config) {
2541 return;
2542 }
2543
2544 d->mirrorAxisConfig = config;
2545 if (d->image) {
2546 d->image->setMirrorAxesCenter(KisAlgebra2D::absoluteToRelative(d->mirrorAxisConfig.axisPosition(),
2547 d->image->bounds()));
2548 }
2549 setModified(true);
2550
2552}
void sigMirrorAxisConfigChanged()

References KisAlgebra2D::absoluteToRelative(), d, setModified(), and sigMirrorAxisConfigChanged().

◆ setModified()

void KisDocument::setModified ( bool _mod)

Sets the modified flag on the document. This means that it has to be saved or not before deleting it.

1) Ignore setModified calls due to autosaving 2) When closing a document, QUndoStack emits a lot of modified signals, when clearing itself, so we should ignore all of them.

Definition at line 2146 of file KisDocument.cpp.

2147{
2148 if (mod) {
2149 updateEditingTime(false);
2150 }
2151
2156 if (d->isAutosaving || d->documentIsClosing)
2157 return;
2158
2159 //dbgUI<<" url:" << url.path();
2160 //dbgUI<<" mod="<<mod<<" MParts mod="<<KisParts::ReadWritePart::isModified()<<" isModified="<<isModified();
2161
2162 if (mod && !d->autoSaveTimer->isActive()) {
2163 // First change since last autosave -> start the autosave timer
2165 }
2166 d->modifiedAfterAutosave = mod;
2167 d->modifiedWhileSaving = mod;
2168
2169 if (!mod) {
2170 d->imageModifiedWithoutUndo = mod;
2171 }
2172
2173 if (mod == isModified())
2174 return;
2175
2176 d->modified = mod;
2177
2178 if (mod) {
2180 }
2181
2182 Q_EMIT modified(mod);
2183}
void updateEditingTime(bool forceStoreElapsed)
KoColorSpaceMathsTraits< T >::compositetype mod(T a, T b)

References d, documentInfo(), isModified(), modified, setNormalAutoSaveInterval(), updateEditingTime(), and KoDocumentInfo::updateParameters().

◆ setNormalAutoSaveInterval()

void KisDocument::setNormalAutoSaveInterval ( )

Set standard autosave interval that is set by a config file

Definition at line 1824 of file KisDocument.cpp.

1825{
1826 setAutoSaveDelay(d->autoSaveDelay);
1827 d->autoSaveFailureCount = 0;
1828}

References d, and setAutoSaveDelay().

◆ setPaletteList()

void KisDocument::setPaletteList ( const QList< KoColorSetSP > & paletteList,
bool emitSignal = false )

setPaletteList replaces the palettes in the document's local resource storage with the list of palettes passed to this function. It will then Q_EMIT sigPaletteListChanged with both the old and the new list, if emitSignal is true.

Definition at line 2436 of file KisDocument.cpp.

2437{
2438 QList<KoColorSetSP> oldPaletteList;
2439 if (d->linkedResourceStorage) {
2440 QSharedPointer<KisResourceStorage::ResourceIterator> iter = d->linkedResourceStorage->resources(ResourceType::Palettes);
2441 while (iter->hasNext()) {
2442 iter->next();
2443 KoResourceSP resource = iter->resource();
2444 if (resource && resource->valid()) {
2445 oldPaletteList << resource.dynamicCast<KoColorSet>();
2446 }
2447 }
2448 if (oldPaletteList != paletteList) {
2450 Q_FOREACH(KoColorSetSP palette, oldPaletteList) {
2451 if (!paletteList.contains(palette)) {
2452 resourceModel.setResourceInactive(resourceModel.indexForResource(palette));
2453 }
2454 }
2455 Q_FOREACH(KoColorSetSP palette, paletteList) {
2456 if (!oldPaletteList.contains(palette)) {
2457 resourceModel.addResource(palette, d->linkedResourcesStorageID);
2458 }
2459 else {
2460 palette->setStorageLocation(d->linkedResourcesStorageID);
2461 resourceModel.updateResource(palette);
2462 }
2463 }
2464 if (emitSignal) {
2465 Q_EMIT sigPaletteListChanged(oldPaletteList, paletteList);
2466 }
2467 }
2468 }
2469}
void sigPaletteListChanged(const QList< KoColorSetSP > &oldPaletteList, const QList< KoColorSetSP > &newPaletteList)
const QString Palettes

References KisResourceModel::addResource(), d, KisResourceModel::indexForResource(), ResourceType::Palettes, KisAbstractResourceModel::setResourceInactive(), sigPaletteListChanged(), and KisResourceModel::updateResource().

◆ setPath()

void KisDocument::setPath ( const QString & path)

Definition at line 2598 of file KisDocument.cpp.

2599{
2600 const bool changed = path != d->m_path;
2601
2602 d->m_path = path;
2603
2604 if (changed) {
2605 Q_EMIT sigPathChanged(path);
2606 }
2607}
void sigPathChanged(const QString &path)

References d, path(), and sigPathChanged().

◆ setPreActivatedNode()

void KisDocument::setPreActivatedNode ( KisNodeSP activatedNode)

Set the list of nodes that was marked as currently active. Used only for saving loading. Never use it for tools or processing.

Definition at line 2846 of file KisDocument.cpp.

2847{
2848 d->preActivatedNode = activatedNode;
2849}

References d.

◆ setReadWrite()

void KisDocument::setReadWrite ( bool readwrite = true)

Sets whether the document can be edited or is read only.

This recursively applied to all child documents and KisView::updateReadWrite is called for every attached view.

Definition at line 1794 of file KisDocument.cpp.

1795{
1796 const bool changed = readwrite != d->readwrite;
1797
1798 d->readwrite = readwrite;
1799
1800 if (changed) {
1802 }
1803}
void sigReadWriteChanged(bool value)

References d, readwrite, and sigReadWriteChanged().

◆ setRecovered()

void KisDocument::setRecovered ( bool value)

Definition at line 2185 of file KisDocument.cpp.

2186{
2187 const bool changed = value != d->isRecovered;
2188
2189 d->isRecovered = value;
2190
2191 if (changed) {
2192 Q_EMIT sigRecoveredChanged(value);
2193 }
2194}
void sigRecoveredChanged(bool value)

References d, sigRecoveredChanged(), and value().

◆ setReferenceImagesLayer()

void KisDocument::setReferenceImagesLayer ( KisSharedPtr< KisReferenceImagesLayer > layer,
bool updateImage )

Definition at line 2812 of file KisDocument.cpp.

2813{
2814 KisReferenceImagesLayerSP currentReferenceLayer = referenceImagesLayer();
2815
2816 // updateImage=false inherently means we are not changing the
2817 // reference images layer, but just would like to update its signals.
2818 if (currentReferenceLayer == layer && updateImage) {
2819 return;
2820 }
2821
2822 d->referenceLayerConnections.clear();
2823
2824 if (updateImage) {
2825 if (currentReferenceLayer) {
2826 d->image->removeNode(currentReferenceLayer);
2827 }
2828
2829 if (layer) {
2830 d->image->addNode(layer);
2831 }
2832 }
2833
2834 currentReferenceLayer = layer;
2835
2836 if (currentReferenceLayer) {
2837 d->referenceLayerConnections.addConnection(
2838 currentReferenceLayer, SIGNAL(sigUpdateCanvas(QRectF)),
2839 this, SIGNAL(sigReferenceImagesChanged()));
2840 }
2841
2842 Q_EMIT sigReferenceImagesLayerChanged(layer);
2844}

References d, referenceImagesLayer(), sigReferenceImagesChanged(), and sigReferenceImagesLayerChanged().

◆ setStoryboardCommentList()

void KisDocument::setStoryboardCommentList ( const QVector< StoryboardComment > & storyboardCommentList,
bool emitSignal = false )

sets the list of comments for the storyboard docker in the document, emits empty signal if emitSignal is true.

Definition at line 2489 of file KisDocument.cpp.

2490{
2491 d->m_storyboardCommentList = storyboardCommentList;
2492 if (emitSignal) {
2494 }
2495}
void sigStoryboardCommentListChanged()

References d, and sigStoryboardCommentListChanged().

◆ setStoryboardItemList()

void KisDocument::setStoryboardItemList ( const StoryboardItemList & storyboardItemList,
bool emitSignal = false )

sets the storyboardItemList in the document, emits empty signal if emitSignal is true.

Definition at line 2476 of file KisDocument.cpp.

2477{
2478 d->m_storyboardItemList = storyboardItemList;
2479 if (emitSignal) {
2481 }
2482}
void sigStoryboardItemListChanged()

References d, and sigStoryboardItemListChanged().

◆ setUnit()

void KisDocument::setUnit ( const KoUnit & unit)

Sets the unit used to display all measures/distances.

Definition at line 2328 of file KisDocument.cpp.

2329{
2330 if (d->unit != unit) {
2331 d->unit = unit;
2332 Q_EMIT unitChanged(unit);
2333 }
2334}
void unitChanged(const KoUnit &unit)

References d, unit, and unitChanged().

◆ setWarningMessage()

void KisDocument::setWarningMessage ( const QString & warningMsg)

Sets the warning message to be shown to the user (use i18n()!) when loading or saving fails.

Definition at line 2280 of file KisDocument.cpp.

2281{
2282 d->lastWarningMessage = warningMsg;
2283}

References d.

◆ shapeController()

KoShapeControllerBase * KisDocument::shapeController ( ) const

The shape controller matches internal krita image layers with the flake shape hierarchy.

◆ shapeForNode()

KoShapeLayer * KisDocument::shapeForNode ( KisNodeSP layer) const

Definition at line 2783 of file KisDocument.cpp.

2784{
2785 return d->shapeController->shapeForNode(layer);
2786}

References d.

◆ sigAssistantsChanged

void KisDocument::sigAssistantsChanged ( )
signal

◆ sigAudioLevelChanged

void KisDocument::sigAudioLevelChanged ( qreal level)
signal

◆ sigAudioTracksChanged

void KisDocument::sigAudioTracksChanged ( )
signal

◆ sigBackgroundSavingFinished

void KisDocument::sigBackgroundSavingFinished ( KisImportExportErrorCode status,
const QString & errorMessage,
const QString & warningMessage )
signal

◆ sigCompleteBackgroundSaving

void KisDocument::sigCompleteBackgroundSaving ( const KritaUtils::ExportFileJob & job,
KisImportExportErrorCode status,
const QString & errorMessage,
const QString & warningMessage )
signal

◆ sigGridConfigChanged

void KisDocument::sigGridConfigChanged ( const KisGridConfig & config)
signal

◆ sigGuidesConfigChanged

void KisDocument::sigGuidesConfigChanged ( const KisGuidesConfig & config)
signal

◆ sigLoadingFinished

void KisDocument::sigLoadingFinished ( )
signal

◆ sigMirrorAxisConfigChanged

void KisDocument::sigMirrorAxisConfigChanged ( )
signal

◆ sigPaletteListChanged

void KisDocument::sigPaletteListChanged ( const QList< KoColorSetSP > & oldPaletteList,
const QList< KoColorSetSP > & newPaletteList )
signal

Emitted when the palette list has changed. The pointers in oldPaletteList are to be deleted by the resource server.

◆ sigPathChanged

void KisDocument::sigPathChanged ( const QString & path)
signal

◆ sigReadWriteChanged

void KisDocument::sigReadWriteChanged ( bool value)
signal

◆ sigRecoveredChanged

void KisDocument::sigRecoveredChanged ( bool value)
signal

◆ sigReferenceImagesChanged

void KisDocument::sigReferenceImagesChanged ( )
signal

◆ sigReferenceImagesLayerChanged

void KisDocument::sigReferenceImagesLayerChanged ( KisSharedPtr< KisReferenceImagesLayer > layer)
signal

◆ sigSavingFinished

void KisDocument::sigSavingFinished ( const QString & filePath)
signal

◆ sigStoryboardCommentListChanged

void KisDocument::sigStoryboardCommentListChanged ( )
signal

◆ sigStoryboardItemListChanged

void KisDocument::sigStoryboardItemListChanged ( )
signal

◆ slotAutoSave

void KisDocument::slotAutoSave ( )
privateslot

Definition at line 1662 of file KisDocument.cpp.

1663{
1664 slotAutoSaveImpl(std::unique_ptr<KisDocument>());
1665}
void slotAutoSaveImpl(std::unique_ptr< KisDocument > &&optionalClonedDocument)

References slotAutoSaveImpl().

◆ slotAutoSaveImpl()

void KisDocument::slotAutoSaveImpl ( std::unique_ptr< KisDocument > && optionalClonedDocument)
private

Definition at line 1537 of file KisDocument.cpp.

1538{
1539 if (!d->modified || !d->modifiedAfterAutosave) return;
1540 const QString autoSaveFileName = generateAutoSaveFileName(localFilePath());
1541
1542 Q_EMIT statusBarMessage(i18n("Autosaving... %1", autoSaveFileName), successMessageTimeout);
1543
1544 KisUsageLogger::log(QString("Autosaving: %1").arg(autoSaveFileName));
1545
1546 const bool hadClonedDocument = bool(optionalClonedDocument);
1548
1549 if (d->image->isIdle() || hadClonedDocument) {
1550 result = initiateSavingInBackground(i18n("Autosaving..."),
1553 0,
1554 std::move(optionalClonedDocument));
1555 } else {
1556 Q_EMIT statusBarMessage(i18n("Autosaving postponed: document is busy..."), errorMessageTimeout);
1557 }
1558
1559 if (result != KritaUtils::BackgroudSavingStartResult::Success && !hadClonedDocument && d->autoSaveFailureCount >= 3) {
1561 connect(stroke, SIGNAL(sigDocumentCloned(KisDocument*)),
1563 Qt::BlockingQueuedConnection);
1564 connect(stroke, SIGNAL(sigCloningCancelled()),
1565 this, SLOT(slotDocumentCloningCancelled()),
1566 Qt::BlockingQueuedConnection);
1567
1568 KisStrokeId strokeId = d->image->startStroke(stroke);
1569 d->image->endStroke(strokeId);
1570
1572
1575 } else {
1576 d->modifiedAfterAutosave = false;
1577 }
1578}
void slotInitiateAsyncAutosaving(KisDocument *clonedDocument)
void setEmergencyAutoSaveInterval()
void statusBarMessage(const QString &text, int timeout=0)
void slotDocumentCloningCancelled()
void slotCompleteAutoSaving(const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
void setInfiniteAutoSaveInterval()

References d, KritaUtils::Failure, generateAutoSaveFileName(), initiateSavingInBackground(), localFilePath(), KisUsageLogger::log(), nativeFormatMimeType(), KritaUtils::SaveInAutosaveMode, KritaUtils::SaveIsExporting, setEmergencyAutoSaveInterval(), setInfiniteAutoSaveInterval(), slotCompleteAutoSaving(), slotDocumentCloningCancelled(), slotInitiateAsyncAutosaving(), statusBarMessage(), and KritaUtils::Success.

◆ slotChildCompletedSavingInBackground

void KisDocument::slotChildCompletedSavingInBackground ( KisImportExportErrorCode status,
const QString & errorMessage,
const QString & warningMessage )
privateslot

Take back the ownership of the saving mutex and make sure it well be released whatever the result of executing this function will be, even if it asserts.

Definition at line 1497 of file KisDocument.cpp.

1498{
1500
1506 std::unique_lock<QMutex> savingMutexLock(d->savingMutex, std::adopt_lock);
1507
1508 KIS_ASSERT_RECOVER_RETURN(d->backgroundSaveDocument);
1509
1510 if (d->backgroundSaveJob.flags & KritaUtils::SaveInAutosaveMode) {
1511 d->backgroundSaveDocument->d->isAutosaving = false;
1512 }
1513
1514 d->backgroundSaveDocument.release()->deleteLater();
1515
1516 KIS_ASSERT_RECOVER_RETURN(d->backgroundSaveJob.isValid());
1517
1518 const KritaUtils::ExportFileJob job = d->backgroundSaveJob;
1519 d->backgroundSaveJob = KritaUtils::ExportFileJob();
1520
1521 // unlock at the very end
1522 savingMutexLock.unlock();
1523
1524 QFileInfo fi(job.filePath);
1525 KisUsageLogger::log(QString("Completed saving %1 (mime: %2). Result: %3. Warning: %4. Size: %5")
1526 .arg(job.filePath, QString::fromLatin1(job.mimeType),
1527 (!status.isOk() ? errorMessage : "OK"), warningMessage,
1528 QString::number(fi.size())));
1529
1531 // One-shot: disconnect immediately after firing so future save completions
1532 // don't invoke a stale or unrelated slot.
1533 disconnect(d->completeSavingConnection);
1534 d->completeSavingConnection = {};
1535}
bool isSaving() const
#define KIS_ASSERT_RECOVER_RETURN(cond)
Definition kis_assert.h:75

References d, errorMessage(), KritaUtils::ExportFileJob::filePath, KisImportExportErrorCode::isOk(), isSaving(), KIS_ASSERT_RECOVER_RETURN, KisUsageLogger::log(), KritaUtils::ExportFileJob::mimeType, KritaUtils::SaveInAutosaveMode, sigCompleteBackgroundSaving(), and warningMessage().

◆ slotCompleteAutoSaving

void KisDocument::slotCompleteAutoSaving ( const KritaUtils::ExportFileJob & job,
KisImportExportErrorCode status,
const QString & errorMessage,
const QString & warningMessage )
privateslot

Definition at line 1689 of file KisDocument.cpp.

1690{
1691 Q_UNUSED(job);
1692 Q_UNUSED(warningMessage);
1693
1694 const QString fileName = QFileInfo(job.filePath).fileName();
1695
1696 if (!status.isOk()) {
1698 Q_EMIT statusBarMessage(i18nc("%1 --- failing file name, %2 --- error message",
1699 "Error during autosaving %1: %2",
1700 fileName,
1701 exportErrorToUserMessage(status, errorMessage)), errorMessageTimeout);
1702 } else {
1703 KisConfig cfg(true);
1704 d->autoSaveDelay = cfg.autoSaveInterval();
1705
1706 if (!d->modifiedWhileSaving) {
1707 d->autoSaveTimer->stop(); // until the next change
1708 d->autoSaveFailureCount = 0;
1709 } else {
1711 }
1712
1713 Q_EMIT statusBarMessage(i18n("Finished autosaving %1", fileName), successMessageTimeout);
1714 }
1715}
QString exportErrorToUserMessage(KisImportExportErrorCode status, const QString &errorMessage)

References KisConfig::autoSaveInterval(), d, errorMessage(), exportErrorToUserMessage(), KritaUtils::ExportFileJob::filePath, KisImportExportErrorCode::isOk(), setEmergencyAutoSaveInterval(), setNormalAutoSaveInterval(), statusBarMessage(), and warningMessage().

◆ slotCompleteSavingDocument

void KisDocument::slotCompleteSavingDocument ( const KritaUtils::ExportFileJob & job,
KisImportExportErrorCode status,
const QString & errorMessage,
const QString & warningMessage )
privateslot

Definition at line 1045 of file KisDocument.cpp.

1046{
1047 if (status.isCancelled())
1048 return;
1049
1050 const QString fileName = QFileInfo(job.filePath).fileName();
1051
1052 if (!status.isOk()) {
1053 Q_EMIT statusBarMessage(i18nc("%1 --- failing file name, %2 --- error message",
1054 "Error during saving %1: %2",
1055 fileName,
1056 errorMessage), errorMessageTimeout);
1057
1058
1059 if (!fileBatchMode()) {
1060 DlgLoadMessages dlg(i18nc("@title:window", "Krita"),
1061 i18n("Could not save %1.", job.filePath),
1062 errorMessage.split("\n", Qt::SkipEmptyParts)
1063 + warningMessage.split("\n", Qt::SkipEmptyParts),
1064 status.errorMessage());
1065
1066 dlg.exec();
1067 }
1068 }
1069 else {
1070 if (!fileBatchMode() && !warningMessage.isEmpty()) {
1071
1072 QStringList reasons = warningMessage.split("\n", Qt::SkipEmptyParts);
1073
1074 DlgLoadMessages dlg(
1075 i18nc("@title:window", "Krita"),
1076 i18nc("dialog box shown to the user if there were warnings while saving the document, "
1077 "%1 is the file path",
1078 "%1 has been saved but is incomplete.",
1079 job.filePath),
1080 reasons,
1081 reasons.isEmpty()
1082 ? ""
1083 : i18nc("dialog box shown to the user if there were warnings while saving the document",
1084 "Some problems were encountered when saving."));
1085 dlg.exec();
1086 }
1087
1088
1089 if (!(job.flags & KritaUtils::SaveIsExporting)) {
1090 const QString existingAutoSaveBaseName = localFilePath();
1091 const bool wasRecovered = isRecovered();
1092
1093 d->updateDocumentMetadataOnSaving(job.filePath, job.mimeType);
1094
1095 removeAutoSaveFiles(existingAutoSaveBaseName, wasRecovered);
1096 }
1097
1098 Q_EMIT completed();
1099 Q_EMIT sigSavingFinished(job.filePath);
1100
1101 Q_EMIT statusBarMessage(i18n("Finished saving %1", fileName), successMessageTimeout);
1102 }
1103}
void removeAutoSaveFiles(const QString &autosaveBaseName, bool wasRecovered)

References completed(), d, errorMessage(), KisImportExportErrorCode::errorMessage(), fileBatchMode(), KritaUtils::ExportFileJob::filePath, KritaUtils::ExportFileJob::flags, KisImportExportErrorCode::isCancelled(), KisImportExportErrorCode::isOk(), isRecovered, localFilePath(), KritaUtils::ExportFileJob::mimeType, removeAutoSaveFiles(), KritaUtils::SaveIsExporting, sigSavingFinished(), statusBarMessage(), and warningMessage().

◆ slotConfigChanged

void KisDocument::slotConfigChanged ( )
privateslot

Definition at line 2351 of file KisDocument.cpp.

2352{
2353 KisConfig cfg(true);
2354
2355 if (d->undoStack->undoLimit() != cfg.undoStackLimit()) {
2356 if (!d->undoStack->isClean()) {
2357 d->undoStack->clear();
2358 // we set this because the document *has* changed, even though the
2359 // undo history was purged.
2361 }
2362 d->undoStack->setUndoLimit(cfg.undoStackLimit());
2363 }
2364 d->undoStack->setUseCumulativeUndoRedo(cfg.useCumulativeUndoRedo());
2365 d->undoStack->setCumulativeUndoData(cfg.cumulativeUndoData());
2366
2367 d->autoSaveDelay = cfg.autoSaveInterval();
2369}

References KisConfig::autoSaveInterval(), KisConfig::cumulativeUndoData(), d, setImageModifiedWithoutUndo(), setNormalAutoSaveInterval(), KisConfig::undoStackLimit(), and KisConfig::useCumulativeUndoRedo().

◆ slotDocumentCloningCancelled

void KisDocument::slotDocumentCloningCancelled ( )
privateslot

Definition at line 1672 of file KisDocument.cpp.

1673{
1675}

References setEmergencyAutoSaveInterval().

◆ slotImageRootChanged

void KisDocument::slotImageRootChanged ( )
privateslot

Definition at line 2371 of file KisDocument.cpp.

2372{
2373 d->syncDecorationsWrapperLayerState();
2374}

References d.

◆ slotInitiateAsyncAutosaving

void KisDocument::slotInitiateAsyncAutosaving ( KisDocument * clonedDocument)
privateslot

Definition at line 1667 of file KisDocument.cpp.

1668{
1669 slotAutoSaveImpl(std::unique_ptr<KisDocument>(clonedDocument));
1670}

References slotAutoSaveImpl().

◆ slotPerformIdleRoutines

void KisDocument::slotPerformIdleRoutines ( )
privateslot

TODO: automatic purging is disabled for now: it modifies data managers without creating a transaction, which breaks undo.

Definition at line 1677 of file KisDocument.cpp.

1678{
1679 d->image->explicitRegenerateLevelOfDetail();
1680
1681
1685
1686 // d->image->purgeUnusedData(true);
1687}

References d.

◆ slotUndoStackCleanChanged

void KisDocument::slotUndoStackCleanChanged ( bool value)
privateslot

Definition at line 2346 of file KisDocument.cpp.

2347{
2348 setModified(!value || d->imageModifiedWithoutUndo);
2349}

References d, setModified(), and value().

◆ startExportInBackground()

KisImportExportErrorCode KisDocument::startExportInBackground ( const QString & actionName,
const QString & location,
const QString & realLocation,
const QByteArray & mimeType,
bool showWarnings,
KisPropertiesConfigurationSP exportConfiguration,
bool isAdvancedExporting = false )
private

Definition at line 1717 of file KisDocument.cpp.

1723{
1724 d->savingImage = d->image;
1725
1727 if (window) {
1728 if (window->viewManager()) {
1729 d->savingUpdater = window->viewManager()->createThreadedUpdater(actionName);
1730 d->importExportManager->setUpdater(d->savingUpdater);
1731 }
1732 }
1733
1734 KisImportExportErrorCode initializationStatus(ImportExportCodes::OK);
1735 d->childSavingFuture =
1736 d->importExportManager->exportDocumentAsync(location,
1737 realLocation,
1738 mimeType,
1739 initializationStatus,
1740 showWarnings,
1741 exportConfiguration,
1742 isAdvancedExporting);
1743
1744 if (!initializationStatus.isOk()) {
1745 if (d->savingUpdater) {
1746 d->savingUpdater->cancel();
1747 }
1748 d->savingImage.clear();
1749 Q_EMIT sigBackgroundSavingFinished(initializationStatus, initializationStatus.errorMessage(), "");
1750 return initializationStatus;
1751 }
1752
1753 typedef QFutureWatcher<KisImportExportErrorCode> StatusWatcher;
1754 StatusWatcher *watcher = new StatusWatcher();
1755 watcher->setFuture(d->childSavingFuture);
1756
1757 connect(watcher, SIGNAL(finished()), SLOT(finishExportInBackground()));
1758 connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater()));
1759
1760 return initializationStatus;
1761}
void finishExportInBackground()
QPointer< KoUpdater > createThreadedUpdater(const QString &name)

References KisViewManager::createThreadedUpdater(), KisPart::currentMainwindow(), d, KisImportExportErrorCode::errorMessage(), finishExportInBackground(), KisPart::instance(), KisImportExportErrorCode::isOk(), mimeType, ImportExportCodes::OK, sigBackgroundSavingFinished(), and KisMainWindow::viewManager.

◆ statusBarMessage

void KisDocument::statusBarMessage ( const QString & text,
int timeout = 0 )
signal

Emitted e.g. at the beginning of a save operation This is emitted by KisDocument and used by KisView to display a statusbar message

◆ syncDecorationsWrapperLayerState()

void KisDocument::syncDecorationsWrapperLayerState ( )

◆ undoStack()

KUndo2Stack * KisDocument::undoStack ( )

Returns the global undo stack

◆ unit()

KoUnit KisDocument::unit ( ) const

Returns the unit used to display all measures/distances.

◆ unitChanged

void KisDocument::unitChanged ( const KoUnit & unit)
signal

This signal is emitted when the unit is changed by setUnit(). It is common to connect views to it, in order to change the displayed units (e.g. in the rulers)

◆ updateDocumentMetadataOnSaving()

void KisDocument::updateDocumentMetadataOnSaving ( const QString & filePath,
const QByteArray & mimeType )

◆ updateEditingTime()

void KisDocument::updateEditingTime ( bool forceStoreElapsed)

Definition at line 2201 of file KisDocument.cpp.

2202{
2203 QDateTime now = QDateTime::currentDateTime();
2204 int firstModDelta = d->firstMod.secsTo(now);
2205 int lastModDelta = d->lastMod.secsTo(now);
2206
2207 if (lastModDelta > 30) {
2208 d->docInfo->setAboutInfo("editing-time", QString::number(d->docInfo->aboutInfo("editing-time").toInt() + d->firstMod.secsTo(d->lastMod)));
2209 d->firstMod = now;
2210 } else if (firstModDelta > 60 || forceStoreElapsed) {
2211 d->docInfo->setAboutInfo("editing-time", QString::number(d->docInfo->aboutInfo("editing-time").toInt() + firstModDelta));
2212 d->firstMod = now;
2213 }
2214
2215 d->lastMod = now;
2216}

References d.

◆ uploadLinkedResourcesFromLayersToStorage()

void KisDocument::uploadLinkedResourcesFromLayersToStorage ( )

◆ waitForSavingToComplete()

void KisDocument::waitForSavingToComplete ( )

Definition at line 2770 of file KisDocument.cpp.

2771{
2772 if (isSaving()) {
2773 KisAsyncActionFeedback f(i18nc("progress dialog message when the user closes the document that is being saved", "Waiting for saving to complete..."), 0);
2774 f.waitForMutex(d->savingMutex);
2775 }
2776}

References d, and isSaving().

◆ warningMessage()

QString KisDocument::warningMessage ( ) const

Return the last warning message set by loading or saving. Warnings mean that the document could not be completely loaded, but the errors were not absolutely fatal.

Definition at line 2285 of file KisDocument.cpp.

2286{
2287 return d->lastWarningMessage;
2288}

References d.

Friends And Related Symbol Documentation

◆ KisPart

friend class KisPart
friend

Definition at line 532 of file KisDocument.h.

◆ SafeSavingLocker

friend class SafeSavingLocker
friend

Definition at line 533 of file KisDocument.h.

Member Data Documentation

◆ assistants

QList< KisPaintingAssistantSP > KisDocument::assistants

Definition at line 393 of file KisDocument.cpp.

◆ audioLevel

qreal KisDocument::audioLevel = 1.0

Definition at line 399 of file KisDocument.cpp.

◆ audioTracks

QVector<QFileInfo> KisDocument::audioTracks

Definition at line 398 of file KisDocument.cpp.

◆ autoSaveActive

bool KisDocument::autoSaveActive = true

Definition at line 377 of file KisDocument.cpp.

◆ autoSaveDelay

int KisDocument::autoSaveDelay = 300

Definition at line 358 of file KisDocument.cpp.

◆ autoSaveFailureCount

int KisDocument::autoSaveFailureCount = 0

Definition at line 362 of file KisDocument.cpp.

◆ autoSaveTimer

QTimer* KisDocument::autoSaveTimer

Definition at line 354 of file KisDocument.cpp.

◆ backgroundSaveDocument

std::unique_ptr<KisDocument> KisDocument::backgroundSaveDocument

Definition at line 408 of file KisDocument.cpp.

◆ backgroundSaveJob

KritaUtils::ExportFileJob KisDocument::backgroundSaveJob

Definition at line 411 of file KisDocument.cpp.

◆ batchMode

bool KisDocument::batchMode { false }

Definition at line 417 of file KisDocument.cpp.

417{ false };

◆ childSavingFuture

QFuture<KisImportExportErrorCode> KisDocument::childSavingFuture

Definition at line 410 of file KisDocument.cpp.

◆ colorHistoryModel

KisUniqueColorSet * KisDocument::colorHistoryModel

Definition at line 402 of file KisDocument.cpp.

◆ completeSavingConnection

QMetaObject::Connection KisDocument::completeSavingConnection

Definition at line 412 of file KisDocument.cpp.

◆ d

Private* const KisDocument::d
private

Definition at line 765 of file KisDocument.h.

◆ decorationsSyncingDisabled

bool KisDocument::decorationsSyncingDisabled = false

Definition at line 418 of file KisDocument.cpp.

◆ disregardAutosaveFailure

bool KisDocument::disregardAutosaveFailure = false

Definition at line 361 of file KisDocument.cpp.

◆ docInfo

KoDocumentInfo* KisDocument::docInfo = 0

Definition at line 345 of file KisDocument.cpp.

◆ documentIsClosing

bool KisDocument::documentIsClosing = false

Definition at line 420 of file KisDocument.cpp.

◆ embeddedResourcesStorageID

QString KisDocument::embeddedResourcesStorageID

Definition at line 427 of file KisDocument.cpp.

◆ embeddedResourceStorage

KisResourceStorageSP KisDocument::embeddedResourceStorage

Definition at line 428 of file KisDocument.cpp.

◆ firstMod

QDateTime KisDocument::firstMod

Definition at line 379 of file KisDocument.cpp.

◆ globalAssistantsColor

QColor KisDocument::globalAssistantsColor

Definition at line 401 of file KisDocument.cpp.

◆ gridConfig

KisGridConfig KisDocument::gridConfig

Definition at line 404 of file KisDocument.cpp.

◆ guidesConfig

const KisGuidesConfig & KisDocument::guidesConfig

Definition at line 366 of file KisDocument.cpp.

◆ image

KisImageWSP KisDocument::image

Definition at line 384 of file KisDocument.cpp.

◆ imageIdleConnection

QScopedPointer<KisSignalAutoConnection> KisDocument::imageIdleConnection

Definition at line 391 of file KisDocument.cpp.

◆ imageIdleWatcher

KisIdleWatcher KisDocument::imageIdleWatcher

Definition at line 390 of file KisDocument.cpp.

◆ imageModifiedWithoutUndo

bool KisDocument::imageModifiedWithoutUndo = false

Definition at line 406 of file KisDocument.cpp.

◆ importExportManager

KisImportExportManager * KisDocument::importExportManager = 0

Definition at line 349 of file KisDocument.cpp.

◆ isAutosaving

bool KisDocument::isAutosaving = false

Definition at line 360 of file KisDocument.cpp.

◆ isRecovered

bool KisDocument::isRecovered = false

Definition at line 415 of file KisDocument.cpp.

◆ koShapeController

KoShapeController* KisDocument::koShapeController = 0

Definition at line 389 of file KisDocument.cpp.

◆ lastErrorMessage

QString KisDocument::lastErrorMessage

Definition at line 355 of file KisDocument.cpp.

◆ lastMod

QDateTime KisDocument::lastMod

Definition at line 380 of file KisDocument.cpp.

◆ lastWarningMessage

QString KisDocument::lastWarningMessage

Definition at line 356 of file KisDocument.cpp.

◆ linkedResourcesStorageID

QString KisDocument::linkedResourcesStorageID

Definition at line 423 of file KisDocument.cpp.

◆ linkedResourceStorage

KisResourceStorageSP KisDocument::linkedResourceStorage

Definition at line 424 of file KisDocument.cpp.

◆ m_bAutoDetectedMime

bool KisDocument::m_bAutoDetectedMime = false

Definition at line 369 of file KisDocument.cpp.

◆ m_file

QString KisDocument::m_file

Definition at line 371 of file KisDocument.cpp.

◆ m_path

QString KisDocument::m_path

Definition at line 370 of file KisDocument.cpp.

◆ m_storyboardCommentList

QVector<StoryboardComment> KisDocument::m_storyboardCommentList

Definition at line 396 of file KisDocument.cpp.

◆ m_storyboardItemList

StoryboardItemList KisDocument::m_storyboardItemList

Definition at line 395 of file KisDocument.cpp.

◆ mimeType

QByteArray KisDocument::mimeType

Definition at line 351 of file KisDocument.cpp.

◆ mirrorAxisConfig

const KisMirrorAxisConfig & KisDocument::mirrorAxisConfig

Definition at line 367 of file KisDocument.cpp.

◆ modified

bool KisDocument::modified = false

Definition at line 375 of file KisDocument.cpp.

◆ modifiedAfterAutosave

bool KisDocument::modifiedAfterAutosave = false

Definition at line 359 of file KisDocument.cpp.

◆ modifiedWhileSaving

bool KisDocument::modifiedWhileSaving = false

Definition at line 407 of file KisDocument.cpp.

◆ nserver

KisNameServer* KisDocument::nserver

Definition at line 382 of file KisDocument.cpp.

◆ outputMimeType

QByteArray KisDocument::outputMimeType

Definition at line 352 of file KisDocument.cpp.

◆ preActivatedNode

KisNodeSP KisDocument::preActivatedNode

Definition at line 387 of file KisDocument.cpp.

◆ q

KisDocument* KisDocument::q = 0

Definition at line 344 of file KisDocument.cpp.

◆ readwrite

bool KisDocument::readwrite = false

Definition at line 376 of file KisDocument.cpp.

◆ referenceLayerConnections

KisSignalAutoConnectionsStore KisDocument::referenceLayerConnections

Definition at line 413 of file KisDocument.cpp.

◆ savingImage

KisImageSP KisDocument::savingImage

Definition at line 385 of file KisDocument.cpp.

◆ savingMutex

QMutex KisDocument::savingMutex

Definition at line 373 of file KisDocument.cpp.

◆ savingUpdater

QPointer<KoUpdater> KisDocument::savingUpdater

Definition at line 409 of file KisDocument.cpp.

◆ shapeController

KoShapeControllerBase * KisDocument::shapeController = 0

Definition at line 388 of file KisDocument.cpp.

◆ undoStack

KUndo2Stack * KisDocument::undoStack = 0

Definition at line 364 of file KisDocument.cpp.

◆ unit

KoUnit KisDocument::unit

Definition at line 347 of file KisDocument.cpp.

◆ wasStorageAdded

bool KisDocument::wasStorageAdded = false

Definition at line 419 of file KisDocument.cpp.


The documentation for this class was generated from the following files: