game_list_worker.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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)
  186. : vfs(std::move(vfs)), provider(provider), game_dirs(game_dirs),
  187. compatibility_list(compatibility_list) {}
  188. GameListWorker::~GameListWorker() = default;
  189. void GameListWorker::AddTitlesToGameList(GameListDir* parent_dir) {
  190. using namespace FileSys;
  191. auto& system = Core::System::GetInstance();
  192. const auto& cache = dynamic_cast<ContentProviderUnion&>(system.GetContentProvider());
  193. auto installed_games = cache.ListEntriesFilterOrigin(std::nullopt, TitleType::Application,
  194. ContentRecordType::Program);
  195. if (parent_dir->type() == static_cast<int>(GameListItemType::SdmcDir)) {
  196. installed_games = cache.ListEntriesFilterOrigin(
  197. ContentProviderUnionSlot::SDMC, TitleType::Application, ContentRecordType::Program);
  198. } else if (parent_dir->type() == static_cast<int>(GameListItemType::UserNandDir)) {
  199. installed_games = cache.ListEntriesFilterOrigin(
  200. ContentProviderUnionSlot::UserNAND, TitleType::Application, ContentRecordType::Program);
  201. } else if (parent_dir->type() == static_cast<int>(GameListItemType::SysNandDir)) {
  202. installed_games = cache.ListEntriesFilterOrigin(
  203. ContentProviderUnionSlot::SysNAND, TitleType::Application, ContentRecordType::Program);
  204. }
  205. for (const auto& [slot, game] : installed_games) {
  206. if (slot == ContentProviderUnionSlot::FrontendManual) {
  207. continue;
  208. }
  209. const auto file = cache.GetEntryUnparsed(game.title_id, game.type);
  210. std::unique_ptr<Loader::AppLoader> loader = Loader::GetLoader(system, file);
  211. if (!loader) {
  212. continue;
  213. }
  214. std::vector<u8> icon;
  215. std::string name;
  216. u64 program_id = 0;
  217. loader->ReadProgramId(program_id);
  218. const PatchManager patch{program_id, system.GetFileSystemController(),
  219. system.GetContentProvider()};
  220. const auto control = cache.GetEntry(game.title_id, ContentRecordType::Control);
  221. if (control != nullptr) {
  222. GetMetadataFromControlNCA(patch, *control, icon, name);
  223. }
  224. emit EntryReady(MakeGameListEntry(file->GetFullPath(), name, icon, *loader, program_id,
  225. compatibility_list, patch),
  226. parent_dir);
  227. }
  228. }
  229. void GameListWorker::ScanFileSystem(ScanTarget target, const std::string& dir_path, bool deep_scan,
  230. GameListDir* parent_dir) {
  231. auto& system = Core::System::GetInstance();
  232. const auto callback = [this, target, parent_dir,
  233. &system](const std::filesystem::path& path) -> bool {
  234. if (stop_processing) {
  235. // Breaks the callback loop.
  236. return false;
  237. }
  238. const auto physical_name = Common::FS::PathToUTF8String(path);
  239. const auto is_dir = Common::FS::IsDir(path);
  240. if (!is_dir &&
  241. (HasSupportedFileExtension(physical_name) || IsExtractedNCAMain(physical_name))) {
  242. const auto file = vfs->OpenFile(physical_name, FileSys::Mode::Read);
  243. if (!file) {
  244. return true;
  245. }
  246. auto loader = Loader::GetLoader(system, file);
  247. if (!loader) {
  248. return true;
  249. }
  250. const auto file_type = loader->GetFileType();
  251. if (file_type == Loader::FileType::Unknown || file_type == Loader::FileType::Error) {
  252. return true;
  253. }
  254. u64 program_id = 0;
  255. const auto res2 = loader->ReadProgramId(program_id);
  256. if (target == ScanTarget::FillManualContentProvider) {
  257. if (res2 == Loader::ResultStatus::Success && file_type == Loader::FileType::NCA) {
  258. provider->AddEntry(FileSys::TitleType::Application,
  259. FileSys::GetCRTypeFromNCAType(FileSys::NCA{file}.GetType()),
  260. program_id, file);
  261. } else if (res2 == Loader::ResultStatus::Success &&
  262. (file_type == Loader::FileType::XCI ||
  263. file_type == Loader::FileType::NSP)) {
  264. const auto nsp = file_type == Loader::FileType::NSP
  265. ? std::make_shared<FileSys::NSP>(file)
  266. : FileSys::XCI{file}.GetSecurePartitionNSP();
  267. for (const auto& title : nsp->GetNCAs()) {
  268. for (const auto& entry : title.second) {
  269. provider->AddEntry(entry.first.first, entry.first.second, title.first,
  270. entry.second->GetBaseFile());
  271. }
  272. }
  273. }
  274. } else {
  275. std::vector<u64> program_ids;
  276. loader->ReadProgramIds(program_ids);
  277. if (res2 == Loader::ResultStatus::Success && program_ids.size() > 1 &&
  278. (file_type == Loader::FileType::XCI || file_type == Loader::FileType::NSP)) {
  279. for (const auto id : program_ids) {
  280. loader = Loader::GetLoader(system, file, id);
  281. if (!loader) {
  282. continue;
  283. }
  284. std::vector<u8> icon;
  285. [[maybe_unused]] const auto res1 = loader->ReadIcon(icon);
  286. std::string name = " ";
  287. [[maybe_unused]] const auto res3 = loader->ReadTitle(name);
  288. const FileSys::PatchManager patch{id, system.GetFileSystemController(),
  289. system.GetContentProvider()};
  290. emit EntryReady(MakeGameListEntry(physical_name, name, icon, *loader, id,
  291. compatibility_list, patch),
  292. parent_dir);
  293. }
  294. } else {
  295. std::vector<u8> icon;
  296. [[maybe_unused]] const auto res1 = loader->ReadIcon(icon);
  297. std::string name = " ";
  298. [[maybe_unused]] const auto res3 = loader->ReadTitle(name);
  299. const FileSys::PatchManager patch{program_id, system.GetFileSystemController(),
  300. system.GetContentProvider()};
  301. emit EntryReady(MakeGameListEntry(physical_name, name, icon, *loader,
  302. program_id, compatibility_list, patch),
  303. parent_dir);
  304. }
  305. }
  306. } else if (is_dir) {
  307. watch_list.append(QString::fromStdString(physical_name));
  308. }
  309. return true;
  310. };
  311. if (deep_scan) {
  312. Common::FS::IterateDirEntriesRecursively(dir_path, callback,
  313. Common::FS::DirEntryFilter::All);
  314. } else {
  315. Common::FS::IterateDirEntries(dir_path, callback, Common::FS::DirEntryFilter::File);
  316. }
  317. }
  318. void GameListWorker::run() {
  319. stop_processing = false;
  320. provider->ClearAllEntries();
  321. for (UISettings::GameDir& game_dir : game_dirs) {
  322. if (game_dir.path == QStringLiteral("SDMC")) {
  323. auto* const game_list_dir = new GameListDir(game_dir, GameListItemType::SdmcDir);
  324. emit DirEntryReady(game_list_dir);
  325. AddTitlesToGameList(game_list_dir);
  326. } else if (game_dir.path == QStringLiteral("UserNAND")) {
  327. auto* const game_list_dir = new GameListDir(game_dir, GameListItemType::UserNandDir);
  328. emit DirEntryReady(game_list_dir);
  329. AddTitlesToGameList(game_list_dir);
  330. } else if (game_dir.path == QStringLiteral("SysNAND")) {
  331. auto* const game_list_dir = new GameListDir(game_dir, GameListItemType::SysNandDir);
  332. emit DirEntryReady(game_list_dir);
  333. AddTitlesToGameList(game_list_dir);
  334. } else {
  335. watch_list.append(game_dir.path);
  336. auto* const game_list_dir = new GameListDir(game_dir);
  337. emit DirEntryReady(game_list_dir);
  338. ScanFileSystem(ScanTarget::FillManualContentProvider, game_dir.path.toStdString(),
  339. game_dir.deep_scan, game_list_dir);
  340. ScanFileSystem(ScanTarget::PopulateGameList, game_dir.path.toStdString(),
  341. game_dir.deep_scan, game_list_dir);
  342. }
  343. }
  344. emit Finished(watch_list);
  345. }
  346. void GameListWorker::Cancel() {
  347. this->disconnect();
  348. stop_processing = true;
  349. }