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 989e9d28..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)) { @@ -281,10 +308,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; @@ -440,19 +467,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()) { @@ -614,17 +639,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 { @@ -650,9 +675,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}; @@ -712,18 +736,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(), @@ -734,20 +758,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"); @@ -758,12 +777,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; @@ -787,16 +804,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", @@ -814,12 +826,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()) { @@ -846,16 +856,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", @@ -910,22 +915,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 " @@ -961,19 +959,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"); @@ -992,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) { @@ -1013,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(); @@ -1032,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))) { @@ -1067,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), @@ -1089,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; @@ -1099,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) { @@ -1245,9 +1258,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; } @@ -1339,28 +1351,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"); @@ -1572,25 +1579,43 @@ 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", 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 &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(); + 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); + if (legacyV1) { + 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(); + } + if (!legacyV1) { + xml.writeEndElement(); + } } xml.writeEndElement(); xml.writeEndDocument(); @@ -1646,11 +1671,13 @@ void Cache::validate() { void Cache::verifyFiles(QDirIterator &dirIt, int &filesDeleted, int ¬DeletedCount, QString resType) { - 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()); + } } } @@ -1674,7 +1701,8 @@ void Cache::merge(bool overwrite, const QString &otherCacheFolder) { 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(); @@ -1682,47 +1710,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, @@ -1731,7 +1761,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) { @@ -1791,15 +1850,16 @@ void Cache::addResource(Resource &resource, GameEntry &entry, const QString &cacheAbsolutePath, const Settings &config, QString &output) { QMutexLocker locker(&cacheMutex); + QList &romRes = resources[resource.cacheId]; 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; a + // failed replacement removes it below. + int replaceAt = -1; + 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) { - it.remove(); + replaceAt = i; } else { cacheMiss = false; } @@ -1939,8 +1999,17 @@ void Cache::addResource(Resource &resource, GameEntry &entry, } } // add record to cache index - resources.append(resource); + if (replaceAt >= 0) { + romRes[replaceAt] = resource; + } else { + 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 + romRes.removeAt(replaceAt); + } ncprintf("\033[1;33mWarning! Cannot add resource to cache. Have " "you run out of disk space?\n\033[0m"); } @@ -2063,9 +2132,8 @@ QString Cache::getQuickId(const QFileInfo &info) { 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) { + for (const auto &res : resources.value(cacheId)) { + if (scraper.isEmpty() || res.source == scraper) { return true; } } @@ -2076,9 +2144,8 @@ void Cache::fillBlanks(GameEntry &entry, const QString scraper) { QMutexLocker locker(&cacheMutex); 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 (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 ab006e2e..ddadaaaa 100644 --- a/src/cache.h +++ b/src/cache.h @@ -36,6 +36,7 @@ #include #include #include +#include class Skyscraper; @@ -72,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); @@ -80,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); @@ -107,10 +113,12 @@ class Cache { void merge(bool overwrite, const QString &otherCacheFolder); private: - QList getResources(); + const QMap> &getResources() const; + int resourceCount() const; private: QDir cacheDir; + QString dbFormat; QMutex cacheMutex; QMutex quickIdMutex; @@ -118,7 +126,10 @@ class Cache { QMap resCountsMap; - QList resources; + // 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 @@ -137,6 +148,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, 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");