game_list_worker.cpp 17 KB

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