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

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

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

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

2878{
2879 return d->globalAssistantsColor;
2880}

References d.

◆ autoSaveOnPause()

void KisDocument::autoSaveOnPause ( )

Start saving when android activity is pushed to the background.

Definition at line 2040 of file KisDocument.cpp.

2041{
2042 if (!d->modified || !d->modifiedAfterAutosave)
2043 return;
2044
2045 const QString autoSaveFileName = generateAutoSaveFileName(localFilePath());
2046
2047 bool started = exportDocumentSync(autoSaveFileName, nativeFormatMimeType());
2048
2049 if (started)
2050 {
2051 d->modifiedAfterAutosave = false;
2052 dbgAndroid << "autoSaveOnPause successful";
2053 }
2054 else
2055 {
2056 qWarning() << "Could not auto-save when paused";
2057 }
2058}
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 2155 of file KisDocument.cpp.

2156{
2157 QString c;
2158 const QString _url(QFileInfo(path()).fileName());
2159
2160 // if URL is empty...it is probably an unsaved file
2161 if (_url.isEmpty()) {
2162 c = " [" + i18n("Not Saved") + "] ";
2163 } else {
2164 c = _url; // Fall back to document URL
2165 }
2166
2167 return c;
2168}
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 2303 of file KisDocument.cpp.

2304{
2305 d->undoStack->clear();
2306}

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

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

References KisDocument().

◆ closePath()

bool KisDocument::closePath ( bool promptToSave = true)

Definition at line 2501 of file KisDocument.cpp.

2502{
2503 if (promptToSave) {
2504 if ( isReadWrite() && isModified()) {
2505 Q_FOREACH (KisView *view, KisPart::instance()->views()) {
2506 if (view && view->document() == this) {
2507 if (!view->queryClose()) {
2508 return false;
2509 }
2510 }
2511 }
2512 }
2513 }
2514 // Not modified => ok and delete temp file.
2515 d->mimeType = QByteArray();
2516
2517 // It always succeeds for a read-only part,
2518 // but the return value exists for reimplementations
2519 // (e.g. pressing cancel for a modified read-write part)
2520 return true;
2521}
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:1155

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

1195{
1197}

References copyFromDocumentImpl(), and REPLACE.

◆ copyFromDocumentImpl()

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

Definition at line 1199 of file KisDocument.cpp.

1200{
1201 if (policy == REPLACE) {
1202 d->decorationsSyncingDisabled = true;
1203 d->copyFrom(*(rhs.d), this);
1204 d->decorationsSyncingDisabled = false;
1205
1206 d->undoStack->clear();
1207 } else {
1208 // in CONSTRUCT mode, d should be already initialized
1209 connect(KisConfigNotifier::instance(), SIGNAL(configChanged()), SLOT(slotConfigChanged()));
1210 connect(d->undoStack, SIGNAL(cleanChanged(bool)), this, SLOT(slotUndoStackCleanChanged(bool)));
1211 connect(d->autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
1212
1213 d->shapeController = new KisShapeController(d->nserver, d->undoStack, this);
1214 d->koShapeController = new KoShapeController(0, d->shapeController);
1215 }
1216
1217 setObjectName(rhs.objectName());
1218
1220
1221 if (rhs.d->image) {
1222 if (policy == REPLACE) {
1223 d->image->barrierLock(/* readOnly = */ false);
1224 rhs.d->image->barrierLock(/* readOnly = */ true);
1225 d->image->copyFromImage(*(rhs.d->image));
1226 d->image->unlock();
1227 rhs.d->image->unlock();
1228
1229 setCurrentImage(d->image, /* forceInitialUpdate = */ true);
1230 } else {
1231 // clone the image with keeping the GUIDs of the layers intact
1232 // NOTE: we expect the image to be locked!
1233 setCurrentImage(rhs.image()->clone(/* exactCopy = */ true), /* forceInitialUpdate = */ false);
1234 }
1235 }
1236
1237 if (policy == REPLACE) {
1238 d->syncDecorationsWrapperLayerState();
1239 }
1240
1241 if (rhs.d->preActivatedNode) {
1242 QQueue<KisNodeSP> linearizedNodes;
1243 KisLayerUtils::recursiveApplyNodes(rhs.d->image->root(),
1244 [&linearizedNodes](KisNodeSP node) {
1245 linearizedNodes.enqueue(node);
1246 });
1248 [&linearizedNodes, &rhs, this](KisNodeSP node) {
1249 KisNodeSP refNode = linearizedNodes.dequeue();
1250 if (rhs.d->preActivatedNode.data() == refNode.data()) {
1251 d->preActivatedNode = node;
1252 }
1253 });
1254 }
1255
1256 // reinitialize references' signal connection
1257 KisReferenceImagesLayerSP referencesLayer = this->referenceImagesLayer();
1258 if (referencesLayer) {
1259 d->referenceLayerConnections.clear();
1260 d->referenceLayerConnections.addConnection(
1261 referencesLayer, SIGNAL(sigUpdateCanvas(QRectF)),
1262 this, SIGNAL(sigReferenceImagesChanged()));
1263
1264 Q_EMIT sigReferenceImagesLayerChanged(referencesLayer);
1266 }
1267
1268 KisDecorationsWrapperLayerSP decorationsLayer =
1269 KisLayerUtils::findNodeByType<KisDecorationsWrapperLayer>(d->image->root());
1270 if (decorationsLayer) {
1271 decorationsLayer->setDocument(this);
1272 }
1273
1274
1275 if (policy == REPLACE) {
1276 setModified(true);
1277 }
1278}
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 2486 of file KisDocument.cpp.

2487{
2488 return new KoDocumentInfoDlg(parent, docInfo);
2489}
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 2176 of file KisDocument.cpp.

2177{
2178 QDomImplementation impl;
2179 QString url = QString("http://www.calligra.org/DTD/%1-%2.dtd").arg(appName).arg(version);
2180 QDomDocumentType dtype = impl.createDocumentType(tagName,
2181 QString("-//KDE//DTD %1 %2//EN").arg(appName).arg(version),
2182 url);
2183 // The namespace URN doesn't need to include the version number.
2184 QString namespaceURN = QString("http://www.calligra.org/DTD/%1").arg(appName);
2185 QDomDocument doc = impl.createDocument(namespaceURN, tagName, dtype);
2186 doc.insertBefore(doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""), doc.documentElement());
2187 return doc;
2188}

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

2171{
2172 return createDomDocument("krita", tagName, version);
2173}
QDomDocument createDomDocument(const QString &tagName, const QString &version) const

References createDomDocument().

◆ createUndoStore()

KisUndoStore * KisDocument::createUndoStore ( )

Definition at line 2857 of file KisDocument.cpp.

2858{
2859 return new KisDocumentUndoStore(this);
2860}

◆ documentBounds()

QRectF KisDocument::documentBounds ( ) const

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

Definition at line 2887 of file KisDocument.cpp.

2888{
2889 QRectF bounds = d->image->bounds();
2890
2892
2893 if (referenceImagesLayer) {
2895 }
2896
2897 return bounds;
2898}
#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 1780 of file KisDocument.cpp.

1781{
1782 return d->docInfo;
1783}

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

723{
724 return d->embeddedResourcesStorageID;
725}

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

2203{
2204 return d->lastErrorMessage;
2205}

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

881{
882 using namespace KritaUtils;
883
884 SaveFlags flags = SaveIsExporting;
885 if (showWarnings) {
886 flags |= SaveShowWarnings;
887 }
888
889 KisUsageLogger::log(QString("Exporting Document: %1 as %2. %3 * %4 pixels, %5 layers, %6 frames, %7 "
890 "framerate. Export configuration: %8")
891 .arg(path, QString::fromLatin1(mimeType), QString::number(d->image->width()),
892 QString::number(d->image->height()), QString::number(d->image->nlayers()),
893 QString::number(d->image->animationInterface()->totalLength()),
894 QString::number(d->image->animationInterface()->framerate()),
895 (exportConfiguration ? exportConfiguration->toXML() : "No configuration")));
896
898 mimeType,
899 flags),
900 exportConfiguration, isAdvancedExporting);
901}
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 737 of file KisDocument.cpp.

