game_list_worker.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <memory>
  4. #include <string>
  5. #include <utility>
  6. #include <vector>
  7. #include <QDir>
  8. #include <QFile>
  9. #include <QFileInfo>
  10. #include <QSettings>
  11. #include "common/fs/fs.h"
  12. #include "common/fs/path_util.h"
  13. #include "core/core.h"
  14. #include "core/file_sys/card_image.h"
  15. #include "core/file_sys/content_archive.h"
  16. #include "core/file_sys/control_metadata.h"
  17. #include "core/file_sys/mode.h"
  18. #include "core/file_sys/nca_metadata.h"
  19. #include "core/file_sys/patch_manager.h"
  20. #include "core/file_sys/registered_cache.h"
  21. #include "core/file_sys/submission_package.h"
  22. #include "core/loader/loader.h"
  23. #include "yuzu/compatibility_list.h"
  24. #include "yuzu/game_list.h"
  25. #include "yuzu/game_list_p.h"
  26. #include "yuzu/game_list_worker.h"
  27. #include "yuzu/uisettings.h"
  28. namespace {
  29. QString GetGameListCachedObject(const std::string& filename, const std::string& ext,
  30. const std::function<QString()>& generator) {
  31. if (!UISettings::values.cache_game_list || filename == "0000000000000000") {
  32. return generator();
  33. }
  34. const auto path =
  35. Common::FS::PathToUTF8String(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  36. "game_list" / fmt::format("{}.{}", filename, ext));
  37. void(Common::FS::CreateParentDirs(path));
  38. if (!Common::FS::Exists(path)) {
  39. const auto str = generator();
  40. QFile file{QString::fromStdString(path)};
  41. if (file.open(QFile::WriteOnly)) {
  42. file.write(str.toUtf8());
  43. }
  44. return str;
  45. }
  46. QFile file{QString::fromStdString(path)};
  47. if (file.open(QFile::ReadOnly)) {
  48. return QString::fromUtf8(file.readAll());
  49. }
  50. return generator();
  51. }
  52. std::pair<std::vector<u8>, std::string> GetGameListCachedObject(
  53. const std::string& filename, const std::string& ext,
  54. const std::function<std::pair<std::vector<u8>, std::string>()>& generator) {
  55. if (!UISettings::values.cache_game_list || filename == "0000000000000000") {
  56. return generator();
  57. }
  58. const auto game_list_dir =
  59. Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) / "game_list";
  60. const auto jpeg_name = fmt::format("{}.jpeg", filename);
  61. const auto app_name = fmt::format("{}.appname.txt", filename);
  62. const auto path1 = Common::FS::PathToUTF8String(game_list_dir / jpeg_name);
  63. const auto path2 = Common::FS::PathToUTF8String(game_list_dir / app_name);
  64. void(Common::FS::CreateParentDirs(path1));
  65. if (!Common::FS::Exists(path1) || !Common::FS::Exists(path2)) {
  66. const auto [icon, nacp] = generator();
  67. QFile file1{QString::fromStdString(path1)};
  68. if (!file1.open(QFile::WriteOnly)) {
  69. LOG_ERROR(Frontend, "Failed to open cache file.");
  70. return generator();
  71. }
  72. if (!file1.resize(icon.size())) {
  73. LOG_ERROR(Frontend, "Failed to resize cache file to necessary size.");
  74. return generator();
  75. }
  76. if (file1.write(reinterpret_cast<const char*>(icon.data()), icon.size()) !=
  77. s64(icon.size())) {
  78. LOG_ERROR(Frontend, "Failed to write data to cache file.");
  79. return generator();
  80. }
  81. QFile file2{QString::fromStdString(path2)};
  82. if (file2.open(QFile::WriteOnly)) {
  83. file2.write(nacp.data(), nacp.size());
  84. }
  85. return std::make_pair(icon, nacp);
  86. }
  87. QFile file1(QString::fromStdString(path1));
  88. QFile file2(QString::fromStdString(path2));
  89. if (!file1.open(QFile::ReadOnly)) {
  90. LOG_ERROR(Frontend, "Failed to open cache file for reading.");
  91. return generator();
  92. }
  93. if (!file2.open(QFile::ReadOnly)) {
  94. LOG_ERROR(Frontend, "Failed to open cache file for reading.");
  95. return generator();
  96. }
  97. std::vector<u8> vec(file1.size());
  98. if (file1.read(reinterpret_cast<char*>(vec.data()), vec.size()) !=
  99. static_cast<s64>(vec.size())) {
  100. return generator();
  101. }
  102. const auto data = file2.readAll();
  103. return std::make_pair(vec, data.toStdString());
  104. }
  105. void GetMetadataFromControlNCA(const FileSys::PatchManager& patch_manager, const FileSys::NCA& nca,
  106. std::vector<u8>& icon, std::string& name) {
  107. std::tie(icon, name) = GetGameListCachedObject(
  108. fmt::format("{:016X}", patch_manager.GetTitleID()), {}, [&patch_manager, &nca] {
  109. const auto [nacp, icon_f] = patch_manager.ParseControlNCA(nca);
  110. return std::make_pair(icon_f->ReadAllBytes(), nacp->GetApplicationName());
  111. });
  112. }
  113. bool HasSupportedFileExtension(const std::string& file_name) {
  114. const QFileInfo file = QFileInfo(QString::fromStdString(file_name));
  115. return GameList::supported_file_extensions.contains(file.suffix(), Qt::CaseInsensitive);
  116. }
  117. bool IsExtractedNCAMain(const std::string& file_name) {
  118. return QFileInfo(QString::fromStdString(file_name)).fileName() == QStringLiteral("main");
  119. }
  120. QString FormatGameName(const std::string& physical_name) {
  121. const QString physical_name_as_qstring = QString::fromStdString(physical_name);
  122. const QFileInfo file_info(physical_name_as_qstring);
  123. if (IsExtractedNCAMain(physical_name)) {
  124. return file_info.dir().path();
  125. }
  126. return physical_name_as_qstring;
  127. }
  128. QString FormatPatchNameVersions(const FileSys::PatchManager& patch_manager,
  129. Loader::AppLoader& loader, bool updatable = true) {
  130. QString out;
  131. FileSys::VirtualFile update_raw;
  132. loader.ReadUpdateRaw(update_raw);
  133. for (const auto& kv : patch_manager.GetPatchVersionNames(update_raw)) {
  134. const bool is_update = kv.first == "Update" || kv.first == "[D] Update";
  135. if (!updatable && is_update) {
  136. continue;
  137. }
  138. const QString type = QString::fromStdString(kv.first);
  139. if (kv.second.empty()) {
  140. out.append(QStringLiteral("%1\n").arg(type));
  141. } else {
  142. auto ver = kv.second;
  143. // Display container name for packed updates
  144. if (is_update && ver == "PACKED") {
  145. ver = Loader::GetFileTypeString(loader.GetFileType());
  146. }
  147. out.append(QStringLiteral("%1 (%2)\n").arg(type, QString::fromStdString(ver)));
  148. }
  149. }
  150. out.chop(1);
  151. return out;
  152. }
  153. QList<QStandardItem*> MakeGameListEntry(const std::string& path, const std::string& name,
  154. const std::vector<u8>& icon, Loader::AppLoader& loader,
  155. u64 program_id, const CompatibilityList& compatibility_list,
  156. const FileSys::PatchManager& patch) {
  157. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  158. // The game list uses this as compatibility number for untested games
  159. QString compatibility{QStringLiteral("99")};
  160. if (it != compatibility_list.end()) {
  161. compatibility = it->second.first;
  162. }
  163. const auto file_type = loader.GetFileType();
  164. const auto file_type_string = QString::fromStdString(Loader::GetFileTypeString(file_type));
  165. QList<QStandardItem*> list{
  166. new GameListItemPath(FormatGameName(path), icon, QString::fromStdString(name),
  167. file_type_string, program_id),
  168. new GameListItemCompat(compatibility),
  169. new GameListItem(file_type_string),
  170. new GameListItemSize(Common::FS::GetSize(path)),
  171. };
  172. const auto patch_versions = GetGameListCachedObject(
  173. fmt::format("{:016X}", patch.GetTitleID()), "pv.txt", [&patch, &loader] {
  174. return FormatPatchNameVersions(patch, loader, loader.IsRomFSUpdatable());
  175. });
  176. list.insert(2, new GameListItem(patch_versions));
  177. return list;
  178. }
  179. } // Anonymous namespace
  180. GameListWorker::GameListWorker(FileSys::VirtualFilesystem vfs,
  181. FileSys::ManualContentProvider* provider,
  182. QVector<UISettings::GameDir>& game_dirs,
  183. const CompatibilityList& compatibility_list, Core::System& system_)
  184. : vfs(std::move(vfs)), provider(provider), game_dirs(game_dirs),
  185. compatibility_list(compatibility_list), system{system_} {}
  186. GameListWorker::~GameListWorker() = default;
  187. void GameListWorker::AddTitlesToGameList(GameListDir* parent_dir) {
  188. using namespace FileSys;
  189. const auto& cache = dynamic_cast<ContentProviderUnion&>(system.GetContentProvider());
  190. auto installed_games = cache.ListEntriesFilterOrigin(std::nullopt, TitleType::Application,
  191. ContentRecordType::Program);
  192. if (parent_dir->type() == static_cast<int>(GameListItemType::SdmcDir)) {
  193. installed_games = cache.ListEntriesFilterOrigin(
  194. ContentProviderUnionSlot::SDMC, TitleType::Application, ContentRecordType::Program);
  195. } else if (parent_dir->type() == static_cast<int>(GameListItemType::UserNandDir)) {
  196. installed_games = cache.ListEntriesFilterOrigin(
  197. ContentProviderUnionSlot::UserNAND, TitleType::Application, ContentRecordType::Program);
  198. } else if (parent_dir->type() == static_cast<int>(GameListItemType::SysNandDir)) {
  199. installed_games = cache.ListEntriesFilterOrigin(
  200. ContentProviderUnionSlot::SysNAND, TitleType::Application, ContentRecordType::Program);
  201. }
  202. for (const auto& [slot, game] : installed_games) {
  203. if (slot == ContentProviderUnionSlot::FrontendManual) {
  204. continue;
  205. }
  206. const auto file = cache.GetEntryUnparsed(game.title_id, game.type);
  207. std::unique_ptr<Loader::AppLoader> loader = Loader::GetLoader(system, file);
  208. if (!loader) {
  209. continue;
  210. }
  211. std::vector<u8> icon;
  212. std::string name;
  213. u64 program_id = 0;
  214. loader->ReadProgramId(program_id);
  215. const PatchManager patch{program_id, system.GetFileSystemController(),
  216. system.GetContentProvider()};
  217. const auto control = cache.GetEntry(game.title_id, ContentRecordType::Control);
  218. if (control != nullptr) {
  219. GetMetadataFromControlNCA(patch, *control, icon, name);
  220. }
  221. emit EntryReady(MakeGameListEntry(file->GetFullPath(), name, icon, *loader, program_id,
  222. compatibility_list, patch),
  223. parent_dir);
  224. }
  225. }
  226. void GameListWorker::ScanFileSystem(ScanTarget target, const std::string& dir_path, bool deep_scan,
  227. GameListDir* parent_dir) {
  228. const auto callback = [this, target, parent_dir](const std::filesystem::path& path) -> bool {
  229. if (stop_processing) {
  230. // Breaks the callback loop.
  231. return false;
  232. }
  233. const auto physical_name = Common::FS::PathToUTF8String(path);
  234. const auto is_dir = Common::FS::IsDir(path);
  235. if (!is_dir &&
  236. (HasSupportedFileExtension(physical_name) || IsExtractedNCAMain(physical_name))) {
  237. const auto file = vfs->OpenFile(physical_name, FileSys::Mode::Read);
  238. if (!file) {
  239. return true;
  240. }
  241. auto loader = Loader::GetLoader(system, file);
  242. if (!loader) {
  243. return true;
  244. }
  245. const auto file_type = loader->GetFileType();
  246. if (file_type == Loader::FileType::Unknown || file_type == Loader::FileType::Error) {
  247. return true;
  248. }
  249. u64 program_id = 0;
  250. const auto res2 = loader->ReadProgramId(program_id);
  251. if (target == ScanTarget::FillManualContentProvider) {
  252. if (res2 == Loader::ResultStatus::Success && file_type == Loader::FileType::NCA) {
  253. provider->AddEntry(FileSys::TitleType::Application,
  254. FileSys::GetCRTypeFromNCAType(FileSys::NCA{file}.GetType()),
  255. program_id, file);
  256. } else if (res2 == Loader::ResultStatus::Success &&
  257. (file_type == Loader::FileType::XCI ||
  258. file_type == Loader::FileType::NSP)) {
  259. const auto nsp = file_type == Loader::FileType::NSP
  260. ? std::make_shared<FileSys::NSP>(file)
  261. : FileSys::XCI{file}.GetSecurePartitionNSP();
  262. for (const auto& title : nsp->GetNCAs()) {
  263. for (const auto& entry : title.second) {
  264. provider->AddEntry(entry.first.first, entry.first.second, title.first,
  265. entry.second->GetBaseFile());
  266. }
  267. }
  268. }
  269. } else {
  270. std::vector<u64> program_ids;
  271. loader->ReadProgramIds(program_ids);
  272. if (res2 == Loader::ResultStatus::Success && program_ids.size() > 1 &&
  273. (file_type == Loader::FileType::XCI || file_type == Loader::FileType::NSP)) {
  274. for (const auto id : program_ids) {
  275. loader = Loader::GetLoader(system, file, id);
  276. if (!loader) {
  277. continue;
  278. }
  279. std::vector<u8> icon;
  280. [[maybe_unused]] const auto res1 = loader->ReadIcon(icon);
  281. std::string name = " ";
  282. [[maybe_unused]] const auto res3 = loader->ReadTitle(name);
  283. const FileSys::PatchManager patch{id, system.GetFileSystemController(),
  284. system.GetContentProvider()};
  285. emit EntryReady(MakeGameListEntry(physical_name, name, icon, *loader, id,
  286. compatibility_list, patch),
  287. parent_dir);
  288. }
  289. } else {
  290. std::vector<u8> icon;
  291. [[maybe_unused]] const auto res1 = loader->ReadIcon(icon);
  292. std::string name = " ";
  293. [[maybe_unused]] const auto res3 = loader->ReadTitle(name);
  294. const FileSys::PatchManager patch{program_id, system.GetFileSystemController(),
  295. system.GetContentProvider()};
  296. emit EntryReady(MakeGameListEntry(physical_name, name, icon, *loader,
  297. program_id, compatibility_list, patch),
  298. parent_dir);
  299. }
  300. }
  301. } else if (is_dir) {
  302. watch_list.append(QString::fromStdString(physical_name));
  303. }
  304. return true;
  305. };
  306. if (deep_scan) {
  307. Common::FS::IterateDirEntriesRecursively(dir_path, callback,
  308. Common::FS::DirEntryFilter::All);
  309. } else {
  310. Common::FS::IterateDirEntries(dir_path, callback, Common::FS::DirEntryFilter::File);
  311. }
  312. }
  313. void GameListWorker::run() {
  314. stop_processing = false;
  315. provider->ClearAllEntries();
  316. for (UISettings::GameDir& game_dir : game_dirs) {
  317. if (game_dir.path == QStringLiteral("SDMC")) {
  318. auto* const game_list_dir = new GameListDir(game_dir, GameListItemType::SdmcDir);
  319. emit DirEntryReady(game_list_dir);
  320. AddTitlesToGameList(game_list_dir);
  321. } else if (game_dir.path == QStringLiteral("UserNAND")) {
  322. auto* const game_list_dir = new GameListDir(game_dir, GameListItemType::UserNandDir);
  323. emit DirEntryReady(game_list_dir);
  324. AddTitlesToGameList(game_list_dir);
  325. } else if (game_dir.path == QStringLiteral("SysNAND")) {
  326. auto* const game_list_dir = new GameListDir(game_dir, GameListItemType::SysNandDir);
  327. emit DirEntryReady(game_list_dir);
  328. AddTitlesToGameList(game_list_dir);
  329. } else {
  330. watch_list.append(game_dir.path);
  331. auto* const game_list_dir = new GameListDir(game_dir);
  332. emit DirEntryReady(game_list_dir);
  333. ScanFileSystem(ScanTarget::FillManualContentProvider, game_dir.path.toStdString(),
  334. game_dir.deep_scan, game_list_dir);
  335. ScanFileSystem(ScanTarget::PopulateGameList, game_dir.path.toStdString(),
  336. game_dir.deep_scan, game_list_dir);
  337. }
  338. }
  339. emit Finished(watch_list);
  340. }
  341. void GameListWorker::Cancel() {
  342. this->disconnect();
  343. stop_processing = true;
  344. }