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< KisPaintingAssistantSPassistants () const
 
QColor assistantsGlobalColor ()
 
void autoSaveOnPause ()
 Start saving when android activity is pushed to the background.
 
QString caption () const
 
void clearUndoHistory ()
 
KisDocumentclone (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< KoColorcolorHistory ()
 
void copyFrom (const Private &rhs, KisDocument *q)
 
void copyFromDocument (const KisDocument &rhs)
 
void copyFromImpl (const Private &rhs, KisDocument *q, KisDocument::CopyPolicy policy)
 
KoDocumentInfoDlgcreateDocumentInfoDialog (QWidget *parent, KoDocumentInfo *docInfo) const
 
QDomDocument createDomDocument (const QString &tagName, const QString &version) const
 
KisUndoStorecreateUndoStore ()
 
QRectF documentBounds () const
 
KoDocumentInfodocumentInfo () 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< StoryboardCommentgetStoryboardCommentsList ()
 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 KisGuidesConfigguidesConfig () const
 returns the guides data for this document.
 
void hackPreliminarySetImage (KisImageSP image)
 
KisImageWSP image () const
 
bool importDocument (const QString &path)
 
KisImportExportManagerimportExportManager () 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< KoResourceLoadResultlinkedDocumentResources ()
 linkedDocumentResources List returns all the resources linked to the document, such as palettes
 
QString linkedResourcesStorageId () const
 
bool loadNativeFormat (const QString &file)
 
QString localFilePath () const
 
KisDocumentlockAndCloneForSaving ()
 try to clone the image. This method handles all the locking for you. If locking has failed, no cloning happens
 
KisDocumentlockAndCloneImpl (bool fetchResourcesFromLayers)
 
KisDocumentlockAndCreateSnapshot ()
 
QByteArray mimeType () const
 
const KisMirrorAxisConfigmirrorAxisConfig () 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< KisReferenceImagesLayerreferenceImagesLayer () 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 setColorHistory (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)
 
KoShapeControllerBaseshapeController () const
 
KoShapeLayershapeForNode (KisNodeSP layer) const
 
void syncDecorationsWrapperLayerState ()
 
KUndo2StackundoStack ()
 
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< KisPaintingAssistantSPassistants
 
qreal audioLevel = 1.0
 
QVector< QFileInfo > audioTracks
 
bool autoSaveActive = true
 
int autoSaveDelay = 300
 
int autoSaveFailureCount = 0
 
QTimer * autoSaveTimer
 
QScopedPointer< KisDocumentbackgroundSaveDocument
 
KritaUtils::ExportFileJob backgroundSaveJob
 
bool batchMode { false }
 
QFuture< KisImportExportErrorCodechildSavingFuture
 
QList< KoColorcolorHistory
 
QMetaObject::Connection completeSavingConnection
 
bool decorationsSyncingDisabled = false
 
bool disregardAutosaveFailure = false
 
KoDocumentInfodocInfo = 0
 
bool documentIsClosing = false
 
QString embeddedResourcesStorageID
 
KisResourceStorageSP embeddedResourceStorage
 
QDateTime firstMod
 
QColor globalAssistantsColor
 
KisGridConfig gridConfig
 
KisGuidesConfig guidesConfig
 
KisImageSP image
 
QScopedPointer< KisSignalAutoConnectionimageIdleConnection
 
KisIdleWatcher imageIdleWatcher
 
bool imageModifiedWithoutUndo = false
 
KisImportExportManagerimportExportManager = 0
 
bool isAutosaving = false
 
bool isRecovered = false
 
KoShapeControllerkoShapeController = 0
 
QString lastErrorMessage
 
QDateTime lastMod
 
QString lastWarningMessage
 
QString linkedResourcesStorageID
 
KisResourceStorageSP linkedResourceStorage
 
bool m_bAutoDetectedMime = false
 
QString m_file
 
QString m_path
 
QVector< StoryboardCommentm_storyboardCommentList
 
StoryboardItemList m_storyboardItemList
 
QByteArray mimeType
 
KisMirrorAxisConfig mirrorAxisConfig
 
bool modified = false
 
bool modifiedAfterAutosave = false
 
bool modifiedWhileSaving = false
 
KisNameServernserver
 
QByteArray outputMimeType
 
KisNodeWSP preActivatedNode
 
KisDocumentq = 0
 
bool readwrite = false
 
KisSignalAutoConnectionsStore referenceLayerConnections
 
KisImageSP savingImage
 
QMutex savingMutex
 
QPointer< KoUpdatersavingUpdater
 
KisShapeControllershapeController = 0
 
KUndo2StackundoStack = 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
KisCanvas2canvas
 
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 294 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 722 of file KisDocument.h.

722 {
723 CONSTRUCT = 0,
724 REPLACE
725 };
@ 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 79 of file KisDocument.h.

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

Constructor & Destructor Documentation

◆ ~Private()

KisDocument::~Private ( )
inline

Definition at line 337 of file KisDocument.cpp.

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

◆ KisDocument() [1/2]

KisDocument::KisDocument ( bool addStorage = true)
explicitprotected

Definition at line 603 of file KisDocument.cpp.

604 : d(new Private(this))
605{
606 connect(KisConfigNotifier::instance(), SIGNAL(configChanged()), SLOT(slotConfigChanged()));
607 connect(d->undoStack, SIGNAL(cleanChanged(bool)), this, SLOT(slotUndoStackCleanChanged(bool)));
608 connect(d->autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
609 setObjectName(newObjectName());
610
611#ifdef Q_OS_MACOS
613 if (bookmarkmngr->isSandboxed()) {
614 connect(this, SIGNAL(sigSavingFinished(const QString&)), bookmarkmngr, SLOT(slotCreateBookmark(const QString&)));
615 }
616#endif
617
618
619 if (addStorage) {
620 d->linkedResourcesStorageID = QUuid::createUuid().toString();
621 d->linkedResourceStorage.reset(new KisResourceStorage(d->linkedResourcesStorageID));
622 KisResourceLocator::instance()->addStorage(d->linkedResourcesStorageID, d->linkedResourceStorage);
623
624 d->embeddedResourcesStorageID = QUuid::createUuid().toString();
625 d->embeddedResourceStorage.reset(new KisResourceStorage(d->embeddedResourcesStorageID));
626 KisResourceLocator::instance()->addStorage(d->embeddedResourcesStorageID, d->embeddedResourceStorage);
627
628 d->wasStorageAdded = true;
629 }
630
631 // preload the krita resources
633
634 d->shapeController = new KisShapeController(d->nserver, d->undoStack, this);
635 d->koShapeController = new KoShapeController(0, d->shapeController);
636
638}
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 640 of file KisDocument.cpp.

641 : QObject(),
642 d(new Private(*rhs.d, this))
643{
645
646 if (addStorage) {
647 KisResourceLocator::instance()->addStorage(d->linkedResourcesStorageID, d->linkedResourceStorage);
648 KisResourceLocator::instance()->addStorage(d->embeddedResourcesStorageID, d->embeddedResourceStorage);
649 d->wasStorageAdded = true;
650 }
651}
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 653 of file KisDocument.cpp.

654{
655 d->documentIsClosing = true;
656
657 // wait until all the pending operations are in progress
659 d->imageIdleWatcher.setTrackedImage(0);
660
666
667 d->autoSaveTimer->disconnect(this);
668 d->autoSaveTimer->stop();
669
670 delete d->importExportManager;
671
672 // Despite being QObject they needs to be deleted before the image
673 delete d->shapeController;
674
675 delete d->koShapeController;
676
677 if (d->image) {
678 d->image->animationInterface()->blockBackgroundFrameGeneration();
679
680 d->image->notifyAboutToBeDeleted();
681
694 d->image->requestStrokeCancellation();
695 d->image->waitForDone();
696
697 // clear undo commands that can still point to the image
698 d->undoStack->clear();
699 d->image->waitForDone();
700
701 KisImageWSP sanityCheckPointer = d->image;
702 Q_UNUSED(sanityCheckPointer);
703
704 // The following line trigger the deletion of the image
705 d->image.clear();
706
707 // check if the image has actually been deleted
708 KIS_SAFE_ASSERT_RECOVER_NOOP(!sanityCheckPointer.isValid());
709 }
710
711 if (d->wasStorageAdded) {
712 if (KisResourceLocator::instance()->hasStorage(d->linkedResourcesStorageID)) {
713 KisResourceLocator::instance()->removeStorage(d->linkedResourcesStorageID);
714 }
715 if (KisResourceLocator::instance()->hasStorage(d->embeddedResourcesStorageID)) {
716 KisResourceLocator::instance()->removeStorage(d->embeddedResourcesStorageID);
717 }
718 }
719
720 delete d;
721}
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 2945 of file KisDocument.cpp.

2946{
2947 return d->globalAssistantsColor;
2948}

References d.

◆ autoSaveOnPause()

void KisDocument::autoSaveOnPause ( )

Start saving when android activity is pushed to the background.

Definition at line 2108 of file KisDocument.cpp.

2109{
2110 if (!d->modified || !d->modifiedAfterAutosave)
2111 return;
2112
2113 const QString autoSaveFileName = generateAutoSaveFileName(localFilePath());
2114
2115 bool started = exportDocumentSync(autoSaveFileName, nativeFormatMimeType());
2116
2117 if (started)
2118 {
2119 d->modifiedAfterAutosave = false;
2120 dbgAndroid << "autoSaveOnPause successful";
2121 }
2122 else
2123 {
2124 qWarning() << "Could not auto-save when paused";
2125 }
2126}
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:62

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 2223 of file KisDocument.cpp.

2224{
2225 QString c;
2226 const QString _url(QFileInfo(path()).fileName());
2227
2228 // if URL is empty...it is probably an unsaved file
2229 if (_url.isEmpty()) {
2230 c = " [" + i18n("Not Saved") + "] ";
2231 } else {
2232 c = _url; // Fall back to document URL
2233 }
2234
2235 return c;
2236}
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 2371 of file KisDocument.cpp.

2372{
2373 d->undoStack->clear();
2374}

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 733 of file KisDocument.cpp.

734{
735 return new KisDocument(*this, addStorage);
736}
KisDocument(bool addStorage=true)

References KisDocument().

◆ closePath()

bool KisDocument::closePath ( bool promptToSave = true)

Definition at line 2569 of file KisDocument.cpp.

2570{
2571 if (promptToSave) {
2572 if ( isReadWrite() && isModified()) {
2573 Q_FOREACH (KisView *view, KisPart::instance()->views()) {
2574 if (view && view->document() == this) {
2575 if (!view->queryClose()) {
2576 return false;
2577 }
2578 }
2579 }
2580 }
2581 }
2582 // Not modified => ok and delete temp file.
2583 d->mimeType = QByteArray();
2584
2585 // It always succeeds for a read-only part,
2586 // but the return value exists for reimplementations
2587 // (e.g. pressing cancel for a modified read-write part)
2588 return true;
2589}
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:1151

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

◆ colorHistory()

QList< KoColor > KisDocument::colorHistory ( )

◆ completed

void KisDocument::completed ( )
signal

◆ copyFrom()

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

◆ copyFromDocument()

void KisDocument::copyFromDocument ( const KisDocument & rhs)

Definition at line 1248 of file KisDocument.cpp.

1249{
1251}

References copyFromDocumentImpl(), and REPLACE.

◆ copyFromDocumentImpl()

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

Definition at line 1253 of file KisDocument.cpp.

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

2555{
2556 return new KoDocumentInfoDlg(parent, docInfo);
2557}
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 2244 of file KisDocument.cpp.

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

◆ 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 2238 of file KisDocument.cpp.

2239{
2240 return createDomDocument("krita", tagName, version);
2241}
QDomDocument createDomDocument(const QString &tagName, const QString &version) const

References createDomDocument().

◆ createUndoStore()

KisUndoStore * KisDocument::createUndoStore ( )

Definition at line 2925 of file KisDocument.cpp.

2926{
2927 return new KisDocumentUndoStore(this);
2928}

◆ documentBounds()

QRectF KisDocument::documentBounds ( ) const

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

Definition at line 2955 of file KisDocument.cpp.

2956{
2957 QRectF bounds = d->image->bounds();
2958
2960
2961 if (referenceImagesLayer) {
2963 }
2964
2965 return bounds;
2966}
#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 1842 of file KisDocument.cpp.

1843{
1844 return d->docInfo;
1845}

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 723 of file KisDocument.cpp.

724{
725 return d->embeddedResourcesStorageID;
726}

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 2270 of file KisDocument.cpp.

2271{
2272 return d->lastErrorMessage;
2273}

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 928 of file KisDocument.cpp.

929{
930 using namespace KritaUtils;
931
932 SaveFlags flags = SaveIsExporting;
933 if (showWarnings) {
934 flags |= SaveShowWarnings;
935 }
936
937 KisUsageLogger::log(QString("Exporting Document: %1 as %2. %3 * %4 pixels, %5 layers, %6 frames, %7 "
938 "framerate. Export configuration: %8")
939 .arg(path, QString::fromLatin1(mimeType), QString::number(d->image->width()),
940 QString::number(d->image->height()), QString::number(d->image->nlayers()),
941 QString::number(d->image->animationInterface()->totalLength()),
942 QString::number(d->image->animationInterface()->framerate()),
943 (exportConfiguration ? exportConfiguration->toXML() : "No configuration")));
944
946 mimeType,
947 flags),
948 exportConfiguration, isAdvancedExporting);
949}
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 738 of file KisDocument.cpp.

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