738{
739 QFileInfo filePathInfo(job.filePath);
740
741 if (filePathInfo.exists() && !filePathInfo.isWritable()) {
743 i18n("%1 cannot be written to. Please save under a different name.", job.filePath),
744 "");
745 return false;
746 }
747
748 KisConfig cfg(true);
749 if (cfg.backupFile() && filePathInfo.exists()) {
750
751 QString backupDir;
752
753 switch(cfg.readEntry<int>("backupfilelocation", 0)) {
754 case 1:
755 backupDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
756 break;
757 case 2:
758 backupDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
759 break;
760 default:
761#ifdef Q_OS_ANDROID
762 // We deal with URIs, there may or may not be a "directory"
764 QDir().mkpath(backupDir);
765#endif
766
767#ifdef Q_OS_MACOS
769 if (bookmarkmngr->isSandboxed()) {
770 // If the user does not have directory permission force backup
771 // files to be inside Container tmp
772 QUrl fileUrl = QUrl::fromLocalFile(job.filePath);
773 if( !bookmarkmngr->parentDirHasPermissions(fileUrl.path()) ) {
774 backupDir = QDir::tempPath();
775 }
776 }
777#endif
778
779 // Do nothing: the empty string is user file location
780 break;
781 }
782
783 int numOfBackupsKept = cfg.readEntry<int>("numberofbackupfiles", 1);
784 QString suffix = cfg.readEntry<QString>("backupfilesuffix", "~");
785
786 if (numOfBackupsKept == 1) {
787 if (!KisBackup::simpleBackupFile(job.filePath, backupDir, suffix)) {
788 qWarning() << "Failed to create simple backup file!" << job.filePath << backupDir << suffix;
789 KisUsageLogger::log(QString("Failed to create a simple backup for %1 in %2.")
790 .arg(job.filePath, backupDir.isEmpty()
791 ? "the same location as the file"
792 : backupDir));
793 slotCompleteSavingDocument(job, ImportExportCodes::ErrorWhileWriting, i18nc("Saving error message", "Failed to create a backup file"), "");
794 return false;
795 }
796 else {
797 KisUsageLogger::log(QString("Create a simple backup for %1 in %2.")
798 .arg(job.filePath, backupDir.isEmpty()
799 ? "the same location as the file"
800 : backupDir));
801 }
802 }
803 else if (numOfBackupsKept > 1) {
804 if (!KisBackup::numberedBackupFile(job.filePath, backupDir, suffix, numOfBackupsKept)) {
805 qWarning() << "Failed to create numbered backup file!" << job.filePath << backupDir << suffix;
806 KisUsageLogger::log(QString("Failed to create a numbered backup for %2.")
807 .arg(job.filePath, backupDir.isEmpty()
808 ? "the same location as the file"
809 : backupDir));
810 slotCompleteSavingDocument(job, ImportExportCodes::ErrorWhileWriting, i18nc("Saving error message", "Failed to create a numbered backup file"), "");
811 return false;
812 }
813 else {
814 KisUsageLogger::log(QString("Create a simple backup for %1 in %2.")
815 .arg(job.filePath, backupDir.isEmpty()
816 ? "the same location as the file"
817 : backupDir));
818 }
819 }
820 }
821
822 //KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(!job.mimeType.isEmpty(), false);
823 if (job.mimeType.isEmpty()) {
825 slotCompleteSavingDocument(job, error, error.errorMessage(), "");
826 return false;
827
828 }
829
830 const QString actionName =
832 i18n("Exporting Document...") :
833 i18n("Saving Document...");
834
838 job, exportConfiguration, isAdvancedExporting);
839
841 QString errorShortLog;
842 QString errorMessage;
844
845 switch (result) {
847 errorShortLog = "another save operation is in progress";
848 errorMessage = i18n("Could not start saving %1. Wait until the current save operation has finished.", job.filePath);
849 errorCode = ImportExportCodes::Failure;
850 break;
852 errorShortLog = "failed to lock and clone the image";
853 errorMessage = i18n("Could not start saving %1. Image is busy", job.filePath);
854 errorCode = ImportExportCodes::Busy;
855 break;
857 errorShortLog = "failed to start background saving";
858 errorMessage = i18n("Could not start saving %1. Unknown failure has happened", job.filePath);
859 errorCode = ImportExportCodes::Failure;
860 break;
863 break;
865 // noop, not possible
866 break;
867 }
868
869 KisUsageLogger::log(QString("Failed to initiate saving %1 in background: %2").arg(job.filePath).arg(errorShortLog));
870
871 slotCompleteSavingDocument(job, errorCode,
873 "");
874 return false;
875 }
876
878}
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 1280 of file KisDocument.cpp.

1281{
1282 {
1289 Private::StrippedSafeSavingLocker locker(&d->savingMutex, d->image);
1290 if (!locker.successfullyLocked()) {
1291 return false;
1292 }
1293 }
1294
1295 d->savingImage = d->image;
1296
1298 d->importExportManager->
1299 exportDocument(path, path, mimeType, false, exportConfiguration);
1300
1301 d->savingImage = 0;
1302
1303 return status.isOk();
1304}
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 2867 of file KisDocument.cpp.

2868{
2869 return errorMessage.isEmpty() ? status.errorMessage() : errorMessage;
2870}

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

1090{
1091 return d->batchMode;
1092}

References d.

◆ finishExportInBackground

void KisDocument::finishExportInBackground ( )
privateslot

Definition at line 1696 of file KisDocument.cpp.

1697{
1698 KIS_SAFE_ASSERT_RECOVER(d->childSavingFuture.isFinished()) {
1700 return;
1701 }
1702
1703 KisImportExportErrorCode status = d->childSavingFuture.result();
1704 QString errorMessage = status.errorMessage();
1705 QString warningMessage = d->lastWarningMessage;
1706
1707 if (!d->lastErrorMessage.isEmpty()) {
1709 errorMessage = d->lastErrorMessage;
1710 } else {
1711 errorMessage += "\n" + d->lastErrorMessage;
1712 }
1713 }
1714
1715 d->savingImage.clear();
1716 d->childSavingFuture = QFuture<KisImportExportErrorCode>();
1717 d->lastErrorMessage.clear();
1718 d->lastWarningMessage.clear();
1719
1720 if (d->savingUpdater) {
1721 d->savingUpdater->setProgress(100);
1722 }
1723
1725}
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 1833 of file KisDocument.cpp.

1834{
1835 QString retval;
1836
1837 // Using the extension allows to avoid relying on the mime magic when opening
1838 const QString extension (".kra");
1839 QString prefix = KisConfig(true).readEntry<bool>("autosavefileshidden") ? QString(".") : QString();
1840 QRegularExpression autosavePattern1("^\\..+-autosave.kra$");
1841 QRegularExpression autosavePattern2("^.+-autosave.kra$");
1842
1843 QFileInfo fi(path);
1844 QString dir = fi.absolutePath();
1845
1846#ifdef Q_OS_ANDROID
1847 // URIs may or may not have a directory backing them, so we save to our default autosave location
1848 if (path.startsWith("content://")) {
1850 QDir().mkpath(dir);
1851 }
1852#endif
1853
1854 QString filename = fi.fileName();
1855
1856 if (path.isEmpty() || autosavePattern1.match(filename).hasMatch() || autosavePattern2.match(filename).hasMatch() || !fi.isWritable()) {
1857 // Never saved?
1858 retval = QString("%1%2%3%4-%5-%6-autosave%7")
1860 .arg('/')
1861 .arg(prefix)
1862 .arg("krita")
1863 .arg(qApp->applicationPid())
1864 .arg(objectName())
1865 .arg(extension);
1866 } else {
1867 // Beware: don't reorder arguments
1868 // otherwise in case of filename = '1-file.kra' it will become '.-file.kra-autosave.kra' instead of '.1-file.kra-autosave.kra'
1869 retval = QString("%1%2%3%4-autosave%5").arg(dir).arg('/').arg(prefix).arg(filename).arg(extension);
1870 }
1871
1872 //qDebug() << "generateAutoSaveFileName() for path" << path << ":" << retval;
1873 return retval;
1874}
T readEntry(const QString &name, const T &defaultValue=T())
Definition kis_config.h:819

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

