Krita is a free and open source cross-platform application that offers an end-to-end solution for creating digital art files from scratch built on the KDE and Qt frameworks.
C++
Fix loading presets with conflicting embedded resources
Dmitry Kazakovd86c29e21755
diff --git a/libs/image/brushengine/kis_paintop_preset.cpp b/libs/image/brushengine/kis_paintop_preset.cppindex 8123a3eb02..e598b80605 100644--- a/libs/image/brushengine/kis_paintop_preset.cpp+++ b/libs/image/brushengine/kis_paintop_preset.cpp@@ -211,7 +211,7 @@ bool KisPaintOpPreset::loadFromDevice(QIODevice *dev, KisResourcesInterfaceSP reKoResourceSP existingResource = resourcesInterface->source(resourceType)- .bestMatch(md5sum, filename, name);+ .exactMatch(md5sum, filename, name);if (existingResource) {continue;@@ -592,7 +592,7 @@ QList<KoResourceLoadResult> KisPaintOpPreset::sideLoadedResources(KisResourcesIn* Do not load the existing resources. There is no use for it.*/if (!globalResourcesInterface->source(sig.type)- .bestMatch(sig.md5sum, sig.filename, sig.name)) {+ .exactMatch(sig.md5sum, sig.filename, sig.name)) {resources << resource;}diff --git a/libs/image/tests/KisPaintOpPresetTest.cpp b/libs/image/tests/KisPaintOpPresetTest.cppindex 49b565c37e..45b4f7419b 100644--- a/libs/image/tests/KisPaintOpPresetTest.cpp+++ b/libs/image/tests/KisPaintOpPresetTest.cpp@@ -6,10 +6,14 @@#include "KisPaintOpPresetTest.h"-#include "simpletest.h"+#include <testimage.h>++#include <testutil.h>+#include <KisResourceModel.h>#include "kis_paintop_preset.h"#include "KisLocalStrokeResources.h"+#include <KisGlobalResourcesInterface.h>#include <QFileInfo>@@ -111,4 +115,88 @@ void KisPaintOpPresetTest::testLoadingEmbeddedResources()QCOMPARE(realEmbeddedSignatures, toSet(expectedEmbeddedResources));}-SIMPLE_TEST_MAIN(KisPaintOpPresetTest)+void KisPaintOpPresetTest::testConflictingEmbeddedPatterns()+{+ QSharedPointer<KisLocalStrokeResources> emptyLocalResources(new KisLocalStrokeResources());+ KisResourcesInterfaceSP resourcesInterface = KisGlobalResourcesInterface::instance();++ KisResourceModel model(ResourceType::PaintOpPresets);++ int verticalPatternResourceId = -1;++ {+ /// Firstly, load a preset that embeds a patterns with+ /// "stripes-pat.png" name++ QString presetFileName(TestUtil::fetchDataFileLazy("conflicting-patterns/preset-stripes-vert.kpp"));+ QFile file(presetFileName);+ file.open(QFile::ReadOnly);++ KoResourceSP resource = model.importResource(QFileInfo(presetFileName).fileName(), &file, false, "memory");+ QVERIFY(resource);++ KisPaintOpPresetSP preset = resource.dynamicCast<KisPaintOpPreset>();++ KoPatternSP loadedPattern = preset->linkedResources(resourcesInterface).first().resource<KoPattern>();+ QVERIFY(loadedPattern);+ QCOMPARE(loadedPattern->name(), "stripes-pat.png");+ QCOMPARE(loadedPattern->md5Sum(), "d3bc7abb7136295578c6b3af3da02fcc");++ QVERIFY(loadedPattern->resourceId() >= 0);+ verticalPatternResourceId = loadedPattern->resourceId();+ }++ {+ /// Secondly, load a preset that embeds the same pattern, it should reuse+ /// the same pattern object++ QString presetFileName(TestUtil::fetchDataFileLazy("conflicting-patterns/preset-stripes-vert-v2.kpp"));+ QFile file(presetFileName);+ file.open(QFile::ReadOnly);++ KoResourceSP resource = model.importResource(QFileInfo(presetFileName).fileName(), &file, false, "memory");+ QVERIFY(resource);++ KisPaintOpPresetSP preset = resource.dynamicCast<KisPaintOpPreset>();++ KoPatternSP loadedPattern = preset->linkedResources(resourcesInterface).first().resource<KoPattern>();+ QVERIFY(loadedPattern);+ QCOMPARE(loadedPattern->name(), "stripes-pat.png");+ QCOMPARE(loadedPattern->md5Sum(), "d3bc7abb7136295578c6b3af3da02fcc");++ // Krita should reuse the same pattern object+ QCOMPARE(loadedPattern->resourceId(), verticalPatternResourceId);+ }++ {+ /// Now load a preset that also embeds a "stripes-pat.png" pattern,+ /// but a different one (with a different md5sum)++ QString presetFileName(TestUtil::fetchDataFileLazy("conflicting-patterns/preset-stripes-cross.kpp"));+ QFile file(presetFileName);+ file.open(QFile::ReadOnly);++ KoResourceSP resource = model.importResource(QFileInfo(presetFileName).fileName(), &file, false, "memory");+ QVERIFY(resource);++ KisPaintOpPresetSP preset = resource.dynamicCast<KisPaintOpPreset>();++ /// try to fetch the signature of the linked resource by loading+ /// in an empty environment+ auto resourcesForEmptyEnvironment = preset->linkedResources(emptyLocalResources);+ QCOMPARE(resourcesForEmptyEnvironment.size(), 1);+ QCOMPARE(resourcesForEmptyEnvironment.first().type(), KoResourceLoadResult::FailedLink);+ const QString requiredMd5Sum = resourcesForEmptyEnvironment.first().signature().md5sum;+ QCOMPARE(requiredMd5Sum, "cca80dd27e4085ef089729462714e942");++ // now try to load in real environment, it should fetch the correct+ // deduplicated resource (with a different filename, but same MD5)+ KoPatternSP loadedPattern = preset->linkedResources(resourcesInterface).first().resource<KoPattern>();+ QVERIFY(loadedPattern);+ QCOMPARE(loadedPattern->md5Sum(), requiredMd5Sum);++ QVERIFY(loadedPattern->resourceId() != verticalPatternResourceId);+ }+}++KISTEST_MAIN(KisPaintOpPresetTest)diff --git a/libs/image/tests/KisPaintOpPresetTest.h b/libs/image/tests/KisPaintOpPresetTest.hindex 3c8db0fb48..1d21972c42 100644--- a/libs/image/tests/KisPaintOpPresetTest.h+++ b/libs/image/tests/KisPaintOpPresetTest.h@@ -16,6 +16,7 @@ private Q_SLOTS:void testLoadingEmbeddedResources_data();void testLoadingEmbeddedResources();+ void testConflictingEmbeddedPatterns();};#endif // KISPAINTOPPRESETTEST_Hdiff --git a/libs/image/tests/data/conflicting-patterns/preset-stripes-cross.kpp b/libs/image/tests/data/conflicting-patterns/preset-stripes-cross.kppnew file mode 100644index 0000000000..be1aaf5a78Binary files /dev/null and b/libs/image/tests/data/conflicting-patterns/preset-stripes-cross.kpp differdiff --git a/libs/image/tests/data/conflicting-patterns/preset-stripes-vert-v2.kpp b/libs/image/tests/data/conflicting-patterns/preset-stripes-vert-v2.kppnew file mode 100644index 0000000000..0eb9c41d31Binary files /dev/null and b/libs/image/tests/data/conflicting-patterns/preset-stripes-vert-v2.kpp differdiff --git a/libs/image/tests/data/conflicting-patterns/preset-stripes-vert.kpp b/libs/image/tests/data/conflicting-patterns/preset-stripes-vert.kppnew file mode 100644index 0000000000..49b4258748Binary files /dev/null and b/libs/image/tests/data/conflicting-patterns/preset-stripes-vert.kpp differdiff --git a/libs/resources/KisResourceLocator.cpp b/libs/resources/KisResourceLocator.cppindex 9477e2feeb..6ab8fc5d9f 100644--- a/libs/resources/KisResourceLocator.cpp+++ b/libs/resources/KisResourceLocator.cpp@@ -153,7 +153,7 @@ bool KisResourceLocator::resourceCached(QString storageLocation, const QString &void KisResourceLocator::loadRequiredResources(KoResourceSP resource){auto loadResourcesGroup =- [this] (QList<KoResourceLoadResult> resources,+ [this, parentResource = resource] (QList<KoResourceLoadResult> resources,const QString &resourceGroup) {Q_FOREACH (KoResourceLoadResult res, resources) {@@ -167,8 +167,7 @@ void KisResourceLocator::loadRequiredResources(KoResourceSP resource)QByteArray data = res.embeddedResource().data();QBuffer buffer(&data);buffer.open(QBuffer::ReadOnly);-- importResource(sig.type, sig.filename, &buffer, false, "memory");+ importResourceDeduplicateFileName(sig.type, sig.filename, &buffer, "memory");break;}case KoResourceLoadResult::FailedLink:@@ -599,6 +598,35 @@ KoResourceSP KisResourceLocator::importResource(const QString &resourceType, conreturn nullptr;}+namespace {+QString findDeduplicatedFileName(const QString &resourceType, const QString &proposedFileName, KisResourceStorageSP storage)+{+ const QFileInfo fileInfo(proposedFileName);+ QString fileName = fileInfo.fileName();+ int counter = 0;++ Q_FOREVER {+ QString resourceUrl = resourceType + "/" + fileName;++ if (storage->resource(resourceUrl)) {+ fileName =+ QString("%1_embedded_%2.%3").arg(fileInfo.baseName()).arg(counter++).arg(fileInfo.completeSuffix());+ } else {+ break;+ }+ }+ return fileName;+}+}++KoResourceSP KisResourceLocator::importResourceDeduplicateFileName(const QString &resourceType, const QString &proposedFileName, QIODevice *device, const QString &storageLocation)+{+ KisResourceStorageSP storage = d->storages[makeStorageLocationAbsolute(storageLocation)];+ const QString fileName = findDeduplicatedFileName(resourceType, proposedFileName, storage);+ return importResource(resourceType, fileName, device, false, storageLocation);+}++bool KisResourceLocator::importWillOverwriteResource(const QString &resourceType, const QString &fileName, const QString &storageLocation) const{KisResourceStorageSP storage = d->storages[makeStorageLocationAbsolute(storageLocation)];diff --git a/libs/resources/KisResourceLocator.h b/libs/resources/KisResourceLocator.hindex e8cd0cfa8f..1d4673056e 100644--- a/libs/resources/KisResourceLocator.h+++ b/libs/resources/KisResourceLocator.h@@ -228,6 +228,22 @@ private:*/KoResourceSP importResource(const QString &resourceType, const QString &fileName, QIODevice *device, const bool allowOverwrite, const QString &storageLocation = QString());+ /**+ * @brief importResourceDeduplicateFileName imports the resource fith file name deduplication+ *+ * When loading embedded resources from another resources, we should make sure they+ * do not overwrite anything and land in the database unconditionally. That is why we might+ * need to rename them on loading. The parent resource will (hopefully) still be able to+ * address them using md5sum.+ *+ * @param resourceType+ * @param proposedFileName: filename that should be assigned to the resource (will possibly be changed)+ * @param device: QIODevice where the resource should be loaded from+ * @param storageLocation: optional, the storage where the resource will be stored. Empty means in the default Folder storage.+ * @return the imported resource, which has been added to the database and the cache+ */+ KoResourceSP importResourceDeduplicateFileName(const QString &resourceType, const QString &proposedFileName, QIODevice *device, const QString &storageLocation = QString());+/*** @brief return whether importing will overwrite some existing resource* @param resourceTypediff --git a/libs/resources/KisResourcesInterface.cpp b/libs/resources/KisResourcesInterface.cppindex 981e9cf414..9074a2fa19 100644--- a/libs/resources/KisResourcesInterface.cpp+++ b/libs/resources/KisResourcesInterface.cpp@@ -13,6 +13,7 @@#include "kis_debug.h"//#define SANITY_CHECKS+#define CRASH_ON_SANITY_CHECK_FAILUREKisResourcesInterface::KisResourcesInterface()@@ -69,6 +70,16 @@ KisResourcesInterface::ResourceSourceAdapter::~ResourceSourceAdapter()}KoResourceSP KisResourcesInterface::ResourceSourceAdapter::bestMatch(const QString md5, const QString filename, const QString name)+{+ return findResource(md5, filename, name, false);+}++KoResourceSP KisResourcesInterface::ResourceSourceAdapter::exactMatch(const QString md5, const QString filename, const QString name)+{+ return findResource(md5, filename, name, true);+}++KoResourceSP KisResourcesInterface::ResourceSourceAdapter::findResource(const QString md5, const QString filename, const QString name, bool exactMatch){QVector<QPair<KoResourceSP, int>> foundResources;@@ -92,6 +103,12 @@ KoResourceSP KisResourcesInterface::ResourceSourceAdapter::bestMatch(const QStrifoundResources.append(qMakePair(res, penalty));}++ /// In case of exact match we **must** find the resource+ /// via its md5 if provided+ if (exactMatch && foundResources.isEmpty()) {+ return {};+ }}#ifdef SANITY_CHECKS@@ -144,8 +161,13 @@ KoResourceSP KisResourcesInterface::ResourceSourceAdapter::bestMatch(const QStriqWarning() << "KisResourcesInterface::ResourceSourceAdapter::bestMatch: failed to fetch a resource using md5; falling back for filename...";qWarning() << " requested:" << ppVar(md5) << ppVar(filename) << ppVar(name);qWarning() << " found:" << result;+ qWarning() << " candidates:" << foundResources;++#ifdef CRASH_ON_SANITY_CHECK_FAILURE+ qFatal("Exiting...");+#endif /* CRASH_ON_SANITY_CHECK_FAILURE */}-#endif+#endif /* SANITY_CHECKS */return result;}diff --git a/libs/resources/KisResourcesInterface.h b/libs/resources/KisResourcesInterface.hindex 8821084d51..3e334b7929 100644--- a/libs/resources/KisResourcesInterface.h+++ b/libs/resources/KisResourcesInterface.h@@ -65,6 +65,19 @@ public:KoResourceSP bestMatch(const QString md5, const QString filename, const QString name);+ /**+ * @brief exactMatch retrieves a resource, preferably by md5, but with filename and name+ * as fallback for older files that do not store the md5sum. If the resource is+ * not found by md5 and the md5 isn't empty, then nullptr is returned (that is the+ * difference to bestMatch).+ *+ * If multiple resources with the same md5 exist, then it prefers the one+ * with the same filename and name.+ *+ * @return a resource, or 0 of the resource doesn't exist.+ */+ KoResourceSP exactMatch(const QString md5, const QString filename, const QString name);+/*** Same as bestMatch(), but returns KoResourceLoadResult. In case the* resource is not found in the backend storage, the load-result@@ -75,6 +88,8 @@ public:virtual KoResourceSP fallbackResource() const = 0;+ private:+ KoResourceSP findResource(const QString md5, const QString filename, const QString name, bool exactMatch);private:Q_DISABLE_COPY(ResourceSourceAdapter);const QString m_type;@@ -117,9 +132,10 @@ private:}public:/**- * @brief resource retrieves a resource, preferably by md5, but with filename and name- * as fallback for older files that do not store the md5sum. Note that if the resource is- * not found by md5 if the md5 isn't empty, we do NOT then look by filename.+ * @brief bestMatch retrieves a resource, preferably by md5, but with filename and name+ * as fallback for older files that do not store the md5sum. If the resource is+ * not found by md5 and the md5 isn't empty, then it will try to fallback to searching+ * by filename, but will show a warning in case sanity checks are enabled.** If multiple resources with the same md5 exist, then it prefers the one* with the same filename and name.@@ -131,6 +147,21 @@ public:return m_source->bestMatch(md5, filename, name).dynamicCast<T>();}+ /**+ * @brief exactMatch retrieves a resource, preferably by md5, but with filename and name+ * as fallback for older files that do not store the md5sum. If the resource is+ * not found by md5 and the md5 isn't empty, then nullptr is returned (that is the+ * difference to bestMatch).+ *+ * If multiple resources with the same md5 exist, then it prefers the one+ * with the same filename and name.+ *+ * @return a resource, or 0 of the resource doesn't exist.+ */+ QSharedPointer<T> exactMatch(const QString md5, const QString filename, const QString name) {+ return m_source->exactMatch(md5, filename, name).dynamicCast<T>();+ }+/*** Same as bestMatch(), but returns KoResourceLoadResult. In case the* resource is not found in the backend storage, the load-resultdiff --git a/libs/resources/KoResourceLoadResult.cpp b/libs/resources/KoResourceLoadResult.cppindex 630dbd87b0..d6a09aae6f 100644--- a/libs/resources/KoResourceLoadResult.cpp+++ b/libs/resources/KoResourceLoadResult.cpp@@ -79,3 +79,23 @@ KoResourceLoadResult::Type KoResourceLoadResult::type() const[](const KoEmbeddedResource &) { return EmbeddedResource; }}, m_d->value);}++QDebug operator<<(QDebug debug, const KoResourceLoadResult &result)+{+ QDebugStateSaver saver(debug);+ debug.nospace();++ switch (result.type()) {+ case KoResourceLoadResult::ExistingResource:+ debug << "KoResourceLoadResult(ExistingResource:" << result.signature() << ")";+ break;+ case KoResourceLoadResult::EmbeddedResource:+ debug << "KoResourceLoadResult(EmbeddedResource:" << result.signature() << ")";+ break;+ case KoResourceLoadResult::FailedLink:+ debug << "KoResourceLoadResult(FailedLink:" << result.signature() << ")";+ break;+ }++ return debug;+}diff --git a/libs/resources/KoResourceLoadResult.h b/libs/resources/KoResourceLoadResult.hindex e6a3c85a85..bf21c5019a 100644--- a/libs/resources/KoResourceLoadResult.h+++ b/libs/resources/KoResourceLoadResult.h@@ -7,6 +7,7 @@#define KORESOURCELOADRESULT_H#include <QSharedPointer>+#include <QDebug>#include <KoResourceSignature.h>#include <KoEmbeddedResource.h>@@ -86,4 +87,6 @@ private:const QScopedPointer<Private> m_d;};+KRITARESOURCES_EXPORT QDebug operator<<(QDebug debug, const KoResourceLoadResult &result);+#endif // KORESOURCELOADRESULT_H