1335{
1336 {
1343 Private::StrippedSafeSavingLocker locker(&d->savingMutex, d->image);
1344 if (!locker.successfullyLocked()) {
1345 return false;
1346 }
1347 }
1348
1349 d->savingImage = d->image;
1350
1352 d->importExportManager->
1353 exportDocument(path, path, mimeType, false, exportConfiguration);
1354
1355 d->savingImage = 0;
1356
1357 return status.isOk();
1358}
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 2935 of file KisDocument.cpp.

2936{
2937 return errorMessage.isEmpty() ? status.errorMessage() : errorMessage;
2938}

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 177 of file KisDocument.h.

177{ return QStringList() << KIS_MIME_TYPE; }
#define KIS_MIME_TYPE
Definition KisDocument.h:56
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 1143 of file KisDocument.cpp.

1144{
1145 return d->batchMode;
1146}

References d.

◆ finishExportInBackground

void KisDocument::finishExportInBackground ( )
privateslot

Definition at line 1758 of file KisDocument.cpp.

1759{
1760 KIS_SAFE_ASSERT_RECOVER(d->childSavingFuture.isFinished()) {
1762 return;
1763 }
1764
1765 KisImportExportErrorCode status = d->childSavingFuture.result();
1766 QString errorMessage = status.errorMessage();
1767 QString warningMessage = d->lastWarningMessage;
1768
1769 if (!d->lastErrorMessage.isEmpty()) {
1771 errorMessage = d->lastErrorMessage;
1772 } else {
1773 errorMessage += "\n" + d->lastErrorMessage;
1774 }
1775 }
1776
1777 d->savingImage.clear();
1778 d->childSavingFuture = QFuture<KisImportExportErrorCode>();
1779 d->lastErrorMessage.clear();
1780 d->lastWarningMessage.clear();
1781
1782 if (d->savingUpdater) {
1783 d->savingUpdater->setProgress(100);
1784 }
1785
1787}
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 1895 of file KisDocument.cpp.

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

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 1852 of file KisDocument.cpp.