1791{
1792 KisImageSP image = d->image;
1793 if (d->savingImage) image = d->savingImage;
1794
1795 if (image) {
1796 QRect bounds = image->bounds();
1797 QSize originalSize = bounds.size();
1798 // QSize may round down one dimension to zero on extreme aspect rations, so ensure 1px minimum
1799 QSize newSize = originalSize.scaled(size, Qt::KeepAspectRatio).expandedTo({1, 1});
1800
1801 bool pixelArt = false;
1802 // determine if the image is pixel art or not
1803 if (originalSize.width() < size.width() && originalSize.height() < size.height()) {
1804 // the image must be smaller than the requested preview
1805 // the scale must be integer
1806 if (newSize.height()%originalSize.height() == 0 && newSize.width()%originalSize.width() == 0) {
1807 pixelArt = true;
1808 }
1809 }
1810
1811 QPixmap px;
1812 if (pixelArt) {
1813 // do not scale while converting (because it uses Bicubic)
1814 QImage original = image->convertToQImage(originalSize, 0);
1815 // scale using FastTransformation, which is probably Nearest neighbour, suitable for pixel art
1816 QImage scaled = original.scaled(newSize, Qt::KeepAspectRatio, Qt::FastTransformation);
1817 px = QPixmap::fromImage(scaled);
1818 } else {
1819 px = QPixmap::fromImage(image->convertToQImage(newSize, 0));
1820 }
1821 if (px.size() == QSize(0,0)) {
1822 px = QPixmap(newSize);
1823 QPainter gc(&px);
1824 QBrush checkBrush = QBrush(KisCanvasWidgetBase::createCheckersImage(newSize.width() / 5));
1825 gc.fillRect(px.rect(), checkBrush);
1826 gc.end();
1827 }
1828 return px;
1829 }
1830 return QPixmap(size);
1831}
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 2440 of file KisDocument.cpp.

2441{
2442 return d->audioLevel;
2443}

References d.

◆ getAudioTracks()

QVector< QFileInfo > KisDocument::getAudioTracks ( ) const

Definition at line 2424 of file KisDocument.cpp.

2424 {
2425 return d->audioTracks;
2426}

References d.

◆ getStoryboardCommentsList()

QVector< StoryboardComment > KisDocument::getStoryboardCommentsList ( )

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

Definition at line 2411 of file KisDocument.cpp.

2412{
2413 return d->m_storyboardCommentList;
2414}

References d.

◆ getStoryboardItemList()

StoryboardItemList KisDocument::getStoryboardItemList ( )

returns the list of pointers to storyboard Items for the document

Definition at line 2398 of file KisDocument.cpp.

2399{
2400 return d->m_storyboardItemList;
2401}

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

2835{
2837
2838 // we set image without connecting idle-watcher, because loading
2839 // hasn't been finished yet
2840 d->image = image;
2841 d->shapeController->setImage(image);
2842}
#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 1876 of file KisDocument.cpp.

1877{
1878 bool ret;
1879
1880 dbgUI << "path=" << _path;
1881
1882 // open...
1883 ret = openPath(_path);
1884
1885 // reset url & m_file (kindly? set by KisParts::openUrl()) to simulate a
1886 // File --> Import
1887 if (ret) {
1888 dbgUI << "success, resetting url";
1889 resetPath();
1890 }
1891
1892 return ret;
1893}
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 1307 of file KisDocument.cpp.

1311{
1312 return initiateSavingInBackground(actionName, receiverObject, receiverMethod,
1313 job, exportConfiguration, std::unique_ptr<KisDocument>(), isAdvancedExporting);
1314}

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

1321{
1323
1324 QScopedPointer<KisDocument> clonedDocument;
1325
1326 if (!optionalClonedDocument) {
1327 clonedDocument.reset(lockAndCloneForSaving());
1328 } else {
1329 clonedDocument.reset(optionalClonedDocument.release());
1330 }
1331
1332 if (!d->savingMutex.tryLock()){
1334 }
1335
1340 std::unique_lock<QMutex> savingMutexLock(d->savingMutex, std::adopt_lock);
1341
1342 if (!clonedDocument) {
1344 }
1345
1346 auto waitForImage = [] (KisImageSP image) {
1348 if (window) {
1349 if (window->viewManager()) {
1351 }
1352 }
1353 };
1354
1355 {
1356 KisNodeSP newRoot = clonedDocument->image()->root();
1359 waitForImage(clonedDocument->image());
1360 }
1361 }
1362
1363 if (clonedDocument->image()->hasOverlaySelectionMask()) {
1364 clonedDocument->image()->setOverlaySelectionMask(0);
1365 waitForImage(clonedDocument->image());
1366 }
1367
1368 KisConfig cfg(true);
1369 if (cfg.trimKra()) {
1370 clonedDocument->image()->cropImage(clonedDocument->image()->bounds());
1371 clonedDocument->image()->purgeUnusedData(false);
1372 waitForImage(clonedDocument->image());
1373 }
1374
1375 KIS_SAFE_ASSERT_RECOVER(clonedDocument->image()->isIdle()) {
1376 waitForImage(clonedDocument->image());
1377 }
1378
1381
1391 savingMutexLock.release();
1392
1393 d->backgroundSaveDocument.reset(clonedDocument.take());
1394 d->backgroundSaveJob = job;
1395 d->modifiedWhileSaving = false;
1396
1397 if (d->backgroundSaveJob.flags & KritaUtils::SaveInAutosaveMode) {
1398 d->backgroundSaveDocument->d->isAutosaving = true;
1399 }
1400
1401 connect(d->backgroundSaveDocument.data(),
1402 SIGNAL(sigBackgroundSavingFinished(KisImportExportErrorCode, QString, QString)),
1403 this,
1405
1406
1407 connect(this, SIGNAL(sigCompleteBackgroundSaving(KritaUtils::ExportFileJob, KisImportExportErrorCode, QString, QString)),
1408 receiverObject, receiverMethod, Qt::UniqueConnection);
1409
1411 d->backgroundSaveDocument->startExportInBackground(actionName,
1412 job.filePath,
1413 job.filePath,
1414 job.mimeType,
1416 exportConfiguration, isAdvancedExporting);
1417 if (!error.isOk()) {
1418 // the state should have been deinitialized in slotChildCompletedSavingInBackground()
1419 KIS_SAFE_ASSERT_RECOVER (!d->backgroundSaveDocument && !d->backgroundSaveJob.isValid()) {
1420 d->backgroundSaveDocument.take()->deleteLater();
1421 d->savingMutex.unlock();
1422 d->backgroundSaveJob = KritaUtils::ExportFileJob();
1423 }
1424 if (error.isCancelled()) {
1426 }
1428 }
1429
1431}
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 1775 of file KisDocument.cpp.

1776{
1777 return d->autoSaveActive;
1778}

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

1786{
1787 return d->modified;
1788}

References d.

◆ isNativeFormat()

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

Checks whether a given mimeType can be handled natively.

Definition at line 2190 of file KisDocument.cpp.

2191{
2193 return true;
2194 return extraNativeMimeTypes().contains(mimeType);
2195}
static QStringList extraNativeMimeTypes()

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

◆ isReadWrite()

bool KisDocument::isReadWrite ( ) const

Definition at line 2491 of file KisDocument.cpp.

2492{
2493 return d->readwrite;
2494}

References d.

◆ isRecovered()

bool KisDocument::isRecovered ( ) const

◆ isSaving()

bool KisDocument::isSaving ( ) const

Definition at line 2698 of file KisDocument.cpp.

2699{
2700 const bool result = d->savingMutex.tryLock();
2701 if (result) {
2702 d->savingMutex.unlock();
2703 }
2704 return !result;
2705}

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

2327{
2329 if (!d->linkedResourceStorage) {
2330 return result;
2331 }
2332
2333 Q_FOREACH(const QString &resourceType, KisResourceLoaderRegistry::instance()->resourceTypes()) {
2334 QSharedPointer<KisResourceStorage::ResourceIterator> iter = d->linkedResourceStorage->resources(resourceType);
2335 while (iter->hasNext()) {
2336 iter->next();
2337
2338 QBuffer buf;
2339 buf.open(QBuffer::WriteOnly);
2340 bool exportSuccessful =
2341 d->linkedResourceStorage->exportResource(iter->url(), &buf);
2342
2343 KoResourceSP resource = d->linkedResourceStorage->resource(iter->url());
2344 exportSuccessful &= bool(resource);
2345
2346 const QString name = resource ? resource->name() : QString();
2347 const QString fileName = QFileInfo(iter->url()).fileName();
2348 const KoResourceSignature signature(resourceType,
2349 KoMD5Generator::generateHash(buf.data()),
2350 fileName, name);
2351
2352 if (exportSuccessful) {
2353 result << KoEmbeddedResource(signature, buf.data());
2354 } else {
2355 result << signature;
2356 }
2357 }
2358 }
2359
2360 return result;
2361}
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 727 of file KisDocument.cpp.

