Krita Source Code Documentation
Loading...
Searching...
No Matches
KisResourceLocator.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2018 Boudewijn Rempt <boud@valdyas.org>
3 *
4 * SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
8
9#include <QApplication>
10#include <QDebug>
11#include <QList>
12#include <QDir>
13#include <QDirIterator>
14#include <QFileInfo>
15#include <QMessageBox>
16#include <QVersionNumber>
17#include <QSqlQuery>
18#include <QSqlError>
19#include <QBuffer>
20
21#include <kconfig.h>
22#include <kconfiggroup.h>
23#include <ksharedconfig.h>
24#include <klocalizedstring.h>
25
26#include <KritaVersionWrapper.h>
27#include <KisMimeDatabase.h>
28#include <kis_assert.h>
29#include <kis_debug.h>
30#include <KisUsageLogger.h>
31
32#include "KoResourcePaths.h"
33#include "KisResourceStorage.h"
34#include "KisResourceCacheDb.h"
36#include "KisMemoryStorage.h"
39#include <KisStorageModel.h>
40#include <KoMD5Generator.h>
43
44#include "ResourceDebug.h"
45
46const QString KisResourceLocator::resourceLocationKey {"ResourceDirectory"};
47
49public:
51 QMap<QString, KisResourceStorageSP> storages;
52 QHash<QPair<QString, QString>, KoResourceSP> resourceCache;
53 QMap<QPair<QString, QString>, KisTagSP> tagCache;
55};
56
58 : QObject(parent)
59 , d(new Private())
60{
61}
62
64{
65 // Not a regular Q_GLOBAL_STATIC, because we want this deleted as
66 // part of the app destructor.
67 KisResourceLocator *locator = qApp->findChild<KisResourceLocator *>(QString());
68 if (!locator) {
69 locator = new KisResourceLocator(qApp);
70 }
71 return locator;
72}
73
77
78KisResourceLocator::LocatorError KisResourceLocator::initialize(const QString &installationResourcesLocation)
79{
81
82 d->resourceLocation = KoResourcePaths::getAppDataLocation();
83
84 if (!d->resourceLocation.endsWith('/')) d->resourceLocation += '/';
85
86 QFileInfo fi(d->resourceLocation);
87
88 if (!fi.exists()) {
89 if (!QDir().mkpath(d->resourceLocation)) {
90 d->errorMessages << i18n("1. Could not create the resource location at %1.", d->resourceLocation);
92 }
93 initializationStatus = InitializationStatus::FirstRun;
94 }
95
96 if (!fi.isWritable()) {
97 d->errorMessages << i18n("2. The resource location at %1 is not writable.", d->resourceLocation);
99 }
100
101 // Check whether we're updating from an older version
102 if (initializationStatus != InitializationStatus::FirstRun) {
103 QFile fi(d->resourceLocation + '/' + "KRITA_RESOURCE_VERSION");
104 if (!fi.exists()) {
105 initializationStatus = InitializationStatus::FirstUpdate;
106 }
107 else {
108 fi.open(QFile::ReadOnly);
109 QVersionNumber resource_version = QVersionNumber::fromString(QString::fromUtf8(fi.readAll()));
110 QVersionNumber krita_version = QVersionNumber::fromString(KritaVersionWrapper::versionString());
111 if (krita_version > resource_version) {
112 initializationStatus = InitializationStatus::Updating;
113 }
114 else {
115 initializationStatus = InitializationStatus::Initialized;
116 }
117 }
118 }
119
120 if (initializationStatus != InitializationStatus::Initialized) {
121 KisResourceLocator::LocatorError res = firstTimeInstallation(initializationStatus, installationResourcesLocation);
122 if (res != LocatorError::Ok) {
123 return res;
124 }
125 initializationStatus = InitializationStatus::Initialized;
126 }
127
128 if (!synchronizeDb()) {
130 }
131
132 return LocatorError::Ok;
133}
134
136{
137 return d->errorMessages;
138}
139
141{
142 return d->resourceLocation;
143}
144
145bool KisResourceLocator::resourceCached(QString storageLocation, const QString &resourceType, const QString &filename) const
146{
147 storageLocation = makeStorageLocationAbsolute(storageLocation);
148 QPair<QString, QString> key = QPair<QString, QString> (storageLocation, resourceType + "/" + filename);
149
150 return d->resourceCache.contains(key);
151}
152
154{
155 auto loadResourcesGroup =
156 [this] (QList<KoResourceLoadResult> resources,
157 const QString &resourceGroup) {
158
159 Q_FOREACH (KoResourceLoadResult res, resources) {
160 switch (res.type())
161 {
163 KIS_SAFE_ASSERT_RECOVER_NOOP(res.resource()->resourceId() >= 0);
164 break;
167 QByteArray data = res.embeddedResource().data();
168 QBuffer buffer(&data);
169 buffer.open(QBuffer::ReadOnly);
170
171 importResource(sig.type, sig.filename, &buffer, false, "memory");
172 break;
173 }
175 qWarning() << "Failed to load" << resourceGroup << "resource:" << res.signature();
176 break;
177 }
178 }
179 };
180
185 loadResourcesGroup(resource->takeSideLoadedResources(KisGlobalResourcesInterface::instance()), "side-loaded");
186
190 loadResourcesGroup(resource->requiredResources(KisGlobalResourcesInterface::instance()), "linked");
191}
192
193KisTagSP KisResourceLocator::tagForUrl(const QString &tagUrl, const QString resourceType)
194{
195 if (d->tagCache.contains(QPair<QString, QString>(resourceType, tagUrl))) {
196 return d->tagCache[QPair<QString, QString>(resourceType, tagUrl)];
197 }
198
199 KisTagSP tag = tagForUrlNoCache(tagUrl, resourceType);
200
201 if (tag && tag->valid()) {
202 d->tagCache[QPair<QString, QString>(resourceType, tagUrl)] = tag;
203 }
204
205 return tag;
206}
207
208KisTagSP KisResourceLocator::tagForUrlNoCache(const QString &tagUrl, const QString resourceType)
209{
210 QSqlQuery query;
211 bool r = query.prepare("SELECT tags.id\n"
212 ", tags.url\n"
213 ", tags.active\n"
214 ", tags.name\n"
215 ", tags.comment\n"
216 ", tags.filename\n"
217 ", resource_types.name as resource_type\n"
218 ", resource_types.id\n"
219 "FROM tags\n"
220 ", resource_types\n"
221 "WHERE tags.resource_type_id = resource_types.id\n"
222 "AND resource_types.name = :resource_type\n"
223 "AND tags.url = :tag_url\n");
224
225 if (!r) {
226 qWarning() << "Could not prepare KisResourceLocator::tagForUrl query" << query.lastError();
227 return KisTagSP();
228 }
229
230 query.bindValue(":resource_type", resourceType);
231 query.bindValue(":tag_url", tagUrl);
232
233 r = query.exec();
234 if (!r) {
235 qWarning() << "Could not execute KisResourceLocator::tagForUrl query" << query.lastError() << query.boundValues();
236 return KisTagSP();
237 }
238
239 r = query.first();
240 if (!r) {
241 return KisTagSP();
242 }
243
244 KisTagSP tag(new KisTag());
245
246 int tagId = query.value("tags.id").toInt();
247 int resourceTypeId = query.value("resource_types.id").toInt();
248
249 tag->setUrl(query.value("url").toString());
250 tag->setResourceType(resourceType);
251 tag->setId(query.value("id").toInt());
252 tag->setActive(query.value("active").toBool());
253 tag->setName(query.value("name").toString());
254 tag->setComment(query.value("comment").toString());
255 tag->setFilename(query.value("filename").toString());
256 tag->setValid(true);
257
258
259 QMap<QString, QString> names;
260 QMap<QString, QString> comments;
261
262 r = query.prepare("SELECT language\n"
263 ", name\n"
264 ", comment\n"
265 "FROM tag_translations\n"
266 "WHERE tag_id = :id");
267
268 if (!r) {
269 qWarning() << "Could not prepare KisResourceLocator::tagForUrl translation query" << query.lastError();
270 }
271
272 query.bindValue(":id", tag->id());
273
274 if (!query.exec()) {
275 qWarning() << "Could not execute KisResourceLocator::tagForUrl translation query" << query.lastError();
276 }
277
278 while (query.next()) {
279 names[query.value(0).toString()] = query.value(1).toString();
280 comments[query.value(0).toString()] = query.value(2).toString();
281 }
282
283 tag->setNames(names);
284 tag->setComments(comments);
285
286 QSqlQuery defaultResourcesQuery;
287
288 if (!defaultResourcesQuery.prepare("SELECT resources.filename\n"
289 "FROM resources\n"
290 ", resource_tags\n"
291 "WHERE resource_tags.tag_id = :tag_id\n"
292 "AND resources.resource_type_id = :type_id\n"
293 "AND resource_tags.resource_id = resources.id\n"
294 "AND resource_tags.active = 1\n")) {
295 qWarning() << "Could not prepare resource/tag query" << defaultResourcesQuery.lastError();
296 }
297
298 defaultResourcesQuery.bindValue(":tag_id", tagId);
299 defaultResourcesQuery.bindValue(":type_id", resourceTypeId);
300
301 if (!defaultResourcesQuery.exec()) {
302 qWarning() << "Could not execute resource/tag query" << defaultResourcesQuery.lastError();
303 }
304
305 QStringList resourceFileNames;
306
307 while (defaultResourcesQuery.next()) {
308 resourceFileNames << defaultResourcesQuery.value("resources.filename").toString();
309 }
310
311 tag->setDefaultResources(resourceFileNames);
312
313 return tag;
314}
315
316
317KoResourceSP KisResourceLocator::resource(QString storageLocation, const QString &resourceType, const QString &filename)
318{
319 storageLocation = makeStorageLocationAbsolute(storageLocation);
320
321 QPair<QString, QString> key = QPair<QString, QString> (storageLocation, resourceType + "/" + filename);
322
324 if (d->resourceCache.contains(key)) {
325 resource = d->resourceCache[key];
326 }
327 else {
328 KisResourceStorageSP storage = d->storages[storageLocation];
329 if (!storage) {
330 qWarning() << "Could not find storage" << storageLocation;
331 return 0;
332 }
333
334 resource = storage->resource(resourceType + "/" + filename);
335
336 if (resource) {
337 d->resourceCache[key] = resource;
338 // load all the embedded resources into temporary "memory" storage
340 }
341 }
342
343 if (!resource) {
344 qWarning() << "KoResourceSP KisResourceLocator::resource" << storageLocation << resourceType << filename << "was not found";
345 return 0;
346 }
347
348 resource->setStorageLocation(storageLocation);
349 Q_ASSERT(!resource->storageLocation().isEmpty());
350
351 if (resource->resourceId() < 0 || resource->version() < 0) {
352 QSqlQuery q;
353 if (!q.prepare("SELECT resources.id\n"
354 ", versioned_resources.version as version\n"
355 ", versioned_resources.md5sum as md5sum\n"
356 ", resources.name\n"
357 ", resources.status\n"
358 "FROM resources\n"
359 ", storages\n"
360 ", resource_types\n"
361 ", versioned_resources\n"
362 "WHERE storages.id = resources.storage_id\n"
363 "AND storages.location = :storage_location\n"
364 "AND resource_types.id = resources.resource_type_id\n"
365 "AND resource_types.name = :resource_type\n"
366 "AND resources.filename = :filename\n"
367 "AND versioned_resources.resource_id = resources.id\n"
368 "AND versioned_resources.version = (SELECT MAX(version) FROM versioned_resources WHERE versioned_resources.resource_id = resources.id)")) {
369 qWarning() << "Could not prepare id/version query" << q.lastError();
370
371 }
372
373 q.bindValue(":storage_location", makeStorageLocationRelative(storageLocation));
374 q.bindValue(":resource_type", resourceType);
375 q.bindValue(":filename", filename);
376
377 if (!q.exec()) {
378 qWarning() << "Could not execute id/version query" << q.lastError() << q.boundValues();
379 }
380
381 if (!q.first()) {
382 qWarning() << "Could not find the resource in the database" << storageLocation << resourceType << filename;
383 }
384
385 resource->setResourceId(q.value(0).toInt());
386 Q_ASSERT(resource->resourceId() >= 0);
387
388 resource->setVersion(q.value(1).toInt());
389 Q_ASSERT(resource->version() >= 0);
390
391 resource->setMD5Sum(q.value(2).toString());
392 Q_ASSERT(!resource->md5Sum().isEmpty());
393
394 resource->setActive(q.value(4).toBool());
395
396 // To override resources that use the filename for the name, which is versioned, and we don't want the version number in the name
397 resource->setName(q.value(3).toString());;
398 }
399
400 if (!resource) {
401 qWarning() << "Could not find resource" << resourceType + "/" + filename;
402 return 0;
403 }
404
405 return resource;
406}
407
414
415bool KisResourceLocator::setResourceActive(int resourceId, bool active)
416{
417 // First remove the resource from the cache
418 ResourceStorage rs = getResourceStorage(resourceId);
419 QPair<QString, QString> key = QPair<QString, QString> (rs.storageLocation, rs.resourceType + "/" + rs.resourceFileName);
420
421 d->resourceCache.remove(key);
422 if (!active) {
424 }
425
426 bool result = KisResourceCacheDb::setResourceActive(resourceId, active);
427
428 Q_EMIT resourceActiveStateChanged(rs.resourceType, resourceId);
429
430 return result;
431}
432
433KoResourceSP KisResourceLocator::importResourceFromFile(const QString &resourceType, const QString &fileName, const bool allowOverwrite, const QString &storageLocation)
434{
435 QFile f(fileName);
436 if (!f.open(QFile::ReadOnly)) {
437 qWarning() << "Could not open" << fileName << "for loading";
438 return nullptr;
439 }
440
441 return importResource(resourceType, fileName, &f, allowOverwrite, storageLocation);
442}
443
444KoResourceSP KisResourceLocator::importResource(const QString &resourceType, const QString &fileName, QIODevice *device, const bool allowOverwrite, const QString &storageLocation)
445{
446 KisResourceStorageSP storage = d->storages[makeStorageLocationAbsolute(storageLocation)];
447
448 QByteArray resourceData = device->readAll();
450
451 {
452 QBuffer buf(&resourceData);
453 buf.open(QBuffer::ReadOnly);
454
456
457 if (!loader) {
458 qWarning() << "Could not import" << fileName << ": resource doesn't load.";
459 return nullptr;
460 }
461
462 resource = loader->load(QFileInfo(fileName).fileName(), buf, KisGlobalResourcesInterface::instance());
463 }
464
465 if (!resource || !resource->valid()) {
466 qWarning() << "Could not import" << fileName << ": resource doesn't load.";
467 return nullptr;
468 }
469
470 const QString md5 = KoMD5Generator::generateHash(resourceData);
471 const QString resourceUrl = resourceType + "/" + resource->filename();
472
473 const KoResourceSP existingResource = storage->resource(resourceUrl);
474
475 if (existingResource) {
476 const QString existingResourceMd5Sum = storage->resourceMd5(resourceUrl);
477
478 if (!allowOverwrite) {
479 return nullptr;
480 }
481
482 if (existingResourceMd5Sum == md5 &&
483 existingResource->filename() == resource->filename()) {
484
492 int existingResourceId = -1;
493 bool r = KisResourceCacheDb::getResourceIdFromFilename(existingResource->filename(), resourceType, storageLocation, existingResourceId);
494
495 if (r && existingResourceId > 0) {
496 return resourceForId(existingResourceId);
497 }
498 }
499
500 qWarning() << "A resource with the same filename but a different MD5 already exists in the storage" << resourceType << fileName << storageLocation;
501 if (storageLocation == "") {
502 qWarning() << "Proceeding with overwriting the existing resource...";
503 // remove all versions of the resource from the resource folder
504 QStringList versionsLocations;
505
506 // this resource has id -1, we need correct id
507 int existingResourceId = -1;
508 bool r = KisResourceCacheDb::getResourceIdFromVersionedFilename(existingResource->filename(), resourceType, storageLocation, existingResourceId);
509
510 if (r && existingResourceId >= 0) {
511 if (KisResourceCacheDb::getAllVersionsLocations(existingResourceId, versionsLocations)) {
512
513 for (int i = 0; i < versionsLocations.size(); i++) {
514 QFileInfo fi(this->resourceLocationBase() + "/" + resourceType + "/" + versionsLocations[i]);
515 if (fi.exists()) {
516 r = QFile::remove(fi.filePath());
517 if (!r) {
518 qWarning() << "KisResourceLocator::importResourceFromFile: Removal of " << fi.filePath()
519 << "was requested, but it wasn't possible, something went wrong.";
520 }
521 } else {
522 qWarning() << "KisResourceLocator::importResourceFromFile: Removal of " << fi.filePath()
523 << "was requested, but it doesn't exist.";
524 }
525 }
526 } else {
527 qWarning() << "KisResourceLocator::importResourceFromFile: Finding all locations for " << existingResourceId << "was requested, but it failed.";
528 return nullptr;
529 }
530 } else {
531 qWarning() << "KisResourceLocator::importResourceFromFile: there is no resource file found in the location of " << storageLocation << resource->filename() << resourceType;
532 return nullptr;
533 }
534
535 Q_EMIT beginExternalResourceRemove(resourceType, {existingResourceId});
536
537 // remove everything related to this resource from the database (remember about tags and versions!!!)
538 r = KisResourceCacheDb::removeResourceCompletely(existingResourceId);
539
540 {
541 const QString absoluteStorageLocation = makeStorageLocationAbsolute(resource->storageLocation());
542 KisResourceThumbnailCache::instance()->remove(absoluteStorageLocation, resourceType, existingResource->filename());
543 }
544
545 Q_EMIT endExternalResourceRemove(resourceType);
546
547 if (!r) {
548 qWarning() << "KisResourceLocator::importResourceFromFile: Removing resource with id " << existingResourceId << "completely from the database failed.";
549 return nullptr;
550 }
551
552 } else {
553 qWarning() << "KisResourceLocator::importResourceFromFile: Overwriting of the resource was denied, aborting import.";
554 return nullptr;
555 }
556 }
557
558 QBuffer buf(&resourceData);
559 buf.open(QBuffer::ReadOnly);
560
561 if (storage->importResource(resourceUrl, &buf)) {
562 resource = storage->resource(resourceUrl);
563
564 if (!resource) {
565 qWarning() << "Could not retrieve imported resource from the storage" << resourceType << fileName << storageLocation;
566 return nullptr;
567 }
568
569 resource->setStorageLocation(storageLocation);
570 resource->setMD5Sum(storage->resourceMd5(resourceUrl));
571 resource->setVersion(0);
572 resource->setDirty(false);
574
575 Q_EMIT beginExternalResourceImport(resourceType, 1);
576
577 // Insert into the database
578 const bool result = KisResourceCacheDb::addResource(storage,
579 storage->timeStampForResource(resourceType, resource->filename()),
580 resource,
581 resourceType);
582
583 Q_EMIT endExternalResourceImport(resourceType);
584
585 if (!result) {
586 return nullptr;
587 }
588
589 // resourceCaches use absolute locations
590 const QString absoluteStorageLocation = makeStorageLocationAbsolute(resource->storageLocation());
591 const QPair<QString, QString> key = {absoluteStorageLocation, resourceType + "/" + resource->filename()};
592 // Add to the cache
593 d->resourceCache[key] = resource;
595
596 return resource;
597 }
598
599 return nullptr;
600}
601
602bool KisResourceLocator::importWillOverwriteResource(const QString &resourceType, const QString &fileName, const QString &storageLocation) const
603{
604 KisResourceStorageSP storage = d->storages[makeStorageLocationAbsolute(storageLocation)];
605
606 const QString resourceUrl = resourceType + "/" + QFileInfo(fileName).fileName();
607
608 const KoResourceSP existingResource = storage->resource(resourceUrl);
609
610 return !existingResource.isNull();
611}
612
613bool KisResourceLocator::exportResource(KoResourceSP resource, QIODevice *device)
614{
615 if (!resource || !resource->valid() || resource->resourceId() < 0) return false;
616
617 const QString resourceUrl = resource->resourceType().first + "/" + resource->filename();
618 KisResourceStorageSP storage = d->storages[makeStorageLocationAbsolute(resource->storageLocation())];
619 return storage->exportResource(resourceUrl, device);
620}
621
622bool KisResourceLocator::addResource(const QString &resourceType, const KoResourceSP resource, const QString &storageLocation)
623{
624 if (!resource || !resource->valid()) return false;
625
626 KisResourceStorageSP storage = d->storages[makeStorageLocationAbsolute(storageLocation)];
627 Q_ASSERT(storage);
628
629 //If we have gotten this far and the resource still doesn't have a filename to save to, we should generate one.
630 if (resource->filename().isEmpty()) {
631 resource->setFilename(resource->name().split(" ").join("_") + resource->defaultFileExtension());
632 }
633
634 if (resource->version() != 0) { // Can happen with cloned resources
635 resource->setVersion(0);
636 }
637
638 // Save the resource to the storage storage
639 if (!storage->addResource(resource)) {
640 qWarning() << "Could not add resource" << resource->filename() << "to the storage" << storageLocation;
641 return false;
642 }
643
644 resource->setStorageLocation(storageLocation);
645 resource->setMD5Sum(storage->resourceMd5(resourceType + "/" + resource->filename()));
646 resource->setDirty(false);
648
649 d->resourceCache[QPair<QString, QString>(storageLocation, resourceType + "/" + resource->filename())] = resource;
650
656 const bool result = KisResourceCacheDb::addResource(storage,
657 storage->timeStampForResource(resourceType, resource->filename()),
658 resource,
659 resourceType);
660 return result;
661}
662
663bool KisResourceLocator::updateResource(const QString &resourceType, const KoResourceSP resource)
664{
665 QString storageLocation = makeStorageLocationAbsolute(resource->storageLocation());
666
667 Q_ASSERT(d->storages.contains(storageLocation));
668
669 if (resource->resourceId() < 0) {
670 return addResource(resourceType, resource);
671 }
672
673 KisResourceStorageSP storage = d->storages[storageLocation];
674
675 if (!storage->supportsVersioning()) return false;
676
677 // remove older version
678 KisResourceThumbnailCache::instance()->remove(storageLocation, resourceType, resource->filename());
679
680 resource->updateThumbnail();
681 resource->setVersion(resource->version() + 1);
682 resource->setActive(true);
683
684 if (!storage->saveAsNewVersion(resource)) {
685 qWarning() << "Failed to save the new version of " << resource->name() << "to storage" << storageLocation;
686 return false;
687 }
688
689 resource->setMD5Sum(storage->resourceMd5(resourceType + "/" + resource->filename()));
690 resource->setDirty(false);
692
693 // The version needs already to have been incremented
694 if (!KisResourceCacheDb::addResourceVersion(resource->resourceId(), QDateTime::currentDateTime(), storage, resource)) {
695 qWarning() << "Failed to add a new version of the resource to the database" << resource->name();
696 return false;
697 }
698
699 if (!setMetaDataForResource(resource->resourceId(), resource->metadata())) {
700 qWarning() << "Failed to update resource metadata" << resource;
701 return false;
702 }
703
704 // Update the resource in the cache
705 QPair<QString, QString> key = QPair<QString, QString> (storageLocation, resourceType + "/" + resource->filename());
706 d->resourceCache[key] = resource;
708
709 return true;
710}
711
712bool KisResourceLocator::reloadResource(const QString &resourceType, const KoResourceSP resource)
713{
714 // This resource isn't in the database yet, so we cannot reload it
715 if (resource->resourceId() < 0) return false;
716
717 QString storageLocation = makeStorageLocationAbsolute(resource->storageLocation());
718 Q_ASSERT(d->storages.contains(storageLocation));
719
720 KisResourceStorageSP storage = d->storages[storageLocation];
721
722 if (!storage->loadVersionedResource(resource)) {
723 qWarning() << "Failed to reload the resource" << resource->name() << "from storage" << storageLocation;
724 return false;
725 }
726
727 resource->setMD5Sum(storage->resourceMd5(resourceType + "/" + resource->filename()));
728 resource->setDirty(false);
730
731 // We haven't changed the version of the resource, so the cache must be still valid
732 QPair<QString, QString> key = QPair<QString, QString> (storageLocation, resourceType + "/" + resource->filename());
733 Q_ASSERT(d->resourceCache[key] == resource);
734
735 return true;
736}
737
738QMap<QString, QVariant> KisResourceLocator::metaDataForResource(int id) const
739{
740 return KisResourceCacheDb::metaDataForId(id, "resources");
741}
742
743bool KisResourceLocator::setMetaDataForResource(int id, QMap<QString, QVariant> map) const
744{
745 return KisResourceCacheDb::updateMetaDataForId(map, id, "resources");
746}
747
748QMap<QString, QVariant> KisResourceLocator::metaDataForStorage(const QString &storageLocation) const
749{
750 QMap<QString, QVariant> metadata;
751 if (!d->storages.contains(makeStorageLocationAbsolute(storageLocation))) {
752 qWarning() << storageLocation << "not in" << d->storages.keys();
753 return metadata;
754 }
755
756 KisResourceStorageSP st = d->storages[makeStorageLocationAbsolute(storageLocation)];
757
758 if (d->storages[makeStorageLocationAbsolute(storageLocation)].isNull()) {
759 return metadata;
760 }
761
762 Q_FOREACH(const QString key, st->metaDataKeys()) {
763 metadata[key] = st->metaData(key);
764 }
765 return metadata;
766}
767
768void KisResourceLocator::setMetaDataForStorage(const QString &storageLocation, QMap<QString, QVariant> map) const
769{
770 Q_ASSERT(d->storages.contains(storageLocation));
771 Q_FOREACH(const QString &key, map.keys()) {
772 d->storages[storageLocation]->setMetaData(key, map[key]);
773 }
774}
775
776void KisResourceLocator::purge(const QString &storageLocation)
777{
778 Q_FOREACH(const auto key, d->resourceCache.keys()) {
779 if (key.first == storageLocation) {
780 d->resourceCache.remove(key);
782 }
783 }
784}
785
786bool KisResourceLocator::addStorage(const QString &storageLocation, KisResourceStorageSP storage)
787{
788 if (d->storages.contains(storageLocation)) {
789 if (!removeStorage(storageLocation)) {
790 qWarning() << "could not remove" << storageLocation;
791 return false;
792 }
793 }
794
795 QVector<std::pair<QString, int>> addedResources;
796 Q_FOREACH(const QString &type, KisResourceLoaderRegistry::instance()->resourceTypes()) {
797 int numAddedResources = 0;
798
799 QSharedPointer<KisResourceStorage::ResourceIterator> it = storage->resources(type);
800 while (it->hasNext()) {
801 it->next();
802 numAddedResources++;
803 }
804
805 if (numAddedResources > 0) {
806 addedResources << std::make_pair(type, numAddedResources);
807 }
808 }
809
810 Q_FOREACH (const auto &typedResources, addedResources) {
811 Q_EMIT beginExternalResourceImport(typedResources.first, typedResources.second);
812 }
813
814 d->storages[storageLocation] = storage;
815 if (!KisResourceCacheDb::addStorage(storage, false)) {
816 d->errorMessages.append(i18n("Could not add %1 to the database", storage->location()));
817 qWarning() << d->errorMessages;
818 return false;
819 }
820
822 d->errorMessages.append(QString("Could not add tags for storage %1 to the cache database").arg(storage->location()));
823 qWarning() << d->errorMessages;
824 return false;
825 }
826
827 Q_FOREACH (const auto &typedResources, addedResources) {
828 Q_EMIT endExternalResourceImport(typedResources.first);
829 }
830
831 Q_EMIT storageAdded(makeStorageLocationRelative(storage->location()));
832 return true;
833}
834
835bool KisResourceLocator::removeStorage(const QString &storageLocation)
836{
837 // Cloned documents have a document storage, but that isn't in the locator.
838 if (!d->storages.contains(storageLocation)) {
839 return true;
840 }
841
843
844 Q_FOREACH(const QString &type, KisResourceLoaderRegistry::instance()->resourceTypes()) {
845 const QVector<int> resources = KisResourceCacheDb::resourcesForStorage(type, storageLocation);
846 if (!resources.isEmpty()) {
847 removedResources << std::make_pair(type, resources);
848 }
849 }
850
851 Q_FOREACH (const auto &typedResources, removedResources) {
852 Q_EMIT beginExternalResourceRemove(typedResources.first, typedResources.second);
853 }
854
855 purge(storageLocation);
856
857 KisResourceStorageSP storage = d->storages.take(storageLocation);
858
859 if (!KisResourceCacheDb::deleteStorage(storage)) {
860 d->errorMessages.append(i18n("Could not remove storage %1 from the database", storage->location()));
861 qWarning() << d->errorMessages;
862 return false;
863 }
864
865 Q_FOREACH (const auto &typedResources, removedResources) {
866 Q_EMIT endExternalResourceRemove(typedResources.first);
867 }
868
869 Q_EMIT storageRemoved(makeStorageLocationRelative(storage->location()));
870
871 return true;
872}
873
874bool KisResourceLocator::hasStorage(const QString &document)
875{
876 return d->storages.contains(document);
877}
878
880{
881 QSqlQuery query;
882
883 if (!query.prepare("SELECT tags.url \n"
884 ", resource_types.name \n"
885 "FROM tags\n"
886 ", resource_types\n"
887 "WHERE tags.resource_type_id = resource_types.id\n"))
888 {
889 qWarning() << "Could not prepare save tags query" << query.lastError();
890 return;
891 }
892
893 if (!query.exec()) {
894 qWarning() << "Could not execute save tags query" << query.lastError();
895 return;
896 }
897
898 // this needs to use ResourcePaths because it is sometimes called during initialization
899 // (when the database versions don't match up and tags need to be saved)
900 QString resourceLocation = KoResourcePaths::getAppDataLocation() + "/";
901
902 while (query.next()) {
903 // Save tag...
904 KisTagSP tag = tagForUrlNoCache(query.value("tags.url").toString(),
905 query.value("resource_types.name").toString());
906
907 if (!tag || !tag->valid()) {
908 continue;
909 }
910
911
912 QString filename = tag->filename();
913 if (filename.isEmpty() || QFileInfo(filename).suffix().isEmpty()) {
914 filename = tag->url() + ".tag";
915 }
916
917
918 if (QFileInfo(filename).suffix() != "tag" && QFileInfo(filename).suffix() != "TAG") {
919 // it's either .abr file, or maybe a .bundle
920 // or something else, but not a tag file
921 dbgResources << "Skipping saving tag " << tag->name(false) << filename << tag->resourceType();
922 continue;
923 }
924
925 filename.remove(resourceLocation);
926
927 QFile f(resourceLocation + "/" + tag->resourceType() + '/' + filename);
928
929 if (!f.open(QFile::WriteOnly)) {
930 qWarning () << "Could not open tag file for writing" << f.fileName();
931 continue;
932 }
933
934 QBuffer buf;
935 buf.open(QIODevice::WriteOnly);;
936
937 if (!tag->save(buf)) {
938 qWarning() << "Could not save tag to" << f.fileName();
939 buf.close();
940 f.close();
941 continue;
942 }
943
944 f.write(buf.data());
945 f.flush();
946
947 f.close();
948 }
949}
950
951void KisResourceLocator::purgeTag(const QString tagUrl, const QString resourceType)
952{
953 d->tagCache.remove(QPair<QString, QString>(resourceType, tagUrl));
954}
955
957{
958 const QString storageLocation = makeStorageLocationAbsolute(resource->storageLocation());
959 KisResourceStorageSP storage = d->storages[storageLocation];
960 if (!storage) {
961 qWarning() << "Could not find storage" << storageLocation;
962 return QString();
963 }
964
965 const QString resourceUrl = resource->resourceType().first + "/" + resource->filename();
966
967 return storage->resourceFilePath(resourceUrl);
968}
969
971{
973 qWarning() << i18n("Could not synchronize updated font registry with the database");
974 } else {
975 Q_EMIT storageResynchronized(fontStorage()->location(), false);
976 }
977}
978
979KisResourceLocator::LocatorError KisResourceLocator::firstTimeInstallation(InitializationStatus initializationStatus, const QString &installationResourcesLocation)
980{
981 Q_EMIT progressMessage(i18n("Krita is running for the first time. Initialization will take some time."));
982 Q_UNUSED(initializationStatus);
983
984 Q_FOREACH(const QString &folder, KisResourceLoaderRegistry::instance()->resourceTypes()) {
985 QDir dir(d->resourceLocation + '/' + folder + '/');
986 if (!dir.exists()) {
987 if (!QDir().mkpath(d->resourceLocation + '/' + folder + '/')) {
988 d->errorMessages << i18n("3. Could not create the resource location at %1.", dir.path());
990 }
991 }
992 }
993
994 Q_FOREACH(const QString &folder, KisResourceLoaderRegistry::instance()->resourceTypes()) {
995 QDir dir(installationResourcesLocation + '/' + folder + '/');
996 if (dir.exists()) {
997 Q_FOREACH(const QString &entry, dir.entryList(QDir::Files | QDir::Readable)) {
998 QFile f(dir.canonicalPath() + '/'+ entry);
999 if (!QFileInfo(d->resourceLocation + '/' + folder + '/' + entry).exists()) {
1000 if (!f.copy(d->resourceLocation + '/' + folder + '/' + entry)) {
1001 d->errorMessages << i18n("Could not copy resource %1 to %2", f.fileName(), d->resourceLocation + '/' + folder + '/' + entry);
1002 }
1003 }
1004 }
1005 }
1006 }
1007
1008 // And add bundles and adobe libraries
1009 QStringList filters = QStringList() << "*.bundle" << "*.abr" << "*.asl";
1010 QDirIterator iter(installationResourcesLocation, filters, QDir::Files, QDirIterator::Subdirectories);
1011 while (iter.hasNext()) {
1012 iter.next();
1013 Q_EMIT progressMessage(i18n("Installing the resources from bundle %1.", iter.filePath()));
1014 QFile f(iter.filePath());
1015 Q_ASSERT(f.exists());
1016 if (!f.copy(d->resourceLocation + '/' + iter.fileName())) {
1017 d->errorMessages << i18n("Could not copy resource %1 to %2", f.fileName(), d->resourceLocation);
1018 }
1019 }
1020
1021 QFile f(d->resourceLocation + '/' + "KRITA_RESOURCE_VERSION");
1022 f.open(QFile::WriteOnly);
1023 f.write(KritaVersionWrapper::versionString().toUtf8());
1024 f.close();
1025
1026 return LocatorError::Ok;
1027}
1028
1030{
1031 d->storages.clear();
1032 d->resourceCache.clear();
1033
1034 // Add the folder
1036 Q_ASSERT(storage->location() == d->resourceLocation);
1037 d->storages[d->resourceLocation] = storage;
1038
1039 // Add the memory storage
1040 d->storages["memory"] = QSharedPointer<KisResourceStorage>::create("memory");
1041 d->storages["memory"]->setMetaData(KisResourceStorage::s_meta_name, i18n("Temporary Resources"));
1042
1043 // Add font storage
1045 if (fontStorage && fontStorage->valid()) {
1046 d->storages["fontregistry"] = fontStorage;
1047 d->storages["fontregistry"]->setMetaData(KisResourceStorage::s_meta_name, i18n("Font Storage"));
1048 }
1049
1050 // And add bundles and adobe libraries
1051 QStringList filters = QStringList() << "*.bundle" << "*.abr" << "*.asl";
1052 QDirIterator iter(d->resourceLocation, filters, QDir::Files, QDirIterator::Subdirectories);
1053 while (iter.hasNext()) {
1054 iter.next();
1056 if (!storage->valid()) {
1057 // we still add the storage to the list and try to read whatever possible
1058 qWarning() << "KisResourceLocator::findStorages: the storage is invalid" << storage->location();
1059 }
1060 d->storages[storage->location()] = storage;
1061 }
1062
1063 // Add any missing storage types to the resource cache database.
1064 Q_FOREACH(const KisResourceStorage::StorageType &type, KisStoragePluginRegistry::instance()->storageTypes()) {
1066 }
1067}
1068
1070{
1071 return d->storages.values();
1072}
1073
1075{
1076 if (!d->storages.contains(location)) {
1077 qWarning() << "No" << location << "storage defined:" << d->storages.keys();
1078 return 0;
1079 }
1080 KisResourceStorageSP storage = d->storages[location];
1081 if (!storage || !storage->valid()) {
1082 qWarning() << "Could not retrieve the" << location << "storage object or the object is not valid";
1083 return 0;
1084 }
1085
1086 return storage;
1087}
1088
1090{
1091 return storageByLocation(d->resourceLocation);
1092}
1093
1098
1100{
1101 return storageByLocation("fontregistry");
1102}
1103
1105{
1106 ResourceStorage rs;
1107
1108 QSqlQuery q;
1109 bool r = q.prepare("SELECT storages.location\n"
1110 ", resource_types.name as resource_type\n"
1111 ", resources.filename\n"
1112 "FROM resources\n"
1113 ", storages\n"
1114 ", resource_types\n"
1115 "WHERE resources.id = :resource_id\n"
1116 "AND resources.storage_id = storages.id\n"
1117 "AND resource_types.id = resources.resource_type_id");
1118 if (!r) {
1119 qWarning() << "KisResourceLocator::removeResource: could not prepare query." << q.lastError();
1120 return rs;
1121 }
1122
1123
1124 q.bindValue(":resource_id", resourceId);
1125
1126 r = q.exec();
1127 if (!r) {
1128 qWarning() << "KisResourceLocator::removeResource: could not execute query." << q.lastError();
1129 return rs;
1130 }
1131
1132 q.first();
1133
1134 QString storageLocation = q.value("location").toString();
1135 QString resourceType= q.value("resource_type").toString();
1136 QString resourceFilename = q.value("filename").toString();
1137
1138 rs.storageLocation = makeStorageLocationAbsolute(storageLocation);
1139 rs.resourceType = resourceType;
1140 rs.resourceFileName = resourceFilename;
1141
1142 return rs;
1143}
1144
1145QString KisResourceLocator::makeStorageLocationAbsolute(QString storageLocation) const
1146{
1147// debugResource << "makeStorageLocationAbsolute" << storageLocation;
1148
1149 if (storageLocation.isEmpty()) {
1150 return resourceLocationBase();
1151 }
1152
1153 if (QFileInfo(storageLocation).isRelative() && (storageLocation.endsWith(".bundle", Qt::CaseInsensitive)
1154 || storageLocation.endsWith(".asl", Qt::CaseInsensitive)
1155 || storageLocation.endsWith(".abr", Qt::CaseInsensitive))) {
1156 if (resourceLocationBase().endsWith('/') || resourceLocationBase().endsWith("\\")) {
1157 storageLocation = resourceLocationBase() + storageLocation;
1158 }
1159 else {
1160 storageLocation = resourceLocationBase() + '/' + storageLocation;
1161 }
1162 }
1163
1164// debugResource << "\t" << storageLocation;
1165 return storageLocation;
1166}
1167
1169{
1170 Q_EMIT progressMessage(i18n("Synchronizing the resources."));
1171
1172 d->errorMessages.clear();
1173
1174 // Add resource types that have been added since first-time installation.
1175 Q_FOREACH(auto loader, KisResourceLoaderRegistry::instance()->values()) {
1176 KisResourceCacheDb::registerResourceType(loader->resourceType());
1177 }
1178
1179
1180 findStorages();
1181 Q_FOREACH(const KisResourceStorageSP storage, d->storages) {
1183 d->errorMessages.append(i18n("Could not synchronize %1 with the database", storage->location()));
1184 } else {
1185 Q_EMIT storageResynchronized(storage->location(), true);
1186 }
1187 }
1188
1189 Q_FOREACH(const KisResourceStorageSP storage, d->storages) {
1190 if (!KisResourceCacheDb::addStorageTags(storage)) {
1191 d->errorMessages.append(i18n("Could not synchronize %1 with the database", storage->location()));
1192 }
1193 }
1194
1196
1206
1207 // now remove the storages that no longer exists
1208 KisStorageModel model;
1209
1210 QList<QString> storagesToRemove;
1211 for (int i = 0; i < model.rowCount(); i++) {
1212 QModelIndex idx = model.index(i, 0);
1213 QString location = model.data(idx, Qt::UserRole + KisStorageModel::Location).toString();
1214 storagesToRemove << location;
1215 }
1216
1217 for (int i = 0; i < storagesToRemove.size(); i++) {
1218 QString location = storagesToRemove[i];
1219 if (!d->storages.contains(this->makeStorageLocationAbsolute(location))) {
1220 if (!KisResourceCacheDb::deleteStorage(location)) {
1221 d->errorMessages.append(i18n("Could not remove storage %1 from the database", this->makeStorageLocationAbsolute(location)));
1222 qWarning() << d->errorMessages;
1223 return false;
1224 }
1225 Q_EMIT storageRemoved(this->makeStorageLocationAbsolute(location));
1226 }
1227 }
1228
1229
1230 d->errorMessages <<
1232
1233 d->resourceCache.clear();
1234 return d->errorMessages.isEmpty();
1235}
1236
1237
1239{
1240// debugResource << "makeStorageLocationRelative" << location << "locationbase" << resourceLocationBase();
1241 return location.remove(resourceLocationBase());
1242}
QList< QString > QStringList
QSharedPointer< KisTag > KisTagSP
Definition KisTag.h:20
static KisResourcesInterfaceSP instance()
static QString mimeTypeForFile(const QString &file, bool checkExistingFiles=true)
Find the mimetype for the given filename. The filename must include a suffix.
static bool addStorage(KisResourceStorageSP storage, bool preinstalled)
static bool addResource(KisResourceStorageSP storage, QDateTime timestamp, KoResourceSP resource, const QString &resourceType)
static bool getAllVersionsLocations(int resourceId, QStringList &outVersionsLocationsList)
static bool addResourceVersion(int resourceId, QDateTime timestamp, KisResourceStorageSP storage, KoResourceSP resource)
addResourceVersion adds a new version of the resource to the database. The resource itself already sh...
static bool removeOrphanedMetaData()
removeOrphanedMetaData Previous versions of Krita never removed metadata, so this function doublechec...
static bool updateMetaDataForId(const QMap< QString, QVariant > map, int id, const QString &tableName)
setMetaDataForId removes all metadata for the given id and table name, and inserts the metadata in th...
static QMap< QString, QVariant > metaDataForId(int id, const QString &tableName)
metaDataForId
static QVector< int > resourcesForStorage(const QString &resourceType, const QString &storageLocation)
static bool getResourceIdFromFilename(QString filename, QString resourceType, QString storageLocation, int &outResourceId)
The function will find the resource only if it is the latest version.
static bool deleteStorage(KisResourceStorageSP storage)
Actually delete the storage and all its resources from the database (i.e., nothing is set to inactive...
static bool setResourceActive(int resourceId, bool active=false)
Make this resource active or inactive; this does not remove the resource from disk or from the databa...
static bool removeResourceCompletely(int resourceId)
static bool addStorageTags(KisResourceStorageSP storage)
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 bool registerResourceType(const QString &resourceType)
registerResourceType registers this resource type in the database
static bool synchronizeStorage(KisResourceStorageSP storage)
static bool registerStorageType(const KisResourceStorage::StorageType storageType)
registerStorageType registers this storage type in the database
The KisResourceLoader class is an abstract interface class that must be implemented by actual resourc...
bool load(KoResourceSP resource, QIODevice &dev, KisResourcesInterfaceSP resourcesInterface)
static KisResourceLoaderRegistry * instance()
KisResourceLoaderBase * loader(const QString &resourceType, const QString &mimetype) const
QHash< QPair< QString, QString >, KoResourceSP > resourceCache
QMap< QString, KisResourceStorageSP > storages
QMap< QPair< QString, QString >, KisTagSP > tagCache
KisResourceStorageSP folderStorage() const
QMap< QString, QVariant > metaDataForStorage(const QString &storageLocation) const
metaDataForStorage
void progressMessage(const QString &)
LocatorError initialize(const QString &installationResourcesLocation)
initialize Setup the resource locator for use.
QScopedPointer< Private > d
KisTagSP tagForUrl(const QString &tagUrl, const QString resourceType)
tagForUrl create a tag from the database
bool resourceCached(QString storageLocation, const QString &resourceType, const QString &filename) const
KoResourceSP resource(QString storageLocation, const QString &resourceType, const QString &filename)
resource finds a physical resource in one of the storages
KoResourceSP importResource(const QString &resourceType, const QString &fileName, QIODevice *device, const bool allowOverwrite, const QString &storageLocation=QString())
importResource
bool addResource(const QString &resourceType, const KoResourceSP resource, const QString &storageLocation=QString())
addResource adds the given resource to the database and potentially a storage
static const QString resourceLocationKey
void updateFontStorage()
This updates the "fontregistry" storage. Called when the font directories change;.
KisResourceStorageSP fontStorage() const
void endExternalResourceRemove(const QString &resourceType)
Emitted when the locator finished importing the embedded resource.
KisResourceStorageSP storageByLocation(const QString &location) const
void storageRemoved(const QString &location)
Emitted whenever a storage is removed.
bool exportResource(KoResourceSP resource, QIODevice *device)
exportResource
void purge(const QString &storageLocation)
purge purges the local resource cache
QStringList errorMessages() const
errorMessages
QList< KisResourceStorageSP > storages() const
ResourceStorage getResourceStorage(int resourceId) const
bool updateResource(const QString &resourceType, const KoResourceSP resource)
updateResource
void storageAdded(const QString &location)
Emitted whenever a storage is added.
QString resourceLocationBase() const
resourceLocationBase is the place where all resource storages (folder, bundles etc....
bool removeStorage(const QString &storageLocation)
removeStorage removes the temporary storage from the database
KisResourceStorageSP memoryStorage() const
void storagesBulkSynchronizationFinished()
void beginExternalResourceImport(const QString &resourceType, int numResources)
Emitted when the locator needs to add an embedded resource.
bool hasStorage(const QString &storageLocation)
hasStorage can be used to check whether the given storage already exists
void beginExternalResourceRemove(const QString &resourceType, const QVector< int > resourceIds)
Emitted when the locator needs to add an embedded resource.
void loadRequiredResources(KoResourceSP resource)
QString makeStorageLocationRelative(QString location) const
bool reloadResource(const QString &resourceType, const KoResourceSP resource)
Reloads the resource from its persistent storage.
QString makeStorageLocationAbsolute(QString storageLocation) const
bool addStorage(const QString &storageLocation, KisResourceStorageSP storage)
addStorage Adds a new resource storage to the database. The storage is will be marked as not pre-inst...
static void saveTags()
saveTags saves all tags to .tag files in the resource folder
QMap< QString, QVariant > metaDataForResource(int id) const
metaDataForResource
QString filePathForResource(KoResourceSP resource)
bool importWillOverwriteResource(const QString &resourceType, const QString &fileName, const QString &storageLocation=QString()) const
return whether importing will overwrite some existing resource
void setMetaDataForStorage(const QString &storageLocation, QMap< QString, QVariant > map) const
setMetaDataForStorage
bool setMetaDataForResource(int id, QMap< QString, QVariant > map) const
setMetaDataForResource
void endExternalResourceImport(const QString &resourceType)
Emitted when the locator finished importing the embedded resource.
bool setResourceActive(int resourceId, bool active)
setResourceActive
KisResourceLocator(QObject *parent)
static KisTagSP tagForUrlNoCache(const QString &tagUrl, const QString resourceType)
tagForUrlNoCache create a tag from the database, don't use cache
void purgeTag(const QString tagUrl, const QString resourceType)
void storageResynchronized(const QString &storage, bool isBulkResynchronization)
LocatorError firstTimeInstallation(InitializationStatus initializationStatus, const QString &installationResourcesLocation)
void resourceActiveStateChanged(const QString &resourceType, int resourceId)
Emitted when a resource changes its active state.
KoResourceSP resourceForId(int resourceId)
resourceForId returns the resource with the given id, or 0 if no such resource exists....
static KisResourceLocator * instance()
KoResourceSP importResourceFromFile(const QString &resourceType, const QString &fileName, const bool allowOverwrite, const QString &storageLocation=QString())
importResourceFromFile
static const QString s_meta_name
void insert(const QString &storageLocation, const QString &resourceType, const QString &filename, const QImage &image)
static KisResourceThumbnailCache * instance()
void remove(const QString &storageLocation, const QString &resourceType, const QString &filename)
int rowCount(const QModelIndex &parent=QModelIndex()) const override
QVariant data(const QModelIndex &index, int role) const override
static KisStoragePluginRegistry * instance()
The KisTag loads a tag from a .tag file. A .tag file is a .desktop file. The following fields are imp...
Definition KisTag.h:34
const KoResourceSignature & signature() const
QByteArray data() const
static QString generateHash(const QString &filename)
generateHash reads the given file and generates a hex-encoded md5sum for the file.
KoResourceSP resource() const noexcept
KoEmbeddedResource embeddedResource() const noexcept
KoResourceSignature signature() const
static QString getAppDataLocation()
A simple wrapper object for the main information about the resource.
#define KIS_SAFE_ASSERT_RECOVER_NOOP(cond)
Definition kis_assert.h:130
#define dbgResources
Definition kis_debug.h:43
KRITAVERSION_EXPORT QString versionString(bool checkGit=false)