1853{
1854 KisImageSP image = d->image;
1855 if (d->savingImage) image = d->savingImage;
1856
1857 if (image) {
1858 QRect bounds = image->bounds();
1859 QSize originalSize = bounds.size();
1860 // QSize may round down one dimension to zero on extreme aspect rations, so ensure 1px minimum
1861 QSize newSize = originalSize.scaled(size, Qt::KeepAspectRatio).expandedTo({1, 1});
1862
1863 bool pixelArt = false;
1864 // determine if the image is pixel art or not
1865 if (originalSize.width() < size.width() && originalSize.height() < size.height()) {
1866 // the image must be smaller than the requested preview
1867 // the scale must be integer
1868 if (newSize.height()%originalSize.height() == 0 && newSize.width()%originalSize.width() == 0) {
1869 pixelArt = true;
1870 }
1871 }
1872
1873 QPixmap px;
1874 if (pixelArt) {
1875 // do not scale while converting (because it uses Bicubic)
1876 QImage original = image->convertToQImage(originalSize, 0);
1877 // scale using FastTransformation, which is probably Nearest neighbour, suitable for pixel art
1878 QImage scaled = original.scaled(newSize, Qt::KeepAspectRatio, Qt::FastTransformation);
1879 px = QPixmap::fromImage(scaled);
1880 } else {
1881 px = QPixmap::fromImage(image->convertToQImage(newSize, 0));
1882 }
1883 if (px.size() == QSize(0,0)) {
1884 px = QPixmap(newSize);
1885 QPainter gc(&px);
1886 QBrush checkBrush = QBrush(KisCanvasWidgetBase::createCheckersImage(newSize.width() / 5));
1887 gc.fillRect(px.rect(), checkBrush);
1888 gc.end();
1889 }
1890 return px;
1891 }
1892 return QPixmap(size);
1893}
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 2508 of file KisDocument.cpp.

2509{
2510 return d->audioLevel;
2511}

References d.

◆ getAudioTracks()

QVector< QFileInfo > KisDocument::getAudioTracks ( ) const

Definition at line 2492 of file KisDocument.cpp.

2492 {
2493 return d->audioTracks;
2494}

References d.

◆ getStoryboardCommentsList()

QVector< StoryboardComment > KisDocument::getStoryboardCommentsList ( )

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

Definition at line 2479 of file KisDocument.cpp.

2480{
2481 return d->m_storyboardCommentList;
2482}

References d.

◆ getStoryboardItemList()

StoryboardItemList KisDocument::getStoryboardItemList ( )

returns the list of pointers to storyboard Items for the document

Definition at line 2466 of file KisDocument.cpp.

2467{
2468 return d->m_storyboardItemList;
2469}

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 2902 of file KisDocument.cpp.

2903{
2905
2906 // we set image without connecting idle-watcher, because loading
2907 // hasn't been finished yet
2908 d->image = image;
2909 d->shapeController->setImage(image);
2910}
#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 1938 of file KisDocument.cpp.

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

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 1361 of file KisDocument.cpp.

1365{
1366 return initiateSavingInBackground(actionName, receiverObject, receiverMethod,
1367 job, exportConfiguration, std::unique_ptr<KisDocument>(), isAdvancedExporting);
1368}

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 1370 of file KisDocument.cpp.

1375{
1377
1378 QScopedPointer<KisDocument> clonedDocument;
1379
1380 if (!optionalClonedDocument) {
1381 clonedDocument.reset(lockAndCloneForSaving());
1382 } else {
1383 clonedDocument.reset(optionalClonedDocument.release());
1384 }
1385
1386 if (!d->savingMutex.tryLock()){
1388 }
1389
1394 std::unique_lock<QMutex> savingMutexLock(d->savingMutex, std::adopt_lock);
1395
1396 if (!clonedDocument) {
1398 }
1399
1400 auto waitForImage = [] (KisImageSP image) {
1402 if (window) {
1403 if (window->viewManager()) {
1405 }
1406 }
1407 };
1408
1409 {
1410 KisNodeSP newRoot = clonedDocument->image()->root();
1413 waitForImage(clonedDocument->image());
1414 }
1415 }
1416
1417 if (clonedDocument->image()->hasOverlaySelectionMask()) {
1418 clonedDocument->image()->setOverlaySelectionMask(0);
1419 waitForImage(clonedDocument->image());
1420 }
1421
1422 KisConfig cfg(true);
1423 if (cfg.trimKra()) {
1424 clonedDocument->image()->cropImage(clonedDocument->image()->bounds());
1425 clonedDocument->image()->purgeUnusedData(false);
1426 waitForImage(clonedDocument->image());
1427 }
1428
1429 KIS_SAFE_ASSERT_RECOVER(clonedDocument->image()->isIdle()) {
1430 waitForImage(clonedDocument->image());
1431 }
1432
1435
1445 savingMutexLock.release();
1446
1447 d->backgroundSaveDocument.reset(clonedDocument.take());
1448 d->backgroundSaveJob = job;
1449 d->modifiedWhileSaving = false;
1450
1451 if (d->backgroundSaveJob.flags & KritaUtils::SaveInAutosaveMode) {
1452 d->backgroundSaveDocument->d->isAutosaving = true;
1453 }
1454
1455 connect(d->backgroundSaveDocument.data(),
1456 SIGNAL(sigBackgroundSavingFinished(KisImportExportErrorCode, QString, QString)),
1457 this,
1459
1460
1461 if (d->completeSavingConnection) {
1462 disconnect(d->completeSavingConnection);
1463 }
1464 d->completeSavingConnection = connect(
1466 receiverObject, receiverMethod);
1467
1469 d->backgroundSaveDocument->startExportInBackground(actionName,
1470 job.filePath,
1471 job.filePath,
1472 job.mimeType,
1474 exportConfiguration, isAdvancedExporting);
1475 if (!error.isOk()) {
1476 // the state should have been deinitialized in slotChildCompletedSavingInBackground()
1477 KIS_SAFE_ASSERT_RECOVER (!d->backgroundSaveDocument && !d->backgroundSaveJob.isValid()) {
1478 d->backgroundSaveDocument.take()->deleteLater();
1479 d->savingMutex.unlock();
1480 d->backgroundSaveJob = KritaUtils::ExportFileJob();
1481 }
1482 if (error.isCancelled()) {
1484 }
1486 }
1487
1489}
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:459
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 1837 of file KisDocument.cpp.

1838{
1839 return d->autoSaveActive;
1840}

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 1847 of file KisDocument.cpp.

1848{
1849 return d->modified;
1850}

References d.

◆ isNativeFormat()

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

Checks whether a given mimeType can be handled natively.

Definition at line 2258 of file KisDocument.cpp.

2259{
2261 return true;
2262 return extraNativeMimeTypes().contains(mimeType);
2263}
static QStringList extraNativeMimeTypes()

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

◆ isReadWrite()

bool KisDocument::isReadWrite ( ) const

Definition at line 2559 of file KisDocument.cpp.

2560{
2561 return d->readwrite;
2562}

References d.

◆ isRecovered()

bool KisDocument::isRecovered ( ) const

◆ isSaving()

bool KisDocument::isSaving ( ) const

Definition at line 2766 of file KisDocument.cpp.

2767{
2768 const bool result = d->savingMutex.tryLock();
2769 if (result) {
2770 d->savingMutex.unlock();
2771 }
2772 return !result;
2773}

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 2394 of file KisDocument.cpp.

2395{
2397 if (!d->linkedResourceStorage) {
2398 return result;
2399 }
2400
2401 Q_FOREACH(const QString &resourceType, KisResourceLoaderRegistry::instance()->resourceTypes()) {
2402 QSharedPointer<KisResourceStorage::ResourceIterator> iter = d->linkedResourceStorage->resources(resourceType);
2403 while (iter->hasNext()) {
2404 iter->next();
2405
2406 QBuffer buf;
2407 buf.open(QBuffer::WriteOnly);
2408 bool exportSuccessful =
2409 d->linkedResourceStorage->exportResource(iter->url(), &buf);
2410
2411 KoResourceSP resource = d->linkedResourceStorage->resource(iter->url());
2412 exportSuccessful &= bool(resource);
2413
2414 const QString name = resource ? resource->name() : QString();
2415 const QString fileName = QFileInfo(iter->url()).fileName();
2416 const KoResourceSignature signature(resourceType,
2417 KoMD5Generator::generateHash(buf.data()),
2418 fileName, name);
2419
2420 if (exportSuccessful) {
2421 result << KoEmbeddedResource(signature, buf.data());
2422 } else {
2423 result << signature;
2424 }
2425 }
2426 }
2427
2428 return result;
2429}
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 728 of file KisDocument.cpp.