728{
729 return d->linkedResourcesStorageID;
730}

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

2069{
2070 return openPath(file_);
2071}

References openPath().

◆ localFilePath()

QString KisDocument::localFilePath ( ) const

Definition at line 2536 of file KisDocument.cpp.

2537{
2538 return d->m_file;
2539}

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

1185{
1186 return d->lockAndCloneImpl(true);
1187}

References d.

◆ lockAndCloneImpl()

KisDocument * KisDocument::lockAndCloneImpl ( bool fetchResourcesFromLayers)

◆ lockAndCreateSnapshot()

KisDocument * KisDocument::lockAndCreateSnapshot ( )

Definition at line 1189 of file KisDocument.cpp.

1190{
1191 return d->lockAndCloneImpl(false);
1192}

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

2599{
2600 Q_ASSERT(cs);
2601
2603
2604 if (!cs) return false;
2605
2606 KisCursorOverrideLock cursorLock(Qt::BusyCursor);
2607
2608 image = new KisImage(createUndoStore(), width, height, cs, name);
2609
2610 Q_CHECK_PTR(image);
2611
2612 connect(image, SIGNAL(sigImageModified()), this, SLOT(setImageModified()), Qt::UniqueConnection);
2613 connect(image, SIGNAL(sigImageModifiedWithoutUndo()), this, SLOT(setImageModifiedWithoutUndo()), Qt::UniqueConnection);
2614 image->setResolution(imageResolution, imageResolution);
2615
2617 image->waitForDone();
2618
2619 documentInfo()->setAboutInfo("title", name);
2620 documentInfo()->setAboutInfo("abstract", description);
2621
2622 KisConfig cfg(false);
2623 cfg.defImageWidth(width);
2624 cfg.defImageHeight(height);
2625 cfg.defImageResolution(imageResolution);
2626 if (!cfg.useDefaultColorSpace())
2627 {
2628 cfg.defColorModel(image->colorSpace()->colorModelId().id());
2629 cfg.setDefaultColorDepth(image->colorSpace()->colorDepthId().id());
2630 cfg.defColorProfile(image->colorSpace()->profile()->name());
2631 }
2632
2633 bool autopin = cfg.autoPinLayersToTimeline();
2634
2635 KisLayerSP bgLayer;
2636 if (bgStyle == KisConfig::RASTER_LAYER || bgStyle == KisConfig::FILL_LAYER) {
2637 KoColor strippedAlpha = bgColor;
2638 strippedAlpha.setOpacity(OPACITY_OPAQUE_U8);
2639
2640 if (bgStyle == KisConfig::RASTER_LAYER) {
2641 bgLayer = new KisPaintLayer(image.data(), i18nc("Name for the bottom-most layer in the layerstack", "Background"), OPACITY_OPAQUE_U8, cs);
2642 bgLayer->paintDevice()->setDefaultPixel(strippedAlpha);
2643 bgLayer->setPinnedToTimeline(autopin);
2644 } else if (bgStyle == KisConfig::FILL_LAYER) {
2646 filter_config->setProperty("color", strippedAlpha.toQColor());
2647 filter_config->createLocalResourcesSnapshot();
2648 bgLayer = new KisGeneratorLayer(image.data(), i18nc("Name of automatically created background color fill layer", "Background Fill"), filter_config, image->globalSelection());
2649 }
2650
2651 bgLayer->setOpacity(bgColor.opacityU8());
2652
2653 if (numberOfLayers > 1) {
2654 //Lock bg layer if others are present.
2655 bgLayer->setUserLocked(true);
2656 }
2657 }
2658 else { // KisConfig::CANVAS_COLOR (needs an unlocked starting layer).
2660 bgLayer = new KisPaintLayer(image.data(), image->nextLayerName(), OPACITY_OPAQUE_U8, cs);
2661 }
2662
2663 Q_CHECK_PTR(bgLayer);
2664 image->addNode(bgLayer.data(), image->rootLayer().data());
2665 bgLayer->setDirty(QRect(0, 0, width, height));
2666
2667 // reset mirror axis to default:
2668 d->mirrorAxisConfig.setAxisPosition(QRectF(image->bounds()).center());
2670
2671 for(int i = 1; i < numberOfLayers; ++i) {
2673 layer->setPinnedToTimeline(autopin);
2674 image->addNode(layer, image->root(), i);
2675 layer->setDirty(QRect(0, 0, width, height));
2676 }
2677
2678 {
2680 if (window) {
2685 }
2686 }
2687
2689 QString("Created image \"%1\", %2 * %3 pixels, %4 dpi. Color model: %6 %5 (%7). Layers: %8")
2690 .arg(name, QString::number(width), QString::number(height),
2691 QString::number(imageResolution * 72.0), image->colorSpace()->colorModelId().name(),
2693 QString::number(numberOfLayers)));
2694
2695 return true;
2696}
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 1965 of file KisDocument.cpp.

1966{
1967 //dbgUI <<"for" << localFilePath();
1968 if (!QFile::exists(localFilePath()) && !fileBatchMode()) {
1969 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"), i18n("File %1 does not exist.", localFilePath()));
1970 return false;
1971 }
1972
1973 QString filename = localFilePath();
1974 QString typeName = mimeType();
1975
1976 if (typeName.isEmpty()) {
1977 typeName = KisMimeDatabase::mimeTypeForFile(filename);
1978 }
1979
1980 // Allow to open backup files, don't keep the mimeType application/x-trash.
1981 if (typeName == "application/x-trash") {
1982 QString path = filename;
1983 while (path.length() > 0) {
1984 path.chop(1);
1985 typeName = KisMimeDatabase::mimeTypeForFile(path);
1986 //qDebug() << "\t" << path << typeName;
1987 if (!typeName.isEmpty()) {
1988 break;
1989 }
1990 }
1991 //qDebug() << "chopped" << filename << "to" << path << "Was trash, is" << typeName;
1992 }
1993 dbgUI << localFilePath() << "type:" << typeName;
1994
1996 KoUpdaterPtr updater;
1997 if (window && window->viewManager()) {
1998 updater = window->viewManager()->createUnthreadedUpdater(i18n("Opening document"));
1999 d->importExportManager->setUpdater(updater);
2000 }
2001
2002 KisImportExportErrorCode status = d->importExportManager->importDocument(localFilePath(), typeName);
2003
2004 if (!status.isOk()) {
2005 if (window && window->viewManager()) {
2006 updater->cancel();
2007 }
2008 QString msg = status.errorMessage();
2009 KisUsageLogger::log(QString("Loading %1 failed: %2").arg(prettyPath(), msg));
2010
2011 if (!msg.isEmpty() && !fileBatchMode()) {
2012 DlgLoadMessages dlg(i18nc("@title:window", "Krita"),
2013 i18n("Could not open %1.", prettyPath()),
2014 errorMessage().split("\n", Qt::SkipEmptyParts)
2015 + warningMessage().split("\n", Qt::SkipEmptyParts),
2016 msg);
2017
2018 dlg.exec();
2019 }
2020 return false;
2021 }
2022 else if (!warningMessage().isEmpty() && !fileBatchMode()) {
2023 DlgLoadMessages dlg(i18nc("@title:window", "Krita"),
2024 i18n("There were problems opening %1.", prettyPath()),
2025 warningMessage().split("\n", Qt::SkipEmptyParts));
2026
2027 dlg.exec();
2028 setPath(QString());
2029 }
2030
2031 setMimeTypeAfterLoading(typeName);
2032 d->syncDecorationsWrapperLayerState();
2033 Q_EMIT sigLoadingFinished();
2034
2035 undoStack()->clear();
2036
2037 return true;
2038}
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 1896 of file KisDocument.cpp.

