Krita Source Code Documentation
Loading...
Searching...
No Matches
KisDocument.cpp
Go to the documentation of this file.
1/* This file is part of the Krita project
2 *
3 * SPDX-FileCopyrightText: 2014 Boudewijn Rempt <boud@valdyas.org>
4 *
5 * SPDX-License-Identifier: LGPL-2.0-or-later
6 */
7
8#include "KisMainWindow.h" // XXX: remove
9#include <QMessageBox>
10
11#include <KisMimeDatabase.h>
12
13#include <KoCanvasBase.h>
14#include <KoColor.h>
15#include <KoColorProfile.h>
16#include <KoColorSpaceEngine.h>
17#include <KoColorSpace.h>
19#include <KoDocumentInfoDlg.h>
20#include <KoDocumentInfo.h>
21#include <KoUnit.h>
22#include <KoID.h>
23#include <KoProgressProxy.h>
24#include <KoProgressUpdater.h>
25#include <KoSelection.h>
26#include <KoShape.h>
27#include <KoShapeController.h>
28#include <KoStore.h>
29#include <KoUpdater.h>
30#include <KoXmlWriter.h>
31#include <KoStoreDevice.h>
32#include <KoDialog.h>
35#include <KoMD5Generator.h>
36#include <KisResourceStorage.h>
37#include <KisResourceLocator.h>
38#include <KisResourceTypes.h>
42#include <KisResourceCacheDb.h>
43#include <KoEmbeddedResource.h>
44#include <KisUsageLogger.h>
45#include <klocalizedstring.h>
46#include <kis_debug.h>
47#include <kis_generator_layer.h>
50#include <kdesktopfile.h>
51#include <kconfiggroup.h>
52#include <KisBackup.h>
53#include <KisView.h>
54
55#include <QTextBrowser>
56#include <QApplication>
57#include <QBuffer>
58#include <QStandardPaths>
59#include <QDir>
60#include <QDomDocument>
61#include <QDomElement>
62#include <QFileInfo>
63#include <QImage>
64#include <QList>
65#include <QMutex>
66#include <QPainter>
67#include <QRect>
68#include <QScopedPointer>
69#include <QScopedValueRollback>
70#include <QSize>
71#include <QStringList>
72#include <QtGlobal>
73#include <QTimer>
74#include <QWidget>
75#include <QFuture>
76#include <QFutureWatcher>
77#include <QUuid>
78
79// Krita Image
81#include <kis_config.h>
83#include <kis_group_layer.h>
84#include <kis_image.h>
85#include <kis_layer.h>
86#include <kis_name_server.h>
87#include <kis_paint_layer.h>
88#include <kis_painter.h>
89#include <kis_selection.h>
90#include <kis_fill_painter.h>
92#include <kis_idle_watcher.h>
95#include "KisUniqueColorSet.h"
96#include "kis_layer_utils.h"
97#include "kis_selection_mask.h"
98
99// Local
100#include "KisViewManager.h"
101#include "kis_clipboard.h"
103#include "canvas/kis_canvas2.h"
108#include "kis_node_manager.h"
109#include "KisPart.h"
110#include "KisApplication.h"
111#include "KisDocument.h"
113#include "KisView.h"
114#include "kis_grid_config.h"
115#include "kis_guides_config.h"
116#include "KisImageBarrierLock.h"
119
120#include <mutex>
121#include "kis_config_notifier.h"
124
125#include <kis_algebra_2d.h>
126#include <KisMirrorAxisConfig.h>
130
131// Define the protocol used here for embedded documents' URL
132// This used to "store" but QUrl didn't like it,
133// so let's simply make it "tar" !
134#define STORE_PROTOCOL "tar"
135// The internal path is a hack to make QUrl happy and for document children
136#define INTERNAL_PROTOCOL "intern"
137#define INTERNAL_PREFIX "intern:/"
138// Warning, keep it sync in koStore.cc
139
140#include <unistd.h>
141
142#ifdef Q_OS_MACOS
144#endif
145
146using namespace std;
147
148namespace {
149constexpr int errorMessageTimeout = 5000;
150constexpr int successMessageTimeout = 1000;
151}
152
153
154/**********************************************************
155 *
156 * KisDocument
157 *
158 **********************************************************/
159
160//static
162{
163 static int s_docIFNumber = 0;
164 QString name; name.setNum(s_docIFNumber++); name.prepend("document_");
165 return name;
166}
167
168
169class UndoStack : public KUndo2Stack
170{
171public:
173 : KUndo2Stack(doc),
174 m_doc(doc)
175 {
176 }
177
178 void setIndex(int idx) override {
181 }
182
184 KisImageWSP image = this->image();
185 image->unlock();
186
192 while(!image->tryBarrierLock()) {
193 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
194 }
195 }
196
197 void undo() override {
200 }
201
202
203 void redo() override {
206 }
207
208private:
210 KisImageWSP currentImage = m_doc->image();
211 Q_ASSERT(currentImage);
212 return currentImage;
213 }
214
215 void setIndexImpl(int idx) {
216 KisImageWSP image = this->image();
218 if(image->tryBarrierLock()) {
220 image->unlock();
221 }
222 }
223
224 void undoImpl() {
225 KisImageWSP image = this->image();
227
229 return;
230 }
231
232 if(image->tryBarrierLock()) {
234 image->unlock();
235 }
236 }
237
238 void redoImpl() {
239 KisImageWSP image = this->image();
241
242 if(image->tryBarrierLock()) {
244 image->unlock();
245 }
246 }
247
257 if (m_recursionCounter > 0) return;
258
260
261 while (!m_postponedJobs.isEmpty()) {
262 PostponedJob job = m_postponedJobs.dequeue();
263 switch (job.type) {
265 setIndexImpl(job.index);
266 break;
268 redoImpl();
269 break;
271 undoImpl();
272 break;
273 }
274 }
275
277 }
278
279private:
281
283 enum Type {
284 Undo = 0,
287 };
289 int index = 0;
290 };
291 QQueue<PostponedJob> m_postponedJobs;
292
294};
295
296class Q_DECL_HIDDEN KisDocument::Private
297{
298public:
300 : q(_q)
301 , docInfo(new KoDocumentInfo(_q)) // deleted by QObject
302 , importExportManager(new KisImportExportManager(_q)) // deleted manually
303 , autoSaveTimer(new QTimer(_q))
304 , undoStack(new UndoStack(_q)) // deleted by QObject
305 , m_bAutoDetectedMime(false)
306 , modified(false)
307 , readwrite(true)
308 , autoSaveActive(true)
309 , firstMod(QDateTime::currentDateTime())
310 , lastMod(firstMod)
311 , nserver(new KisNameServer(1))
312 , imageIdleWatcher(2000 /*ms*/)
313 , globalAssistantsColor(KisConfig(true).defaultAssistantsColor())
314 , batchMode(false)
315 {
316 if (QLocale().measurementSystem() == QLocale::ImperialSystem) {
317 unit = KoUnit::Inch;
318 } else {
319 unit = KoUnit::Centimeter;
320 }
321 connect(&imageIdleWatcher, SIGNAL(startedIdleMode()), q, SLOT(slotPerformIdleRoutines()));
322 }
323
324 Private(const Private &rhs, KisDocument *_q)
325 : q(_q)
326 , docInfo(new KoDocumentInfo(*rhs.docInfo, _q))
327 , importExportManager(new KisImportExportManager(_q))
328 , autoSaveTimer(new QTimer(_q))
329 , undoStack(new UndoStack(_q))
330 , nserver(new KisNameServer(*rhs.nserver))
331 , preActivatedNode(0) // the node is from another hierarchy!
332 , imageIdleWatcher(2000 /*ms*/)
333 , colorHistoryModel(rhs.colorHistoryModel)
334 {
335 copyFromImpl(rhs, _q, CONSTRUCT);
336 connect(&imageIdleWatcher, SIGNAL(startedIdleMode()), q, SLOT(slotPerformIdleRoutines()));
337 }
338
340 // Don't delete m_d->shapeController because it's in a QObject hierarchy.
341 delete nserver;
342 }
343
345 KoDocumentInfo *docInfo = 0;
346
348
349 KisImportExportManager *importExportManager = 0; // The filter-manager to use when loading/saving [for the options]
350
351 QByteArray mimeType; // The actual mimeType of the document
352 QByteArray outputMimeType; // The mimeType to use when saving
353
355 QString lastErrorMessage; // see openFile()
357
358 int autoSaveDelay = 300; // in seconds, 0 to disable.
359 bool modifiedAfterAutosave = false;
360 bool isAutosaving = false;
361 bool disregardAutosaveFailure = false;
362 int autoSaveFailureCount = 0;
363
364 KUndo2Stack *undoStack = 0;
365
368
369 bool m_bAutoDetectedMime = false; // whether the mimeType in the arguments was detected by the part itself
370 QString m_path; // local url - the one displayed to the user.
371 QString m_file; // Local file - the only one the part implementation should deal with.
372
374
375 bool modified = false;
376 bool readwrite = false;
377 bool autoSaveActive = true;
378
379 QDateTime firstMod;
380 QDateTime lastMod;
381
383
386
388 KisShapeController* shapeController = 0;
389 KoShapeController* koShapeController = 0;
391 QScopedPointer<KisSignalAutoConnection> imageIdleConnection;
392
394
397
399 qreal audioLevel = 1.0;
400
403
405
406 bool imageModifiedWithoutUndo = false;
407 bool modifiedWhileSaving = false;
408 std::unique_ptr<KisDocument> backgroundSaveDocument;
412 QMetaObject::Connection completeSavingConnection;
414
415 bool isRecovered = false;
416
417 bool batchMode { false };
418 bool decorationsSyncingDisabled = false;
419 bool wasStorageAdded = false;
420 bool documentIsClosing = false;
421
422 // Resources saved in the .kra document
425
426 // Resources saved into other components of the kra file
429
431
433 image = _image;
434
435 imageIdleWatcher.setTrackedImage(image);
436 }
437
438 void copyFrom(const Private &rhs, KisDocument *q);
440
442 KisDocument* lockAndCloneImpl(bool fetchResourcesFromLayers);
443
444 void updateDocumentMetadataOnSaving(const QString &filePath, const QByteArray &mimeType);
445
448 class StrippedSafeSavingLocker;
449};
450
451
452void KisDocument::Private::syncDecorationsWrapperLayerState()
453{
454 if (!this->image || this->decorationsSyncingDisabled) return;
455
456 KisImageSP image = this->image;
457 KisDecorationsWrapperLayerSP decorationsLayer =
458 KisLayerUtils::findNodeByType<KisDecorationsWrapperLayer>(image->root());
459
460 const bool needsDecorationsWrapper =
461 gridConfig.showGrid() || (guidesConfig.showGuides() && guidesConfig.hasGuides()) || !assistants.isEmpty();
462
463 struct SyncDecorationsWrapperStroke : public KisSimpleStrokeStrategy {
464 SyncDecorationsWrapperStroke(KisDocument *document, bool needsDecorationsWrapper)
465 : KisSimpleStrokeStrategy(QLatin1String("sync-decorations-wrapper"),
466 kundo2_noi18n("start-isolated-mode")),
467 m_document(document),
468 m_needsDecorationsWrapper(needsDecorationsWrapper)
469 {
473 }
474
475 void initStrokeCallback() override {
476 KisDecorationsWrapperLayerSP decorationsLayer =
477 KisLayerUtils::findNodeByType<KisDecorationsWrapperLayer>(m_document->image()->root());
478
479 if (m_needsDecorationsWrapper && !decorationsLayer) {
480 m_document->image()->addNode(new KisDecorationsWrapperLayer(m_document));
481 } else if (!m_needsDecorationsWrapper && decorationsLayer) {
482 m_document->image()->removeNode(decorationsLayer);
483 }
484 }
485
486 private:
487 KisDocument *m_document = 0;
488 bool m_needsDecorationsWrapper = false;
489 };
490
491 KisStrokeId id = image->startStroke(new SyncDecorationsWrapperStroke(q, needsDecorationsWrapper));
492 image->endStroke(id);
493}
494
495void KisDocument::Private::copyFrom(const Private &rhs, KisDocument *q)
496{
497 copyFromImpl(rhs, q, KisDocument::REPLACE);
498}
499
500void KisDocument::Private::copyFromImpl(const Private &rhs, KisDocument *q, KisDocument::CopyPolicy policy)
501{
502 if (policy == REPLACE) {
503 delete docInfo;
504 }
505 docInfo = (new KoDocumentInfo(*rhs.docInfo, q));
506 unit = rhs.unit;
507 mimeType = rhs.mimeType;
508 outputMimeType = rhs.outputMimeType;
509
510 if (policy == REPLACE) {
511 q->setGuidesConfig(rhs.guidesConfig);
512 q->setMirrorAxisConfig(rhs.mirrorAxisConfig);
513 q->setModified(rhs.modified);
516 q->setStoryboardCommentList(rhs.m_storyboardCommentList);
517 q->setAudioTracks(rhs.audioTracks);
518 q->setAudioVolume(rhs.audioLevel);
519 q->setGridConfig(rhs.gridConfig);
520 colorHistoryModel.setColorList(rhs.colorHistoryModel.colorList());
521 } else {
522 // in CONSTRUCT mode, we cannot use the functions of KisDocument
523 // because KisDocument does not yet have a pointer to us.
524 guidesConfig = rhs.guidesConfig;
525 mirrorAxisConfig = rhs.mirrorAxisConfig;
526 modified = rhs.modified;
527 assistants = KisPaintingAssistant::cloneAssistantList(rhs.assistants);
528 m_storyboardItemList = StoryboardItem::cloneStoryboardItemList(rhs.m_storyboardItemList);
529 m_storyboardCommentList = rhs.m_storyboardCommentList;
530 audioTracks = rhs.audioTracks;
531 audioLevel = rhs.audioLevel;
532 gridConfig = rhs.gridConfig;
533 }
534 imageModifiedWithoutUndo = rhs.imageModifiedWithoutUndo;
535 m_bAutoDetectedMime = rhs.m_bAutoDetectedMime;
536 m_path = rhs.m_path;
537 m_file = rhs.m_file;
538 readwrite = rhs.readwrite;
539 autoSaveActive = rhs.autoSaveActive;
540 firstMod = rhs.firstMod;
541 lastMod = rhs.lastMod;
542 // XXX: the display properties will be shared between different snapshots
543 globalAssistantsColor = rhs.globalAssistantsColor;
544 batchMode = rhs.batchMode;
545
546
547 if (rhs.linkedResourceStorage) {
548 linkedResourceStorage = rhs.linkedResourceStorage->clone();
549 }
550
551 if (rhs.embeddedResourceStorage) {
552 embeddedResourceStorage = rhs.embeddedResourceStorage->clone();
553 }
554
555}
556
558public:
559 StrippedSafeSavingLocker(QMutex *savingMutex, KisImageSP image)
560 : m_locked(false)
561 , m_image(image)
562 , m_savingLock(savingMutex)
563 , m_imageLock(image, std::defer_lock)
564
565 {
575 m_locked = std::try_lock(m_imageLock, *m_savingLock) < 0;
576
577 if (!m_locked) {
579 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
580
581 // one more try...
582 m_locked = std::try_lock(m_imageLock, *m_savingLock) < 0;
583 }
584 }
585
587 if (m_locked) {
588 m_imageLock.unlock();
589 m_savingLock->unlock();
590 }
591 }
592
593 bool successfullyLocked() const {
594 return m_locked;
595 }
596
597private:
598 Q_DISABLE_COPY_MOVE(StrippedSafeSavingLocker)
599
600 bool m_locked;
601 KisImageSP m_image;
602 QMutex *m_savingLock;
603 KisImageReadOnlyBarrierLock m_imageLock;
604};
605
606KisDocument::KisDocument(bool addStorage)
607 : d(new Private(this))
608{
609 connect(KisConfigNotifier::instance(), SIGNAL(configChanged()), SLOT(slotConfigChanged()));
610 connect(d->undoStack, SIGNAL(cleanChanged(bool)), this, SLOT(slotUndoStackCleanChanged(bool)));
611 connect(d->autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
612 setObjectName(newObjectName());
613
614#ifdef Q_OS_MACOS
616 if (bookmarkmngr->isSandboxed()) {
617 connect(this, SIGNAL(sigSavingFinished(const QString&)), bookmarkmngr, SLOT(slotCreateBookmark(const QString&)));
618 }
619#endif
620
621
622 if (addStorage) {
623 d->linkedResourcesStorageID = QUuid::createUuid().toString();
624 d->linkedResourceStorage.reset(new KisResourceStorage(d->linkedResourcesStorageID));
625 KisResourceLocator::instance()->addStorage(d->linkedResourcesStorageID, d->linkedResourceStorage);
626
627 d->embeddedResourcesStorageID = QUuid::createUuid().toString();
628 d->embeddedResourceStorage.reset(new KisResourceStorage(d->embeddedResourcesStorageID));
629 KisResourceLocator::instance()->addStorage(d->embeddedResourcesStorageID, d->embeddedResourceStorage);
630
631 d->wasStorageAdded = true;
632 }
633
634 // preload the krita resources
636
637 d->shapeController = new KisShapeController(d->nserver, d->undoStack, this);
638 d->koShapeController = new KoShapeController(0, d->shapeController);
639
640 slotConfigChanged();
641}
642
643KisDocument::KisDocument(const KisDocument &rhs, bool addStorage)
644 : QObject(),
645 d(new Private(*rhs.d, this))
646{
648
649 if (addStorage) {
650 KisResourceLocator::instance()->addStorage(d->linkedResourcesStorageID, d->linkedResourceStorage);
651 KisResourceLocator::instance()->addStorage(d->embeddedResourcesStorageID, d->embeddedResourceStorage);
652 d->wasStorageAdded = true;
653 }
654}
655
657{
658 d->documentIsClosing = true;
659
660 // wait until all the pending operations are in progress
662 d->imageIdleWatcher.setTrackedImage(0);
663
669
670 d->autoSaveTimer->disconnect(this);
671 d->autoSaveTimer->stop();
672
673 delete d->importExportManager;
674
675 // Despite being QObject they needs to be deleted before the image
676 delete d->shapeController;
677
678 delete d->koShapeController;
679
680 if (d->image) {
681 d->image->animationInterface()->blockBackgroundFrameGeneration();
682
683 d->image->notifyAboutToBeDeleted();
684
697 d->image->requestStrokeCancellation();
698 d->image->waitForDone();
699
700 // clear undo commands that can still point to the image
701 d->undoStack->clear();
702 d->image->waitForDone();
703
704 KisImageWSP sanityCheckPointer = d->image;
705 Q_UNUSED(sanityCheckPointer);
706
707 // The following line trigger the deletion of the image
708 d->image.clear();
709
710 // check if the image has actually been deleted
711 KIS_SAFE_ASSERT_RECOVER_NOOP(!sanityCheckPointer.isValid());
712 }
713
714 if (d->wasStorageAdded) {
715 if (KisResourceLocator::instance()->hasStorage(d->linkedResourcesStorageID)) {
716 KisResourceLocator::instance()->removeStorage(d->linkedResourcesStorageID);
717 }
718 if (KisResourceLocator::instance()->hasStorage(d->embeddedResourcesStorageID)) {
719 KisResourceLocator::instance()->removeStorage(d->embeddedResourcesStorageID);
720 }
721 }
722
723 delete d;
724}
725
727{
728 return d->embeddedResourcesStorageID;
729}
730
732{
733 return d->linkedResourcesStorageID;
734}
735
737{
738 return new KisDocument(*this, addStorage);
739}
740
741bool KisDocument::exportDocumentImpl(const KritaUtils::ExportFileJob &job, KisPropertiesConfigurationSP exportConfiguration, bool isAdvancedExporting)
742{
743 // ANDROID NOTES (other comments in this file reference this one!)
744 //
745 // The Android file system doesn't work like on a real operating system.
746 // Instead of normal file paths, we get to deal with "content URIs", which
747 // can have various kinds of storage providers behind them. For example,
748 // there's a "normal" storage provider, a slightly less normal documents
749 // provider, a Google Drive provider and various kinds of third-party
750 // providers that are mostly just good at losing the data you give them.
751 // For example, we have reports of compression programs that provide a
752 // storage provider to write to ZIP or RAR archives or something. Except
753 // that they don't seem to work at all, they just accept the data with no
754 // error and throw it on the floor.
755 //
756 // The providers are particularly unreliable with regards to permissions,
757 // so calling "isWritable" will just always return false on some of them.
758 // This includes the default provider on some devices, which means checking
759 // whether a file is writable will mean that the user can't save anything!
760 // So, all the Android code skips over the writability check and assumes the
761 // files are writable. If they're not, we'll notice later anyway, by the
762 // fact that writing to them fails.
763 //
764 // Another issue is that it's only possible to overwrite files using File >
765 // Save. Using File > Save As or File > Export can't replace existing
766 // files. The reason for this is that we have to go through the operating
767 // system to request access to a file and the only things you can ask for
768 // is to open an existing file or to create a new file. Out of necessity,
769 // Save As and Export use the latter. If the user selects an existing file,
770 // the operating system "helpfully" appends a number to the path, *after*
771 // the file extension of course, because it hates the living. So that's
772 // another reason we can't go with the "safer" option of assuming that files
773 // aren't writable in some cases, since that would prevent the user from
774 // saving them normally and end up with a lot of "kiki.kra (2)".
775 //
776 // Also, when you request a file from the operating system, it always
777 // creates an empty file. That means checking whether a file exists will
778 // pretty much always succeed, so to know whether a file actually exists
779 // you have to check whether it isn't empty. Of course providers may fail to
780 // implement this correctly, but I'm not aware of any of them botching it
781 // that hard. Well, at least none of the ones that actually save files, as
782 // mentioned above some of them just seem to lose whatever you give them.
783
784 QFileInfo filePathInfo(job.filePath);
785 bool fileExists = filePathInfo.exists();
786#ifdef Q_OS_ANDROID
787 if (fileExists) {
788 fileExists = filePathInfo.size() > 0;
789 }
790#else
791 if (fileExists && !filePathInfo.isWritable()) {
793 i18n("%1 cannot be written to. Please save under a different name.", job.filePath),
794 "");
795 return false;
796 }
797#endif
798
799 KisConfig cfg(true);
800 if (cfg.backupFile() && fileExists) {
801
802 QString backupDir;
803
804 switch(cfg.readEntry<int>("backupfilelocation", 0)) {
805 case 1:
806 backupDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
807 break;
808 case 2:
809 backupDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
810 break;
811 default:
812#ifdef Q_OS_ANDROID
813 // We deal with URIs, there may or may not be a "directory"
815 QDir().mkpath(backupDir);
816#endif
817
818#ifdef Q_OS_MACOS
820 if (bookmarkmngr->isSandboxed()) {
821 // If the user does not have directory permission force backup
822 // files to be inside Container tmp
823 QUrl fileUrl = QUrl::fromLocalFile(job.filePath);
824 if( !bookmarkmngr->parentDirHasPermissions(fileUrl.path()) ) {
825 backupDir = QDir::tempPath();
826 }
827 }
828#endif
829
830 // Do nothing: the empty string is user file location
831 break;
832 }
833
834 int numOfBackupsKept = cfg.readEntry<int>("numberofbackupfiles", 1);
835 QString suffix = cfg.readEntry<QString>("backupfilesuffix", "~");
836
837 if (numOfBackupsKept == 1) {
838 if (!KisBackup::simpleBackupFile(job.filePath, backupDir, suffix)) {
839 qWarning() << "Failed to create simple backup file!" << job.filePath << backupDir << suffix;
840 KisUsageLogger::log(QString("Failed to create a simple backup for %1 in %2.")
841 .arg(job.filePath, backupDir.isEmpty()
842 ? "the same location as the file"
843 : backupDir));
844 slotCompleteSavingDocument(job, ImportExportCodes::ErrorWhileWriting, i18nc("Saving error message", "Failed to create a backup file"), "");
845 return false;
846 }
847 else {
848 KisUsageLogger::log(QString("Create a simple backup for %1 in %2.")
849 .arg(job.filePath, backupDir.isEmpty()
850 ? "the same location as the file"
851 : backupDir));
852 }
853 }
854 else if (numOfBackupsKept > 1) {
855 if (!KisBackup::numberedBackupFile(job.filePath, backupDir, suffix, numOfBackupsKept)) {
856 qWarning() << "Failed to create numbered backup file!" << job.filePath << backupDir << suffix;
857 KisUsageLogger::log(QString("Failed to create a numbered backup for %2.")
858 .arg(job.filePath, backupDir.isEmpty()
859 ? "the same location as the file"
860 : backupDir));
861 slotCompleteSavingDocument(job, ImportExportCodes::ErrorWhileWriting, i18nc("Saving error message", "Failed to create a numbered backup file"), "");
862 return false;
863 }
864 else {
865 KisUsageLogger::log(QString("Create a simple backup for %1 in %2.")
866 .arg(job.filePath, backupDir.isEmpty()
867 ? "the same location as the file"
868 : backupDir));
869 }
870 }
871 }
872
873 //KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(!job.mimeType.isEmpty(), false);
874 if (job.mimeType.isEmpty()) {
876 slotCompleteSavingDocument(job, error, error.errorMessage(), "");
877 return false;
878
879 }
880
881 const QString actionName =
883 i18n("Exporting Document...") :
884 i18n("Saving Document...");
885
889 job, exportConfiguration, isAdvancedExporting);
890
892 QString errorShortLog;
893 QString errorMessage;
895
896 switch (result) {
898 errorShortLog = "another save operation is in progress";
899 errorMessage = i18n("Could not start saving %1. Wait until the current save operation has finished.", job.filePath);
900 errorCode = ImportExportCodes::Failure;
901 break;
903 errorShortLog = "failed to lock and clone the image";
904 errorMessage = i18n("Could not start saving %1. Image is busy", job.filePath);
905 errorCode = ImportExportCodes::Busy;
906 break;
908 errorShortLog = "failed to start background saving";
909 errorMessage = i18n("Could not start saving %1. Unknown failure has happened", job.filePath);
910 errorCode = ImportExportCodes::Failure;
911 break;
914 break;
916 // noop, not possible
917 break;
918 }
919
920 KisUsageLogger::log(QString("Failed to initiate saving %1 in background: %2").arg(job.filePath).arg(errorShortLog));
921
922 slotCompleteSavingDocument(job, errorCode,
924 "");
925 return false;
926 }
927
929}
930
931bool KisDocument::exportDocument(const QString &path, const QByteArray &mimeType, bool isAdvancedExporting, bool showWarnings, KisPropertiesConfigurationSP exportConfiguration)
932{
933 using namespace KritaUtils;
934
935 SaveFlags flags = SaveIsExporting;
936 if (showWarnings) {
937 flags |= SaveShowWarnings;
938 }
939
940 KisUsageLogger::log(QString("Exporting Document: %1 as %2. %3 * %4 pixels, %5 layers, %6 frames, %7 "
941 "framerate. Export configuration: %8")
942 .arg(path, QString::fromLatin1(mimeType), QString::number(d->image->width()),
943 QString::number(d->image->height()), QString::number(d->image->nlayers()),
944 QString::number(d->image->animationInterface()->totalLength()),
945 QString::number(d->image->animationInterface()->framerate()),
946 (exportConfiguration ? exportConfiguration->toXML() : "No configuration")));
947
949 mimeType,
950 flags),
951 exportConfiguration, isAdvancedExporting);
952}
953
954bool KisDocument::saveAs(const QString &_path, const QByteArray &mimeType, bool showWarnings, KisPropertiesConfigurationSP exportConfiguration)
955{
956 using namespace KritaUtils;
957
958 KisUsageLogger::log(QString("Saving Document %9 as %1 (mime: %2). %3 * %4 pixels, %5 layers. %6 frames, "
959 "%7 framerate. Export configuration: %8")
960 .arg(_path, QString::fromLatin1(mimeType), QString::number(d->image->width()),
961 QString::number(d->image->height()), QString::number(d->image->nlayers()),
962 QString::number(d->image->animationInterface()->totalLength()),
963 QString::number(d->image->animationInterface()->framerate()),
964 (exportConfiguration ? exportConfiguration->toXML() : "No configuration"),
965 path()));
966
967 // Check whether it's an existing resource were are saving to
968 if (resourceSavingFilter(_path, mimeType, exportConfiguration)) {
969 return true;
970 }
971
973 mimeType,
974 showWarnings ? SaveShowWarnings : SaveNone),
975 exportConfiguration);
976}
977
978bool KisDocument::save(bool showWarnings, KisPropertiesConfigurationSP exportConfiguration)
979{
980 return saveAs(path(), mimeType(), showWarnings, exportConfiguration);
981}
982
984{
985 QBuffer buffer;
986
988 filter->setBatchMode(true);
989 filter->setMimeType(nativeFormatMimeType());
990
991 Private::StrippedSafeSavingLocker locker(&d->savingMutex, d->image);
992 if (!locker.successfullyLocked()) {
993 return buffer.data();
994 }
995
996 // temporary set the saving image to avoid shared pointer
997 // leaking (see bug 528540)
998 QScopedValueRollback<KisImageSP> rollback(d->savingImage, d->image);
999
1000 if (!filter->convert(this, &buffer).isOk()) {
1001 qWarning() << "serializeToByteArray():: Could not export to our native format";
1002 }
1003
1004 return buffer.data();
1005}
1006
1007class DlgLoadMessages : public QMessageBox
1008{
1009public:
1010 DlgLoadMessages(const QString &title,
1011 const QString &message,
1012 const QStringList &warnings = {},
1013 const QString &details = {})
1014 : QMessageBox(QMessageBox::Warning, title, message, QMessageBox::Ok, qApp->activeWindow())
1015 {
1016 if (!details.isEmpty()) {
1017 setInformativeText(details);
1018 }
1019 if (!warnings.isEmpty()) {
1020 setDetailedText(warnings);
1021 }
1022 }
1023
1024private:
1026 {
1027 QMessageBox::setDetailedText(text.first());
1028
1029 QTextEdit *messageBox = findChild<QTextEdit *>();
1030
1031 if (messageBox) {
1032 messageBox->setAcceptRichText(true);
1033
1034 QString warning = "<html><body><ul>";
1035 Q_FOREACH (const QString &i, text) {
1036 warning += "\n<li>" + i + "</li>";
1037 }
1038 warning += "</ul></body></html>";
1039
1040 messageBox->setText(warning);
1041 }
1042 }
1043};
1044
1045void KisDocument::slotCompleteSavingDocument(const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
1046{
1047 if (status.isCancelled())
1048 return;
1049
1050 const QString fileName = QFileInfo(job.filePath).fileName();
1051
1052 if (!status.isOk()) {
1053 Q_EMIT statusBarMessage(i18nc("%1 --- failing file name, %2 --- error message",
1054 "Error during saving %1: %2",
1055 fileName,
1056 errorMessage), errorMessageTimeout);
1057
1058
1059 if (!fileBatchMode()) {
1060 DlgLoadMessages dlg(i18nc("@title:window", "Krita"),
1061 i18n("Could not save %1.", job.filePath),
1062 errorMessage.split("\n", Qt::SkipEmptyParts)
1063 + warningMessage.split("\n", Qt::SkipEmptyParts),
1064 status.errorMessage());
1065
1066 dlg.exec();
1067 }
1068 }
1069 else {
1070 if (!fileBatchMode() && !warningMessage.isEmpty()) {
1071
1072 QStringList reasons = warningMessage.split("\n", Qt::SkipEmptyParts);
1073
1074 DlgLoadMessages dlg(
1075 i18nc("@title:window", "Krita"),
1076 i18nc("dialog box shown to the user if there were warnings while saving the document, "
1077 "%1 is the file path",
1078 "%1 has been saved but is incomplete.",
1079 job.filePath),
1080 reasons,
1081 reasons.isEmpty()
1082 ? ""
1083 : i18nc("dialog box shown to the user if there were warnings while saving the document",
1084 "Some problems were encountered when saving."));
1085 dlg.exec();
1086 }
1087
1088
1089 if (!(job.flags & KritaUtils::SaveIsExporting)) {
1090 const QString existingAutoSaveBaseName = localFilePath();
1091 const bool wasRecovered = isRecovered();
1092
1093 d->updateDocumentMetadataOnSaving(job.filePath, job.mimeType);
1094
1095 removeAutoSaveFiles(existingAutoSaveBaseName, wasRecovered);
1096 }
1097
1098 Q_EMIT completed();
1099 Q_EMIT sigSavingFinished(job.filePath);
1100
1101 Q_EMIT statusBarMessage(i18n("Finished saving %1", fileName), successMessageTimeout);
1102 }
1103}
1104
1105void KisDocument::Private::updateDocumentMetadataOnSaving(const QString &filePath, const QByteArray &mimeType)
1106{
1107 q->setPath(filePath);
1108 q->setLocalFilePath(filePath);
1109 q->setMimeType(mimeType);
1110 q->updateEditingTime(true);
1111
1112#ifdef Q_OS_ANDROID
1113 // See the comment titled "ANDROID NOTES" in this file for an explanation of
1114 // what this is about. (This is not that comment.)
1115 q->setReadWrite(true);
1116#else
1117 QFileInfo fi(filePath);
1118 q->setReadWrite(fi.isWritable());
1119#endif
1120
1121 if (!modifiedWhileSaving) {
1128 if (undoStack->isClean()) {
1129 q->setModified(false);
1130 } else {
1131 imageModifiedWithoutUndo = false;
1132 undoStack->setClean();
1133 }
1134 }
1135 q->setRecovered(false);
1136}
1137
1138QByteArray KisDocument::mimeType() const
1139{
1140 return d->mimeType;
1141}
1142
1143void KisDocument::setMimeType(const QByteArray & mimeType)
1144{
1145 d->mimeType = mimeType;
1146}
1147
1149{
1150 return d->batchMode;
1151}
1152
1153void KisDocument::setFileBatchMode(const bool batchMode)
1154{
1155 d->batchMode = batchMode;
1156}
1157
1158void KisDocument::Private::uploadLinkedResourcesFromLayersToStorage()
1159{
1164
1165 KisDocument *doc = q;
1166
1168 [doc] (KisNodeSP node) {
1169 if (KisNodeFilterInterface *layer = dynamic_cast<KisNodeFilterInterface*>(node.data())) {
1170 KisFilterConfigurationSP filterConfig = layer->filter();
1171 if (!filterConfig) return;
1172
1173 QList<KoResourceLoadResult> linkedResources = filterConfig->linkedResources(KisGlobalResourcesInterface::instance());
1174
1175 Q_FOREACH (const KoResourceLoadResult &result, linkedResources) {
1176 KIS_SAFE_ASSERT_RECOVER(result.type() != KoResourceLoadResult::EmbeddedResource) { continue; }
1177
1178 KoResourceSP resource = result.resource();
1179
1180 if (!resource) {
1181 qWarning() << "WARNING: KisDocument::lockAndCloneForSaving failed to fetch a resource" << result.signature();
1182 continue;
1183 }
1184
1185 QBuffer buf;
1186 buf.open(QBuffer::WriteOnly);
1187
1188 KisResourceModel model(resource->resourceType().first);
1189 bool res = model.exportResource(resource, &buf);
1190
1191 buf.close();
1192
1193 if (!res) {
1194 qWarning() << "WARNING: KisDocument::lockAndCloneForSaving failed to export resource" << result.signature();
1195 continue;
1196 }
1197
1198 buf.open(QBuffer::ReadOnly);
1199
1200 res = doc->d->linkedResourceStorage->importResource(resource->resourceType().first + "/" + resource->filename(), &buf);
1201
1202 buf.close();
1203
1204 if (!res) {
1205 qWarning() << "WARNING: KisDocument::lockAndCloneForSaving failed to import resource" << result.signature();
1206 continue;
1207 }
1208 }
1209
1210 }
1211 });
1212}
1213
1214KisDocument *KisDocument::Private::lockAndCloneImpl(bool fetchResourcesFromLayers)
1215{
1216 // force update of all the asynchronous nodes before cloning
1217 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1219
1221 if (window) {
1222 if (window->viewManager()) {
1223 if (!window->viewManager()->blockUntilOperationsFinished(image)) {
1224 return 0;
1225 }
1226 }
1227 }
1228
1229 Private::StrippedSafeSavingLocker locker(&savingMutex, image);
1230 if (!locker.successfullyLocked()) {
1231 return 0;
1232 }
1233
1234 KisDocument *doc = new KisDocument(*this->q, false);
1235
1236 if (fetchResourcesFromLayers) {
1237 doc->d->uploadLinkedResourcesFromLayersToStorage();
1238 }
1239
1240 return doc;
1241}
1242
1244{
1245 return d->lockAndCloneImpl(true);
1246}
1247
1249{
1250 return d->lockAndCloneImpl(false);
1251}
1252
1257
1259{
1260 if (policy == REPLACE) {
1261 d->decorationsSyncingDisabled = true;
1262 d->copyFrom(*(rhs.d), this);
1263 d->decorationsSyncingDisabled = false;
1264
1265 d->undoStack->clear();
1266 } else {
1267 // in CONSTRUCT mode, d should be already initialized
1268 connect(KisConfigNotifier::instance(), SIGNAL(configChanged()), SLOT(slotConfigChanged()));
1269 connect(d->undoStack, SIGNAL(cleanChanged(bool)), this, SLOT(slotUndoStackCleanChanged(bool)));
1270 connect(d->autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
1271
1272 d->shapeController = new KisShapeController(d->nserver, d->undoStack, this);
1273 d->koShapeController = new KoShapeController(0, d->shapeController);
1274 }
1275
1276 setObjectName(rhs.objectName());
1277
1279
1280 if (rhs.d->image) {
1281 if (policy == REPLACE) {
1282 d->image->barrierLock(/* readOnly = */ false);
1283 rhs.d->image->barrierLock(/* readOnly = */ true);
1284 d->image->copyFromImage(*(rhs.d->image));
1285 d->image->unlock();
1286 rhs.d->image->unlock();
1287
1288 setCurrentImage(d->image, /* forceInitialUpdate = */ true);
1289 } else {
1290 // clone the image with keeping the GUIDs of the layers intact
1291 // NOTE: we expect the image to be locked!
1292 setCurrentImage(rhs.image()->clone(/* exactCopy = */ true), /* forceInitialUpdate = */ false);
1293 }
1294 }
1295
1296 if (policy == REPLACE) {
1297 d->syncDecorationsWrapperLayerState();
1298 }
1299
1300 if (rhs.d->preActivatedNode) {
1301 QQueue<KisNodeSP> linearizedNodes;
1302 KisLayerUtils::recursiveApplyNodes(rhs.d->image->root(),
1303 [&linearizedNodes](KisNodeSP node) {
1304 linearizedNodes.enqueue(node);
1305 });
1307 [&linearizedNodes, &rhs, this](KisNodeSP node) {
1308 KisNodeSP refNode = linearizedNodes.dequeue();
1309 if (rhs.d->preActivatedNode.data() == refNode.data()) {
1310 d->preActivatedNode = node;
1311 }
1312 });
1313 }
1314
1315 // reinitialize references' signal connection
1316 KisReferenceImagesLayerSP referencesLayer = this->referenceImagesLayer();
1317 if (referencesLayer) {
1318 d->referenceLayerConnections.clear();
1319 d->referenceLayerConnections.addConnection(
1320 referencesLayer, SIGNAL(sigUpdateCanvas(QRectF)),
1321 this, SIGNAL(sigReferenceImagesChanged()));
1322
1323 Q_EMIT sigReferenceImagesLayerChanged(referencesLayer);
1324 Q_EMIT sigReferenceImagesChanged();
1325 }
1326
1327 KisDecorationsWrapperLayerSP decorationsLayer =
1328 KisLayerUtils::findNodeByType<KisDecorationsWrapperLayer>(d->image->root());
1329 if (decorationsLayer) {
1330 decorationsLayer->setDocument(this);
1331 }
1332
1333
1334 if (policy == REPLACE) {
1335 setModified(true);
1336 }
1337}
1338
1339bool KisDocument::exportDocumentSync(const QString &path, const QByteArray &mimeType, KisPropertiesConfigurationSP exportConfiguration)
1340{
1341 {
1348 Private::StrippedSafeSavingLocker locker(&d->savingMutex, d->image);
1349 if (!locker.successfullyLocked()) {
1350 return false;
1351 }
1352 }
1353
1354 d->savingImage = d->image;
1355
1357 d->importExportManager->
1358 exportDocument(path, path, mimeType, false, exportConfiguration);
1359
1360 d->savingImage = 0;
1361
1362 return status.isOk();
1363}
1364
1365
1367 const QObject *receiverObject, const char *receiverMethod,
1368 const KritaUtils::ExportFileJob &job,
1369 KisPropertiesConfigurationSP exportConfiguration,bool isAdvancedExporting)
1370{
1371 return initiateSavingInBackground(actionName, receiverObject, receiverMethod,
1372 job, exportConfiguration, std::unique_ptr<KisDocument>(), isAdvancedExporting);
1373}
1374
1376 const QObject *receiverObject, const char *receiverMethod,
1377 const KritaUtils::ExportFileJob &job,
1378 KisPropertiesConfigurationSP exportConfiguration,
1379 std::unique_ptr<KisDocument> &&optionalClonedDocument,bool isAdvancedExporting)
1380{
1382
1383 std::unique_ptr<KisDocument> clonedDocument;
1384
1385 if (!optionalClonedDocument) {
1386 clonedDocument.reset(lockAndCloneForSaving());
1387 } else {
1388 clonedDocument.reset(optionalClonedDocument.release());
1389 }
1390
1391 if (!d->savingMutex.tryLock()){
1393 }
1394
1399 std::unique_lock<QMutex> savingMutexLock(d->savingMutex, std::adopt_lock);
1400
1401 if (!clonedDocument) {
1403 }
1404
1405 auto waitForImage = [] (KisImageSP image) {
1407 if (window) {
1408 if (window->viewManager()) {
1410 }
1411 }
1412 };
1413
1414 {
1415 KisNodeSP newRoot = clonedDocument->image()->root();
1418 waitForImage(clonedDocument->image());
1419 }
1420 }
1421
1422 if (clonedDocument->image()->hasOverlaySelectionMask()) {
1423 clonedDocument->image()->setOverlaySelectionMask(0);
1424 waitForImage(clonedDocument->image());
1425 }
1426
1427 KisConfig cfg(true);
1428 if (cfg.trimKra()) {
1429 clonedDocument->image()->cropImage(clonedDocument->image()->bounds());
1430 clonedDocument->image()->purgeUnusedData(false);
1431 waitForImage(clonedDocument->image());
1432 }
1433
1434 KIS_SAFE_ASSERT_RECOVER(clonedDocument->image()->isIdle()) {
1435 waitForImage(clonedDocument->image());
1436 }
1437
1440
1450 savingMutexLock.release();
1451
1452 d->backgroundSaveDocument.reset(clonedDocument.release());
1453 d->backgroundSaveJob = job;
1454 d->modifiedWhileSaving = false;
1455
1456 if (d->backgroundSaveJob.flags & KritaUtils::SaveInAutosaveMode) {
1457 d->backgroundSaveDocument->d->isAutosaving = true;
1458 }
1459
1460 connect(d->backgroundSaveDocument.get(),
1461 SIGNAL(sigBackgroundSavingFinished(KisImportExportErrorCode, QString, QString)),
1462 this,
1464
1465
1466 if (d->completeSavingConnection) {
1467 disconnect(d->completeSavingConnection);
1468 }
1469 d->completeSavingConnection = connect(
1471 receiverObject, receiverMethod);
1472
1474 d->backgroundSaveDocument->startExportInBackground(actionName,
1475 job.filePath,
1476 job.filePath,
1477 job.mimeType,
1479 exportConfiguration, isAdvancedExporting);
1480 if (!error.isOk()) {
1481 // the state should have been deinitialized in slotChildCompletedSavingInBackground()
1482 KIS_SAFE_ASSERT_RECOVER (!d->backgroundSaveDocument && !d->backgroundSaveJob.isValid()) {
1483 d->backgroundSaveDocument.release()->deleteLater();
1484 d->savingMutex.unlock();
1485 d->backgroundSaveJob = KritaUtils::ExportFileJob();
1486 }
1487 if (error.isCancelled()) {
1489 }
1491 }
1492
1494}
1495
1496
1497void KisDocument::slotChildCompletedSavingInBackground(KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
1498{
1500
1506 std::unique_lock<QMutex> savingMutexLock(d->savingMutex, std::adopt_lock);
1507
1508 KIS_ASSERT_RECOVER_RETURN(d->backgroundSaveDocument);
1509
1510 if (d->backgroundSaveJob.flags & KritaUtils::SaveInAutosaveMode) {
1511 d->backgroundSaveDocument->d->isAutosaving = false;
1512 }
1513
1514 d->backgroundSaveDocument.release()->deleteLater();
1515
1516 KIS_ASSERT_RECOVER_RETURN(d->backgroundSaveJob.isValid());
1517
1518 const KritaUtils::ExportFileJob job = d->backgroundSaveJob;
1519 d->backgroundSaveJob = KritaUtils::ExportFileJob();
1520
1521 // unlock at the very end
1522 savingMutexLock.unlock();
1523
1524 QFileInfo fi(job.filePath);
1525 KisUsageLogger::log(QString("Completed saving %1 (mime: %2). Result: %3. Warning: %4. Size: %5")
1526 .arg(job.filePath, QString::fromLatin1(job.mimeType),
1527 (!status.isOk() ? errorMessage : "OK"), warningMessage,
1528 QString::number(fi.size())));
1529
1531 // One-shot: disconnect immediately after firing so future save completions
1532 // don't invoke a stale or unrelated slot.
1533 disconnect(d->completeSavingConnection);
1534 d->completeSavingConnection = {};
1535}
1536
1537void KisDocument::slotAutoSaveImpl(std::unique_ptr<KisDocument> &&optionalClonedDocument)
1538{
1539 if (!d->modified || !d->modifiedAfterAutosave) return;
1540 const QString autoSaveFileName = generateAutoSaveFileName(localFilePath());
1541
1542 Q_EMIT statusBarMessage(i18n("Autosaving... %1", autoSaveFileName), successMessageTimeout);
1543
1544 KisUsageLogger::log(QString("Autosaving: %1").arg(autoSaveFileName));
1545
1546 const bool hadClonedDocument = bool(optionalClonedDocument);
1548
1549 if (d->image->isIdle() || hadClonedDocument) {
1550 result = initiateSavingInBackground(i18n("Autosaving..."),
1553 0,
1554 std::move(optionalClonedDocument));
1555 } else {
1556 Q_EMIT statusBarMessage(i18n("Autosaving postponed: document is busy..."), errorMessageTimeout);
1557 }
1558
1559 if (result != KritaUtils::BackgroudSavingStartResult::Success && !hadClonedDocument && d->autoSaveFailureCount >= 3) {
1561 connect(stroke, SIGNAL(sigDocumentCloned(KisDocument*)),
1563 Qt::BlockingQueuedConnection);
1564 connect(stroke, SIGNAL(sigCloningCancelled()),
1565 this, SLOT(slotDocumentCloningCancelled()),
1566 Qt::BlockingQueuedConnection);
1567
1568 KisStrokeId strokeId = d->image->startStroke(stroke);
1569 d->image->endStroke(strokeId);
1570
1572
1575 } else {
1576 d->modifiedAfterAutosave = false;
1577 }
1578}
1579
1580bool KisDocument::resourceSavingFilter(const QString &path, const QByteArray &mimeType, KisPropertiesConfigurationSP exportConfiguration)
1581{
1582 if (QFileInfo(path).absolutePath().startsWith(KisResourceLocator::instance()->resourceLocationBase())) {
1583
1584 QStringList pathParts = QFileInfo(path).absolutePath().split('/');
1585 if (pathParts.size() > 0) {
1586 QString resourceType = pathParts.last();
1587 if (KisResourceLoaderRegistry::instance()->resourceTypes().contains(resourceType)) {
1588
1589 KisResourceModel model(resourceType);
1591
1592 QString tempFileName = QDir::tempPath() + "/" + QFileInfo(path).fileName();
1593
1594 if (QFileInfo(path).exists()) {
1595
1596 int outResourceId;
1597 KoResourceSP res;
1598 if (KisResourceCacheDb::getResourceIdFromVersionedFilename(QFileInfo(path).fileName(), resourceType, "", outResourceId)) {
1599 res = model.resourceForId(outResourceId);
1600 }
1601
1602 if (res) {
1603 d->modifiedWhileSaving = false;
1604
1605 if (!exportConfiguration) {
1606 QScopedPointer<KisImportExportFilter> filter(
1608 if (filter) {
1609 exportConfiguration = filter->defaultConfiguration(nativeFormatMimeType(), mimeType);
1610 }
1611 }
1612
1613 if (exportConfiguration) {
1614 // make sure the name of the resource doesn't change
1615 exportConfiguration->setProperty("name", res->name());
1616 }
1617
1618 if (exportDocumentSync(tempFileName, mimeType, exportConfiguration)) {
1619 QFile f2(tempFileName);
1620 KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(f2.open(QFile::ReadOnly), false);
1621
1622 QByteArray ba = f2.readAll();
1623
1624 QBuffer buf(&ba);
1625 buf.open(QBuffer::ReadOnly);
1626
1627
1628
1629 if (res->loadFromDevice(&buf, KisGlobalResourcesInterface::instance())) {
1630 if (model.updateResource(res)) {
1631 const QString filePath =
1633
1634 d->updateDocumentMetadataOnSaving(filePath, mimeType);
1635
1636 return true;
1637 }
1638 }
1639 }
1640 }
1641 }
1642 else {
1643 d->modifiedWhileSaving = false;
1644 if (exportDocumentSync(tempFileName, mimeType, exportConfiguration)) {
1645 KoResourceSP res = model.importResourceFile(tempFileName, false);
1646 if (res) {
1647 const QString filePath =
1649
1650 d->updateDocumentMetadataOnSaving(filePath, mimeType);
1651
1652 return true;
1653 }
1654 }
1655 }
1656 }
1657 }
1658 }
1659 return false;
1660}
1661
1663{
1664 slotAutoSaveImpl(std::unique_ptr<KisDocument>());
1665}
1666
1668{
1669 slotAutoSaveImpl(std::unique_ptr<KisDocument>(clonedDocument));
1670}
1671
1676
1678{
1679 d->image->explicitRegenerateLevelOfDetail();
1680
1681
1685
1686 // d->image->purgeUnusedData(true);
1687}
1688
1689void KisDocument::slotCompleteAutoSaving(const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
1690{
1691 Q_UNUSED(job);
1692 Q_UNUSED(warningMessage);
1693
1694 const QString fileName = QFileInfo(job.filePath).fileName();
1695
1696 if (!status.isOk()) {
1698 Q_EMIT statusBarMessage(i18nc("%1 --- failing file name, %2 --- error message",
1699 "Error during autosaving %1: %2",
1700 fileName,
1701 exportErrorToUserMessage(status, errorMessage)), errorMessageTimeout);
1702 } else {
1703 KisConfig cfg(true);
1704 d->autoSaveDelay = cfg.autoSaveInterval();
1705
1706 if (!d->modifiedWhileSaving) {
1707 d->autoSaveTimer->stop(); // until the next change
1708 d->autoSaveFailureCount = 0;
1709 } else {
1711 }
1712
1713 Q_EMIT statusBarMessage(i18n("Finished autosaving %1", fileName), successMessageTimeout);
1714 }
1715}
1716
1718 const QString &location,
1719 const QString &realLocation,
1720 const QByteArray &mimeType,
1721 bool showWarnings,
1722 KisPropertiesConfigurationSP exportConfiguration, bool isAdvancedExporting)
1723{
1724 d->savingImage = d->image;
1725
1727 if (window) {
1728 if (window->viewManager()) {
1729 d->savingUpdater = window->viewManager()->createThreadedUpdater(actionName);
1730 d->importExportManager->setUpdater(d->savingUpdater);
1731 }
1732 }
1733
1734 KisImportExportErrorCode initializationStatus(ImportExportCodes::OK);
1735 d->childSavingFuture =
1736 d->importExportManager->exportDocumentAsync(location,
1737 realLocation,
1738 mimeType,
1739 initializationStatus,
1740 showWarnings,
1741 exportConfiguration,
1742 isAdvancedExporting);
1743
1744 if (!initializationStatus.isOk()) {
1745 if (d->savingUpdater) {
1746 d->savingUpdater->cancel();
1747 }
1748 d->savingImage.clear();
1749 Q_EMIT sigBackgroundSavingFinished(initializationStatus, initializationStatus.errorMessage(), "");
1750 return initializationStatus;
1751 }
1752
1753 typedef QFutureWatcher<KisImportExportErrorCode> StatusWatcher;
1754 StatusWatcher *watcher = new StatusWatcher();
1755 watcher->setFuture(d->childSavingFuture);
1756
1757 connect(watcher, SIGNAL(finished()), SLOT(finishExportInBackground()));
1758 connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater()));
1759
1760 return initializationStatus;
1761}
1762
1764{
1765 KIS_SAFE_ASSERT_RECOVER(d->childSavingFuture.isFinished()) {
1767 return;
1768 }
1769
1770 KisImportExportErrorCode status = d->childSavingFuture.result();
1771 QString errorMessage = status.errorMessage();
1772 QString warningMessage = d->lastWarningMessage;
1773
1774 if (!d->lastErrorMessage.isEmpty()) {
1776 errorMessage = d->lastErrorMessage;
1777 } else {
1778 errorMessage += "\n" + d->lastErrorMessage;
1779 }
1780 }
1781
1782 d->savingImage.clear();
1783 d->childSavingFuture = QFuture<KisImportExportErrorCode>();
1784 d->lastErrorMessage.clear();
1785 d->lastWarningMessage.clear();
1786
1787 if (d->savingUpdater) {
1788 d->savingUpdater->setProgress(100);
1789 }
1790
1792}
1793
1794void KisDocument::setReadWrite(bool readwrite)
1795{
1796 const bool changed = readwrite != d->readwrite;
1797
1798 d->readwrite = readwrite;
1799
1800 if (changed) {
1802 }
1803}
1804
1805void KisDocument::setAutoSaveActive(bool autoSaveActive)
1806{
1807 const bool changed = autoSaveActive != d->autoSaveActive;
1808
1809 if (changed) {
1810 d->autoSaveActive = autoSaveActive;
1812 }
1813}
1814
1816{
1817 if (isReadWrite() && delay > 0 && d->autoSaveActive) {
1818 d->autoSaveTimer->start(delay * 1000);
1819 } else {
1820 d->autoSaveTimer->stop();
1821 }
1822}
1823
1825{
1826 setAutoSaveDelay(d->autoSaveDelay);
1827 d->autoSaveFailureCount = 0;
1828}
1829
1831{
1832 const int emergencyAutoSaveInterval = 10; /* sec */
1833 setAutoSaveDelay(emergencyAutoSaveInterval);
1834 d->autoSaveFailureCount++;
1835}
1836
1841
1843{
1844 return d->autoSaveActive;
1845}
1846
1848{
1849 return d->docInfo;
1850}
1851
1853{
1854 return d->modified;
1855}
1856
1857QPixmap KisDocument::generatePreview(const QSize& size)
1858{
1859 KisImageSP image = d->image;
1860 if (d->savingImage) image = d->savingImage;
1861
1862 if (image) {
1863 QRect bounds = image->bounds();
1864 QSize originalSize = bounds.size();
1865 // QSize may round down one dimension to zero on extreme aspect rations, so ensure 1px minimum
1866 QSize newSize = originalSize.scaled(size, Qt::KeepAspectRatio).expandedTo({1, 1});
1867
1868 bool pixelArt = false;
1869 // determine if the image is pixel art or not
1870 if (originalSize.width() < size.width() && originalSize.height() < size.height()) {
1871 // the image must be smaller than the requested preview
1872 // the scale must be integer
1873 if (newSize.height()%originalSize.height() == 0 && newSize.width()%originalSize.width() == 0) {
1874 pixelArt = true;
1875 }
1876 }
1877
1878 QPixmap px;
1879 if (pixelArt) {
1880 // do not scale while converting (because it uses Bicubic)
1881 QImage original = image->convertToQImage(originalSize, 0);
1882 // scale using FastTransformation, which is probably Nearest neighbour, suitable for pixel art
1883 QImage scaled = original.scaled(newSize, Qt::KeepAspectRatio, Qt::FastTransformation);
1884 px = QPixmap::fromImage(scaled);
1885 } else {
1886 px = QPixmap::fromImage(image->convertToQImage(newSize, 0));
1887 }
1888 if (px.size() == QSize(0,0)) {
1889 px = QPixmap(newSize);
1890 QPainter gc(&px);
1891 QBrush checkBrush = QBrush(KisCanvasWidgetBase::createCheckersImage(newSize.width() / 5));
1892 gc.fillRect(px.rect(), checkBrush);
1893 gc.end();
1894 }
1895 return px;
1896 }
1897 return QPixmap(size);
1898}
1899
1900QString KisDocument::generateAutoSaveFileName(const QString & path) const
1901{
1902 QString retval;
1903
1904 // Using the extension allows to avoid relying on the mime magic when opening
1905 const QString extension (".kra");
1906 QString prefix = KisConfig(true).readEntry<bool>("autosavefileshidden") ? QString(".") : QString();
1907 QRegularExpression autosavePattern1("^\\..+-autosave.kra$");
1908 QRegularExpression autosavePattern2("^.+-autosave.kra$");
1909
1910 QFileInfo fi(path);
1911 QString dir = fi.absolutePath();
1912
1913#ifdef Q_OS_ANDROID
1914 // URIs may or may not have a directory backing them, so we save to our default autosave location
1915 if (path.startsWith("content://")) {
1917 QDir().mkpath(dir);
1918 }
1919#endif
1920
1921 QString filename = fi.fileName();
1922
1923 if (path.isEmpty() || autosavePattern1.match(filename).hasMatch() || autosavePattern2.match(filename).hasMatch() || !fi.isWritable()) {
1924 // Never saved?
1925 retval = QString("%1%2%3%4-%5-%6-autosave%7")
1927 .arg('/')
1928 .arg(prefix)
1929 .arg("krita")
1930 .arg(qApp->applicationPid())
1931 .arg(objectName())
1932 .arg(extension);
1933 } else {
1934 // Beware: don't reorder arguments
1935 // otherwise in case of filename = '1-file.kra' it will become '.-file.kra-autosave.kra' instead of '.1-file.kra-autosave.kra'
1936 retval = QString("%1%2%3%4-autosave%5").arg(dir).arg('/').arg(prefix).arg(filename).arg(extension);
1937 }
1938
1939 //qDebug() << "generateAutoSaveFileName() for path" << path << ":" << retval;
1940 return retval;
1941}
1942
1943bool KisDocument::importDocument(const QString &_path)
1944{
1945 bool ret;
1946
1947 dbgUI << "path=" << _path;
1948
1949 // open...
1950 ret = openPath(_path);
1951
1952 // reset url & m_file (kindly? set by KisParts::openUrl()) to simulate a
1953 // File --> Import
1954 if (ret) {
1955 dbgUI << "success, resetting url";
1956 resetPath();
1957 }
1958
1959 return ret;
1960}
1961
1962
1963bool KisDocument::openPath(const QString &_path, OpenFlags flags)
1964{
1965 dbgUI << "path=" << _path;
1966 d->lastErrorMessage.clear();
1967
1968 // Reimplemented, to add a check for autosave files and to improve error reporting
1969 if (_path.isEmpty()) {
1970 d->lastErrorMessage = i18n("Malformed Path\n%1", _path); // ## used anywhere ?
1971 return false;
1972 }
1973
1974 QString path = _path;
1975 QString original = "";
1976 bool autosaveOpened = false;
1977 if (!fileBatchMode()) {
1978 QString file = path;
1979 QString asf = generateAutoSaveFileName(file);
1980 if (QFile::exists(asf)) {
1981 KisApplication *kisApp = static_cast<KisApplication*>(qApp);
1982 kisApp->hideSplashScreen();
1983 //qDebug() <<"asf=" << asf;
1984 // ## TODO compare timestamps ?
1985 KisRecoverNamedAutosaveDialog dlg(0, file, asf);
1986 dlg.exec();
1987 int res = dlg.result();
1988
1989 switch (res) {
1991 original = file;
1992 path = asf;
1993 autosaveOpened = true;
1994 break;
1996 KisUsageLogger::log(QString("Removing autosave file: %1").arg(asf));
1997 QFile::remove(asf);
1998 break;
1999 default: // Cancel
2000 return false;
2001 }
2002 }
2003 }
2004
2005 bool ret = openPathInternal(path);
2006
2007 if (autosaveOpened || flags & RecoveryFile) {
2008 setReadWrite(true); // enable save button
2009 setModified(true);
2010 setRecovered(true);
2011
2012 setPath(original); // since it was an autosave, it will be a local file
2013 setLocalFilePath(original);
2014 }
2015 else {
2016 if (ret) {
2017
2018 if (!(flags & DontAddToRecent)) {
2019 KisPart::instance()->addRecentURLToAllMainWindows(QUrl::fromLocalFile(_path));
2020 }
2021
2022#ifdef Q_OS_ANDROID
2023 // See the comment titled "ANDROID NOTES" in this file for an
2024 // explanation of what this is about. (This is not that comment.)
2025 setReadWrite(true);
2026#else
2027 QFileInfo fi(_path);
2028 setReadWrite(fi.isWritable());
2029#endif
2030 }
2031
2032 setRecovered(false);
2033 }
2034
2035 return ret;
2036}
2037
2039{
2040 //dbgUI <<"for" << localFilePath();
2041 if (!QFile::exists(localFilePath()) && !fileBatchMode()) {
2042 QMessageBox::critical(qApp->activeWindow(), i18nc("@title:window", "Krita"), i18n("File %1 does not exist.", localFilePath()));
2043 return false;
2044 }
2045
2046 QString filename = localFilePath();
2047 QString typeName = mimeType();
2048
2049 if (typeName.isEmpty()) {
2050 typeName = KisMimeDatabase::mimeTypeForFile(filename);
2051 }
2052
2053 // Allow to open backup files, don't keep the mimeType application/x-trash.
2054 if (typeName == "application/x-trash") {
2055 QString path = filename;
2056 while (path.length() > 0) {
2057 path.chop(1);
2058 typeName = KisMimeDatabase::mimeTypeForFile(path);
2059 //qDebug() << "\t" << path << typeName;
2060 if (!typeName.isEmpty()) {
2061 break;
2062 }
2063 }
2064 //qDebug() << "chopped" << filename << "to" << path << "Was trash, is" << typeName;
2065 }
2066 dbgUI << localFilePath() << "type:" << typeName;
2067
2069 KoUpdaterPtr updater;
2070 if (window && window->viewManager()) {
2071 updater = window->viewManager()->createUnthreadedUpdater(i18n("Opening document"));
2072 d->importExportManager->setUpdater(updater);
2073 }
2074
2075 KisImportExportErrorCode status = d->importExportManager->importDocument(localFilePath(), typeName);
2076
2077 if (!status.isOk()) {
2078 if (window && window->viewManager()) {
2079 updater->cancel();
2080 }
2081 QString msg = status.errorMessage();
2082 KisUsageLogger::log(QString("Loading %1 failed: %2").arg(prettyPath(), msg));
2083
2084 if (!msg.isEmpty() && !fileBatchMode()) {
2085 DlgLoadMessages dlg(i18nc("@title:window", "Krita"),
2086 i18n("Could not open %1.", prettyPath()),
2087 errorMessage().split("\n", Qt::SkipEmptyParts)
2088 + warningMessage().split("\n", Qt::SkipEmptyParts),
2089 msg);
2090
2091 dlg.exec();
2092 }
2093 return false;
2094 }
2095 else if (!warningMessage().isEmpty() && !fileBatchMode()) {
2096 DlgLoadMessages dlg(i18nc("@title:window", "Krita"),
2097 i18n("There were problems opening %1.", prettyPath()),
2098 warningMessage().split("\n", Qt::SkipEmptyParts));
2099
2100 dlg.exec();
2101 setPath(QString());
2102 }
2103
2104 setMimeTypeAfterLoading(typeName);
2105 d->syncDecorationsWrapperLayerState();
2106 Q_EMIT sigLoadingFinished();
2107
2108 undoStack()->clear();
2109
2110 return true;
2111}
2112
2114{
2115 if (!d->modified || !d->modifiedAfterAutosave)
2116 return;
2117
2118 const QString autoSaveFileName = generateAutoSaveFileName(localFilePath());
2119
2120 bool started = exportDocumentSync(autoSaveFileName, nativeFormatMimeType());
2121
2122 if (started)
2123 {
2124 d->modifiedAfterAutosave = false;
2125 dbgAndroid << "autoSaveOnPause successful";
2126 }
2127 else
2128 {
2129 qWarning() << "Could not auto-save when paused";
2130 }
2131}
2132
2133// shared between openFile and koMainWindow's "create new empty document" code
2134void KisDocument::setMimeTypeAfterLoading(const QString& mimeType)
2135{
2136 d->mimeType = mimeType.toLatin1();
2137 d->outputMimeType = d->mimeType;
2138}
2139
2140
2141bool KisDocument::loadNativeFormat(const QString & file_)
2142{
2143 return openPath(file_);
2144}
2145
2147{
2148 if (mod) {
2149 updateEditingTime(false);
2150 }
2151
2156 if (d->isAutosaving || d->documentIsClosing)
2157 return;
2158
2159 //dbgUI<<" url:" << url.path();
2160 //dbgUI<<" mod="<<mod<<" MParts mod="<<KisParts::ReadWritePart::isModified()<<" isModified="<<isModified();
2161
2162 if (mod && !d->autoSaveTimer->isActive()) {
2163 // First change since last autosave -> start the autosave timer
2165 }
2166 d->modifiedAfterAutosave = mod;
2167 d->modifiedWhileSaving = mod;
2168
2169 if (!mod) {
2170 d->imageModifiedWithoutUndo = mod;
2171 }
2172
2173 if (mod == isModified())
2174 return;
2175
2176 d->modified = mod;
2177
2178 if (mod) {
2180 }
2181
2182 Q_EMIT modified(mod);
2183}
2184
2186{
2187 const bool changed = value != d->isRecovered;
2188
2189 d->isRecovered = value;
2190
2191 if (changed) {
2192 Q_EMIT sigRecoveredChanged(value);
2193 }
2194}
2195
2196bool KisDocument::isRecovered() const
2197{
2198 return d->isRecovered;
2199}
2200
2201void KisDocument::updateEditingTime(bool forceStoreElapsed)
2202{
2203 QDateTime now = QDateTime::currentDateTime();
2204 int firstModDelta = d->firstMod.secsTo(now);
2205 int lastModDelta = d->lastMod.secsTo(now);
2206
2207 if (lastModDelta > 30) {
2208 d->docInfo->setAboutInfo("editing-time", QString::number(d->docInfo->aboutInfo("editing-time").toInt() + d->firstMod.secsTo(d->lastMod)));
2209 d->firstMod = now;
2210 } else if (firstModDelta > 60 || forceStoreElapsed) {
2211 d->docInfo->setAboutInfo("editing-time", QString::number(d->docInfo->aboutInfo("editing-time").toInt() + firstModDelta));
2212 d->firstMod = now;
2213 }
2214
2215 d->lastMod = now;
2216}
2217
2219{
2220 QString _url(path());
2221#ifdef Q_OS_WIN
2222 _url = QDir::toNativeSeparators(_url);
2223#endif
2224 return _url;
2225}
2226
2227// Get caption from document info (title(), in about page)
2229{
2230 QString c;
2231 const QString _url(QFileInfo(path()).fileName());
2232
2233 // if URL is empty...it is probably an unsaved file
2234 if (_url.isEmpty()) {
2235 c = " [" + i18n("Not Saved") + "] ";
2236 } else {
2237 c = _url; // Fall back to document URL
2238 }
2239
2240 return c;
2241}
2242
2243QDomDocument KisDocument::createDomDocument(const QString& tagName, const QString& version) const
2244{
2245 return createDomDocument("krita", tagName, version);
2246}
2247
2248//static
2249QDomDocument KisDocument::createDomDocument(const QString& appName, const QString& tagName, const QString& version)
2250{
2251 QDomImplementation impl;
2252 QString url = QString("http://www.calligra.org/DTD/%1-%2.dtd").arg(appName).arg(version);
2253 QDomDocumentType dtype = impl.createDocumentType(tagName,
2254 QString("-//KDE//DTD %1 %2//EN").arg(appName).arg(version),
2255 url);
2256 // The namespace URN doesn't need to include the version number.
2257 QString namespaceURN = QString("http://www.calligra.org/DTD/%1").arg(appName);
2258 QDomDocument doc = impl.createDocument(namespaceURN, tagName, dtype);
2259 doc.insertBefore(doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""), doc.documentElement());
2260 return doc;
2261}
2262
2263bool KisDocument::isNativeFormat(const QByteArray& mimeType) const
2264{
2266 return true;
2267 return extraNativeMimeTypes().contains(mimeType);
2268}
2269
2270void KisDocument::setErrorMessage(const QString& errMsg)
2271{
2272 d->lastErrorMessage = errMsg;
2273}
2274
2276{
2277 return d->lastErrorMessage;
2278}
2279
2280void KisDocument::setWarningMessage(const QString& warningMsg)
2281{
2282 d->lastWarningMessage = warningMsg;
2283}
2284
2286{
2287 return d->lastWarningMessage;
2288}
2289
2290
2291void KisDocument::removeAutoSaveFiles(const QString &autosaveBaseName, bool wasRecovered)
2292{
2293 // Eliminate any auto-save file
2294 QString asf = generateAutoSaveFileName(autosaveBaseName); // the one in the current dir
2295 if (QFile::exists(asf)) {
2296 KisUsageLogger::log(QString("Removing autosave file: %1").arg(asf));
2297 QFile::remove(asf);
2298 }
2299 asf = generateAutoSaveFileName(QString()); // and the one in $HOME
2300
2301 if (QFile::exists(asf)) {
2302 KisUsageLogger::log(QString("Removing autosave file: %1").arg(asf));
2303 QFile::remove(asf);
2304 }
2305
2306 QList<QRegularExpression> expressions;
2307
2308 expressions << QRegularExpression("^\\..+-autosave.kra$")
2309 << QRegularExpression("^.+-autosave.kra$");
2310
2311 Q_FOREACH(const QRegularExpression &rex, expressions) {
2312 if (wasRecovered &&
2313 !autosaveBaseName.isEmpty() &&
2314 rex.match(QFileInfo(autosaveBaseName).fileName()).hasMatch() &&
2315 QFile::exists(autosaveBaseName)) {
2316
2317 KisUsageLogger::log(QString("Removing autosave file: %1").arg(autosaveBaseName));
2318 QFile::remove(autosaveBaseName);
2319 }
2320 }
2321}
2322
2324{
2325 return d->unit;
2326}
2327
2329{
2330 if (d->unit != unit) {
2331 d->unit = unit;
2332 Q_EMIT unitChanged(unit);
2333 }
2334}
2335
2337{
2338 return d->undoStack;
2339}
2340
2342{
2343 return d->importExportManager;
2344}
2345
2347{
2348 setModified(!value || d->imageModifiedWithoutUndo);
2349}
2350
2352{
2353 KisConfig cfg(true);
2354
2355 if (d->undoStack->undoLimit() != cfg.undoStackLimit()) {
2356 if (!d->undoStack->isClean()) {
2357 d->undoStack->clear();
2358 // we set this because the document *has* changed, even though the
2359 // undo history was purged.
2361 }
2362 d->undoStack->setUndoLimit(cfg.undoStackLimit());
2363 }
2364 d->undoStack->setUseCumulativeUndoRedo(cfg.useCumulativeUndoRedo());
2365 d->undoStack->setCumulativeUndoData(cfg.cumulativeUndoData());
2366
2367 d->autoSaveDelay = cfg.autoSaveInterval();
2369}
2370
2372{
2373 d->syncDecorationsWrapperLayerState();
2374}
2375
2377{
2378 d->undoStack->clear();
2379}
2380
2382{
2383 return d->gridConfig;
2384}
2385
2387{
2388 if (d->gridConfig != config) {
2389 d->gridConfig = config;
2390 d->syncDecorationsWrapperLayerState();
2391 Q_EMIT sigGridConfigChanged(config);
2392
2393 // Store last assigned value as future default...
2394 KisConfig cfg(false);
2395 cfg.setDefaultGridSpacing(config.spacing());
2396 }
2397}
2398
2400{
2402 if (!d->linkedResourceStorage) {
2403 return result;
2404 }
2405
2406 Q_FOREACH(const QString &resourceType, KisResourceLoaderRegistry::instance()->resourceTypes()) {
2407 QSharedPointer<KisResourceStorage::ResourceIterator> iter = d->linkedResourceStorage->resources(resourceType);
2408 while (iter->hasNext()) {
2409 iter->next();
2410
2411 QBuffer buf;
2412 buf.open(QBuffer::WriteOnly);
2413 bool exportSuccessful =
2414 d->linkedResourceStorage->exportResource(iter->url(), &buf);
2415
2416 KoResourceSP resource = d->linkedResourceStorage->resource(iter->url());
2417 exportSuccessful &= bool(resource);
2418
2419 const QString name = resource ? resource->name() : QString();
2420 const QString fileName = QFileInfo(iter->url()).fileName();
2421 const KoResourceSignature signature(resourceType,
2422 KoMD5Generator::generateHash(buf.data()),
2423 fileName, name);
2424
2425 if (exportSuccessful) {
2426 result << KoEmbeddedResource(signature, buf.data());
2427 } else {
2428 result << signature;
2429 }
2430 }
2431 }
2432
2433 return result;
2434}
2435
2436void KisDocument::setPaletteList(const QList<KoColorSetSP > &paletteList, bool emitSignal)
2437{
2438 QList<KoColorSetSP> oldPaletteList;
2439 if (d->linkedResourceStorage) {
2440 QSharedPointer<KisResourceStorage::ResourceIterator> iter = d->linkedResourceStorage->resources(ResourceType::Palettes);
2441 while (iter->hasNext()) {
2442 iter->next();
2443 KoResourceSP resource = iter->resource();
2444 if (resource && resource->valid()) {
2445 oldPaletteList << resource.dynamicCast<KoColorSet>();
2446 }
2447 }
2448 if (oldPaletteList != paletteList) {
2450 Q_FOREACH(KoColorSetSP palette, oldPaletteList) {
2451 if (!paletteList.contains(palette)) {
2452 resourceModel.setResourceInactive(resourceModel.indexForResource(palette));
2453 }
2454 }
2455 Q_FOREACH(KoColorSetSP palette, paletteList) {
2456 if (!oldPaletteList.contains(palette)) {
2457 resourceModel.addResource(palette, d->linkedResourcesStorageID);
2458 }
2459 else {
2460 palette->setStorageLocation(d->linkedResourcesStorageID);
2461 resourceModel.updateResource(palette);
2462 }
2463 }
2464 if (emitSignal) {
2465 Q_EMIT sigPaletteListChanged(oldPaletteList, paletteList);
2466 }
2467 }
2468 }
2469}
2470
2472{
2473 return d->m_storyboardItemList;
2474}
2475
2476void KisDocument::setStoryboardItemList(const StoryboardItemList &storyboardItemList, bool emitSignal)
2477{
2478 d->m_storyboardItemList = storyboardItemList;
2479 if (emitSignal) {
2481 }
2482}
2483
2485{
2486 return d->m_storyboardCommentList;
2487}
2488
2489void KisDocument::setStoryboardCommentList(const QVector<StoryboardComment> &storyboardCommentList, bool emitSignal)
2490{
2491 d->m_storyboardCommentList = storyboardCommentList;
2492 if (emitSignal) {
2494 }
2495}
2496
2498 return d->audioTracks;
2499}
2500
2502{
2503 d->audioTracks = f;
2504 Q_EMIT sigAudioTracksChanged();
2505}
2506
2508{
2509 d->audioLevel = level;
2510 Q_EMIT sigAudioLevelChanged(level);
2511}
2512
2514{
2515 return d->audioLevel;
2516}
2517
2519{
2520 return d->guidesConfig;
2521}
2522
2524{
2525 if (d->guidesConfig == data) return;
2526
2527 d->guidesConfig = data;
2528 d->syncDecorationsWrapperLayerState();
2529 Q_EMIT sigGuidesConfigChanged(d->guidesConfig);
2530}
2531
2532
2534{
2535 return d->mirrorAxisConfig;
2536}
2537
2539{
2540 if (d->mirrorAxisConfig == config) {
2541 return;
2542 }
2543
2544 d->mirrorAxisConfig = config;
2545 if (d->image) {
2546 d->image->setMirrorAxesCenter(KisAlgebra2D::absoluteToRelative(d->mirrorAxisConfig.axisPosition(),
2547 d->image->bounds()));
2548 }
2549 setModified(true);
2550
2552}
2553
2555 setPath(QString());
2556 setLocalFilePath(QString());
2557}
2558
2560{
2561 return new KoDocumentInfoDlg(parent, docInfo);
2562}
2563
2565{
2566 return d->readwrite;
2567}
2568
2569QString KisDocument::path() const
2570{
2571 return d->m_path;
2572}
2573
2574bool KisDocument::closePath(bool promptToSave)
2575{
2576 if (promptToSave) {
2577 if ( isReadWrite() && isModified()) {
2578 Q_FOREACH (KisView *view, KisPart::instance()->views()) {
2579 if (view && view->document() == this) {
2580 if (!view->queryClose()) {
2581 return false;
2582 }
2583 }
2584 }
2585 }
2586 }
2587 // Not modified => ok and delete temp file.
2588 d->mimeType = QByteArray();
2589
2590 // It always succeeds for a read-only part,
2591 // but the return value exists for reimplementations
2592 // (e.g. pressing cancel for a modified read-write part)
2593 return true;
2594}
2595
2596
2597
2598void KisDocument::setPath(const QString &path)
2599{
2600 const bool changed = path != d->m_path;
2601
2602 d->m_path = path;
2603
2604 if (changed) {
2605 Q_EMIT sigPathChanged(path);
2606 }
2607}
2608
2610{
2611 return d->m_file;
2612}
2613
2614
2615void KisDocument::setLocalFilePath( const QString &localFilePath )
2616{
2617 d->m_file = localFilePath;
2618}
2619
2620bool KisDocument::openPathInternal(const QString &path)
2621{
2622 if ( path.isEmpty() ) {
2623 return false;
2624 }
2625
2626 if (d->m_bAutoDetectedMime) {
2627 d->mimeType = QByteArray();
2628 d->m_bAutoDetectedMime = false;
2629 }
2630
2631 QByteArray mimeType = d->mimeType;
2632
2633 if ( !closePath() ) {
2634 return false;
2635 }
2636
2637 d->mimeType = mimeType;
2638 setPath(path);
2639
2640 d->m_file.clear();
2641
2642 d->m_file = d->m_path;
2643
2644 bool ret = false;
2645 // set the mimeType only if it was not already set (for example, by the host application)
2646 if (d->mimeType.isEmpty()) {
2647 // get the mimeType of the file
2648 // using findByUrl() to avoid another string -> url conversion
2649 QString mime = KisMimeDatabase::mimeTypeForFile(d->m_path);
2650 d->mimeType = mime.toLocal8Bit();
2651 d->m_bAutoDetectedMime = true;
2652 }
2653
2654 setPath(d->m_path);
2655 ret = openFile();
2656
2657 if (ret) {
2658 Q_EMIT completed();
2659 }
2660 else {
2661 Q_EMIT canceled(QString());
2662 }
2663 return ret;
2664}
2665
2666bool KisDocument::newImage(const QString& name,
2667 qint32 width, qint32 height,
2668 const KoColorSpace* cs,
2669 const KoColor &bgColor, KisConfig::BackgroundStyle bgStyle,
2670 int numberOfLayers,
2671 const QString &description, const double imageResolution)
2672{
2673 Q_ASSERT(cs);
2674
2676
2677 if (!cs) return false;
2678
2679 KisCursorOverrideLock cursorLock(Qt::BusyCursor);
2680
2681 image = new KisImage(createUndoStore(), width, height, cs, name);
2682
2683 Q_CHECK_PTR(image);
2684
2685 connect(image, SIGNAL(sigImageModified()), this, SLOT(setImageModified()), Qt::UniqueConnection);
2686 connect(image, SIGNAL(sigImageModifiedWithoutUndo()), this, SLOT(setImageModifiedWithoutUndo()), Qt::UniqueConnection);
2687 image->setResolution(imageResolution, imageResolution);
2688
2690 image->waitForDone();
2691
2692 documentInfo()->setAboutInfo("title", name);
2693 documentInfo()->setAboutInfo("abstract", description);
2694
2695 KisConfig cfg(false);
2696 const bool autopin = cfg.autoPinLayersToTimeline();
2697
2698 KisLayerSP bgLayer;
2699 if (bgStyle == KisConfig::RASTER_LAYER || bgStyle == KisConfig::FILL_LAYER) {
2700 KoColor strippedAlpha = bgColor;
2701 strippedAlpha.setOpacity(OPACITY_OPAQUE_U8);
2702
2703 if (bgStyle == KisConfig::RASTER_LAYER) {
2704 bgLayer = new KisPaintLayer(image.data(), i18nc("Name for the bottom-most layer in the layerstack", "Background"), OPACITY_OPAQUE_U8, cs);
2705 bgLayer->paintDevice()->setDefaultPixel(strippedAlpha);
2706 bgLayer->setPinnedToTimeline(autopin);
2707 } else if (bgStyle == KisConfig::FILL_LAYER) {
2709 filter_config->setProperty("color", strippedAlpha.toQColor());
2710 filter_config->createLocalResourcesSnapshot();
2711 bgLayer = new KisGeneratorLayer(image.data(), i18nc("Name of automatically created background color fill layer", "Background Fill"), filter_config, image->globalSelection());
2712 }
2713
2714 bgLayer->setOpacity(bgColor.opacityU8());
2715
2716 if (numberOfLayers > 1) {
2717 //Lock bg layer if others are present.
2718 bgLayer->setUserLocked(true);
2719 }
2720 }
2721 else { // KisConfig::CANVAS_COLOR (needs an unlocked starting layer).
2723 bgLayer = new KisPaintLayer(image.data(), image->nextLayerName(), OPACITY_OPAQUE_U8, cs);
2724 }
2725
2726 Q_CHECK_PTR(bgLayer);
2727 image->addNode(bgLayer.data(), image->rootLayer().data());
2728 bgLayer->setDirty(QRect(0, 0, width, height));
2729
2730 // reset mirror axis to default:
2731 d->mirrorAxisConfig.setAxisPosition(QRectF(image->bounds()).center());
2733
2734 for(int i = 1; i < numberOfLayers; ++i) {
2736 layer->setPinnedToTimeline(autopin);
2737 image->addNode(layer, image->root(), i);
2738 layer->setDirty(QRect(0, 0, width, height));
2739 }
2740
2741 {
2743 if (window) {
2748 }
2749 }
2750
2752 QString("Created image \"%1\", %2 * %3 pixels, %4 dpi. Color model: %6 %5 (%7). Layers: %8")
2753 .arg(name, QString::number(width), QString::number(height),
2754 QString::number(imageResolution * 72.0), image->colorSpace()->colorModelId().name(),
2756 QString::number(numberOfLayers)));
2757
2758 return true;
2759}
2760
2762{
2763 const bool result = d->savingMutex.tryLock();
2764 if (result) {
2765 d->savingMutex.unlock();
2766 }
2767 return !result;
2768}
2769
2771{
2772 if (isSaving()) {
2773 KisAsyncActionFeedback f(i18nc("progress dialog message when the user closes the document that is being saved", "Waiting for saving to complete..."), 0);
2774 f.waitForMutex(d->savingMutex);
2775 }
2776}
2777
2779{
2780 return d->shapeController;
2781}
2782
2784{
2785 return d->shapeController->shapeForNode(layer);
2786}
2787
2789{
2790 return d->assistants;
2791}
2792
2794{
2795 if (d->assistants != value) {
2796 d->assistants = value;
2797 d->syncDecorationsWrapperLayerState();
2798 Q_EMIT sigAssistantsChanged();
2799 }
2800}
2801
2803{
2804 if (!d->image) return KisReferenceImagesLayerSP();
2805
2806 KisReferenceImagesLayerSP referencesLayer =
2807 KisLayerUtils::findNodeByType<KisReferenceImagesLayer>(d->image->root());
2808
2809 return referencesLayer;
2810}
2811
2813{
2814 KisReferenceImagesLayerSP currentReferenceLayer = referenceImagesLayer();
2815
2816 // updateImage=false inherently means we are not changing the
2817 // reference images layer, but just would like to update its signals.
2818 if (currentReferenceLayer == layer && updateImage) {
2819 return;
2820 }
2821
2822 d->referenceLayerConnections.clear();
2823
2824 if (updateImage) {
2825 if (currentReferenceLayer) {
2826 d->image->removeNode(currentReferenceLayer);
2827 }
2828
2829 if (layer) {
2830 d->image->addNode(layer);
2831 }
2832 }
2833
2834 currentReferenceLayer = layer;
2835
2836 if (currentReferenceLayer) {
2837 d->referenceLayerConnections.addConnection(
2838 currentReferenceLayer, SIGNAL(sigUpdateCanvas(QRectF)),
2839 this, SIGNAL(sigReferenceImagesChanged()));
2840 }
2841
2842 Q_EMIT sigReferenceImagesLayerChanged(layer);
2844}
2845
2847{
2848 d->preActivatedNode = activatedNode;
2849}
2850
2852{
2853 return d->preActivatedNode;
2854}
2855
2857{
2858 return d->image;
2859}
2860
2862{
2863 return d->savingImage;
2864}
2865
2866
2867void KisDocument::setCurrentImage(KisImageSP image, bool forceInitialUpdate, KisNodeSP preActivatedNode)
2868{
2869 if (d->image) {
2870 // Disconnect existing sig/slot connections
2871 d->image->setUndoStore(new KisDumbUndoStore());
2872 d->image->disconnect(this);
2873 d->shapeController->setImage(0);
2874 d->image = 0;
2875 }
2876
2877 if (!image) return;
2878
2879 if (d->linkedResourceStorage){
2880 d->linkedResourceStorage->setMetaData(KisResourceStorage::s_meta_name, image->objectName());
2881 }
2882
2883 d->setImageAndInitIdleWatcher(image);
2884 d->image->setUndoStore(new KisDocumentUndoStore(this));
2885 d->shapeController->setImage(image, preActivatedNode);
2886 d->image->setMirrorAxesCenter(KisAlgebra2D::absoluteToRelative(d->mirrorAxisConfig.axisPosition(), image->bounds()));
2887 setModified(false);
2888 connect(d->image, SIGNAL(sigImageModified()), this, SLOT(setImageModified()), Qt::UniqueConnection);
2889 connect(d->image, SIGNAL(sigImageModifiedWithoutUndo()), this, SLOT(setImageModifiedWithoutUndo()), Qt::UniqueConnection);
2890 connect(d->image, SIGNAL(sigLayersChangedAsync()), this, SLOT(slotImageRootChanged()));
2891
2892 if (forceInitialUpdate) {
2893 d->image->initialRefreshGraph();
2894 }
2895}
2896
2898{
2900
2901 // we set image without connecting idle-watcher, because loading
2902 // hasn't been finished yet
2903 d->image = image;
2904 d->shapeController->setImage(image);
2905}
2906
2908{
2909 // we only set as modified if undo stack is not at clean state
2910 setModified(d->imageModifiedWithoutUndo || !d->undoStack->isClean());
2911}
2912
2914{
2915 d->imageModifiedWithoutUndo = true;
2917}
2918
2919
2924
2925bool KisDocument::isAutosaving() const
2926{
2927 return d->isAutosaving;
2928}
2929
2930QString KisDocument::exportErrorToUserMessage(KisImportExportErrorCode status, const QString &errorMessage)
2931{
2932 return errorMessage.isEmpty() ? status.errorMessage() : errorMessage;
2933}
2934
2936{
2937 d->globalAssistantsColor = color;
2938}
2939
2941{
2942 return d->globalAssistantsColor;
2943}
2944
2946{
2947 QRectF bounds = d->image->bounds();
2948
2950
2951 if (referenceImagesLayer) {
2953 }
2954
2955 return bounds;
2956}
2957
2959{
2960 d->colorHistoryModel.setColorList(colors);
2961}
2962
2964{
2965 return d->colorHistoryModel.colorList();
2966}
2967
2969{
2970 return &d->colorHistoryModel;
2971}
float value(const T *src, size_t ch)
KisSharedPtr< KisReferenceImagesLayer > KisReferenceImagesLayerSP
const quint8 OPACITY_OPAQUE_U8
void setDetailedText(const QStringList &text)
DlgLoadMessages(const QString &title, const QString &message, const QStringList &warnings={}, const QString &details={})
virtual void setIndex(int idx)
virtual void undo()
virtual void redo()
bool setResourceInactive(const QModelIndex &index)
Base class for the Krita app.
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
QList< KoColor > colorHistoryColors() const
static QImage createCheckersImage(qint32 checkSize=-1)
static KisConfigNotifier * instance()
bool backupFile(bool defaultValue=false) const
void setDefaultGridSpacing(QPoint gridSpacing)
bool useCumulativeUndoRedo(bool defaultValue=false) const
KisCumulativeUndoData cumulativeUndoData(bool defaultValue=false) const
bool autoPinLayersToTimeline(bool defaultValue=false) const
bool trimKra(bool defaultValue=false) const
T readEntry(const QString &name, const T &defaultValue=T())
Definition kis_config.h:914
int autoSaveInterval(bool defaultValue=false) const
int undoStackLimit(bool defaultValue=false) const
StrippedSafeSavingLocker(QMutex *savingMutex, KisImageSP image)
QScopedPointer< KisSignalAutoConnection > imageIdleConnection
void slotImageRootChanged()
void completed()
void setAssistants(const QList< KisPaintingAssistantSP > &value)
@replace the current list of assistants with
void waitForSavingToComplete()
QRectF documentBounds() const
QString warningMessage() const
void copyFrom(const Private &rhs, KisDocument *q)
QMutex savingMutex
void removeAutoSaveFiles(const QString &autosaveBaseName, bool wasRecovered)
KisUndoStore * createUndoStore()
bool isReadWrite() const
void slotInitiateAsyncAutosaving(KisDocument *clonedDocument)
void updateDocumentMetadataOnSaving(const QString &filePath, const QByteArray &mimeType)
KisNameServer * nserver
void sigStoryboardCommentListChanged()
QFuture< KisImportExportErrorCode > childSavingFuture
void setEmergencyAutoSaveInterval()
void setFileBatchMode(const bool batchMode)
KisMirrorAxisConfig mirrorAxisConfig
KisSharedPtr< KisReferenceImagesLayer > referenceImagesLayer() const
void clearUndoHistory()
KUndo2Stack * undoStack
bool exportDocument(const QString &path, const QByteArray &mimeType, bool isAdvancedExporting=false, bool showWarnings=false, KisPropertiesConfigurationSP exportConfiguration=0)
KoDocumentInfo * documentInfo() const
void syncDecorationsWrapperLayerState()
void hackPreliminarySetImage(KisImageSP image)
void sigBackgroundSavingFinished(KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
QTimer * autoSaveTimer
KisImageSP image
QString linkedResourcesStorageId() const
void copyFromImpl(const Private &rhs, KisDocument *q, KisDocument::CopyPolicy policy)
QDateTime lastMod
QPixmap generatePreview(const QSize &size)
Generates a preview picture of the document.
KisShapeController * shapeController
static QStringList extraNativeMimeTypes()
KisSignalAutoConnectionsStore referenceLayerConnections
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)
bool save(bool showWarnings, KisPropertiesConfigurationSP exportConfiguration)
KisImportExportManager * importExportManager
void statusBarMessage(const QString &text, int timeout=0)
bool isNativeFormat(const QByteArray &mimeType) const
Checks whether a given mimeType can be handled natively.
void setAudioTracks(QVector< QFileInfo > f)
void sigAudioLevelChanged(qreal level)
KisDocument * lockAndCloneImpl(bool fetchResourcesFromLayers)
void uploadLinkedResourcesFromLayersToStorage()
void slotUndoStackCleanChanged(bool value)
QString localFilePath() const
void sigAssistantsChanged()
void setErrorMessage(const QString &errMsg)
void setMirrorAxisConfig(const KisMirrorAxisConfig &config)
QList< KoColor > colorHistoryColors() const
KoDocumentInfoDlg * createDocumentInfoDialog(QWidget *parent, KoDocumentInfo *docInfo) const
void sigStoryboardItemListChanged()
bool isModified() const
KisImportExportErrorCode startExportInBackground(const QString &actionName, const QString &location, const QString &realLocation, const QByteArray &mimeType, bool showWarnings, KisPropertiesConfigurationSP exportConfiguration, bool isAdvancedExporting=false)
QString exportErrorToUserMessage(KisImportExportErrorCode status, const QString &errorMessage)
void setAssistantsGlobalColor(QColor color)
bool loadNativeFormat(const QString &file)
void updateEditingTime(bool forceStoreElapsed)
void slotAutoSave()
void sigPaletteListChanged(const QList< KoColorSetSP > &oldPaletteList, const QList< KoColorSetSP > &newPaletteList)
void setModified(bool _mod)
void setMimeType(const QByteArray &mimeType)
Sets the mime type for the document.
QDomDocument createDomDocument(const QString &tagName, const QString &version) const
void sigLoadingFinished()
KisDocument * lockAndCloneForSaving()
try to clone the image. This method handles all the locking for you. If locking has failed,...
void sigReadWriteChanged(bool value)
void finishExportInBackground()
void copyFromDocument(const KisDocument &rhs)
void slotDocumentCloningCancelled()
void setWarningMessage(const QString &warningMsg)
QDateTime firstMod
qreal getAudioLevel()
std::unique_ptr< KisDocument > backgroundSaveDocument
void setUnit(const KoUnit &unit)
void setImageModified()
void setPath(const QString &path)
bool saveAs(const QString &path, const QByteArray &mimeType, bool showWarnings, KisPropertiesConfigurationSP exportConfiguration=0)
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)
void setLocalFilePath(const QString &localFilePath)
QList< KoResourceLoadResult > linkedDocumentResources()
linkedDocumentResources List returns all the resources linked to the document, such as palettes
KisDocument * lockAndCreateSnapshot()
void setAutoSaveDelay(int delay)
void setPreActivatedNode(KisNodeSP activatedNode)
QString lastWarningMessage
void sigGuidesConfigChanged(const KisGuidesConfig &config)
void setRecovered(bool value)
QString caption() const
KisGridConfig gridConfig
void slotChildCompletedSavingInBackground(KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
Private(const Private &rhs, KisDocument *_q)
bool importDocument(const QString &path)
QString errorMessage() const
KritaUtils::ExportFileJob backgroundSaveJob
Private(KisDocument *_q)
QColor globalAssistantsColor
KisResourceStorageSP embeddedResourceStorage
static QByteArray nativeFormatMimeType()
void sigAudioTracksChanged()
void setReferenceImagesLayer(KisSharedPtr< KisReferenceImagesLayer > layer, bool updateImage)
bool resourceSavingFilter(const QString &path, const QByteArray &mimeType, KisPropertiesConfigurationSP exportConfiguration)
KisDocument(bool addStorage=true)
void canceled(const QString &)
QString path() const
void setReadWrite(bool readwrite=true)
Sets whether the document can be edited or is read only.
bool isSaving() const
void setImageModifiedWithoutUndo()
Private *const d
void setColorHistoryColors(const QList< KoColor > &colors)
void sigGridConfigChanged(const KisGridConfig &config)
QColor assistantsGlobalColor()
QPointer< KoUpdater > savingUpdater
void autoSaveOnPause()
Start saving when android activity is pushed to the background.
StoryboardItemList getStoryboardItemList()
returns the list of pointers to storyboard Items for the document
QString embeddedResourcesStorageId() const
QString linkedResourcesStorageID
void sigSavingFinished(const QString &filePath)
QString generateAutoSaveFileName(const QString &path) const
KisResourceStorageSP linkedResourceStorage
QMetaObject::Connection completeSavingConnection
KisNodeWSP preActivatedNode
KisImageSP savingImage
void setNormalAutoSaveInterval()
void slotCompleteSavingDocument(const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
void unitChanged(const KoUnit &unit)
KoShapeLayer * shapeForNode(KisNodeSP layer) const
QByteArray mimeType
bool exportDocumentSync(const QString &path, const QByteArray &mimeType, KisPropertiesConfigurationSP exportConfiguration=0)
void setGridConfig(const KisGridConfig &config)
bool closePath(bool promptToSave=true)
QString newObjectName()
void sigPathChanged(const QString &path)
QByteArray serializeToNativeByteArray()
serializeToNativeByteArray daves the document into a .kra file written to a memory-based byte-array
QList< KisPaintingAssistantSP > assistants
void setImageAndInitIdleWatcher(KisImageSP _image)
void setAudioVolume(qreal level)
void setAutoSaveActive(bool autoSaveIsActive)
@ CONSTRUCT
we are copy-constructing a new KisDocument
@ REPLACE
we are replacing the current KisDocument with another
void setGuidesConfig(const KisGuidesConfig &data)
bool openPathInternal(const QString &path)
KisIdleWatcher imageIdleWatcher
bool fileBatchMode() const
QByteArray outputMimeType
QVector< StoryboardComment > getStoryboardCommentsList()
returns the list of comments for the storyboard docker in the document
void setMimeTypeAfterLoading(const QString &mimeType)
void sigCompleteBackgroundSaving(const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
void copyFromDocumentImpl(const KisDocument &rhs, CopyPolicy policy)
void sigReferenceImagesLayerChanged(KisSharedPtr< KisReferenceImagesLayer > layer)
void slotPerformIdleRoutines()
StoryboardItemList m_storyboardItemList
void slotAutoSaveImpl(std::unique_ptr< KisDocument > &&optionalClonedDocument)
void setCurrentImage(KisImageSP image, bool forceInitialUpdate=true, KisNodeSP preActivatedNode=nullptr)
void sigRecoveredChanged(bool value)
QVector< StoryboardComment > m_storyboardCommentList
QVector< QFileInfo > getAudioTracks() const
KisUniqueColorSet colorHistoryModel
bool exportDocumentImpl(const KritaUtils::ExportFileJob &job, KisPropertiesConfigurationSP exportConfiguration, bool isAdvancedExporting=false)
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...
void setPaletteList(const QList< KoColorSetSP > &paletteList, bool emitSignal=false)
setPaletteList replaces the palettes in the document's local resource storage with the list of palett...
void slotCompleteAutoSaving(const KritaUtils::ExportFileJob &job, KisImportExportErrorCode status, const QString &errorMessage, const QString &warningMessage)
void slotConfigChanged()
KisDocument * clone(bool addStorage=false)
creates a clone of the document and returns it. Please make sure that you hold all the necessary lock...
void setInfiniteAutoSaveInterval()
void sigReferenceImagesChanged()
QString lastErrorMessage
KoDocumentInfo * docInfo
QString embeddedResourcesStorageID
void setStoryboardItemList(const StoryboardItemList &storyboardItemList, bool emitSignal=false)
sets the storyboardItemList in the document, emits empty signal if emitSignal is true.
bool openPath(const QString &path, OpenFlags flags=None)
openPath Open a Path
KisGuidesConfig guidesConfig
bool isAutoSaveActive()
QVector< QFileInfo > audioTracks
void sigMirrorAxisConfigChanged()
QString prettyPath() const
The KisDumbUndoStore class doesn't actually save commands, so you cannot undo or redo!
static KisGeneratorRegistry * instance()
static KisResourcesInterfaceSP instance()
QPoint spacing() const
void setTrackedImage(KisImageSP image)
QImage convertToQImage(qint32 x1, qint32 y1, qint32 width, qint32 height, const KoColorProfile *profile)
void waitForDone()
KisGroupLayerSP rootLayer() const
UndoResult tryUndoUnfinishedLod0Stroke()
const KoColorSpace * colorSpace() const
void unlock()
Definition kis_image.cc:831
void requestUndoDuringStroke()
QString nextLayerName(const QString &baseName="") const
Definition kis_image.cc:741
bool assignImageProfile(const KoColorProfile *profile, bool blockAllUpdates=false)
KisImage * clone(bool exactCopy=false)
Definition kis_image.cc:427
void setDefaultProjectionColor(const KoColor &color)
void requestStrokeCancellation()
KisStrokeId startStroke(KisStrokeStrategy *strokeStrategy) override
void requestStrokeEnd()
KisSelectionSP globalSelection() const
Definition kis_image.cc:721
QRect bounds() const override
bool tryBarrierLock(bool readOnly=false)
Tries to lock the image without waiting for the jobs to finish.
Definition kis_image.cc:797
void endStroke(KisStrokeId id) override
void requestRedoDuringStroke()
void setResolution(double xres, double yres)
The class managing all the filters.
static KisImportExportFilter * filterForMimeType(const QString &mimetype, Direction direction)
filterForMimeType loads the relevant import/export plugin and returns it. The caller is responsible f...
static KisMacosSecurityBookmarkManager * instance()
Main window for Krita.
KisViewManager * viewManager
static QString mimeTypeForFile(const QString &file, bool checkExistingFiles=true)
Find the mimetype for the given filename. The filename must include a suffix.
The KisMirrorAxisConfig class stores configuration for the KisMirrorAxis canvas decoration....
void setDefaultPixel(const KoColor &defPixel)
static MemoryReleaseObject * createMemoryReleaseObject()
static QList< KisPaintingAssistantSP > cloneAssistantList(const QList< KisPaintingAssistantSP > &list)
void addRecentURLToAllMainWindows(QUrl url, QUrl oldUrl=QUrl())
Definition KisPart.cpp:573
static KisPart * instance()
Definition KisPart.cpp:131
KisMainWindow * currentMainwindow() const
Definition KisPart.cpp:458
The KisRecoverNamedAutosaveDialog class is a dialog to recover already existing files from autosave.
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...
static KisResourceLoaderRegistry * instance()
bool removeStorage(const QString &storageLocation)
removeStorage removes the temporary storage from the database
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...
QString filePathForResource(KoResourceSP resource)
static KisResourceLocator * instance()
The KisResourceModel class provides the main access to resources. It is possible to filter the resour...
KoResourceSP resourceForId(int id) const
KoResourceSP importResourceFile(const QString &filename, const bool allowOverwrite, const QString &storageId=QString("")) override
importResourceFile
bool updateResource(KoResourceSP resource) override
updateResource creates a new version of the resource in the storage and in the database....
bool addResource(KoResourceSP resource, const QString &storageId=QString("")) override
addResource adds the given resource to the database and storage. If the resource already exists in th...
void setResourceFilter(ResourceFilter filter) override
QModelIndex indexForResource(KoResourceSP resource) const override
indexFromResource
static KisResourceServerProvider * instance()
static const QString s_meta_name
void enableJob(JobType type, bool enable=true, KisStrokeJobData::Sequentiality sequentiality=KisStrokeJobData::SEQUENTIAL, KisStrokeJobData::Exclusivity exclusivity=KisStrokeJobData::NORMAL)
void setClearsRedoOnStart(bool value)
void setRequestsOtherStrokesToEnd(bool value)
static void log(const QString &message)
Logs with date/time.
bool blockUntilOperationsFinished(KisImageSP image)
blockUntilOperationsFinished blocks the GUI of the application until execution of actions on image is...
QPointer< KoUpdater > createThreadedUpdater(const QString &name)
void blockUntilOperationsFinishedForced(KisImageSP image)
blockUntilOperationsFinished blocks the GUI of the application until execution of actions on image is...
QPointer< KoUpdater > createUnthreadedUpdater(const QString &name)
create a new progress updater
KisCanvasResourceProvider * canvasResourceProvider()
QPointer< KisDocument > document
Definition KisView.cpp:121
bool queryClose()
Definition KisView.cpp:1161
bool isValid() const
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
The dialog that shows information about the document.
The class containing all meta information about a document.
void setAboutInfo(const QString &info, const QString &data)
T get(const QString &id) const
QString name() const
Definition KoID.cpp:68
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.
@ Centimeter
Definition KoUnit.h:78
@ Inch
Definition KoUnit.h:77
static StoryboardItemList cloneStoryboardItemList(const StoryboardItemList &list)
KisDocument * m_doc
QQueue< PostponedJob > m_postponedJobs
void notifySetIndexChangedOneCommand() override
KisImageWSP image()
int m_recursionCounter
void undo() override
UndoStack(KisDocument *doc)
void processPostponedJobs()
void undoImpl()
void redoImpl()
void setIndex(int idx) override
void redo() override
void setIndexImpl(int idx)
#define KIS_ASSERT_RECOVER_RETURN_VALUE(cond, val)
Definition kis_assert.h:85
#define KIS_SAFE_ASSERT_RECOVER(cond)
Definition kis_assert.h:126
#define KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(cond, val)
Definition kis_assert.h:129
#define KIS_SAFE_ASSERT_RECOVER_RETURN(cond)
Definition kis_assert.h:128
#define KIS_ASSERT_RECOVER_RETURN(cond)
Definition kis_assert.h:75
#define KIS_SAFE_ASSERT_RECOVER_NOOP(cond)
Definition kis_assert.h:130
#define bounds(x, a, b)
#define dbgUI
Definition kis_debug.h:56
#define dbgAndroid
Definition kis_debug.h:65
KUndo2MagicString kundo2_noi18n(const QString &text)
QPointF absoluteToRelative(const QPointF &pt, const QRectF &rc)
bool hasDelayedNodeWithUpdates(KisNodeSP root)
void recursiveApplyNodes(NodePointer node, Functor func)
void forceAllDelayedNodesUpdate(KisNodeSP root)
const QString Palettes
void setPinnedToTimeline(bool pinned)
virtual void setUserLocked(bool l)
void setOpacity(quint8 val)
KisImageWSP image
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