729{
730 return d->linkedResourcesStorageID;
731}

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 2136 of file KisDocument.cpp.

2137{
2138 return openPath(file_);
2139}

References openPath().

◆ localFilePath()

QString KisDocument::localFilePath ( ) const

Definition at line 2604 of file KisDocument.cpp.

2605{
2606 return d->m_file;
2607}

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 1238 of file KisDocument.cpp.

1239{
1240 return d->lockAndCloneImpl(true);
1241}

References d.

◆ lockAndCloneImpl()

KisDocument * KisDocument::lockAndCloneImpl ( bool fetchResourcesFromLayers)

◆ lockAndCreateSnapshot()

KisDocument * KisDocument::lockAndCreateSnapshot ( )

Definition at line 1243 of file KisDocument.cpp.

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

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 170 of file KisDocument.h.

170{ 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 2661 of file KisDocument.cpp.

2667{
2668 Q_ASSERT(cs);
2669
2671
2672 if (!cs) return false;
2673
2674 KisCursorOverrideLock cursorLock(Qt::BusyCursor);
2675
2676 image = new KisImage(createUndoStore(), width, height, cs, name);
2677
2678 Q_CHECK_PTR(image);
2679
2680 connect(image, SIGNAL(sigImageModified()), this, SLOT(setImageModified()), Qt::UniqueConnection);
2681 connect(image, SIGNAL(sigImageModifiedWithoutUndo()), this, SLOT(setImageModifiedWithoutUndo()), Qt::UniqueConnection);
2682 image->setResolution(imageResolution, imageResolution);
2683
2685 image->waitForDone();
2686
2687 documentInfo()->setAboutInfo("title", name);
2688 documentInfo()->setAboutInfo("abstract", description);
2689
2690 KisConfig cfg(false);
2691 cfg.defImageWidth(width);
2692 cfg.defImageHeight(height);
2693 cfg.defImageResolution(imageResolution);
2694 if (!cfg.useDefaultColorSpace())
2695 {
2696 cfg.defColorModel(image->colorSpace()->colorModelId().id());
2697 cfg.setDefaultColorDepth(image->colorSpace()->colorDepthId().id());
2698 cfg.defColorProfile(image->colorSpace()->profile()->name());
2699 }
2700
2701 bool autopin = cfg.autoPinLayersToTimeline();
2702
2703 KisLayerSP bgLayer;
2704 if (bgStyle == KisConfig::RASTER_LAYER || bgStyle == KisConfig::FILL_LAYER) {
2705 KoColor strippedAlpha = bgColor;
2706 strippedAlpha.setOpacity(OPACITY_OPAQUE_U8);
2707
2708 if (bgStyle == KisConfig::RASTER_LAYER) {
2709 bgLayer = new KisPaintLayer(image.data(), i18nc("Name for the bottom-most layer in the layerstack", "Background"), OPACITY_OPAQUE_U8, cs);
2710 bgLayer->paintDevice()->setDefaultPixel(strippedAlpha);
2711 bgLayer->setPinnedToTimeline(autopin);
2712 } else if (bgStyle == KisConfig::FILL_LAYER) {
2714 filter_config->setProperty("color", strippedAlpha.toQColor());
2715 filter_config->createLocalResourcesSnapshot();
2716 bgLayer = new KisGeneratorLayer(image.data(), i18nc("Name of automatically created background color fill layer", "Background Fill"), filter_config, image->globalSelection());
2717 }
2718
2719 bgLayer->setOpacity(bgColor.opacityU8());
2720
2721 if (numberOfLayers > 1) {
2722 //Lock bg layer if others are present.
2723 bgLayer->setUserLocked(true);
2724 }
2725 }
2726 else { // KisConfig::CANVAS_COLOR (needs an unlocked starting layer).
2728 bgLayer = new KisPaintLayer(image.data(), image->nextLayerName(), OPACITY_OPAQUE_U8, cs);
2729 }
2730
2731 Q_CHECK_PTR(bgLayer);
2732 image->addNode(bgLayer.data(), image->rootLayer().data());
2733 bgLayer->setDirty(QRect(0, 0, width, height));
2734
2735 // reset mirror axis to default:
2736 d->mirrorAxisConfig.setAxisPosition(QRectF(image->bounds()).center());
2738
2739 for(int i = 1; i < numberOfLayers; ++i) {
2741 layer->setPinnedToTimeline(autopin);
2742 image->addNode(layer, image->root(), i);
2743 layer->setDirty(QRect(0, 0, width, height));
2744 }
2745
2746 {
2748 if (window) {
2753 }
2754 }
2755
2757 QString("Created image \"%1\", %2 * %3 pixels, %4 dpi. Color model: %6 %5 (%7). Layers: %8")
2758 .arg(name, QString::number(width), QString::number(height),
2759 QString::number(imageResolution * 72.0), image->colorSpace()->colorModelId().name(),
2761 QString::number(numberOfLayers)));
2762
2763 return true;
2764}
const quint8 OPACITY_OPAQUE_U8
KisUndoStore * createUndoStore()
KoDocumentInfo * documentInfo() const
void setImageModified()
void setImageModifiedWithoutUndo()
void setColorHistory(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:715
bool assignImageProfile(const KoColorProfile *profile, bool blockAllUpdates=false)
void setDefaultProjectionColor(const KoColor &color)
KisSelectionSP globalSelection() const
Definition kis_image.cc:695
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
QString id() const
Definition KoID.cpp:63
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::colorHistory(), KoColorSpace::colorModelId(), KisImage::colorSpace(), createUndoStore(), KisPart::currentMainwindow(), d, KisSharedPtr< T >::data(), KisBaseProcessor::defaultConfiguration(), KisConfig::defColorModel(), KisConfig::defColorProfile(), KisConfig::defImageHeight(), KisConfig::defImageResolution(), KisConfig::defImageWidth(), documentInfo(), KisConfig::FILL_LAYER, KoGenericRegistry< T >::get(), KisImage::globalSelection(), KoID::id(), 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(), setColorHistory(), setCurrentImage(), KisConfig::setDefaultColorDepth(), KisPaintDevice::setDefaultPixel(), KisImage::setDefaultProjectionColor(), KisNode::setDirty(), setImageModified(), setImageModifiedWithoutUndo(), KoColor::setOpacity(), KisBaseNode::setOpacity(), KisBaseNode::setPinnedToTimeline(), KisImage::setResolution(), KisBaseNode::setUserLocked(), KoColor::toQColor(), KisConfig::useDefaultColorSpace(), KisMainWindow::viewManager, and KisImage::waitForDone().

◆ newObjectName()

QString KisDocument::newObjectName ( )
private

Generate a name for the document.

Definition at line 159 of file KisDocument.cpp.

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

◆ 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 2033 of file KisDocument.cpp.

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

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

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

2565{
2566 return d->m_path;
2567}

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 2213 of file KisDocument.cpp.

2214{
2215 QString _url(path());
2216#ifdef Q_OS_WIN
2217 _url = QDir::toNativeSeparators(_url);
2218#endif
2219 return _url;
2220}

References path().

◆ Private() [1/2]

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

Definition at line 322 of file KisDocument.cpp.

323 : q(_q)
324 , docInfo(new KoDocumentInfo(*rhs.docInfo, _q))
326 , autoSaveTimer(new QTimer(_q))
327 , undoStack(new UndoStack(_q))
328 , nserver(new KisNameServer(*rhs.nserver))
329 , preActivatedNode(0) // the node is from another hierarchy!
330 , imageIdleWatcher(2000 /*ms*/)
331 , colorHistory(rhs.colorHistory)
332 {
333 copyFromImpl(rhs, _q, CONSTRUCT);
334 connect(&imageIdleWatcher, SIGNAL(startedIdleMode()), q, SLOT(slotPerformIdleRoutines()));
335 }
QList< KoColor > colorHistory
QTimer * autoSaveTimer
void copyFromImpl(const Private &rhs, KisDocument *q, KisDocument::CopyPolicy policy)
KisImportExportManager * importExportManager
KisDocument * q
KisNodeWSP preActivatedNode
KisIdleWatcher imageIdleWatcher
void slotPerformIdleRoutines()
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 297 of file KisDocument.cpp.

298 : q(_q)
299 , docInfo(new KoDocumentInfo(_q)) // deleted by QObject
300 , importExportManager(new KisImportExportManager(_q)) // deleted manually
301 , autoSaveTimer(new QTimer(_q))
302 , undoStack(new UndoStack(_q)) // deleted by QObject
303 , m_bAutoDetectedMime(false)
304 , modified(false)
305 , readwrite(true)
306 , autoSaveActive(true)
307 , firstMod(QDateTime::currentDateTime())
309 , nserver(new KisNameServer(1))
310 , imageIdleWatcher(2000 /*ms*/)
311 , globalAssistantsColor(KisConfig(true).defaultAssistantsColor())
312 , batchMode(false)
313 {
314 if (QLocale().measurementSystem() == QLocale::ImperialSystem) {
316 } else {
318 }
319 connect(&imageIdleWatcher, SIGNAL(startedIdleMode()), q, SLOT(slotPerformIdleRoutines()));
320 }
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 2807 of file KisDocument.cpp.

2808{
2809 if (!d->image) return KisReferenceImagesLayerSP();
2810
2811 KisReferenceImagesLayerSP referencesLayer =
2812 KisLayerUtils::findNodeByType<KisReferenceImagesLayer>(d->image->root());
2813
2814 return referencesLayer;
2815}
KisSharedPtr< KisReferenceImagesLayer > KisReferenceImagesLayerSP

References d.

◆ removeAutoSaveFiles()

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

Performs a cleanup of unneeded backup files

Definition at line 2286 of file KisDocument.cpp.

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

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 2549 of file KisDocument.cpp.

2549 {
2550 setPath(QString());
2551 setLocalFilePath(QString());
2552}

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 1575 of file KisDocument.cpp.

1576{
1577 if (QFileInfo(path).absolutePath().startsWith(KisResourceLocator::instance()->resourceLocationBase())) {
1578
1579 QStringList pathParts = QFileInfo(path).absolutePath().split('/');
1580 if (pathParts.size() > 0) {
1581 QString resourceType = pathParts.last();
1582 if (KisResourceLoaderRegistry::instance()->resourceTypes().contains(resourceType)) {
1583
1584 KisResourceModel model(resourceType);
1585 model.setResourceFilter(KisResourceModel::ShowAllResources);
1586
1587 QString tempFileName = QDir::tempPath() + "/" + QFileInfo(path).fileName();
1588
1589 if (QFileInfo(path).exists()) {
1590
1591 int outResourceId;
1592 KoResourceSP res;
1593 if (KisResourceCacheDb::getResourceIdFromVersionedFilename(QFileInfo(path).fileName(), resourceType, "", outResourceId)) {
1594 res = model.resourceForId(outResourceId);
1595 }
1596
1597 if (res) {
1598 d->modifiedWhileSaving = false;
1599
1600 if (!exportConfiguration) {
1601 QScopedPointer<KisImportExportFilter> filter(
1603 if (filter) {
1604 exportConfiguration = filter->defaultConfiguration(nativeFormatMimeType(), mimeType);
1605 }
1606 }
1607
1608 if (exportConfiguration) {
1609 // make sure the name of the resource doesn't change
1610 exportConfiguration->setProperty("name", res->name());
1611 }
1612
1613 if (exportDocumentSync(tempFileName, mimeType, exportConfiguration)) {
1614 QFile f2(tempFileName);
1615 f2.open(QFile::ReadOnly);
1616
1617 QByteArray ba = f2.readAll();
1618
1619 QBuffer buf(&ba);
1620 buf.open(QBuffer::ReadOnly);
1621
1622
1623
1624 if (res->loadFromDevice(&buf, KisGlobalResourcesInterface::instance())) {
1625 if (model.updateResource(res)) {
1626 const QString filePath =
1628
1629 d->updateDocumentMetadataOnSaving(filePath, mimeType);
1630
1631 return true;
1632 }
1633 }
1634 }
1635 }
1636 }
1637 else {
1638 d->modifiedWhileSaving = false;
1639 if (exportDocumentSync(tempFileName, mimeType, exportConfiguration)) {
1640 KoResourceSP res = model.importResourceFile(tempFileName, false);
1641 if (res) {
1642 const QString filePath =
1644
1645 d->updateDocumentMetadataOnSaving(filePath, mimeType);
1646
1647 return true;
1648 }
1649 }
1650 }
1651 }
1652 }
1653 }
1654 return false;
1655}
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...

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

◆ save()

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

Definition at line 975 of file KisDocument.cpp.

976{
977 return saveAs(path(), mimeType(), showWarnings, exportConfiguration);
978}
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 951 of file KisDocument.cpp.

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

981{
982 QBuffer buffer;
983
985 filter->setBatchMode(true);
986 filter->setMimeType(nativeFormatMimeType());
987
988 Private::StrippedSafeSavingLocker locker(&d->savingMutex, d->image);
989 if (!locker.successfullyLocked()) {
990 return buffer.data();
991 }
992
993 d->savingImage = d->image;
994
995 if (!filter->convert(this, &buffer).isOk()) {
996 qWarning() << "serializeToByteArray():: Could not export to our native format";
997 }
998
999 return buffer.data();
1000}

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 2798 of file KisDocument.cpp.

2799{
2800 if (d->assistants != value) {
2801 d->assistants = value;
2802 d->syncDecorationsWrapperLayerState();
2803 Q_EMIT sigAssistantsChanged();
2804 }
2805}
float value(const T *src, size_t ch)
void sigAssistantsChanged()

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

◆ setAssistantsGlobalColor()

void KisDocument::setAssistantsGlobalColor ( QColor color)

Definition at line 2940 of file KisDocument.cpp.

2941{
2942 d->globalAssistantsColor = color;
2943}

References d.

◆ setAudioTracks()

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

Definition at line 2496 of file KisDocument.cpp.

2497{
2498 d->audioTracks = f;
2499 Q_EMIT sigAudioTracksChanged();
2500}
void sigAudioTracksChanged()

References d, and sigAudioTracksChanged().

◆ setAudioVolume()

void KisDocument::setAudioVolume ( qreal level)

Definition at line 2502 of file KisDocument.cpp.

2503{
2504 d->audioLevel = level;
2505 Q_EMIT sigAudioLevelChanged(level);
2506}
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 1800 of file KisDocument.cpp.

1801{
1802 const bool changed = autoSaveActive != d->autoSaveActive;
1803
1804 if (changed) {
1805 d->autoSaveActive = autoSaveActive;
1807 }
1808}
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 1810 of file KisDocument.cpp.

1811{
1812 if (isReadWrite() && delay > 0 && d->autoSaveActive) {
1813 d->autoSaveTimer->start(delay * 1000);
1814 } else {
1815 d->autoSaveTimer->stop();
1816 }
1817}

References d, and isReadWrite().

◆ setColorHistory()

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

Definition at line 2968 of file KisDocument.cpp.

2969{
2970 d->colorHistory = colors;
2971}

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 2872 of file KisDocument.cpp.

2873{
2874 if (d->image) {
2875 // Disconnect existing sig/slot connections
2876 d->image->setUndoStore(new KisDumbUndoStore());
2877 d->image->disconnect(this);
2878 d->shapeController->setImage(0);
2879 d->image = 0;
2880 }
2881
2882 if (!image) return;
2883
2884 if (d->linkedResourceStorage){
2885 d->linkedResourceStorage->setMetaData(KisResourceStorage::s_meta_name, image->objectName());
2886 }
2887
2888 d->setImageAndInitIdleWatcher(image);
2889 d->image->setUndoStore(new KisDocumentUndoStore(this));
2890 d->shapeController->setImage(image, preActivatedNode);
2891 d->image->setMirrorAxesCenter(KisAlgebra2D::absoluteToRelative(d->mirrorAxisConfig.axisPosition(), image->bounds()));
2892 setModified(false);
2893 connect(d->image, SIGNAL(sigImageModified()), this, SLOT(setImageModified()), Qt::UniqueConnection);
2894 connect(d->image, SIGNAL(sigImageModifiedWithoutUndo()), this, SLOT(setImageModifiedWithoutUndo()), Qt::UniqueConnection);
2895 connect(d->image, SIGNAL(sigLayersChangedAsync()), this, SLOT(slotImageRootChanged()));
2896
2897 if (forceInitialUpdate) {
2898 d->image->initialRefreshGraph();
2899 }
2900}
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 1825 of file KisDocument.cpp.

1826{
1827 const int emergencyAutoSaveInterval = 10; /* sec */
1828 setAutoSaveDelay(emergencyAutoSaveInterval);
1829 d->autoSaveFailureCount++;
1830}
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 2265 of file KisDocument.cpp.

2266{
2267 d->lastErrorMessage = errMsg;
2268}

References d.

◆ setFileBatchMode()

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

Definition at line 1148 of file KisDocument.cpp.

1149{
1150 d->batchMode = batchMode;
1151}

References batchMode, and d.

◆ setGridConfig()

void KisDocument::setGridConfig ( const KisGridConfig & config)

Definition at line 2381 of file KisDocument.cpp.

2382{
2383 if (d->gridConfig != config) {
2384 d->gridConfig = config;
2385 d->syncDecorationsWrapperLayerState();
2386 Q_EMIT sigGridConfigChanged(config);
2387
2388 // Store last assigned value as future default...
2389 KisConfig cfg(false);
2390 cfg.setDefaultGridSpacing(config.spacing());
2391 }
2392}
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 2518 of file KisDocument.cpp.

2519{
2520 if (d->guidesConfig == data) return;
2521
2522 d->guidesConfig = data;
2523 d->syncDecorationsWrapperLayerState();
2524 Q_EMIT sigGuidesConfigChanged(d->guidesConfig);
2525}
void sigGuidesConfigChanged(const KisGuidesConfig &config)

References d, and sigGuidesConfigChanged().

◆ setImageAndInitIdleWatcher()

void KisDocument::setImageAndInitIdleWatcher ( KisImageSP _image)
inline

Definition at line 430 of file KisDocument.cpp.

430 {
431 image = _image;
432
434 }
void setTrackedImage(KisImageSP image)

References KisIdleWatcher::setTrackedImage().

◆ setImageModified

void KisDocument::setImageModified ( )
privateslot

Definition at line 2912 of file KisDocument.cpp.

2913{
2914 // we only set as modified if undo stack is not at clean state
2915 setModified(d->imageModifiedWithoutUndo || !d->undoStack->isClean());
2916}

References d, and setModified().

◆ setImageModifiedWithoutUndo

void KisDocument::setImageModifiedWithoutUndo ( )
privateslot

Definition at line 2918 of file KisDocument.cpp.

2919{
2920 d->imageModifiedWithoutUndo = true;
2922}

References d, and setImageModified().

◆ setInfiniteAutoSaveInterval()

void KisDocument::setInfiniteAutoSaveInterval ( )

Disable autosave

Definition at line 1832 of file KisDocument.cpp.

1833{
1834 setAutoSaveDelay(-1);
1835}

References setAutoSaveDelay().

◆ setLocalFilePath()

void KisDocument::setLocalFilePath ( const QString & localFilePath)

Definition at line 2610 of file KisDocument.cpp.

2611{
2612 d->m_file = localFilePath;
2613}

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 1138 of file KisDocument.cpp.

1139{
1140 d->mimeType = mimeType;
1141}

References d, and mimeType.

◆ setMimeTypeAfterLoading()

void KisDocument::setMimeTypeAfterLoading ( const QString & mimeType)

Definition at line 2129 of file KisDocument.cpp.

2130{
2131 d->mimeType = mimeType.toLatin1();
2132 d->outputMimeType = d->mimeType;
2133}

References d, and mimeType.

◆ setMirrorAxisConfig()

void KisDocument::setMirrorAxisConfig ( const KisMirrorAxisConfig & config)

Definition at line 2533 of file KisDocument.cpp.

2534{
2535 if (d->mirrorAxisConfig == config) {
2536 return;
2537 }
2538
2539 d->mirrorAxisConfig = config;
2540 if (d->image) {
2541 d->image->setMirrorAxesCenter(KisAlgebra2D::absoluteToRelative(d->mirrorAxisConfig.axisPosition(),
2542 d->image->bounds()));
2543 }
2544 setModified(true);
2545
2547}
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 2141 of file KisDocument.cpp.

2142{
2143 if (mod) {
2144 updateEditingTime(false);
2145 }
2146
2151 if (d->isAutosaving || d->documentIsClosing)
2152 return;
2153
2154 //dbgUI<<" url:" << url.path();
2155 //dbgUI<<" mod="<<mod<<" MParts mod="<<KisParts::ReadWritePart::isModified()<<" isModified="<<isModified();
2156
2157 if (mod && !d->autoSaveTimer->isActive()) {
2158 // First change since last autosave -> start the autosave timer
2160 }
2161 d->modifiedAfterAutosave = mod;
2162 d->modifiedWhileSaving = mod;
2163
2164 if (!mod) {
2165 d->imageModifiedWithoutUndo = mod;
2166 }
2167
2168 if (mod == isModified())
2169 return;
2170
2171 d->modified = mod;
2172
2173 if (mod) {
2175 }
2176
2177 Q_EMIT modified(mod);
2178}
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 1819 of file KisDocument.cpp.

1820{
1821 setAutoSaveDelay(d->autoSaveDelay);
1822 d->autoSaveFailureCount = 0;
1823}

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 2431 of file KisDocument.cpp.

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

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

◆ setPath()

void KisDocument::setPath ( const QString & path)

Definition at line 2593 of file KisDocument.cpp.

2594{
2595 const bool changed = path != d->m_path;
2596
2597 d->m_path = path;
2598
2599 if (changed) {
2600 Q_EMIT sigPathChanged(path);
2601 }
2602}
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 2851 of file KisDocument.cpp.

2852{
2853 d->preActivatedNode = activatedNode;
2854}

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 1789 of file KisDocument.cpp.

1790{
1791 const bool changed = readwrite != d->readwrite;
1792
1793 d->readwrite = readwrite;
1794
1795 if (changed) {
1797 }
1798}
void sigReadWriteChanged(bool value)

References d, readwrite, and sigReadWriteChanged().

◆ setRecovered()

void KisDocument::setRecovered ( bool value)

Definition at line 2180 of file KisDocument.cpp.

2181{
2182 const bool changed = value != d->isRecovered;
2183
2184 d->isRecovered = value;
2185
2186 if (changed) {
2187 Q_EMIT sigRecoveredChanged(value);
2188 }
2189}
void sigRecoveredChanged(bool value)

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

◆ setReferenceImagesLayer()

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

Definition at line 2817 of file KisDocument.cpp.

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

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 2484 of file KisDocument.cpp.

2485{
2486 d->m_storyboardCommentList = storyboardCommentList;
2487 if (emitSignal) {
2489 }
2490}
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 2471 of file KisDocument.cpp.

2472{
2473 d->m_storyboardItemList = storyboardItemList;
2474 if (emitSignal) {
2476 }
2477}
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 2323 of file KisDocument.cpp.

2324{
2325 if (d->unit != unit) {
2326 d->unit = unit;
2327 Q_EMIT unitChanged(unit);
2328 }
2329}
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 2275 of file KisDocument.cpp.

2276{
2277 d->lastWarningMessage = warningMsg;
2278}

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 2788 of file KisDocument.cpp.

2789{
2790 return d->shapeController->shapeForNode(layer);
2791}

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 1657 of file KisDocument.cpp.

1658{
1659 slotAutoSaveImpl(std::unique_ptr<KisDocument>());
1660}
void slotAutoSaveImpl(std::unique_ptr< KisDocument > &&optionalClonedDocument)

References slotAutoSaveImpl().

◆ slotAutoSaveImpl()

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

Definition at line 1532 of file KisDocument.cpp.

1533{
1534 if (!d->modified || !d->modifiedAfterAutosave) return;
1535 const QString autoSaveFileName = generateAutoSaveFileName(localFilePath());
1536
1537 Q_EMIT statusBarMessage(i18n("Autosaving... %1", autoSaveFileName), successMessageTimeout);
1538
1539 KisUsageLogger::log(QString("Autosaving: %1").arg(autoSaveFileName));
1540
1541 const bool hadClonedDocument = bool(optionalClonedDocument);
1543
1544 if (d->image->isIdle() || hadClonedDocument) {
1545 result = initiateSavingInBackground(i18n("Autosaving..."),
1548 0,
1549 std::move(optionalClonedDocument));
1550 } else {
1551 Q_EMIT statusBarMessage(i18n("Autosaving postponed: document is busy..."), errorMessageTimeout);
1552 }
1553
1554 if (result != KritaUtils::BackgroudSavingStartResult::Success && !hadClonedDocument && d->autoSaveFailureCount >= 3) {
1556 connect(stroke, SIGNAL(sigDocumentCloned(KisDocument*)),
1558 Qt::BlockingQueuedConnection);
1559 connect(stroke, SIGNAL(sigCloningCancelled()),
1560 this, SLOT(slotDocumentCloningCancelled()),
1561 Qt::BlockingQueuedConnection);
1562
1563 KisStrokeId strokeId = d->image->startStroke(stroke);
1564 d->image->endStroke(strokeId);
1565
1567
1570 } else {
1571 d->modifiedAfterAutosave = false;
1572 }
1573}
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 1492 of file KisDocument.cpp.

1493{
1495
1501 std::unique_lock<QMutex> savingMutexLock(d->savingMutex, std::adopt_lock);
1502
1503 KIS_ASSERT_RECOVER_RETURN(d->backgroundSaveDocument);
1504
1505 if (d->backgroundSaveJob.flags & KritaUtils::SaveInAutosaveMode) {
1506 d->backgroundSaveDocument->d->isAutosaving = false;
1507 }
1508
1509 d->backgroundSaveDocument.take()->deleteLater();
1510
1511 KIS_ASSERT_RECOVER_RETURN(d->backgroundSaveJob.isValid());
1512
1513 const KritaUtils::ExportFileJob job = d->backgroundSaveJob;
1514 d->backgroundSaveJob = KritaUtils::ExportFileJob();
1515
1516 // unlock at the very end
1517 savingMutexLock.unlock();
1518
1519 QFileInfo fi(job.filePath);
1520 KisUsageLogger::log(QString("Completed saving %1 (mime: %2). Result: %3. Warning: %4. Size: %5")
1521 .arg(job.filePath, QString::fromLatin1(job.mimeType),
1522 (!status.isOk() ? errorMessage : "OK"), warningMessage,
1523 QString::number(fi.size())));
1524
1526 // One-shot: disconnect immediately after firing so future save completions
1527 // don't invoke a stale or unrelated slot.
1528 disconnect(d->completeSavingConnection);
1529 d->completeSavingConnection = {};
1530}
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 1684 of file KisDocument.cpp.

1685{
1686 Q_UNUSED(job);
1687 Q_UNUSED(warningMessage);
1688
1689 const QString fileName = QFileInfo(job.filePath).fileName();
1690
1691 if (!status.isOk()) {
1693 Q_EMIT statusBarMessage(i18nc("%1 --- failing file name, %2 --- error message",
1694 "Error during autosaving %1: %2",
1695 fileName,
1696 exportErrorToUserMessage(status, errorMessage)), errorMessageTimeout);
1697 } else {
1698 KisConfig cfg(true);
1699 d->autoSaveDelay = cfg.autoSaveInterval();
1700
1701 if (!d->modifiedWhileSaving) {
1702 d->autoSaveTimer->stop(); // until the next change
1703 d->autoSaveFailureCount = 0;
1704 } else {
1706 }
1707
1708 Q_EMIT statusBarMessage(i18n("Finished autosaving %1", fileName), successMessageTimeout);
1709 }
1710}
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 1040 of file KisDocument.cpp.

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

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

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

◆ slotDocumentCloningCancelled

void KisDocument::slotDocumentCloningCancelled ( )
privateslot

Definition at line 1667 of file KisDocument.cpp.

1668{
1670}

References setEmergencyAutoSaveInterval().

◆ slotImageRootChanged

void KisDocument::slotImageRootChanged ( )
privateslot

Definition at line 2366 of file KisDocument.cpp.

2367{
2368 d->syncDecorationsWrapperLayerState();
2369}

References d.

◆ slotInitiateAsyncAutosaving

void KisDocument::slotInitiateAsyncAutosaving ( KisDocument * clonedDocument)
privateslot

Definition at line 1662 of file KisDocument.cpp.

1663{
1664 slotAutoSaveImpl(std::unique_ptr<KisDocument>(clonedDocument));
1665}

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 1672 of file KisDocument.cpp.

1673{
1674 d->image->explicitRegenerateLevelOfDetail();
1675
1676
1680
1681 // d->image->purgeUnusedData(true);
1682}

References d.

◆ slotUndoStackCleanChanged

void KisDocument::slotUndoStackCleanChanged ( bool value)
privateslot

Definition at line 2341 of file KisDocument.cpp.

2342{
2343 setModified(!value || d->imageModifiedWithoutUndo);
2344}

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 1712 of file KisDocument.cpp.

1718{
1719 d->savingImage = d->image;
1720
1722 if (window) {
1723 if (window->viewManager()) {
1724 d->savingUpdater = window->viewManager()->createThreadedUpdater(actionName);
1725 d->importExportManager->setUpdater(d->savingUpdater);
1726 }
1727 }
1728
1729 KisImportExportErrorCode initializationStatus(ImportExportCodes::OK);
1730 d->childSavingFuture =
1731 d->importExportManager->exportDocumentAsync(location,
1732 realLocation,
1733 mimeType,
1734 initializationStatus,
1735 showWarnings,
1736 exportConfiguration,
1737 isAdvancedExporting);
1738
1739 if (!initializationStatus.isOk()) {
1740 if (d->savingUpdater) {
1741 d->savingUpdater->cancel();
1742 }
1743 d->savingImage.clear();
1744 Q_EMIT sigBackgroundSavingFinished(initializationStatus, initializationStatus.errorMessage(), "");
1745 return initializationStatus;
1746 }
1747
1748 typedef QFutureWatcher<KisImportExportErrorCode> StatusWatcher;
1749 StatusWatcher *watcher = new StatusWatcher();
1750 watcher->setFuture(d->childSavingFuture);
1751
1752 connect(watcher, SIGNAL(finished()), SLOT(finishExportInBackground()));
1753 connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater()));
1754
1755 return initializationStatus;
1756}
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 2196 of file KisDocument.cpp.

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