1897{
1898 dbgUI << "path=" << _path;
1899 d->lastErrorMessage.clear();
1900
1901 // Reimplemented, to add a check for autosave files and to improve error reporting
1902 if (_path.isEmpty()) {
1903 d->lastErrorMessage = i18n("Malformed Path\n%1", _path); // ## used anywhere ?
1904 return false;
1905 }
1906
1907 QString path = _path;
1908 QString original = "";
1909 bool autosaveOpened = false;
1910 if (!fileBatchMode()) {
1911 QString file = path;
1912 QString asf = generateAutoSaveFileName(file);
1913 if (QFile::exists(asf)) {
1914 KisApplication *kisApp = static_cast<KisApplication*>(qApp);
1915 kisApp->hideSplashScreen();
1916 //qDebug() <<"asf=" << asf;
1917 // ## TODO compare timestamps ?
1918 KisRecoverNamedAutosaveDialog dlg(0, file, asf);
1919 dlg.exec();
1920 int res = dlg.result();
1921
1922 switch (res) {
1924 original = file;
1925 path = asf;
1926 autosaveOpened = true;
1927 break;
1929 KisUsageLogger::log(QString("Removing autosave file: %1").arg(asf));
1930 QFile::remove(asf);
1931 break;
1932 default: // Cancel
1933 return false;
1934 }
1935 }
1936 }
1937
1938 bool ret = openPathInternal(path);
1939
1940 if (autosaveOpened || flags & RecoveryFile) {
1941 setReadWrite(true); // enable save button
1942 setModified(true);
1943 setRecovered(true);
1944
1945 setPath(original); // since it was an autosave, it will be a local file
1946 setLocalFilePath(original);
1947 }
1948 else {
1949 if (ret) {
1950
1951 if (!(flags & DontAddToRecent)) {
1952 KisPart::instance()->addRecentURLToAllMainWindows(QUrl::fromLocalFile(_path));
1953 }
1954
1955 QFileInfo fi(_path);
1956 setReadWrite(fi.isWritable());
1957 }
1958
1959 setRecovered(false);
1960 }
1961
1962 return ret;
1963}
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 2547 of file KisDocument.cpp.

2548{
2549 if ( path.isEmpty() ) {
2550 return false;
2551 }
2552
2553 if (d->m_bAutoDetectedMime) {
2554 d->mimeType = QByteArray();
2555 d->m_bAutoDetectedMime = false;
2556 }
2557
2558 QByteArray mimeType = d->mimeType;
2559
2560 if ( !closePath() ) {
2561 return false;
2562 }
2563
2564 d->mimeType = mimeType;
2565 setPath(path);
2566
2567 d->m_file.clear();
2568
2569 d->m_file = d->m_path;
2570
2571 bool ret = false;
2572 // set the mimeType only if it was not already set (for example, by the host application)
2573 if (d->mimeType.isEmpty()) {
2574 // get the mimeType of the file
2575 // using findByUrl() to avoid another string -> url conversion
2576 QString mime = KisMimeDatabase::mimeTypeForFile(d->m_path);
2577 d->mimeType = mime.toLocal8Bit();
2578 d->m_bAutoDetectedMime = true;
2579 }
2580
2581 setPath(d->m_path);
2582 ret = openFile();
2583
2584 if (ret) {
2585 Q_EMIT completed();
2586 }
2587 else {
2588 Q_EMIT canceled(QString());
2589 }
2590 return ret;
2591}
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 2496 of file KisDocument.cpp.

2497{
2498 return d->m_path;
2499}

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

2146{
2147 QString _url(path());
2148#ifdef Q_OS_WIN
2149 _url = QDir::toNativeSeparators(_url);
2150#endif
2151 return _url;
2152}

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 , colorHistory(rhs.colorHistory)
329 , nserver(new KisNameServer(*rhs.nserver))
330 , preActivatedNode(0) // the node is from another hierarchy!
331 , imageIdleWatcher(2000 /*ms*/)
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 2739 of file KisDocument.cpp.

2740{
2741 if (!d->image) return KisReferenceImagesLayerSP();
2742
2743 KisReferenceImagesLayerSP referencesLayer =
2744 KisLayerUtils::findNodeByType<KisReferenceImagesLayer>(d->image->root());
2745
2746 return referencesLayer;
2747}
KisSharedPtr< KisReferenceImagesLayer > KisReferenceImagesLayerSP

References d.

◆ removeAutoSaveFiles()

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

Performs a cleanup of unneeded backup files

Definition at line 2218 of file KisDocument.cpp.

2219{
2220 // Eliminate any auto-save file
2221 QString asf = generateAutoSaveFileName(autosaveBaseName); // the one in the current dir
2222 if (QFile::exists(asf)) {
2223 KisUsageLogger::log(QString("Removing autosave file: %1").arg(asf));
2224 QFile::remove(asf);
2225 }
2226 asf = generateAutoSaveFileName(QString()); // and the one in $HOME
2227
2228 if (QFile::exists(asf)) {
2229 KisUsageLogger::log(QString("Removing autosave file: %1").arg(asf));
2230 QFile::remove(asf);
2231 }
2232
2233 QList<QRegularExpression> expressions;
2234
2235 expressions << QRegularExpression("^\\..+-autosave.kra$")
2236 << QRegularExpression("^.+-autosave.kra$");
2237
2238 Q_FOREACH(const QRegularExpression &rex, expressions) {
2239 if (wasRecovered &&
2240 !autosaveBaseName.isEmpty() &&
2241 rex.match(QFileInfo(autosaveBaseName).fileName()).hasMatch() &&
2242 QFile::exists(autosaveBaseName)) {
2243
2244 KisUsageLogger::log(QString("Removing autosave file: %1").arg(autosaveBaseName));
2245 QFile::remove(autosaveBaseName);
2246 }
2247 }
2248}

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

2481 {
2482 setPath(QString());
2483 setLocalFilePath(QString());
2484}

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

1514{
1515 if (QFileInfo(path).absolutePath().startsWith(KisResourceLocator::instance()->resourceLocationBase())) {
1516
1517 QStringList pathParts = QFileInfo(path).absolutePath().split('/');
1518 if (pathParts.size() > 0) {
1519 QString resourceType = pathParts.last();
1520 if (KisResourceLoaderRegistry::instance()->resourceTypes().contains(resourceType)) {
1521
1522 KisResourceModel model(resourceType);
1523 model.setResourceFilter(KisResourceModel::ShowAllResources);
1524
1525 QString tempFileName = QDir::tempPath() + "/" + QFileInfo(path).fileName();
1526
1527 if (QFileInfo(path).exists()) {
1528
1529 int outResourceId;
1530 KoResourceSP res;
1531 if (KisResourceCacheDb::getResourceIdFromVersionedFilename(QFileInfo(path).fileName(), resourceType, "", outResourceId)) {
1532 res = model.resourceForId(outResourceId);
1533 }
1534
1535 if (res) {
1536 d->modifiedWhileSaving = false;
1537
1538 if (!exportConfiguration) {
1539 QScopedPointer<KisImportExportFilter> filter(
1541 if (filter) {
1542 exportConfiguration = filter->defaultConfiguration(nativeFormatMimeType(), mimeType);
1543 }
1544 }
1545
1546 if (exportConfiguration) {
1547 // make sure the name of the resource doesn't change
1548 exportConfiguration->setProperty("name", res->name());
1549 }
1550
1551 if (exportDocumentSync(tempFileName, mimeType, exportConfiguration)) {
1552 QFile f2(tempFileName);
1553 f2.open(QFile::ReadOnly);
1554
1555 QByteArray ba = f2.readAll();
1556
1557 QBuffer buf(&ba);
1558 buf.open(QBuffer::ReadOnly);
1559
1560
1561
1562 if (res->loadFromDevice(&buf, KisGlobalResourcesInterface::instance())) {
1563 if (model.updateResource(res)) {
1564 const QString filePath =
1566
1567 d->updateDocumentMetadataOnSaving(filePath, mimeType);
1568
1569 return true;
1570 }
1571 }
1572 }
1573 }
1574 }
1575 else {
1576 d->modifiedWhileSaving = false;
1577 if (exportDocumentSync(tempFileName, mimeType, exportConfiguration)) {
1578 KoResourceSP res = model.importResourceFile(tempFileName, false);
1579 if (res) {
1580 const QString filePath =
1582
1583 d->updateDocumentMetadataOnSaving(filePath, mimeType);
1584
1585 return true;
1586 }
1587 }
1588 }
1589 }
1590 }
1591 }
1592 return false;
1593}
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 927 of file KisDocument.cpp.

928{
929 return saveAs(path(), mimeType(), showWarnings, exportConfiguration);
930}
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 903 of file KisDocument.cpp.

904{
905 using namespace KritaUtils;
906
907 KisUsageLogger::log(QString("Saving Document %9 as %1 (mime: %2). %3 * %4 pixels, %5 layers. %6 frames, "
908 "%7 framerate. Export configuration: %8")
909 .arg(_path, QString::fromLatin1(mimeType), QString::number(d->image->width()),
910 QString::number(d->image->height()), QString::number(d->image->nlayers()),
911 QString::number(d->image->animationInterface()->totalLength()),
912 QString::number(d->image->animationInterface()->framerate()),
913 (exportConfiguration ? exportConfiguration->toXML() : "No configuration"),
914 path()));
915
916 // Check whether it's an existing resource were are saving to
917 if (resourceSavingFilter(_path, mimeType, exportConfiguration)) {
918 return true;
919 }
920
922 mimeType,
923 showWarnings ? SaveShowWarnings : SaveNone),
924 exportConfiguration);
925}
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 932 of file KisDocument.cpp.

