From b21050854e9eabf0655c1c813afb98c0ff300fba Mon Sep 17 00:00:00 2001 From: Henrik Lindgren Date: Thu, 17 Sep 2026 15:17:45 +0200 Subject: [PATCH 1/3] Cache: index resources by cache id instead of scanning the whole list per ROM hasEntries(), fillBlanks() and addResource() each walked the full QList under cacheMutex for every ROM, so a generate run over a large platform was quadratic in the cache size and serialized across threads. On a synthetic mame- sized cache (15,499 ROMs, 70,480 resources, 20.8 MB db.xml) a cache-mode generate took 76.1 s at -t 1 and 54.2 s at -t 8; with a QHash from cache id to list positions it takes 23.3 s and 5.3 s. The generated gamelist and media tree are byte-identical to the unpatched binary's, and a gather that only skips cached ROMs writes an identical db.xml and quickid.xml. The index is built lazily on first use and invalidated by the bulk mutators (read, edit, purge, vacuum, validate/verifyFiles, merge), which all run before any worker thread exists. addResource() under --flags refresh replaces the resource in place rather than remove-and-append, so positions stay valid; if the replacement's media cannot be written the stale resource is removed as before and the index rebuilt. Co-Authored-By: Claude Fable 5.1 --- src/cache.cpp | 61 +++++++++++++++++++++++++++++++++++++++------------ src/cache.h | 7 ++++++ 2 files changed, 54 insertions(+), 14 deletions(-) diff --git a/src/cache.cpp b/src/cache.cpp index 989e9d28..9399adfa 100644 --- a/src/cache.cpp +++ b/src/cache.cpp @@ -177,6 +177,7 @@ bool Cache::createFolders(const QString &scraper) { } bool Cache::read() { + idIndexValid = false; QFile quickIdFile(quickIdFilePath()); if (quickIdFile.open(QIODevice::ReadOnly)) { ncprintf("Reading and parsing quick id xml, please wait... "); @@ -380,6 +381,7 @@ void Cache::printCacheEditMenu() { int Cache::editResources(QSharedPointer queue, const QString &command, const QString &type) { + idIndexValid = false; // Check sanity of command and parameters, if any if (command == "new" && !txtTypes().contains(type)) { QStringList sortedTypes = txtTypes(); @@ -888,6 +890,7 @@ int Cache::editResources(QSharedPointer queue, const QString &command, } bool Cache::purgeResources(QString purgeStr) { + idIndexValid = false; purgeStr.replace("purge:", ""); QString module = ""; @@ -939,6 +942,7 @@ bool Cache::purgeResources(QString purgeStr) { } bool Cache::purgeAllOnSinglePlatform(const bool unattend) { + idIndexValid = false; if (!unattend) { ncprintf( "\033[1;31mWARNING! You are about to remove ALL " @@ -1294,6 +1298,7 @@ bool Cache::assembleReport(const Settings &config, const QString filter) { bool Cache::vacuumResources(const QString inputFolder, const QString filter, const int verbosity, const bool unattend) { + idIndexValid = false; if (!unattend) { std::string userInput = ""; ncprintf( @@ -1605,6 +1610,7 @@ bool Cache::write(const bool onlyQuickId) { // This verifies all attached media files and deletes those that have no entry // in the cache void Cache::validate() { + idIndexValid = false; // TODO: Add format checks for each resource type, and remove if deemed // corrupt ncprintf("Starting resource cache validation run for %s platform, please " @@ -1646,6 +1652,7 @@ void Cache::validate() { void Cache::verifyFiles(QDirIterator &dirIt, int &filesDeleted, int ¬DeletedCount, QString resType) { + idIndexValid = false; QList resFileNames; for (const auto &resource : resources) { if (resource.type == resType) { @@ -1671,6 +1678,7 @@ void Cache::verifyFiles(QDirIterator &dirIt, int &filesDeleted, } void Cache::merge(bool overwrite, const QString &otherCacheFolder) { + idIndexValid = false; Cache mergeCache(otherCacheFolder); mergeCache.read(); ncprintf("Merging databases, please wait...\n"); @@ -1791,15 +1799,16 @@ void Cache::addResource(Resource &resource, GameEntry &entry, const QString &cacheAbsolutePath, const Settings &config, QString &output) { QMutexLocker locker(&cacheMutex); + ensureIdIndex(); bool cacheMiss = true; - // This type of iterator ensures we can delete items while iterating - QMutableListIterator it(resources); - while (it.hasNext()) { - Resource res = it.next(); - if (res.cacheId == resource.cacheId && res.type == resource.type && - res.source == resource.source) { + // Under --flags refresh the existing resource is replaced in place, which + // keeps every index position valid; a failed replacement removes it below. + int replaceAt = -1; + for (int i : idIndex.value(resource.cacheId)) { + const Resource &res = resources.at(i); + if (res.type == resource.type && res.source == resource.source) { if (config.refresh) { - it.remove(); + replaceAt = i; } else { cacheMiss = false; } @@ -1939,8 +1948,19 @@ void Cache::addResource(Resource &resource, GameEntry &entry, } } // add record to cache index - resources.append(resource); + if (replaceAt >= 0) { + resources[replaceAt] = resource; + } else { + resources.append(resource); + idIndex[resource.cacheId].append(resources.size() - 1); + } } else { + if (replaceAt >= 0) { + // same outcome as before: a refreshed resource that could not + // be written is dropped rather than kept stale + resources.removeAt(replaceAt); + idIndexValid = false; + } ncprintf("\033[1;33mWarning! Cannot add resource to cache. Have " "you run out of disk space?\n\033[0m"); } @@ -2061,11 +2081,23 @@ QString Cache::getQuickId(const QFileInfo &info) { return QString(); } +void Cache::ensureIdIndex() { + if (idIndexValid) { + return; + } + idIndex.clear(); + idIndex.reserve(resources.size()); + for (int i = 0; i < resources.size(); ++i) { + idIndex[resources.at(i).cacheId].append(i); + } + idIndexValid = true; +} + bool Cache::hasEntries(const QString &cacheId, const QString scraper) { QMutexLocker locker(&cacheMutex); - for (const auto &res : resources) { - if ((scraper.isEmpty() || res.source == scraper) && - res.cacheId == cacheId) { + ensureIdIndex(); + for (int i : idIndex.value(cacheId)) { + if (scraper.isEmpty() || resources.at(i).source == scraper) { return true; } } @@ -2074,11 +2106,12 @@ bool Cache::hasEntries(const QString &cacheId, const QString scraper) { void Cache::fillBlanks(GameEntry &entry, const QString scraper) { QMutexLocker locker(&cacheMutex); + ensureIdIndex(); QList matchingResources; // Find all resources related to this particular rom - for (const auto &resource : resources) { - if ((scraper.isEmpty() || resource.source == scraper) && - entry.cacheId == resource.cacheId) { + for (int i : idIndex.value(entry.cacheId)) { + const Resource &resource = resources.at(i); + if (scraper.isEmpty() || resource.source == scraper) { matchingResources.append(resource); } } diff --git a/src/cache.h b/src/cache.h index ab006e2e..8485e9ab 100644 --- a/src/cache.h +++ b/src/cache.h @@ -119,6 +119,13 @@ class Cache { QMap resCountsMap; QList resources; + // cacheId -> positions in 'resources'. Built lazily under cacheMutex so + // hasEntries()/fillBlanks()/addResource() are a hash lookup instead of a + // scan of every cached resource per ROM; any bulk mutation of 'resources' + // (read, purge, vacuum, edit, merge) invalidates it. + QHash> idIndex; + bool idIndexValid = false; + void ensureIdIndex(); QMap> quickIds; // filePath, timestamp + cacheId for quick lookup From e7c52c4de2b60a85c49ada937273adc9f5a47d67 Mon Sep 17 00:00:00 2001 From: Henrik Lindgren Date: Mon, 12 Oct 2026 16:24:49 +0200 Subject: [PATCH 2/3] Cache: store resources keyed by cache id instead of a side index Replace the flat QList plus lazily rebuilt id index with a QMap> filled directly by read(), as suggested in review. Per-rom lookups (hasEntries, fillBlanks, addResource, report, edit mode) go straight to the rom's list, and there is no index to invalidate after purge, vacuum, validate, edit or merge. Vacuum and validate now use set lookups instead of list scans. db.xml is written in cache id order rather than insertion order; the set of resources written is unchanged. On a synthetic 3,000-rom cache, db.xml content, cached media, gamelist, output media and reports match master after generate, edit, purge, vacuum, merge, validate, report and import. On 15,000 roms / 151,500 resources, cache-mode generation takes 23.9 s at -t 1 and 5.2 s at -t 8 (master: 123 s / 95.5 s). Co-Authored-By: Claude Opus 5.5 --- src/cache.cpp | 392 +++++++++++++++++++++++--------------------------- src/cache.h | 19 +-- 2 files changed, 192 insertions(+), 219 deletions(-) diff --git a/src/cache.cpp b/src/cache.cpp index 9399adfa..6b0cd85b 100644 --- a/src/cache.cpp +++ b/src/cache.cpp @@ -177,7 +177,6 @@ bool Cache::createFolders(const QString &scraper) { } bool Cache::read() { - idIndexValid = false; QFile quickIdFile(quickIdFilePath()); if (quickIdFile.open(QIODevice::ReadOnly)) { ncprintf("Reading and parsing quick id xml, please wait... "); @@ -282,10 +281,10 @@ bool Cache::read() { continue; } - resources.append(resource); + resources[resource.cacheId].append(resource); } cacheFile.close(); - resAtLoad = resources.length(); + resAtLoad = resourceCount(); ncprintf("\033[1;32mDone!\033[0m\n"); ncprintf("Successfully parsed %d resources!\n\n", resAtLoad); return true; @@ -381,7 +380,6 @@ void Cache::printCacheEditMenu() { int Cache::editResources(QSharedPointer queue, const QString &command, const QString &type) { - idIndexValid = false; // Check sanity of command and parameters, if any if (command == "new" && !txtTypes().contains(type)) { QStringList sortedTypes = txtTypes(); @@ -442,19 +440,17 @@ int Cache::editResources(QSharedPointer queue, const QString &command, QMap>> connectedRes; int lenType = 0; int lenSrc = 0; - for (const auto &res : resources) { - if (res.cacheId == cacheId) { - QList l = connectedRes[res.type]; - QPair kv = - QPair(res.source, res.value); - l.append(kv); - connectedRes[res.type] = l; - if (res.source.length() > lenSrc) { - lenSrc = res.source.length(); - } - if (res.type.length() > lenType) { - lenType = res.type.length(); - } + for (const auto &res : resources.value(cacheId)) { + QList l = connectedRes[res.type]; + QPair kv = + QPair(res.source, res.value); + l.append(kv); + connectedRes[res.type] = l; + if (res.source.length() > lenSrc) { + lenSrc = res.source.length(); + } + if (res.type.length() > lenType) { + lenType = res.type.length(); } } if (connectedRes.isEmpty()) { @@ -616,17 +612,17 @@ int Cache::editResources(QSharedPointer queue, const QString &command, .hasMatch()) { newRes.value = value; bool updated = false; - QMutableListIterator it(resources); + QList &romRes = resources[cacheId]; + QMutableListIterator it(romRes); while (it.hasNext()) { Resource res = it.next(); - if (res.cacheId == newRes.cacheId && - res.type == newRes.type && + if (res.type == newRes.type && res.source == newRes.source) { it.remove(); updated = true; } } - resources.append(newRes); + romRes.append(newRes); if (updated) { ncprintf("[\033[1;34m*\033[0m] Updated existing "); } else { @@ -652,9 +648,8 @@ int Cache::editResources(QSharedPointer queue, const QString &command, int idx = 1; int lenType = 0; int lenSrc = 0; - for (const auto &res : resources) { - if (res.cacheId == cacheId && - !binTypes().contains(res.type)) { + for (const auto &res : resources.value(cacheId)) { + if (!binTypes().contains(res.type)) { QList l = connectedRes[res.type]; QStringList resValues = {res.cacheId, res.source, res.type, res.value}; @@ -714,18 +709,18 @@ int Cache::editResources(QSharedPointer queue, const QString &command, } else { int chosen = atoi(typeInput.c_str()); if (chosen >= 1 && chosen < idx) { - QString cacheId = idxCacheIdMap[chosen]; + QString resKey = idxCacheIdMap[chosen]; + QList &romRes = resources[cacheId]; int idxInResList = 0; - for (const auto &res : resources) { - if (cacheId == - res.cacheId % res.source % res.type) { + for (const auto &res : romRes) { + if (resKey == res.cacheId % res.source % res.type) { break; } idxInResList++; } - QString delType = resources[idxInResList].type; - QString delSource = resources[idxInResList].source; - resources.removeAt(idxInResList); + QString delType = romRes[idxInResList].type; + QString delSource = romRes[idxInResList].source; + romRes.removeAt(idxInResList); ncprintf("[\033[1;31m-\033[0m] Removed resource: %s " "(%s)\n\n", delType.toStdString().c_str(), @@ -736,20 +731,15 @@ int Cache::editResources(QSharedPointer queue, const QString &command, } } } else if (userInput == "D") { - QMutableListIterator it(resources); - bool found = false; - while (it.hasNext()) { - Resource res = it.next(); - if (res.cacheId == cacheId) { - ncprintf("[\033[1;31m-\033[0m] Removed " - "\033[1;33m%s\033[0m (%s) with " - "value '\033[1;32m%s\033[0m'\n", - res.type.toStdString().c_str(), - res.source.toStdString().c_str(), - res.value.toStdString().c_str()); - it.remove(); - found = true; - } + const QList romRes = resources.take(cacheId); + bool found = !romRes.isEmpty(); + for (const auto &res : romRes) { + ncprintf("[\033[1;31m-\033[0m] Removed " + "\033[1;33m%s\033[0m (%s) with " + "value '\033[1;32m%s\033[0m'\n", + res.type.toStdString().c_str(), + res.source.toStdString().c_str(), + res.value.toStdString().c_str()); } if (!found) ncprintf("No resources found for this rom...\n"); @@ -760,12 +750,10 @@ int Cache::editResources(QSharedPointer queue, const QString &command, "cancel)\n"); QMap modules; int lenSrc = 0; - for (const auto &res : resources) { - if (res.cacheId == cacheId) { - modules[res.source] += 1; - if (res.source.length() > lenSrc) { - lenSrc = res.source.length(); - } + for (const auto &res : resources.value(cacheId)) { + modules[res.source] += 1; + if (res.source.length() > lenSrc) { + lenSrc = res.source.length(); } } QMap::iterator it; @@ -789,16 +777,11 @@ int Cache::editResources(QSharedPointer queue, const QString &command, ncprintf("Resource removal cancelled...\n\n"); continue; } else if (modules.contains(QString(typeInput.c_str()))) { - QMutableListIterator it(resources); - int removed = 0; - while (it.hasNext()) { - Resource res = it.next(); - if (res.cacheId == cacheId && - res.source == QString(typeInput.c_str())) { - it.remove(); - removed++; - } - } + const QString module = QString(typeInput.c_str()); + int removed = removeMatching( + resources[cacheId], [&module](const Resource &res) { + return res.source == module; + }); ncprintf("[\033[1;31m-\033[0m] Removed %d %s connected to " "rom from " "module '\033[1;32m%s\033[0m'\n\n", @@ -816,12 +799,10 @@ int Cache::editResources(QSharedPointer queue, const QString &command, "remove?\033[0m (enter type or press Enter to cancel)\n"); QMap types; int lenType = 0; - for (const auto &res : resources) { - if (res.cacheId == cacheId) { - types[res.type] += 1; - if (res.type.length() > lenType) { - lenType = res.type.length(); - } + for (const auto &res : resources.value(cacheId)) { + types[res.type] += 1; + if (res.type.length() > lenType) { + lenType = res.type.length(); } } for (auto const &key : getKeywordOrder()) { @@ -848,16 +829,11 @@ int Cache::editResources(QSharedPointer queue, const QString &command, ncprintf("Resource removal cancelled...\n\n"); continue; } else if (types.contains(QString(typeInput.c_str()))) { - QMutableListIterator it(resources); - int removed = 0; - while (it.hasNext()) { - Resource res = it.next(); - if (res.cacheId == cacheId && - res.type == QString(typeInput.c_str())) { - it.remove(); - removed++; - } - } + const QString resType = QString(typeInput.c_str()); + int removed = removeMatching( + resources[cacheId], [&resType](const Resource &res) { + return res.type == resType; + }); ncprintf("[\033[1;31m-\033[0m] Removed %d %s connected to " "rom of " "type '\033[1;32m%s\033[0m'\n\n", @@ -890,7 +866,6 @@ int Cache::editResources(QSharedPointer queue, const QString &command, } bool Cache::purgeResources(QString purgeStr) { - idIndexValid = false; purgeStr.replace("purge:", ""); QString module = ""; @@ -913,22 +888,15 @@ bool Cache::purgeResources(QString purgeStr) { int purged = 0; - QMutableListIterator it(resources); - while (it.hasNext()) { - Resource res = it.next(); - bool remove = false; - if ((res.source == module && res.type == type) || - (module.isEmpty() && res.type == type) || - (res.source == module && type.isEmpty())) { - remove = true; - } - if (remove) { - if (!removeMediaFile(res, "Cannot purge media file '%s'")) { - continue; - } - it.remove(); - purged++; - } + for (auto &romRes : resources) { + purged += removeMatching( + romRes, + [&module, &type](const Resource &res) { + return (res.source == module && res.type == type) || + (module.isEmpty() && res.type == type) || + (res.source == module && type.isEmpty()); + }, + "Cannot purge media file '%s'"); } if (purged == 0) { ncprintf("No resources for the current platform found or no match for " @@ -942,7 +910,6 @@ bool Cache::purgeResources(QString purgeStr) { } bool Cache::purgeAllOnSinglePlatform(const bool unattend) { - idIndexValid = false; if (!unattend) { ncprintf( "\033[1;31mWARNING! You are about to remove ALL " @@ -965,19 +932,15 @@ bool Cache::purgeAllOnSinglePlatform(const bool unattend) { int dots = 0; int dotMod = resources.size() * 0.1 + 1; - QMutableListIterator it(resources); - while (it.hasNext()) { + for (auto &romRes : resources) { if (dots % dotMod == 0) { ncprintf("."); fflush(stdout); } dots++; - Resource res = it.next(); - if (!removeMediaFile(res, "Cannot purge media file '%s'")) { - continue; - } - it.remove(); - purged++; + purged += removeMatching( + romRes, [](const Resource &) { return true; }, + "Cannot purge media file '%s'"); } if (purged == 0) { ncprintf("\033[1;32m Foiled!\033[0m\n"); @@ -1249,9 +1212,8 @@ bool Cache::assembleReport(const Settings &config, const QString filter) { } dots++; bool found = false; - for (const auto &res : resources) { - if (res.cacheId == cacheIdList.at(a) && - res.type == resType) { + for (const auto &res : resources.value(cacheIdList.at(a))) { + if (res.type == resType) { found = true; break; } @@ -1298,7 +1260,6 @@ bool Cache::assembleReport(const Settings &config, const QString filter) { bool Cache::vacuumResources(const QString inputFolder, const QString filter, const int verbosity, const bool unattend) { - idIndexValid = false; if (!unattend) { std::string userInput = ""; ncprintf( @@ -1344,28 +1305,23 @@ bool Cache::vacuumResources(const QString inputFolder, const QString filter, cacheDir.dirName().toStdString().c_str()); int vacuumed = 0; - { - QMutableListIterator it(resources); + const QSet romCacheIds(cacheIdList.cbegin(), cacheIdList.cend()); + for (auto romIt = resources.begin(); romIt != resources.end(); ++romIt) { + if (romCacheIds.contains(romIt.key())) { + continue; + } + QMutableListIterator it(romIt.value()); while (it.hasNext()) { Resource res = it.next(); - bool remove = true; - for (const auto &cacheId : cacheIdList) { - if (res.cacheId == cacheId) { - remove = false; - break; - } - } - if (remove) { - if (!removeMediaFile(res, "Cannot remove media file '%s'")) { - continue; - } - if (verbosity > 1) - ncprintf("Purged resource for '%s' with value '%s'...\n", - res.cacheId.toStdString().c_str(), - res.value.toStdString().c_str()); - it.remove(); - vacuumed++; + if (!removeMediaFile(res, "Cannot remove media file '%s'")) { + continue; } + if (verbosity > 1) + ncprintf("Purged resource for '%s' with value '%s'...\n", + res.cacheId.toStdString().c_str(), + res.value.toStdString().c_str()); + it.remove(); + vacuumed++; } } ncprintf("\033[1;32m Done!\033[0m\n"); @@ -1577,7 +1533,7 @@ bool Cache::write(const bool onlyQuickId) { if (!onlyQuickId) { QFile cacheFile(dbFilePath()); if (cacheFile.open(QIODevice::WriteOnly)) { - int resCountNew = static_cast(resources.length()); + int resCountNew = resourceCount(); int delta = resCountNew - resAtLoad; ncprintf("Writing %d (%d%s) resource%s to cache, please wait... ", resCountNew, delta, delta < 0 ? "" : " new", @@ -1587,15 +1543,17 @@ bool Cache::write(const bool onlyQuickId) { xml.setAutoFormatting(true); xml.writeStartDocument(); xml.writeStartElement("resources"); - for (const auto &resource : resources) { - xml.writeStartElement(R_ELEM); - xml.writeAttribute(ATTR_ID, resource.cacheId); - xml.writeAttribute(ATTR_TYPE, resource.type); - xml.writeAttribute(ATTR_SRC, resource.source); - xml.writeAttribute(ATTR_TS, - QString::number(resource.timestamp)); - xml.writeCharacters(resource.value); - xml.writeEndElement(); + for (const auto &romRes : resources) { + for (const auto &resource : romRes) { + xml.writeStartElement(R_ELEM); + xml.writeAttribute(ATTR_ID, resource.cacheId); + xml.writeAttribute(ATTR_TYPE, resource.type); + xml.writeAttribute(ATTR_SRC, resource.source); + xml.writeAttribute(ATTR_TS, + QString::number(resource.timestamp)); + xml.writeCharacters(resource.value); + xml.writeEndElement(); + } } xml.writeEndElement(); xml.writeEndDocument(); @@ -1610,7 +1568,6 @@ bool Cache::write(const bool onlyQuickId) { // This verifies all attached media files and deletes those that have no entry // in the cache void Cache::validate() { - idIndexValid = false; // TODO: Add format checks for each resource type, and remove if deemed // corrupt ncprintf("Starting resource cache validation run for %s platform, please " @@ -1652,12 +1609,13 @@ void Cache::validate() { void Cache::verifyFiles(QDirIterator &dirIt, int &filesDeleted, int ¬DeletedCount, QString resType) { - idIndexValid = false; - QList resFileNames; - for (const auto &resource : resources) { - if (resource.type == resType) { - QFileInfo resInfo(cacheDir.path() + "/" + resource.value); - resFileNames.append(resInfo.absoluteFilePath()); + QSet resFileNames; + for (const auto &romRes : resources) { + for (const auto &resource : romRes) { + if (resource.type == resType) { + QFileInfo resInfo(cacheDir.path() + "/" + resource.value); + resFileNames.insert(resInfo.absoluteFilePath()); + } } } @@ -1678,11 +1636,11 @@ void Cache::verifyFiles(QDirIterator &dirIt, int &filesDeleted, } void Cache::merge(bool overwrite, const QString &otherCacheFolder) { - idIndexValid = false; Cache mergeCache(otherCacheFolder); mergeCache.read(); ncprintf("Merging databases, please wait...\n"); - QList mergeResources = mergeCache.getResources(); + const QMap> &mergeResources = + mergeCache.getResources(); QDir mergeCacheDir(otherCacheFolder); mergeCacheDir.makeAbsolute(); @@ -1690,47 +1648,49 @@ void Cache::merge(bool overwrite, const QString &otherCacheFolder) { int resUpdated = 0; int resMerged = 0; - for (const auto &mergeResource : mergeResources) { - bool resExists = false; - // This type of iterator ensures we can delete items while iterating - QMutableListIterator it(resources); - while (it.hasNext()) { - Resource res = it.next(); - if (res.cacheId == mergeResource.cacheId && - res.type == mergeResource.type && - res.source == mergeResource.source) { - if (overwrite) { - if (!removeMediaFile(res, - "Cannot remove media file '%s' for " - "updating")) { - continue; + for (const auto &mergeRomRes : mergeResources) { + for (const auto &mergeResource : mergeRomRes) { + bool resExists = false; + QList &romRes = resources[mergeResource.cacheId]; + // This type of iterator ensures we can delete items while iterating + QMutableListIterator it(romRes); + while (it.hasNext()) { + Resource res = it.next(); + if (res.type == mergeResource.type && + res.source == mergeResource.source) { + if (overwrite) { + if (!removeMediaFile( + res, "Cannot remove media file '%s' for " + "updating")) { + continue; + } + it.remove(); + } else { + resExists = true; + break; } - it.remove(); - } else { - resExists = true; - break; } } - } - if (!resExists) { - if (binTypes().contains(mergeResource.type)) { - const QString absTgtFile = - cacheDir.path() + "/" + mergeResource.value; - cacheDir.mkpath(absTgtFile); - if (!QFile::copy(mergeCacheDir.path() + "/" + - mergeResource.value, - absTgtFile)) { - ncprintf("Cannot copy media file '%s', skipping...\n", - mergeResource.value.toStdString().c_str()); - continue; + if (!resExists) { + if (binTypes().contains(mergeResource.type)) { + const QString absTgtFile = + cacheDir.path() + "/" + mergeResource.value; + cacheDir.mkpath(absTgtFile); + if (!QFile::copy(mergeCacheDir.path() + "/" + + mergeResource.value, + absTgtFile)) { + ncprintf("Cannot copy media file '%s', skipping...\n", + mergeResource.value.toStdString().c_str()); + continue; + } } + if (overwrite) { + resUpdated++; + } else { + resMerged++; + } + romRes.append(mergeResource); } - if (overwrite) { - resUpdated++; - } else { - resMerged++; - } - resources.append(mergeResource); } } ncprintf("Successfully updated %d %s in cache!\n", resUpdated, @@ -1739,7 +1699,36 @@ void Cache::merge(bool overwrite, const QString &otherCacheFolder) { pluralizeWordStd("resource", resMerged != 1).c_str()); } -QList Cache::getResources() { return resources; } +const QMap> &Cache::getResources() const { + return resources; +} + +int Cache::resourceCount() const { + int count = 0; + for (const auto &romRes : resources) { + count += romRes.size(); + } + return count; +} + +int Cache::removeMatching(QList &romRes, + const std::function &match, + const char *mediaMsg) { + int removed = 0; + QMutableListIterator it(romRes); + while (it.hasNext()) { + Resource res = it.next(); + if (!match(res)) { + continue; + } + if (mediaMsg != nullptr && !removeMediaFile(res, mediaMsg)) { + continue; + } + it.remove(); + removed++; + } + return removed; +} void Cache::addResources(GameEntry &entry, const Settings &config, QString &output) { @@ -1799,13 +1788,13 @@ void Cache::addResource(Resource &resource, GameEntry &entry, const QString &cacheAbsolutePath, const Settings &config, QString &output) { QMutexLocker locker(&cacheMutex); - ensureIdIndex(); + QList &romRes = resources[resource.cacheId]; bool cacheMiss = true; - // Under --flags refresh the existing resource is replaced in place, which - // keeps every index position valid; a failed replacement removes it below. + // Under --flags refresh the existing resource is replaced in place; a + // failed replacement removes it below. int replaceAt = -1; - for (int i : idIndex.value(resource.cacheId)) { - const Resource &res = resources.at(i); + for (int i = 0; i < romRes.size(); ++i) { + const Resource &res = romRes.at(i); if (res.type == resource.type && res.source == resource.source) { if (config.refresh) { replaceAt = i; @@ -1949,17 +1938,15 @@ void Cache::addResource(Resource &resource, GameEntry &entry, } // add record to cache index if (replaceAt >= 0) { - resources[replaceAt] = resource; + romRes[replaceAt] = resource; } else { - resources.append(resource); - idIndex[resource.cacheId].append(resources.size() - 1); + romRes.append(resource); } } else { if (replaceAt >= 0) { // same outcome as before: a refreshed resource that could not // be written is dropped rather than kept stale - resources.removeAt(replaceAt); - idIndexValid = false; + romRes.removeAt(replaceAt); } ncprintf("\033[1;33mWarning! Cannot add resource to cache. Have " "you run out of disk space?\n\033[0m"); @@ -2081,23 +2068,10 @@ QString Cache::getQuickId(const QFileInfo &info) { return QString(); } -void Cache::ensureIdIndex() { - if (idIndexValid) { - return; - } - idIndex.clear(); - idIndex.reserve(resources.size()); - for (int i = 0; i < resources.size(); ++i) { - idIndex[resources.at(i).cacheId].append(i); - } - idIndexValid = true; -} - bool Cache::hasEntries(const QString &cacheId, const QString scraper) { QMutexLocker locker(&cacheMutex); - ensureIdIndex(); - for (int i : idIndex.value(cacheId)) { - if (scraper.isEmpty() || resources.at(i).source == scraper) { + for (const auto &res : resources.value(cacheId)) { + if (scraper.isEmpty() || res.source == scraper) { return true; } } @@ -2106,11 +2080,9 @@ bool Cache::hasEntries(const QString &cacheId, const QString scraper) { void Cache::fillBlanks(GameEntry &entry, const QString scraper) { QMutexLocker locker(&cacheMutex); - ensureIdIndex(); QList matchingResources; // Find all resources related to this particular rom - for (int i : idIndex.value(entry.cacheId)) { - const Resource &resource = resources.at(i); + for (const auto &resource : resources.value(entry.cacheId)) { if (scraper.isEmpty() || resource.source == scraper) { matchingResources.append(resource); } diff --git a/src/cache.h b/src/cache.h index 8485e9ab..550d366f 100644 --- a/src/cache.h +++ b/src/cache.h @@ -36,6 +36,7 @@ #include #include #include +#include class Skyscraper; @@ -107,7 +108,8 @@ class Cache { void merge(bool overwrite, const QString &otherCacheFolder); private: - QList getResources(); + const QMap> &getResources() const; + int resourceCount() const; private: QDir cacheDir; @@ -118,14 +120,10 @@ class Cache { QMap resCountsMap; - QList resources; - // cacheId -> positions in 'resources'. Built lazily under cacheMutex so - // hasEntries()/fillBlanks()/addResource() are a hash lookup instead of a - // scan of every cached resource per ROM; any bulk mutation of 'resources' - // (read, purge, vacuum, edit, merge) invalidates it. - QHash> idIndex; - bool idIndexValid = false; - void ensureIdIndex(); + // cacheId -> all resources of that rom. Keyed so per-rom lookups during + // scraping and gamelist generation do not scan the whole cache; a QMap so + // db.xml is written in a stable order. + QMap> resources; QMap> quickIds; // filePath, timestamp + cacheId for quick lookup @@ -144,6 +142,9 @@ class Cache { QString resType); void verifyResources(int &resourcesDeleted); bool removeMediaFile(Resource &res, const char *msg); + int removeMatching(QList &romRes, + const std::function &match, + const char *mediaMsg = nullptr); bool fillType(const QString &type, QList &matchingResources, QString &result, QString &source); bool doVideoConvert(Resource &resource, QString &cacheFile, From 9a26d4353173c62a07d91087c9ce42b218fb1458 Mon Sep 17 00:00:00 2001 From: Henrik Lindgren Date: Mon, 12 Oct 2026 16:54:25 +0200 Subject: [PATCH 3/3] Cache: add db.xml format v2 grouped by game, keep legacy-v1 writable db.xml v2 stores the resources of a rom inside , so the id is written once per game instead of on every resource, and the file maps directly onto the in-memory cache. The root element carries version="2". read() accepts both layouts (a resource without its own id takes the id of the enclosing game), so existing caches load as before and are written as v2 on the next save. On 151,500 resources db.xml shrinks from 24.8 MB to 19.6 MB. Skyscraper 3.21.1 and older cannot read v2, so the old layout stays available as format 'legacy-v1': - config.ini cacheFormat="legacy-v1" ([main] or []) writes it on every save - --cache convert: rewrites db.xml once, for one platform or, without -p, for all platforms Docs: CACHE.md format section with downgrade warning, CLIHELP.md, CONFIGINI.md, config.ini.example and CHANGELOG.md. Co-Authored-By: Claude Opus 5.5 --- config.ini.example | 1 + docs/CACHE.md | 37 ++++++++++-- docs/CHANGELOG.md | 16 +++++ docs/CLIHELP.md | 15 +++++ docs/CONFIGINI.md | 11 ++++ src/cache.cpp | 100 ++++++++++++++++++++++++++------ src/cache.h | 8 ++- src/cli.cpp | 5 ++ src/settings.cpp | 27 ++++++++- src/settings.h | 3 + src/skyscraper.cpp | 16 ++++- test/settings/config_test.ini | 2 + test/settings/test_settings.cpp | 4 ++ 13 files changed, 216 insertions(+), 29 deletions(-) diff --git a/config.ini.example b/config.ini.example index 4b41d7b0..eb844ab6 100644 --- a/config.ini.example +++ b/config.ini.example @@ -33,6 +33,7 @@ ;includeFrom="./includes.txt" ;gameListBackup="false" ;cacheFolder="./cache" +;cacheFormat="v2" ;cacheResize="false" ;nameTemplate="%t [%f], %P player(s)" ;jpgQuality="95" diff --git a/docs/CACHE.md b/docs/CACHE.md index eb8f06d8..a6681343 100644 --- a/docs/CACHE.md +++ b/docs/CACHE.md @@ -52,7 +52,7 @@ Preferred way of editing the cache is via the various [`--cache`](CLIHELP.md#-ca If you decide to add your own files to the subfolders, you risk them being deleted by Skyscraper later on if it is run with one of the cache cleanup command line options. You've been warned! -**Other cool stuff you CAN DO**: Each subfolder in the `/home//.skyscraper/cache/` folder is self-contained and can be copied to other Skyscraper installations at your convenience. Just copy the folder itself over to some other computer that has Skyscraper v1.6 or later installed, and you can make use of the data when generating game lists. If you add it at a non-default location, set the custom folder with `-d `. +**Other cool stuff you CAN DO**: Each subfolder in the `/home//.skyscraper/cache/` folder is self-contained and can be copied to other Skyscraper installations at your convenience. Just copy the folder itself over to some other computer that has Skyscraper v1.6 or later installed, and you can make use of the data when generating game lists. If you add it at a non-default location, set the custom folder with `-d `. If the other installation is Skyscraper 3.21.1 or older, convert the cache to the `legacy-v1` format first, see below. ### Resource Cache Format @@ -60,15 +60,40 @@ I do not recommend editing the `db.xml` resource cache files manually. But the f **Resource id** -The database consists of resource entries connected to a unique id. The id is calculated from the rom data or, in special cases, the filename (in cases where the file data is a script or a ROM gets changed by the gameplay). An entry can look like this: +The database consists of resource entries connected to a unique id. The id is calculated from the rom data or, in special cases, the filename (in cases where the file data is a script or a ROM gets changed by the gameplay). The resources of one rom are grouped in a `game` element carrying the id: ```xml -Resource data + + + Resource data + ... + + ... + ``` +**Format versions** + +The layout above is format `v2`, written by default. Skyscraper 3.21.1 and older use format `legacy-v1`, a flat list where each resource carries the id itself: + +```xml + + Resource data + ... + +``` + +Skyscraper reads both formats. A `legacy-v1` cache is rewritten as `v2` the next time Skyscraper saves it. + +!!! warning "Going back to an older Skyscraper version" + + Skyscraper 3.21.1 and older cannot read the `v2` format and will treat the cache as empty. Before you use the cache with an older version, run [`--cache convert:legacy-v1`](CLIHELP.md#-cache-convertformat). To keep writing `legacy-v1`, for instance when you share a cache with an older installation, set [`cacheFormat="legacy-v1"`](CONFIGINI.md#cacheformat). + #### Resource Types These resource types contain the provided game data from a scraping diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 6d1e51b7..f77d8ee3 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,22 @@ This page summarizes the changes of each Skyscraper release, a [changlog for humans](https://keepachangelog.com). +### Version 3.22.0 (2026-TBA) + +- Changed: The resource cache is held in memory grouped by game, which makes + game list generation from a large cache several times faster, especially + with multiple threads (`-t`) +- Changed: New resource cache format `v2` for `db.xml`, which groups the + resources by game. Existing caches are read as before and are written as + `v2` on the next save. Skyscraper 3.21.1 and older cannot read `v2`: run + [`--cache convert:legacy-v1`](CLIHELP.md#-cache-convertformat) before going + back to an older version, or set + [`cacheFormat="legacy-v1"`](CONFIGINI.md#cacheformat) to keep writing the + old format. See [Resource Cache Format](CACHE.md#resource-cache-format) +- Added: Cache subcommand + [`--cache convert:`](CLIHELP.md#-cache-convertformat) and + `config.ini` option [`cacheFormat`](CONFIGINI.md#cacheformat) + ### Version 3.21.0 (2026-09-20) - Added: AppImage support for PC (x64) and ARM (aarch64) architectures (with or diff --git a/docs/CLIHELP.md b/docs/CLIHELP.md index f616bb81..9a7cfd97 100644 --- a/docs/CLIHELP.md +++ b/docs/CLIHELP.md @@ -279,6 +279,21 @@ Read more about the resource cache at the [cache documentation](CACHE.md). Outputs a description of all available `--cache` functions. +#### --cache convert:<FORMAT> + +Rewrites the resource cache file `db.xml` in the given format, either `v2` (the default) or `legacy-v1`. Use `legacy-v1` before you use the cache with Skyscraper 3.21.1 or older, which cannot read the `v2` format. See [Resource Cache Format](CACHE.md#resource-cache-format). + +If _no platform is specified_, the caches of all platforms are converted. + +To keep writing the `legacy-v1` format on every run, set [`cacheFormat`](CONFIGINI.md#cacheformat) in your `config.ini`. + +**Example(s)** + +``` +Skyscraper -p snes --cache convert:legacy-v1 +Skyscraper --cache convert:legacy-v1 +``` + #### --cache edit[:new=<TYPE>] Allows editing of any cached resources connected to your roms. The editing mode will go through each of the files in the queue one by one, allowing you to add and remove resources as needed. Any resource you add manually will be prioritized above all others. diff --git a/docs/CONFIGINI.md b/docs/CONFIGINI.md index 61dd5596..ec152ca2 100644 --- a/docs/CONFIGINI.md +++ b/docs/CONFIGINI.md @@ -88,6 +88,7 @@ This is an alphabetical index of all configuration options their usage level and | [brackets](CONFIGINI.md#brackets) | Basic | Y | Y | Y | | | [cacheCovers](CONFIGINI.md#cachecovers) | Basic | Y | Y | | Y | | [cacheFolder](CONFIGINI.md#cachefolder) | Basic | Y | Y | | | +| [cacheFormat](CONFIGINI.md#cacheformat) | Advanced | Y | Y | | | | [cacheMarquees](CONFIGINI.md#cachemarquees) | Basic | Y | Y | | Y | | [cacheRefresh](CONFIGINI.md#cacherefresh) | Basic | Y | | | Y | | [cacheResize](CONFIGINI.md#cacheresize) | Basic | Y | Y | | Y | @@ -272,6 +273,16 @@ Allowed in sections: `[main]`, `[]` --- +#### cacheFormat + +Sets the format in which the resource cache file `db.xml` is written. The default format `v2` groups the resources by game. Set this to `"legacy-v1"` to keep writing the format of Skyscraper 3.21.1 and older, for instance if you share the cache with an older installation. Skyscraper reads both formats regardless of this option. To convert a cache once, use [`--cache convert:`](CLIHELP.md#-cache-convertformat). See also [Resource Cache Format](CACHE.md#resource-cache-format). + +Default value: `v2` +Allowed values: `v2`, `legacy-v1` +Allowed in sections: `[main]`, `[]` + +--- + #### cacheResize By default, to save space, Skyscraper resizes large pieces of artwork before adding them to the resource cache. Setting this option to `"false"` will disable this and save the artwork files with their original resolution. Beware that Skyscraper converts all artwork resources to lossless PNG's when saving them. High resolution images such as covers will take up a lot of space! So set this to `"false"` with caution. diff --git a/src/cache.cpp b/src/cache.cpp index 6b0cd85b..fd161665 100644 --- a/src/cache.cpp +++ b/src/cache.cpp @@ -55,6 +55,8 @@ const QString SRC_USER = "user"; // quickids.xml and db.xml const QString Q_ELEM = "quickid"; +const QString DB_ROOT_ELEM = "resources"; +const QString G_ELEM = "game"; const QString R_ELEM = "resource"; const QString ATTR_FILEPATH = "filepath"; const QString ATTR_ID = "id"; @@ -62,6 +64,13 @@ const QString ATTR_SHA1_LEGACY = "sha1"; const QString ATTR_SRC = "source"; const QString ATTR_TS = "timestamp"; const QString ATTR_TYPE = "type"; +const QString ATTR_VERSION = "version"; + +// db.xml formats: legacy-v1 is the flat list of elements +// written up to 3.21.1, v2 groups the resources of a rom in +const QString FORMAT_LEGACY_V1 = "legacy-v1"; +const QString FORMAT_V2 = "v2"; +const QString FORMAT_DEFAULT = FORMAT_V2; const QStringList NO_RESIZE_MEDIA = {"fanart", "manual", "backcover"}; @@ -148,10 +157,17 @@ static inline std::string pluralizeWordStd(QString word, bool plural) { return pluralizeWord(word, plural).toStdString(); } -Cache::Cache(const QString &cacheFolder) { +Cache::Cache(const QString &cacheFolder, const QString &format) { cacheDir.setPath(cacheFolder); cacheDir.makeAbsolute(); - qDebug() << "Cache folder:" << cacheDir; + setFormat(format); + qDebug() << "Cache folder:" << cacheDir << "format:" << dbFormat; +} + +const QStringList Cache::getFormats() { return {FORMAT_LEGACY_V1, FORMAT_V2}; } + +void Cache::setFormat(const QString &format) { + dbFormat = getFormats().contains(format) ? format : FORMAT_DEFAULT; } bool Cache::createFolders(const QString &scraper) { @@ -228,27 +244,38 @@ bool Cache::read() { ncprintf("Reading and parsing resource cache, please wait... "); fflush(stdout); QXmlStreamReader xml(&cacheFile); + // v2: id of the enclosing , legacy-v1: id is on each + QString gameId; while (!xml.atEnd()) { - if (xml.readNext() != QXmlStreamReader::StartElement) { + QXmlStreamReader::TokenType token = xml.readNext(); + if (token == QXmlStreamReader::EndElement && xml.name() == G_ELEM) { + gameId.clear(); continue; } - if (xml.name() != R_ELEM) { + if (token != QXmlStreamReader::StartElement) { continue; } - QXmlStreamAttributes attribs = xml.attributes(); - if (!attribs.hasAttribute(ATTR_SHA1_LEGACY) && - !attribs.hasAttribute(ATTR_ID)) { - ncprintf("Resource is missing unique id, skipping...\n"); + if (xml.name() == G_ELEM) { + gameId = xml.attributes().value(ATTR_ID).toString(); continue; } - + if (xml.name() != R_ELEM) { + continue; + } + QXmlStreamAttributes attribs = xml.attributes(); Resource resource; if (attribs.hasAttribute( ATTR_SHA1_LEGACY)) { // Obsolete, but needed for backwards // compat resource.cacheId = attribs.value(ATTR_SHA1_LEGACY).toString(); - } else { + } else if (attribs.hasAttribute(ATTR_ID)) { resource.cacheId = attribs.value(ATTR_ID).toString(); + } else { + resource.cacheId = gameId; + } + if (resource.cacheId.isEmpty()) { + ncprintf("Resource is missing unique id, skipping...\n"); + continue; } if (attribs.hasAttribute(ATTR_SRC)) { @@ -959,7 +986,8 @@ bool Cache::purgeAllOnSinglePlatform(const bool unattend) { bool Cache::isCommandValidOnAllPlatform(const QString &command) { QList validCommands({"help", "purge:all", "vacuum", "validate"}); return validCommands.contains(command) || - command.startsWith("report:missing="); + command.startsWith("report:missing=") || + command.startsWith("convert:"); } void Cache::purgeAllOnAllPlatforms(Settings &config, Skyscraper *app) { @@ -980,7 +1008,7 @@ void Cache::purgeAllOnAllPlatforms(Settings &config, Skyscraper *app) { for (const auto &platform : cacheDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { config.platform = platform; - Cache cache(cacheDir.filePath(platform)); + Cache cache(cacheDir.filePath(platform), config.cacheFormat); if (cache.read() && cache.purgeAllOnSinglePlatform(true)) { app->state = Skyscraper::OpMode::NO_INTR; cache.write(); @@ -999,7 +1027,7 @@ bool Cache::reportAllPlatform(Settings &config, Skyscraper *app) { config.cacheFolder = PathTools::concatPath(initCacheFolder, platform); config.inputFolder = PathTools::concatPath(initInputFolder, platform); qDebug() << "reportAllPlatform()" << config.inputFolder; - Cache cache(config.cacheFolder); + Cache cache(config.cacheFolder, config.cacheFormat); if (cache.read()) { if (!cache.assembleReport( config, app->getPlatformFileExtensions(platform))) { @@ -1034,7 +1062,7 @@ void Cache::vacuumAllPlatform(Settings &config, Skyscraper *app) { config.cacheFolder = PathTools::concatPath(initCacheFolder, platform); config.inputFolder = PathTools::concatPath(initInputFolder, platform); qDebug() << "vacuumAllPlatform()" << config.inputFolder; - Cache cache(config.cacheFolder); + Cache cache(config.cacheFolder, config.cacheFormat); if (cache.read() && cache.vacuumResources(QDir(config.inputFolder).filePath(platform), app->getPlatformFileExtensions(platform), @@ -1056,7 +1084,7 @@ void Cache::validateAllPlatform(Settings &config, Skyscraper *app) { config.cacheFolder = PathTools::concatPath(initCacheFolder, platform); config.inputFolder = PathTools::concatPath(initInputFolder, platform); qDebug() << "validateAllPlatform()" << config.inputFolder; - Cache cache(cacheDir.filePath(platform)); + Cache cache(cacheDir.filePath(platform), config.cacheFormat); if (cache.read()) { cache.validate(); app->state = Skyscraper::OpMode::NO_INTR; @@ -1066,6 +1094,24 @@ void Cache::validateAllPlatform(Settings &config, Skyscraper *app) { } } +void Cache::convertAllPlatform(Settings &config, Skyscraper *app, + const QString &format) { + QDir cacheDir(config.cacheFolder); + for (const auto &platform : + cacheDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { + Cache cache(cacheDir.filePath(platform), format); + if (cache.read()) { + ncprintf("Converting resource cache of %s platform to format " + "'%s'...\n", + platform.toStdString().c_str(), + format.toStdString().c_str()); + app->state = Skyscraper::OpMode::NO_INTR; + cache.write(); + app->state = Skyscraper::OpMode::SINGLE; + } + } +} + QList Cache::getFileInfos(const QString &inputFolder, const QString &filter, const bool subdirs) { @@ -1539,14 +1585,27 @@ bool Cache::write(const bool onlyQuickId) { resCountNew, delta, delta < 0 ? "" : " new", resCountNew == 1 ? "" : "s"); fflush(stdout); + const bool legacyV1 = dbFormat == FORMAT_LEGACY_V1; QXmlStreamWriter xml(&cacheFile); xml.setAutoFormatting(true); xml.writeStartDocument(); - xml.writeStartElement("resources"); - for (const auto &romRes : resources) { - for (const auto &resource : romRes) { + xml.writeStartElement(DB_ROOT_ELEM); + if (!legacyV1) { + xml.writeAttribute(ATTR_VERSION, "2"); + } + for (auto it = resources.cbegin(); it != resources.cend(); ++it) { + if (it.value().isEmpty()) { + continue; + } + if (!legacyV1) { + xml.writeStartElement(G_ELEM); + xml.writeAttribute(ATTR_ID, it.key()); + } + for (const auto &resource : it.value()) { xml.writeStartElement(R_ELEM); - xml.writeAttribute(ATTR_ID, resource.cacheId); + if (legacyV1) { + xml.writeAttribute(ATTR_ID, resource.cacheId); + } xml.writeAttribute(ATTR_TYPE, resource.type); xml.writeAttribute(ATTR_SRC, resource.source); xml.writeAttribute(ATTR_TS, @@ -1554,6 +1613,9 @@ bool Cache::write(const bool onlyQuickId) { xml.writeCharacters(resource.value); xml.writeEndElement(); } + if (!legacyV1) { + xml.writeEndElement(); + } } xml.writeEndElement(); xml.writeEndDocument(); diff --git a/src/cache.h b/src/cache.h index 550d366f..ddadaaaa 100644 --- a/src/cache.h +++ b/src/cache.h @@ -73,7 +73,7 @@ struct ResCounts { class Cache { public: - Cache(const QString &cacheFolder); + Cache(const QString &cacheFolder, const QString &format = ""); static bool isCommandValidOnAllPlatform(const QString &command); @@ -81,10 +81,15 @@ class Cache { static bool reportAllPlatform(Settings &config, Skyscraper *app); static void vacuumAllPlatform(Settings &config, Skyscraper *app); static void validateAllPlatform(Settings &config, Skyscraper *app); + static void convertAllPlatform(Settings &config, Skyscraper *app, + const QString &format); + // db.xml formats which can be written, see docs/CACHE.md + static const QStringList getFormats(); static const QStringList getAllResourceTypes(); static const QStringList getBinResourceTypes(); + void setFormat(const QString &format); bool createFolders(const QString &scraper); bool read(); void printPriorities(QString cacheId); @@ -113,6 +118,7 @@ class Cache { private: QDir cacheDir; + QString dbFormat; QMutex cacheMutex; QMutex quickIdMutex; diff --git a/src/cli.cpp b/src/cli.cpp index b6180ecd..e532d882 100644 --- a/src/cli.cpp +++ b/src/cli.cpp @@ -372,6 +372,11 @@ QMap Cli::getSubCommandOpts(const QString subCmd) { {"validate", "Checks the consistency of the cache for the selected platform. " "If platform is omitted it validates over all platforms."}, + {"convert:", + "Rewrites the resource cache 'db.xml' of the selected platform in " + ", which is 'v2' (default) or 'legacy-v1' (readable by " + "Skyscraper 3.21.1 and older). If platform is omitted it " + "converts the caches of all platforms."}, {"edit", "Let's you edit resources for the selected platform for all files " "or a range of files. Add a filename on command line to edit " diff --git a/src/settings.cpp b/src/settings.cpp index 9f084d42..cfdf0253 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -215,6 +215,18 @@ void RuntimeCfg::applyConfigIni(CfgType type, QSettings *settings, } continue; } + if (k == "cacheFormat") { + const QStringList allowed = Cache::getFormats(); + if (allowed.contains(v)) { + config->cacheFormat = v; + } else { + ncprintf("\033[1;33mValue '%s' of parameter %s is ignored. " + "Valid values are: %s.\n\033[0m", + v.toUtf8().constData(), k.toUtf8().constData(), + allowed.join(", ").toUtf8().constData()); + } + continue; + } if (k == "emulator") { if (config->frontend == "attractmode") { config->frontendExtra = v; @@ -841,6 +853,17 @@ void RuntimeCfg::applyCli(bool &inputFolderSet, bool &gameListFolderSet, } else if (config->cacheOptions == "report:missing=help") { Cli::cacheReportMissingUsage(); exit(0); + } else if (config->cacheOptions.startsWith("convert:")) { + const QString format = config->cacheOptions.mid(8); + if (!Cache::getFormats().contains(format)) { + ncprintf("\033[1;31mInvalid format '%s' for '--cache " + "convert:'\033[0m, valid formats are: %s.\n", + format.toUtf8().constData(), + Cache::getFormats().join(", ").toUtf8().constData()); + emit die(2, "invalid cache convert command", + QString("Cannot apply --cache %1") + .arg(config->cacheOptions)); + } } else if (config->cacheOptions.startsWith("purge:")) { if (!validatePurgeParameters(config->cacheOptions)) { ncprintf( @@ -1070,8 +1093,8 @@ bool RuntimeCfg::validateFileParameter(const QString ¶m, QString &val) { bool RuntimeCfg::validateCacheSubCommand(const QString &subCmd) { const QStringList cmdsRe = QStringList( - {"^(edit(:new=[a-z]{4,})?", "help", "merge:.+", "purge:all", - "purge:(m|t)=[a-z]+(,(m|t)=[a-z]+)?", "refresh", + {"^(convert:[a-z0-9-]+", "edit(:new=[a-z]{4,})?", "help", "merge:.+", + "purge:all", "purge:(m|t)=[a-z]+(,(m|t)=[a-z]+)?", "refresh", "report:missing=[a-z]{3,}", "show", "vacuum", "validate)$"}); const QRegularExpression REGEX_CACHE_SUBCMD = QRegularExpression(cmdsRe.join("|")); diff --git a/src/settings.h b/src/settings.h index ba475588..3ef99056 100644 --- a/src/settings.h +++ b/src/settings.h @@ -44,6 +44,8 @@ struct Settings { QString currentDir = ""; QString cacheFolder = ""; + // db.xml format to write, empty means default, see Cache::getFormats() + QString cacheFormat = ""; QString skippedFileString = ""; QString configFile = ""; QString frontend = ""; @@ -221,6 +223,7 @@ class RuntimeCfg : public QObject { {"brackets", QPair("bool", CfgType::MAIN | CfgType::PLATFORM | CfgType::FRONTEND )}, {"cacheCovers", QPair("bool", CfgType::MAIN | CfgType::PLATFORM | CfgType::SCRAPER )}, {"cacheFolder", QPair("str", CfgType::MAIN | CfgType::PLATFORM )}, + {"cacheFormat", QPair("str", CfgType::MAIN | CfgType::PLATFORM )}, {"cacheMarquees", QPair("bool", CfgType::MAIN | CfgType::PLATFORM | CfgType::SCRAPER )}, {"cacheRefresh", QPair("bool", CfgType::MAIN | CfgType::SCRAPER )}, {"cacheResize", QPair("bool", CfgType::MAIN | CfgType::PLATFORM | CfgType::SCRAPER )}, diff --git a/src/skyscraper.cpp b/src/skyscraper.cpp index 47319d90..57d69431 100644 --- a/src/skyscraper.cpp +++ b/src/skyscraper.cpp @@ -99,6 +99,9 @@ void Skyscraper::run() { } else if (config.cacheOptions == "validate") { Cache::validateAllPlatform(config, this); exit(0); + } else if (config.cacheOptions.startsWith("convert:")) { + Cache::convertAllPlatform(config, this, config.cacheOptions.mid(8)); + exit(0); } } @@ -201,7 +204,8 @@ void Skyscraper::run() { } } - cache = QSharedPointer(new Cache(config.cacheFolder)); + cache = QSharedPointer( + new Cache(config.cacheFolder, config.cacheFormat)); if (cacheScrapeMode || cache->createFolders(config.scraper)) { if (!cache->read() && cacheScrapeMode) { ncprintf("No resources for this platform found in the resource " @@ -257,6 +261,16 @@ void Skyscraper::run() { state = SINGLE; exit(0); } + if (config.cacheOptions.startsWith("convert:")) { + const QString format = config.cacheOptions.mid(8); + ncprintf("Converting resource cache to format '%s'...\n", + format.toStdString().c_str()); + cache->setFormat(format); + state = NO_INTR; + cache->write(); + state = SINGLE; + exit(0); + } if (config.cacheOptions.startsWith("merge:")) { QFileInfo mergeCacheInfo(config.cacheOptions.replace("merge:", "")); diff --git a/test/settings/config_test.ini b/test/settings/config_test.ini index 30d78d05..5fbcd3ce 100644 --- a/test/settings/config_test.ini +++ b/test/settings/config_test.ini @@ -4,6 +4,7 @@ artworkXml="/tmp/test_artwork.xml" brackets="false" cacheCovers="false" cacheFolder="/home/pi/.skyscraper/cache/test/" +cacheFormat="legacy-v1" cacheMarquees="false" cacheRefresh="true" cacheResize="false" @@ -69,6 +70,7 @@ artworkXml="/tmp/test_amiga_artwork.xml" brackets="false" cacheCovers="false" cacheFolder="/home/pi/.skyscraper/cache/test/" +cacheFormat="v2" cacheMarquees="false" cacheResize="false" cacheScreenshots="false" diff --git a/test/settings/test_settings.cpp b/test/settings/test_settings.cpp index f38f783c..9ad41f88 100644 --- a/test/settings/test_settings.cpp +++ b/test/settings/test_settings.cpp @@ -188,6 +188,8 @@ private slots: QCOMPARE(config.cacheCovers, exp); exp = settings.value("cacheFolder").toString() + "amiga"; QCOMPARE(config.cacheFolder, exp); + exp = settings.value("cacheFormat"); + QCOMPARE(config.cacheFormat, exp); exp = settings.value("cacheMarquees"); QCOMPARE(config.cacheMarquees, exp); exp = settings.value("cacheRefresh"); @@ -363,6 +365,8 @@ private slots: QCOMPARE(config.cacheCovers, exp); exp = settings.value("cacheFolder"); QCOMPARE(config.cacheFolder, exp); + exp = settings.value("cacheFormat"); + QCOMPARE(config.cacheFormat, exp); exp = settings.value("cacheMarquees"); QCOMPARE(config.cacheMarquees, exp); exp = settings.value("cacheResize");