References d.

◆ uploadLinkedResourcesFromLayersToStorage()

void KisDocument::uploadLinkedResourcesFromLayersToStorage ( )

◆ waitForSavingToComplete()

void KisDocument::waitForSavingToComplete ( )

Definition at line 2775 of file KisDocument.cpp.

2776{
2777 if (isSaving()) {
2778 KisAsyncActionFeedback f(i18nc("progress dialog message when the user closes the document that is being saved", "Waiting for saving to complete..."), 0);
2779 f.waitForMutex(d->savingMutex);
2780 }
2781}

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 2280 of file KisDocument.cpp.

2281{
2282 return d->lastWarningMessage;
2283}

References d.

Friends And Related Symbol Documentation

◆ KisPart

friend class KisPart
friend

Definition at line 531 of file KisDocument.h.

◆ SafeSavingLocker

friend class SafeSavingLocker
friend

Definition at line 532 of file KisDocument.h.

Member Data Documentation

◆ assistants

QList< KisPaintingAssistantSP > KisDocument::assistants

Definition at line 391 of file KisDocument.cpp.

◆ audioLevel

qreal KisDocument::audioLevel = 1.0

Definition at line 397 of file KisDocument.cpp.

◆ audioTracks

QVector<QFileInfo> KisDocument::audioTracks