933{
934 QBuffer buffer;
935
937 filter->setBatchMode(true);
938 filter->setMimeType(nativeFormatMimeType());
939
940 Private::StrippedSafeSavingLocker locker(&d->savingMutex, d->image);
941 if (!locker.successfullyLocked()) {
942 return buffer.data();
943 }
944
945 d->savingImage = d->image;
946
947 if (!filter->convert(this, &buffer).isOk()) {
948 qWarning() << "serializeToByteArray():: Could not export to our native format";
949 }
950
951 return buffer.data();
952}

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

2731{
2732 if (d->assistants != value) {
2733 d->assistants = value;
2734 d->syncDecorationsWrapperLayerState();
2735 Q_EMIT sigAssistantsChanged();
2736 }
2737}
float value(const T *src, size_t ch)
void sigAssistantsChanged()

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

◆ setAssistantsGlobalColor()

void KisDocument::setAssistantsGlobalColor ( QColor color)

Definition at line 2872 of file KisDocument.cpp.

2873{
2874 d->globalAssistantsColor = color;
2875}

References d.

◆ setAudioTracks()

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

Definition at line 2428 of file KisDocument.cpp.

2429{
2430 d->audioTracks = f;
2431 Q_EMIT sigAudioTracksChanged();
2432}
void sigAudioTracksChanged()

References d, and sigAudioTracksChanged().

◆ setAudioVolume()

void KisDocument::setAudioVolume ( qreal level)

Definition at line 2434 of file KisDocument.cpp.

2435{
2436 d->audioLevel = level;
2437 Q_EMIT sigAudioLevelChanged(level);
2438}
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 1738 of file KisDocument.cpp.

1739{
1740 const bool changed = autoSaveActive != d->autoSaveActive;
1741
1742 if (changed) {
1743 d->autoSaveActive = autoSaveActive;
1745 }
1746}
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 1748 of file KisDocument.cpp.

1749{
1750 if (isReadWrite() && delay > 0 && d->autoSaveActive) {
1751 d->autoSaveTimer->start(delay * 1000);
1752 } else {
1753 d->autoSaveTimer->stop();
1754 }
1755}

References d, and isReadWrite().

◆ setColorHistory()

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

Definition at line 2900 of file KisDocument.cpp.

2901{
2902 d->colorHistory = colors;
2903}

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

2805{
2806 if (d->image) {
2807 // Disconnect existing sig/slot connections
2808 d->image->setUndoStore(new KisDumbUndoStore());
2809 d->image->disconnect(this);
2810 d->shapeController->setImage(0);
2811 d->image = 0;
2812 }
2813
2814 if (!image) return;
2815
2816 if (d->linkedResourceStorage){
2817 d->linkedResourceStorage->setMetaData(KisResourceStorage::s_meta_name, image->objectName());
2818 }
2819
2820 d->setImageAndInitIdleWatcher(image);
2821 d->image->setUndoStore(new KisDocumentUndoStore(this));
2822 d->shapeController->setImage(image, preActivatedNode);
2823 d->image->setMirrorAxesCenter(KisAlgebra2D::absoluteToRelative(d->mirrorAxisConfig.axisPosition(), image->bounds()));
2824 setModified(false);
2825 connect(d->image, SIGNAL(sigImageModified()), this, SLOT(setImageModified()), Qt::UniqueConnection);
2826 connect(d->image, SIGNAL(sigImageModifiedWithoutUndo()), this, SLOT(setImageModifiedWithoutUndo()), Qt::UniqueConnection);
2827 connect(d->image, SIGNAL(sigLayersChangedAsync()), this, SLOT(slotImageRootChanged()));
2828
2829 if (forceInitialUpdate) {
2830 d->image->initialRefreshGraph();
2831 }
2832}
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 1763 of file KisDocument.cpp.

1764{
1765 const int emergencyAutoSaveInterval = 10; /* sec */
1766 setAutoSaveDelay(emergencyAutoSaveInterval);
1767 d->autoSaveFailureCount++;
1768}
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 2197 of file KisDocument.cpp.

2198{
2199 d->lastErrorMessage = errMsg;
2200}

References d.

◆ setFileBatchMode()

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

Definition at line 1094 of file KisDocument.cpp.

1095{
1096 d->batchMode = batchMode;
1097}

References batchMode, and d.

◆ setGridConfig()

void KisDocument::setGridConfig ( const KisGridConfig & config)

Definition at line 2313 of file KisDocument.cpp.

2314{
2315 if (d->gridConfig != config) {
2316 d->gridConfig = config;
2317 d->syncDecorationsWrapperLayerState();
2318 Q_EMIT sigGridConfigChanged(config);
2319
2320 // Store last assigned value as future default...
2321 KisConfig cfg(false);
2322 cfg.setDefaultGridSpacing(config.spacing());
2323 }
2324}
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 2450 of file KisDocument.cpp.

2451{
2452 if (d->guidesConfig == data) return;
2453
2454 d->guidesConfig = data;
2455 d->syncDecorationsWrapperLayerState();
2456 Q_EMIT sigGuidesConfigChanged(d->guidesConfig);
2457}
void sigGuidesConfigChanged(const KisGuidesConfig &config)

References d, and sigGuidesConfigChanged().

◆ setImageAndInitIdleWatcher()

void KisDocument::setImageAndInitIdleWatcher ( KisImageSP _image)
inline

Definition at line 429 of file KisDocument.cpp.

429 {
430 image = _image;
431
433 }
void setTrackedImage(KisImageSP image)

References KisIdleWatcher::setTrackedImage().

◆ setImageModified

void KisDocument::setImageModified ( )
privateslot

Definition at line 2844 of file KisDocument.cpp.

2845{
2846 // we only set as modified if undo stack is not at clean state
2847 setModified(d->imageModifiedWithoutUndo || !d->undoStack->isClean());
2848}

References d, and setModified().

◆ setImageModifiedWithoutUndo

void KisDocument::setImageModifiedWithoutUndo ( )
privateslot

Definition at line 2850 of file KisDocument.cpp.

2851{
2852 d->imageModifiedWithoutUndo = true;
2854}

References d, and setImageModified().

◆ setInfiniteAutoSaveInterval()

void KisDocument::setInfiniteAutoSaveInterval ( )

Disable autosave

Definition at line 1770 of file KisDocument.cpp.

1771{
1772 setAutoSaveDelay(-1);
1773}

References setAutoSaveDelay().

◆ setLocalFilePath()

void KisDocument::setLocalFilePath ( const QString & localFilePath)

Definition at line 2542 of file KisDocument.cpp.

2543{
2544 d->m_file = localFilePath;
2545}

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

1085{
1086 d->mimeType = mimeType;
1087}

References d, and mimeType.

◆ setMimeTypeAfterLoading()

void KisDocument::setMimeTypeAfterLoading ( const QString & mimeType)

Definition at line 2061 of file KisDocument.cpp.

2062{
2063 d->mimeType = mimeType.toLatin1();
2064 d->outputMimeType = d->mimeType;
2065}

References d, and mimeType.

◆ setMirrorAxisConfig()

void KisDocument::setMirrorAxisConfig ( const KisMirrorAxisConfig & config)

Definition at line 2465 of file KisDocument.cpp.

2466{
2467 if (d->mirrorAxisConfig == config) {
2468 return;
2469 }
2470
2471 d->mirrorAxisConfig = config;
2472 if (d->image) {
2473 d->image->setMirrorAxesCenter(KisAlgebra2D::absoluteToRelative(d->mirrorAxisConfig.axisPosition(),
2474 d->image->bounds()));
2475 }
2476 setModified(true);
2477
2479}
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 2073 of file KisDocument.cpp.

2074{
2075 if (mod) {
2076 updateEditingTime(false);
2077 }
2078
2083 if (d->isAutosaving || d->documentIsClosing)
2084 return;
2085
2086 //dbgUI<<" url:" << url.path();
2087 //dbgUI<<" mod="<<mod<<" MParts mod="<<KisParts::ReadWritePart::isModified()<<" isModified="<<isModified();
2088
2089 if (mod && !d->autoSaveTimer->isActive()) {
2090 // First change since last autosave -> start the autosave timer
2092 }
2093 d->modifiedAfterAutosave = mod;
2094 d->modifiedWhileSaving = mod;
2095
2096 if (!mod) {
2097 d->imageModifiedWithoutUndo = mod;
2098 }
2099
2100 if (mod == isModified())
2101 return;
2102
2103 d->modified = mod;
2104
2105 if (mod) {
2107 }
2108
2109 Q_EMIT modified(mod);
2110}
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 1757 of file KisDocument.cpp.

1758{
1759 setAutoSaveDelay(d->autoSaveDelay);
1760 d->autoSaveFailureCount = 0;
1761}

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

2364{
2365 QList<KoColorSetSP> oldPaletteList;
2366 if (d->linkedResourceStorage) {
2367 QSharedPointer<KisResourceStorage::ResourceIterator> iter = d->linkedResourceStorage->resources(ResourceType::Palettes);
2368 while (iter->hasNext()) {
2369 iter->next();
2370 KoResourceSP resource = iter->resource();
2371 if (resource && resource->valid()) {
2372 oldPaletteList << resource.dynamicCast<KoColorSet>();
2373 }
2374 }
2375 if (oldPaletteList != paletteList) {
2377 Q_FOREACH(KoColorSetSP palette, oldPaletteList) {
2378 if (!paletteList.contains(palette)) {
2379 resourceModel.setResourceInactive(resourceModel.indexForResource(palette));
2380 }
2381 }
2382 Q_FOREACH(KoColorSetSP palette, paletteList) {
2383 if (!oldPaletteList.contains(palette)) {
2384 resourceModel.addResource(palette, d->linkedResourcesStorageID);
2385 }
2386 else {
2387 palette->setStorageLocation(d->linkedResourcesStorageID);
2388 resourceModel.updateResource(palette);
2389 }
2390 }
2391 if (emitSignal) {
2392 Q_EMIT sigPaletteListChanged(oldPaletteList, paletteList);
2393 }
2394 }
2395 }
2396}
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 2525 of file KisDocument.cpp.

2526{
2527 const bool changed = path != d->m_path;
2528
2529 d->m_path = path;
2530
2531 if (changed) {
2532 Q_EMIT sigPathChanged(path);
2533 }
2534}
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 2783 of file KisDocument.cpp.

2784{
2785 d->preActivatedNode = activatedNode;
2786}

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

1728{
1729 const bool changed = readwrite != d->readwrite;
1730
1731 d->readwrite = readwrite;
1732
1733 if (changed) {
1735 }
1736}
void sigReadWriteChanged(bool value)

References d, readwrite, and sigReadWriteChanged().

◆ setRecovered()

void KisDocument::setRecovered ( bool value)

Definition at line 2112 of file KisDocument.cpp.

2113{
2114 const bool changed = value != d->isRecovered;
2115
2116 d->isRecovered = value;
2117
2118 if (changed) {
2119 Q_EMIT sigRecoveredChanged(value);
2120 }
2121}
void sigRecoveredChanged(bool value)

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

◆ setReferenceImagesLayer()

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

Definition at line 2749 of file KisDocument.cpp.

2750{
2751 KisReferenceImagesLayerSP currentReferenceLayer = referenceImagesLayer();
2752
2753 // updateImage=false inherently means we are not changing the
2754 // reference images layer, but just would like to update its signals.
2755 if (currentReferenceLayer == layer && updateImage) {
2756 return;
2757 }
2758
2759 d->referenceLayerConnections.clear();
2760
2761 if (updateImage) {
2762 if (currentReferenceLayer) {
2763 d->image->removeNode(currentReferenceLayer);
2764 }
2765
2766 if (layer) {
2767 d->image->addNode(layer);
2768 }
2769 }
2770
2771 currentReferenceLayer = layer;
2772
2773 if (currentReferenceLayer) {
2774 d->referenceLayerConnections.addConnection(
2775 currentReferenceLayer, SIGNAL(sigUpdateCanvas(QRectF)),
2776 this, SIGNAL(sigReferenceImagesChanged()));
2777 }
2778
2779 Q_EMIT sigReferenceImagesLayerChanged(layer);
2781}

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

2417{
2418 d->m_storyboardCommentList = storyboardCommentList;
2419 if (emitSignal) {
2421 }
2422}
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 2403 of file KisDocument.cpp.

2404{
2405 d->m_storyboardItemList = storyboardItemList;
2406 if (emitSignal) {
2408 }
2409}
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 2255 of file KisDocument.cpp.

2256{
2257 if (d->unit != unit) {
2258 d->unit = unit;
2259 Q_EMIT unitChanged(unit);
2260 }
2261}
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 2207 of file KisDocument.cpp.

2208{
2209 d->lastWarningMessage = warningMsg;
2210}

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

2721{
2722 return d->shapeController->shapeForNode(layer);
2723}

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

1596{
1597 slotAutoSaveImpl(std::unique_ptr<KisDocument>());
1598}
void slotAutoSaveImpl(std::unique_ptr< KisDocument > &&optionalClonedDocument)

References slotAutoSaveImpl().

◆ slotAutoSaveImpl()

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

Definition at line 1470 of file KisDocument.cpp.

1471{
1472 if (!d->modified || !d->modifiedAfterAutosave) return;
1473 const QString autoSaveFileName = generateAutoSaveFileName(localFilePath());
1474
1475 Q_EMIT statusBarMessage(i18n("Autosaving... %1", autoSaveFileName), successMessageTimeout);
1476
1477 KisUsageLogger::log(QString("Autosaving: %1").arg(autoSaveFileName));
1478
1479 const bool hadClonedDocument = bool(optionalClonedDocument);
1481
1482 if (d->image->isIdle() || hadClonedDocument) {
1483 result = initiateSavingInBackground(i18n("Autosaving..."),
1486 0,
1487 std::move(optionalClonedDocument));
1488 } else {
1489 Q_EMIT statusBarMessage(i18n("Autosaving postponed: document is busy..."), errorMessageTimeout);
1490 }
1491
1492 if (result != KritaUtils::BackgroudSavingStartResult::Success && !hadClonedDocument && d->autoSaveFailureCount >= 3) {
1494 connect(stroke, SIGNAL(sigDocumentCloned(KisDocument*)),
1496 Qt::BlockingQueuedConnection);
1497 connect(stroke, SIGNAL(sigCloningCancelled()),
1498 this, SLOT(slotDocumentCloningCancelled()),
1499 Qt::BlockingQueuedConnection);
1500
1501 KisStrokeId strokeId = d->image->startStroke(stroke);
1502 d->image->endStroke(strokeId);
1503
1505
1508 } else {
1509 d->modifiedAfterAutosave = false;
1510 }
1511}
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 1434 of file KisDocument.cpp.

1435{
1437
1443 std::unique_lock<QMutex> savingMutexLock(d->savingMutex, std::adopt_lock);
1444
1445 KIS_ASSERT_RECOVER_RETURN(d->backgroundSaveDocument);
1446
1447 if (d->backgroundSaveJob.flags & KritaUtils::SaveInAutosaveMode) {
1448 d->backgroundSaveDocument->d->isAutosaving = false;
1449 }
1450
1451 d->backgroundSaveDocument.take()->deleteLater();
1452
1453 KIS_ASSERT_RECOVER_RETURN(d->backgroundSaveJob.isValid());
1454
1455 const KritaUtils::ExportFileJob job = d->backgroundSaveJob;
1456 d->backgroundSaveJob = KritaUtils::ExportFileJob();
1457
1458 // unlock at the very end
1459 savingMutexLock.unlock();
1460
1461 QFileInfo fi(job.filePath);
1462 KisUsageLogger::log(QString("Completed saving %1 (mime: %2). Result: %3. Warning: %4. Size: %5")
1463 .arg(job.filePath, QString::fromLatin1(job.mimeType),
1464 (!status.isOk() ? errorMessage : "OK"), warningMessage,
1465 QString::number(fi.size())));
1466
1468}
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 1622 of file KisDocument.cpp.