Definition at line 396 of file KisDocument.cpp.

◆ autoSaveActive

bool KisDocument::autoSaveActive = true

Definition at line 375 of file KisDocument.cpp.

◆ autoSaveDelay

int KisDocument::autoSaveDelay = 300

Definition at line 356 of file KisDocument.cpp.

◆ autoSaveFailureCount

int KisDocument::autoSaveFailureCount = 0

Definition at line 360 of file KisDocument.cpp.

◆ autoSaveTimer

QTimer* KisDocument::autoSaveTimer

Definition at line 352 of file KisDocument.cpp.

◆ backgroundSaveDocument

QScopedPointer<KisDocument> KisDocument::backgroundSaveDocument

Definition at line 406 of file KisDocument.cpp.

◆ backgroundSaveJob

KritaUtils::ExportFileJob KisDocument::backgroundSaveJob

Definition at line 409 of file KisDocument.cpp.

◆ batchMode

bool KisDocument::batchMode { false }

Definition at line 415 of file KisDocument.cpp.

415{ false };

◆ childSavingFuture

QFuture<KisImportExportErrorCode> KisDocument::childSavingFuture

Definition at line 408 of file KisDocument.cpp.

◆ colorHistory

QList< KoColor > KisDocument::colorHistory

Definition at line 400 of file KisDocument.cpp.