1623{
1624 Q_UNUSED(job);
1625 Q_UNUSED(warningMessage);
1626
1627 const QString fileName = QFileInfo(job.filePath).fileName();
1628
1629 if (!status.isOk()) {
1631 Q_EMIT statusBarMessage(i18nc("%1 --- failing file name, %2 --- error message",
1632 "Error during autosaving %1: %2",
1633 fileName,
1634 exportErrorToUserMessage(status, errorMessage)), errorMessageTimeout);
1635 } else {
1636 KisConfig cfg(true);
1637 d->autoSaveDelay = cfg.autoSaveInterval();
1638
1639 if (!d->modifiedWhileSaving) {
1640 d->autoSaveTimer->stop(); // until the next change
1641 d->autoSaveFailureCount = 0;
1642 } else {
1644 }
1645
1646 Q_EMIT statusBarMessage(i18n("Finished autosaving %1", fileName), successMessageTimeout);
1647 }
1648}
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 992 of file KisDocument.cpp.

993{
994 if (status.isCancelled())
995 return;
996
997 const QString fileName = QFileInfo(job.filePath).fileName();
998
999 if (!status.isOk()) {
1000 Q_EMIT statusBarMessage(i18nc("%1 --- failing file name, %2 --- error message",
1001 "Error during saving %1: %2",
1002 fileName,
1003 errorMessage), errorMessageTimeout);
1004
1005
1006 if (!fileBatchMode()) {
1007 DlgLoadMessages dlg(i18nc("@title:window", "Krita"),
1008 i18n("Could not save %1.", job.filePath),
1009 errorMessage.split("\n", Qt::SkipEmptyParts)
1010 + warningMessage.split("\n", Qt::SkipEmptyParts),
1011 status.errorMessage());
1012
1013 dlg.exec();
1014 }
1015 }
1016 else {
1017 if (!fileBatchMode() && !warningMessage.isEmpty()) {
1018
1019 QStringList reasons = warningMessage.split("\n", Qt::SkipEmptyParts);
1020
1021 DlgLoadMessages dlg(
1022 i18nc("@title:window", "Krita"),
1023 i18nc("dialog box shown to the user if there were warnings while saving the document, "
1024 "%1 is the file path",
1025 "%1 has been saved but is incomplete.",
1026 job.filePath),
1027 reasons,
1028 reasons.isEmpty()
1029 ? ""
1030 : i18nc("dialog box shown to the user if there were warnings while saving the document",
1031 "Some problems were encountered when saving."));
1032 dlg.exec();
1033 }
1034
1035
1036 if (!(job.flags & KritaUtils::SaveIsExporting)) {
1037 const QString existingAutoSaveBaseName = localFilePath();
1038 const bool wasRecovered = isRecovered();
1039
1040 d->updateDocumentMetadataOnSaving(job.filePath, job.mimeType);
1041
1042 removeAutoSaveFiles(existingAutoSaveBaseName, wasRecovered);
1043 }
1044
1045 Q_EMIT completed();
1046 Q_EMIT sigSavingFinished(job.filePath);
1047
1048 Q_EMIT statusBarMessage(i18n("Finished saving %1", fileName), successMessageTimeout);
1049 }
1050}
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 2278 of file KisDocument.cpp.

2279{
2280 KisConfig cfg(true);
2281
2282 if (d->undoStack->undoLimit() != cfg.undoStackLimit()) {
2283 if (!d->undoStack->isClean()) {
2284 d->undoStack->clear();
2285 // we set this because the document *has* changed, even though the
2286 // undo history was purged.
2288 }
2289 d->undoStack->setUndoLimit(cfg.undoStackLimit());
2290 }
2291 d->undoStack->setUseCumulativeUndoRedo(cfg.useCumulativeUndoRedo());
2292 d->undoStack->setCumulativeUndoData(cfg.cumulativeUndoData());
2293
2294 d->autoSaveDelay = cfg.autoSaveInterval();
2296}

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

◆ slotDocumentCloningCancelled

void KisDocument::slotDocumentCloningCancelled ( )
privateslot

Definition at line 1605 of file KisDocument.cpp.

1606{
1608}

References setEmergencyAutoSaveInterval().

◆ slotImageRootChanged

void KisDocument::slotImageRootChanged ( )
privateslot

Definition at line 2298 of file KisDocument.cpp.

2299{
2300 d->syncDecorationsWrapperLayerState();
2301}

References d.

◆ slotInitiateAsyncAutosaving

void KisDocument::slotInitiateAsyncAutosaving ( KisDocument * clonedDocument)
privateslot

Definition at line 1600 of file KisDocument.cpp.

1601{
1602 slotAutoSaveImpl(std::unique_ptr<KisDocument>(clonedDocument));
1603}

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

1611{
1612 d->image->explicitRegenerateLevelOfDetail();
1613
1614
1618
1619 // d->image->purgeUnusedData(true);
1620}

References d.

◆ slotUndoStackCleanChanged

void KisDocument::slotUndoStackCleanChanged ( bool value)
privateslot

Definition at line 2273 of file KisDocument.cpp.

2274{
2275 setModified(!value || d->imageModifiedWithoutUndo);
2276}

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

1656{
1657 d->savingImage = d->image;
1658
1660 if (window) {
1661 if (window->viewManager()) {
1662 d->savingUpdater = window->viewManager()->createThreadedUpdater(actionName);
1663 d->importExportManager->setUpdater(d->savingUpdater);
1664 }
1665 }
1666
1667 KisImportExportErrorCode initializationStatus(ImportExportCodes::OK);
1668 d->childSavingFuture =
1669 d->importExportManager->exportDocumentAsync(location,
1670 realLocation,
1671 mimeType,
1672 initializationStatus,
1673 showWarnings,
1674 exportConfiguration,
1675 isAdvancedExporting);
1676
1677 if (!initializationStatus.isOk()) {
1678 if (d->savingUpdater) {
1679 d->savingUpdater->cancel();
1680 }
1681 d->savingImage.clear();
1682 Q_EMIT sigBackgroundSavingFinished(initializationStatus, initializationStatus.errorMessage(), "");
1683 return initializationStatus;
1684 }
1685
1686 typedef QFutureWatcher<KisImportExportErrorCode> StatusWatcher;
1687 StatusWatcher *watcher = new StatusWatcher();
1688 watcher->setFuture(d->childSavingFuture);
1689
1690 connect(watcher, SIGNAL(finished()), SLOT(finishExportInBackground()));
1691 connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater()));
1692
1693 return initializationStatus;
1694}
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 2128 of file KisDocument.cpp.

2129{
2130 QDateTime now = QDateTime::currentDateTime();
2131 int firstModDelta = d->firstMod.secsTo(now);
2132 int lastModDelta = d->lastMod.secsTo(now);
2133
2134 if (lastModDelta > 30) {
2135 d->docInfo->setAboutInfo("editing-time", QString::number(d->docInfo->aboutInfo("editing-time").toInt() + d->firstMod.secsTo(d->lastMod)));
2136 d->firstMod = now;
2137 } else if (firstModDelta > 60 || forceStoreElapsed) {
2138 d->docInfo->setAboutInfo("editing-time", QString::number(d->docInfo->aboutInfo("editing-time").toInt() + firstModDelta));
2139 d->firstMod = now;
2140 }
2141
2142 d->lastMod = now;
2143}

References d.

◆ uploadLinkedResourcesFromLayersToStorage()

void KisDocument::uploadLinkedResourcesFromLayersToStorage ( )

◆ waitForSavingToComplete()

void KisDocument::waitForSavingToComplete ( )

Definition at line 2707 of file KisDocument.cpp.

2708{
2709 if (isSaving()) {
2710 KisAsyncActionFeedback f(i18nc("progress dialog message when the user closes the document that is being saved", "Waiting for saving to complete..."), 0);
2711 f.waitForMutex(d->savingMutex);
2712 }
2713}

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

2213{
2214 return d->lastWarningMessage;
2215}

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

414{ 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.

◆ d

Private* const KisDocument::d
private

Definition at line 743 of file KisDocument.h.

◆ decorationsSyncingDisabled

bool KisDocument::decorationsSyncingDisabled = false

Definition at line 415 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 417 of file KisDocument.cpp.

◆ embeddedResourcesStorageID

QString KisDocument::embeddedResourcesStorageID

Definition at line 424 of file KisDocument.cpp.

◆ embeddedResourceStorage

KisResourceStorageSP KisDocument::embeddedResourceStorage

Definition at line 425 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 412 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 420 of file KisDocument.cpp.

◆ linkedResourceStorage

KisResourceStorageSP KisDocument::linkedResourceStorage

Definition at line 421 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 410 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 416 of file KisDocument.cpp.


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