◆ completeSavingConnection

QMetaObject::Connection KisDocument::completeSavingConnection

Definition at line 410 of file KisDocument.cpp.

◆ d

Private* const KisDocument::d
private

Definition at line 743 of file KisDocument.h.

◆ decorationsSyncingDisabled

bool KisDocument::decorationsSyncingDisabled = false

Definition at line 416 of file KisDocument.cpp.

◆ disregardAutosaveFailure

bool KisDocument::disregardAutosaveFailure = false

Definition at line 359 of file KisDocument.cpp.

◆ docInfo

KoDocumentInfo* KisDocument::docInfo = 0

Definition at line 343 of file KisDocument.cpp.

◆ documentIsClosing

bool KisDocument::documentIsClosing = false

Definition at line 418 of file KisDocument.cpp.

◆ embeddedResourcesStorageID

QString KisDocument::embeddedResourcesStorageID

Definition at line 425 of file KisDocument.cpp.

◆ embeddedResourceStorage

KisResourceStorageSP KisDocument::embeddedResourceStorage

Definition at line 426 of file KisDocument.cpp.

◆ firstMod

QDateTime KisDocument::firstMod

Definition at line 377 of file KisDocument.cpp.

◆ globalAssistantsColor

QColor KisDocument::globalAssistantsColor

Definition at line 399 of file KisDocument.cpp.

◆ gridConfig

KisGridConfig KisDocument::gridConfig

Definition at line 402 of file KisDocument.cpp.

◆ guidesConfig

const KisGuidesConfig & KisDocument::guidesConfig

Definition at line 364 of file KisDocument.cpp.

◆ image

KisImageWSP KisDocument::image

Definition at line 382 of file KisDocument.cpp.

◆ imageIdleConnection

QScopedPointer<KisSignalAutoConnection> KisDocument::imageIdleConnection

Definition at line 389 of file KisDocument.cpp.

◆ imageIdleWatcher

KisIdleWatcher KisDocument::imageIdleWatcher

Definition at line 388 of file KisDocument.cpp.

◆ imageModifiedWithoutUndo

bool KisDocument::imageModifiedWithoutUndo = false

Definition at line 404 of file KisDocument.cpp.

◆ importExportManager

KisImportExportManager * KisDocument::importExportManager = 0

Definition at line 347 of file KisDocument.cpp.

◆ isAutosaving

bool KisDocument::isAutosaving = false

Definition at line 358 of file KisDocument.cpp.

◆ isRecovered

bool KisDocument::isRecovered = false

Definition at line 413 of file KisDocument.cpp.

◆ koShapeController

KoShapeController* KisDocument::koShapeController = 0

Definition at line 387 of file KisDocument.cpp.

◆ lastErrorMessage

QString KisDocument::lastErrorMessage

Definition at line 353 of file KisDocument.cpp.

◆ lastMod

QDateTime KisDocument::lastMod

Definition at line 378 of file KisDocument.cpp.

◆ lastWarningMessage

QString KisDocument::lastWarningMessage

Definition at line 354 of file KisDocument.cpp.

◆ linkedResourcesStorageID

QString KisDocument::linkedResourcesStorageID

Definition at line 421 of file KisDocument.cpp.

◆ linkedResourceStorage

KisResourceStorageSP KisDocument::linkedResourceStorage

Definition at line 422 of file KisDocument.cpp.

◆ m_bAutoDetectedMime

bool KisDocument::m_bAutoDetectedMime = false

Definition at line 367 of file KisDocument.cpp.

◆ m_file

QString KisDocument::m_file

Definition at line 369 of file KisDocument.cpp.

◆ m_path

QString KisDocument::m_path

Definition at line 368 of file KisDocument.cpp.

◆ m_storyboardCommentList

QVector<StoryboardComment> KisDocument::m_storyboardCommentList

Definition at line 394 of file KisDocument.cpp.

◆ m_storyboardItemList

StoryboardItemList KisDocument::m_storyboardItemList

Definition at line 393 of file KisDocument.cpp.

◆ mimeType

QByteArray KisDocument::mimeType

Definition at line 349 of file KisDocument.cpp.

◆ mirrorAxisConfig

const KisMirrorAxisConfig & KisDocument::mirrorAxisConfig

Definition at line 365 of file KisDocument.cpp.

◆ modified

bool KisDocument::modified = false

Definition at line 373 of file KisDocument.cpp.

◆ modifiedAfterAutosave

bool KisDocument::modifiedAfterAutosave = false

Definition at line 357 of file KisDocument.cpp.

◆ modifiedWhileSaving

bool KisDocument::modifiedWhileSaving = false

Definition at line 405 of file KisDocument.cpp.

◆ nserver

KisNameServer* KisDocument::nserver

Definition at line 380 of file KisDocument.cpp.

◆ outputMimeType

QByteArray KisDocument::outputMimeType

Definition at line 350 of file KisDocument.cpp.

◆ preActivatedNode

KisNodeSP KisDocument::preActivatedNode

Definition at line 385 of file KisDocument.cpp.

◆ q

KisDocument* KisDocument::q = 0

Definition at line 342 of file KisDocument.cpp.

◆ readwrite

bool KisDocument::readwrite = false

Definition at line 374 of file KisDocument.cpp.

◆ referenceLayerConnections

KisSignalAutoConnectionsStore KisDocument::referenceLayerConnections

Definition at line 411 of file KisDocument.cpp.

◆ savingImage

KisImageSP KisDocument::savingImage

Definition at line 383 of file KisDocument.cpp.

◆ savingMutex

QMutex KisDocument::savingMutex

Definition at line 371 of file KisDocument.cpp.

◆ savingUpdater

QPointer<KoUpdater> KisDocument::savingUpdater

Definition at line 407 of file KisDocument.cpp.

◆ shapeController

KoShapeControllerBase * KisDocument::shapeController = 0

Definition at line 386 of file KisDocument.cpp.

◆ undoStack

KUndo2Stack * KisDocument::undoStack = 0

Definition at line 362 of file KisDocument.cpp.

◆ unit

KoUnit KisDocument::unit

Definition at line 345 of file KisDocument.cpp.

◆ wasStorageAdded

bool KisDocument::wasStorageAdded = false

Definition at line 417 of file KisDocument.cpp.


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