game_list.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <regex>
  5. #include <QApplication>
  6. #include <QDir>
  7. #include <QFileInfo>
  8. #include <QHeaderView>
  9. #include <QJsonArray>
  10. #include <QJsonDocument>
  11. #include <QJsonObject>
  12. #include <QKeyEvent>
  13. #include <QMenu>
  14. #include <QThreadPool>
  15. #include <fmt/format.h>
  16. #include "common/common_paths.h"
  17. #include "common/common_types.h"
  18. #include "common/file_util.h"
  19. #include "common/logging/log.h"
  20. #include "core/file_sys/content_archive.h"
  21. #include "core/file_sys/control_metadata.h"
  22. #include "core/file_sys/nca_metadata.h"
  23. #include "core/file_sys/registered_cache.h"
  24. #include "core/file_sys/romfs.h"
  25. #include "core/file_sys/vfs_real.h"
  26. #include "core/hle/service/filesystem/filesystem.h"
  27. #include "core/loader/loader.h"
  28. #include "yuzu/game_list.h"
  29. #include "yuzu/game_list_p.h"
  30. #include "yuzu/main.h"
  31. #include "yuzu/ui_settings.h"
  32. GameList::SearchField::KeyReleaseEater::KeyReleaseEater(GameList* gamelist) : gamelist{gamelist} {}
  33. // EventFilter in order to process systemkeys while editing the searchfield
  34. bool GameList::SearchField::KeyReleaseEater::eventFilter(QObject* obj, QEvent* event) {
  35. // If it isn't a KeyRelease event then continue with standard event processing
  36. if (event->type() != QEvent::KeyRelease)
  37. return QObject::eventFilter(obj, event);
  38. QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
  39. int rowCount = gamelist->tree_view->model()->rowCount();
  40. QString edit_filter_text = gamelist->search_field->edit_filter->text().toLower();
  41. // If the searchfield's text hasn't changed special function keys get checked
  42. // If no function key changes the searchfield's text the filter doesn't need to get reloaded
  43. if (edit_filter_text == edit_filter_text_old) {
  44. switch (keyEvent->key()) {
  45. // Escape: Resets the searchfield
  46. case Qt::Key_Escape: {
  47. if (edit_filter_text_old.isEmpty()) {
  48. return QObject::eventFilter(obj, event);
  49. } else {
  50. gamelist->search_field->edit_filter->clear();
  51. edit_filter_text = "";
  52. }
  53. break;
  54. }
  55. // Return and Enter
  56. // If the enter key gets pressed first checks how many and which entry is visible
  57. // If there is only one result launch this game
  58. case Qt::Key_Return:
  59. case Qt::Key_Enter: {
  60. QStandardItemModel* item_model = new QStandardItemModel(gamelist->tree_view);
  61. QModelIndex root_index = item_model->invisibleRootItem()->index();
  62. QStandardItem* child_file;
  63. QString file_path;
  64. int resultCount = 0;
  65. for (int i = 0; i < rowCount; ++i) {
  66. if (!gamelist->tree_view->isRowHidden(i, root_index)) {
  67. ++resultCount;
  68. child_file = gamelist->item_model->item(i, 0);
  69. file_path = child_file->data(GameListItemPath::FullPathRole).toString();
  70. }
  71. }
  72. if (resultCount == 1) {
  73. // To avoid loading error dialog loops while confirming them using enter
  74. // Also users usually want to run a diffrent game after closing one
  75. gamelist->search_field->edit_filter->setText("");
  76. edit_filter_text = "";
  77. emit gamelist->GameChosen(file_path);
  78. } else {
  79. return QObject::eventFilter(obj, event);
  80. }
  81. break;
  82. }
  83. default:
  84. return QObject::eventFilter(obj, event);
  85. }
  86. }
  87. edit_filter_text_old = edit_filter_text;
  88. return QObject::eventFilter(obj, event);
  89. }
  90. void GameList::SearchField::setFilterResult(int visible, int total) {
  91. QString result_of_text = tr("of");
  92. QString result_text;
  93. if (total == 1) {
  94. result_text = tr("result");
  95. } else {
  96. result_text = tr("results");
  97. }
  98. label_filter_result->setText(
  99. QString("%1 %2 %3 %4").arg(visible).arg(result_of_text).arg(total).arg(result_text));
  100. }
  101. void GameList::SearchField::clear() {
  102. edit_filter->setText("");
  103. }
  104. void GameList::SearchField::setFocus() {
  105. if (edit_filter->isVisible()) {
  106. edit_filter->setFocus();
  107. }
  108. }
  109. GameList::SearchField::SearchField(GameList* parent) : QWidget{parent} {
  110. KeyReleaseEater* keyReleaseEater = new KeyReleaseEater(parent);
  111. layout_filter = new QHBoxLayout;
  112. layout_filter->setMargin(8);
  113. label_filter = new QLabel;
  114. label_filter->setText(tr("Filter:"));
  115. edit_filter = new QLineEdit;
  116. edit_filter->setText("");
  117. edit_filter->setPlaceholderText(tr("Enter pattern to filter"));
  118. edit_filter->installEventFilter(keyReleaseEater);
  119. edit_filter->setClearButtonEnabled(true);
  120. connect(edit_filter, &QLineEdit::textChanged, parent, &GameList::onTextChanged);
  121. label_filter_result = new QLabel;
  122. button_filter_close = new QToolButton(this);
  123. button_filter_close->setText("X");
  124. button_filter_close->setCursor(Qt::ArrowCursor);
  125. button_filter_close->setStyleSheet("QToolButton{ border: none; padding: 0px; color: "
  126. "#000000; font-weight: bold; background: #F0F0F0; }"
  127. "QToolButton:hover{ border: none; padding: 0px; color: "
  128. "#EEEEEE; font-weight: bold; background: #E81123}");
  129. connect(button_filter_close, &QToolButton::clicked, parent, &GameList::onFilterCloseClicked);
  130. layout_filter->setSpacing(10);
  131. layout_filter->addWidget(label_filter);
  132. layout_filter->addWidget(edit_filter);
  133. layout_filter->addWidget(label_filter_result);
  134. layout_filter->addWidget(button_filter_close);
  135. setLayout(layout_filter);
  136. }
  137. /**
  138. * Checks if all words separated by spaces are contained in another string
  139. * This offers a word order insensitive search function
  140. *
  141. * @param haystack String that gets checked if it contains all words of the userinput string
  142. * @param userinput String containing all words getting checked
  143. * @return true if the haystack contains all words of userinput
  144. */
  145. static bool ContainsAllWords(const QString& haystack, const QString& userinput) {
  146. const QStringList userinput_split =
  147. userinput.split(' ', QString::SplitBehavior::SkipEmptyParts);
  148. return std::all_of(userinput_split.begin(), userinput_split.end(),
  149. [&haystack](const QString& s) { return haystack.contains(s); });
  150. }
  151. // Event in order to filter the gamelist after editing the searchfield
  152. void GameList::onTextChanged(const QString& newText) {
  153. int rowCount = tree_view->model()->rowCount();
  154. QString edit_filter_text = newText.toLower();
  155. QModelIndex root_index = item_model->invisibleRootItem()->index();
  156. // If the searchfield is empty every item is visible
  157. // Otherwise the filter gets applied
  158. if (edit_filter_text.isEmpty()) {
  159. for (int i = 0; i < rowCount; ++i) {
  160. tree_view->setRowHidden(i, root_index, false);
  161. }
  162. search_field->setFilterResult(rowCount, rowCount);
  163. } else {
  164. int result_count = 0;
  165. for (int i = 0; i < rowCount; ++i) {
  166. const QStandardItem* child_file = item_model->item(i, 0);
  167. const QString file_path =
  168. child_file->data(GameListItemPath::FullPathRole).toString().toLower();
  169. QString file_name = file_path.mid(file_path.lastIndexOf('/') + 1);
  170. const QString file_title =
  171. child_file->data(GameListItemPath::TitleRole).toString().toLower();
  172. const QString file_programmid =
  173. child_file->data(GameListItemPath::ProgramIdRole).toString().toLower();
  174. // Only items which filename in combination with its title contains all words
  175. // that are in the searchfield will be visible in the gamelist
  176. // The search is case insensitive because of toLower()
  177. // I decided not to use Qt::CaseInsensitive in containsAllWords to prevent
  178. // multiple conversions of edit_filter_text for each game in the gamelist
  179. if (ContainsAllWords(file_name.append(' ').append(file_title), edit_filter_text) ||
  180. (file_programmid.count() == 16 && edit_filter_text.contains(file_programmid))) {
  181. tree_view->setRowHidden(i, root_index, false);
  182. ++result_count;
  183. } else {
  184. tree_view->setRowHidden(i, root_index, true);
  185. }
  186. search_field->setFilterResult(result_count, rowCount);
  187. }
  188. }
  189. }
  190. void GameList::onFilterCloseClicked() {
  191. main_window->filterBarSetChecked(false);
  192. }
  193. GameList::GameList(FileSys::VirtualFilesystem vfs, GMainWindow* parent)
  194. : QWidget{parent}, vfs(std::move(vfs)) {
  195. watcher = new QFileSystemWatcher(this);
  196. connect(watcher, &QFileSystemWatcher::directoryChanged, this, &GameList::RefreshGameDirectory);
  197. this->main_window = parent;
  198. layout = new QVBoxLayout;
  199. tree_view = new QTreeView;
  200. search_field = new SearchField(this);
  201. item_model = new QStandardItemModel(tree_view);
  202. tree_view->setModel(item_model);
  203. tree_view->setAlternatingRowColors(true);
  204. tree_view->setSelectionMode(QHeaderView::SingleSelection);
  205. tree_view->setSelectionBehavior(QHeaderView::SelectRows);
  206. tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel);
  207. tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel);
  208. tree_view->setSortingEnabled(true);
  209. tree_view->setEditTriggers(QHeaderView::NoEditTriggers);
  210. tree_view->setUniformRowHeights(true);
  211. tree_view->setContextMenuPolicy(Qt::CustomContextMenu);
  212. item_model->insertColumns(0, COLUMN_COUNT);
  213. item_model->setHeaderData(COLUMN_NAME, Qt::Horizontal, "Name");
  214. item_model->setHeaderData(COLUMN_COMPATIBILITY, Qt::Horizontal, "Compatibility");
  215. item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, "File type");
  216. item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, "Size");
  217. connect(tree_view, &QTreeView::activated, this, &GameList::ValidateEntry);
  218. connect(tree_view, &QTreeView::customContextMenuRequested, this, &GameList::PopupContextMenu);
  219. // We must register all custom types with the Qt Automoc system so that we are able to use it
  220. // with signals/slots. In this case, QList falls under the umbrells of custom types.
  221. qRegisterMetaType<QList<QStandardItem*>>("QList<QStandardItem*>");
  222. layout->setContentsMargins(0, 0, 0, 0);
  223. layout->setSpacing(0);
  224. layout->addWidget(tree_view);
  225. layout->addWidget(search_field);
  226. setLayout(layout);
  227. }
  228. GameList::~GameList() {
  229. emit ShouldCancelWorker();
  230. }
  231. void GameList::setFilterFocus() {
  232. if (tree_view->model()->rowCount() > 0) {
  233. search_field->setFocus();
  234. }
  235. }
  236. void GameList::setFilterVisible(bool visibility) {
  237. search_field->setVisible(visibility);
  238. }
  239. void GameList::clearFilter() {
  240. search_field->clear();
  241. }
  242. void GameList::AddEntry(const QList<QStandardItem*>& entry_items) {
  243. item_model->invisibleRootItem()->appendRow(entry_items);
  244. }
  245. void GameList::ValidateEntry(const QModelIndex& item) {
  246. // We don't care about the individual QStandardItem that was selected, but its row.
  247. const int row = item_model->itemFromIndex(item)->row();
  248. const QStandardItem* child_file = item_model->invisibleRootItem()->child(row, COLUMN_NAME);
  249. const QString file_path = child_file->data(GameListItemPath::FullPathRole).toString();
  250. if (file_path.isEmpty())
  251. return;
  252. if (!QFileInfo::exists(file_path))
  253. return;
  254. const QFileInfo file_info{file_path};
  255. if (file_info.isDir()) {
  256. const QDir dir{file_path};
  257. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  258. if (matching_main.size() == 1) {
  259. emit GameChosen(dir.path() + DIR_SEP + matching_main[0]);
  260. }
  261. return;
  262. }
  263. // Users usually want to run a diffrent game after closing one
  264. search_field->clear();
  265. emit GameChosen(file_path);
  266. }
  267. void GameList::DonePopulating(QStringList watch_list) {
  268. // Clear out the old directories to watch for changes and add the new ones
  269. auto watch_dirs = watcher->directories();
  270. if (!watch_dirs.isEmpty()) {
  271. watcher->removePaths(watch_dirs);
  272. }
  273. // Workaround: Add the watch paths in chunks to allow the gui to refresh
  274. // This prevents the UI from stalling when a large number of watch paths are added
  275. // Also artificially caps the watcher to a certain number of directories
  276. constexpr int LIMIT_WATCH_DIRECTORIES = 5000;
  277. constexpr int SLICE_SIZE = 25;
  278. int len = std::min(watch_list.length(), LIMIT_WATCH_DIRECTORIES);
  279. for (int i = 0; i < len; i += SLICE_SIZE) {
  280. watcher->addPaths(watch_list.mid(i, i + SLICE_SIZE));
  281. QCoreApplication::processEvents();
  282. }
  283. tree_view->setEnabled(true);
  284. int rowCount = tree_view->model()->rowCount();
  285. search_field->setFilterResult(rowCount, rowCount);
  286. if (rowCount > 0) {
  287. search_field->setFocus();
  288. }
  289. }
  290. void GameList::PopupContextMenu(const QPoint& menu_location) {
  291. QModelIndex item = tree_view->indexAt(menu_location);
  292. if (!item.isValid())
  293. return;
  294. int row = item_model->itemFromIndex(item)->row();
  295. QStandardItem* child_file = item_model->invisibleRootItem()->child(row, COLUMN_NAME);
  296. u64 program_id = child_file->data(GameListItemPath::ProgramIdRole).toULongLong();
  297. QMenu context_menu;
  298. QAction* open_save_location = context_menu.addAction(tr("Open Save Data Location"));
  299. QAction* navigate_to_gamedb_entry = context_menu.addAction(tr("Navigate to GameDB entry"));
  300. open_save_location->setEnabled(program_id != 0);
  301. auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  302. navigate_to_gamedb_entry->setVisible(it != compatibility_list.end() && program_id != 0);
  303. connect(open_save_location, &QAction::triggered,
  304. [&]() { emit OpenFolderRequested(program_id, GameListOpenTarget::SaveData); });
  305. connect(navigate_to_gamedb_entry, &QAction::triggered,
  306. [&]() { emit NavigateToGamedbEntryRequested(program_id, compatibility_list); });
  307. context_menu.exec(tree_view->viewport()->mapToGlobal(menu_location));
  308. }
  309. void GameList::LoadCompatibilityList() {
  310. QFile compat_list{":compatibility_list/compatibility_list.json"};
  311. if (!compat_list.open(QFile::ReadOnly | QFile::Text)) {
  312. LOG_ERROR(Frontend, "Unable to open game compatibility list");
  313. return;
  314. }
  315. if (compat_list.size() == 0) {
  316. LOG_WARNING(Frontend, "Game compatibility list is empty");
  317. return;
  318. }
  319. const QByteArray content = compat_list.readAll();
  320. if (content.isEmpty()) {
  321. LOG_ERROR(Frontend, "Unable to completely read game compatibility list");
  322. return;
  323. }
  324. const QString string_content = content;
  325. QJsonDocument json = QJsonDocument::fromJson(string_content.toUtf8());
  326. QJsonArray arr = json.array();
  327. for (const QJsonValue& value : arr) {
  328. QJsonObject game = value.toObject();
  329. if (game.contains("compatibility") && game["compatibility"].isDouble()) {
  330. int compatibility = game["compatibility"].toInt();
  331. QString directory = game["directory"].toString();
  332. QJsonArray ids = game["releases"].toArray();
  333. for (const QJsonValue& value : ids) {
  334. QJsonObject object = value.toObject();
  335. QString id = object["id"].toString();
  336. compatibility_list.emplace(
  337. id.toUpper().toStdString(),
  338. std::make_pair(QString::number(compatibility), directory));
  339. }
  340. }
  341. }
  342. }
  343. void GameList::PopulateAsync(const QString& dir_path, bool deep_scan) {
  344. if (!FileUtil::Exists(dir_path.toStdString()) ||
  345. !FileUtil::IsDirectory(dir_path.toStdString())) {
  346. LOG_ERROR(Frontend, "Could not find game list folder at {}", dir_path.toLocal8Bit().data());
  347. search_field->setFilterResult(0, 0);
  348. return;
  349. }
  350. tree_view->setEnabled(false);
  351. // Delete any rows that might already exist if we're repopulating
  352. item_model->removeRows(0, item_model->rowCount());
  353. emit ShouldCancelWorker();
  354. GameListWorker* worker = new GameListWorker(vfs, dir_path, deep_scan, compatibility_list);
  355. connect(worker, &GameListWorker::EntryReady, this, &GameList::AddEntry, Qt::QueuedConnection);
  356. connect(worker, &GameListWorker::Finished, this, &GameList::DonePopulating,
  357. Qt::QueuedConnection);
  358. // Use DirectConnection here because worker->Cancel() is thread-safe and we want it to cancel
  359. // without delay.
  360. connect(this, &GameList::ShouldCancelWorker, worker, &GameListWorker::Cancel,
  361. Qt::DirectConnection);
  362. QThreadPool::globalInstance()->start(worker);
  363. current_worker = std::move(worker);
  364. }
  365. void GameList::SaveInterfaceLayout() {
  366. UISettings::values.gamelist_header_state = tree_view->header()->saveState();
  367. }
  368. void GameList::LoadInterfaceLayout() {
  369. auto header = tree_view->header();
  370. if (!header->restoreState(UISettings::values.gamelist_header_state)) {
  371. // We are using the name column to display icons and titles
  372. // so make it as large as possible as default.
  373. header->resizeSection(COLUMN_NAME, header->width());
  374. }
  375. item_model->sort(header->sortIndicatorSection(), header->sortIndicatorOrder());
  376. }
  377. const QStringList GameList::supported_file_extensions = {"nso", "nro", "nca", "xci"};
  378. static bool HasSupportedFileExtension(const std::string& file_name) {
  379. const QFileInfo file = QFileInfo(QString::fromStdString(file_name));
  380. return GameList::supported_file_extensions.contains(file.suffix(), Qt::CaseInsensitive);
  381. }
  382. static bool IsExtractedNCAMain(const std::string& file_name) {
  383. return QFileInfo(QString::fromStdString(file_name)).fileName() == "main";
  384. }
  385. static QString FormatGameName(const std::string& physical_name) {
  386. const QString physical_name_as_qstring = QString::fromStdString(physical_name);
  387. const QFileInfo file_info(physical_name_as_qstring);
  388. if (IsExtractedNCAMain(physical_name)) {
  389. return file_info.dir().path();
  390. }
  391. return physical_name_as_qstring;
  392. }
  393. void GameList::RefreshGameDirectory() {
  394. if (!UISettings::values.gamedir.isEmpty() && current_worker != nullptr) {
  395. LOG_INFO(Frontend, "Change detected in the games directory. Reloading game list.");
  396. search_field->clear();
  397. PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  398. }
  399. }
  400. static void GetMetadataFromControlNCA(const std::shared_ptr<FileSys::NCA>& nca,
  401. std::vector<u8>& icon, std::string& name) {
  402. const auto control_dir = FileSys::ExtractRomFS(nca->GetRomFS());
  403. if (control_dir == nullptr)
  404. return;
  405. const auto nacp_file = control_dir->GetFile("control.nacp");
  406. if (nacp_file == nullptr)
  407. return;
  408. FileSys::NACP nacp(nacp_file);
  409. name = nacp.GetApplicationName();
  410. FileSys::VirtualFile icon_file = nullptr;
  411. for (const auto& language : FileSys::LANGUAGE_NAMES) {
  412. icon_file = control_dir->GetFile("icon_" + std::string(language) + ".dat");
  413. if (icon_file != nullptr) {
  414. icon = icon_file->ReadAllBytes();
  415. break;
  416. }
  417. }
  418. }
  419. GameListWorker::GameListWorker(
  420. FileSys::VirtualFilesystem vfs, QString dir_path, bool deep_scan,
  421. const std::unordered_map<std::string, std::pair<QString, QString>>& compatibility_list)
  422. : vfs(std::move(vfs)), dir_path(std::move(dir_path)), deep_scan(deep_scan),
  423. compatibility_list(compatibility_list) {}
  424. GameListWorker::~GameListWorker() = default;
  425. void GameListWorker::AddInstalledTitlesToGameList(std::shared_ptr<FileSys::RegisteredCache> cache) {
  426. const auto installed_games = cache->ListEntriesFilter(FileSys::TitleType::Application,
  427. FileSys::ContentRecordType::Program);
  428. for (const auto& game : installed_games) {
  429. const auto& file = cache->GetEntryUnparsed(game);
  430. std::unique_ptr<Loader::AppLoader> loader = Loader::GetLoader(file);
  431. if (!loader)
  432. continue;
  433. std::vector<u8> icon;
  434. std::string name;
  435. u64 program_id = 0;
  436. loader->ReadProgramId(program_id);
  437. const auto& control = cache->GetEntry(game.title_id, FileSys::ContentRecordType::Control);
  438. if (control != nullptr)
  439. GetMetadataFromControlNCA(control, icon, name);
  440. emit EntryReady({
  441. new GameListItemPath(
  442. FormatGameName(file->GetFullPath()), icon, QString::fromStdString(name),
  443. QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType())),
  444. program_id),
  445. new GameListItem(
  446. QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType()))),
  447. new GameListItemSize(file->GetSize()),
  448. });
  449. }
  450. const auto control_data = cache->ListEntriesFilter(FileSys::TitleType::Application,
  451. FileSys::ContentRecordType::Control);
  452. for (const auto& entry : control_data) {
  453. const auto nca = cache->GetEntry(entry);
  454. if (nca != nullptr)
  455. nca_control_map.insert_or_assign(entry.title_id, nca);
  456. }
  457. }
  458. void GameListWorker::FillControlMap(const std::string& dir_path) {
  459. const auto nca_control_callback = [this](u64* num_entries_out, const std::string& directory,
  460. const std::string& virtual_name) -> bool {
  461. std::string physical_name = directory + DIR_SEP + virtual_name;
  462. if (stop_processing)
  463. return false; // Breaks the callback loop.
  464. bool is_dir = FileUtil::IsDirectory(physical_name);
  465. QFileInfo file_info(physical_name.c_str());
  466. if (!is_dir && file_info.suffix().toStdString() == "nca") {
  467. auto nca =
  468. std::make_shared<FileSys::NCA>(vfs->OpenFile(physical_name, FileSys::Mode::Read));
  469. if (nca->GetType() == FileSys::NCAContentType::Control)
  470. nca_control_map.insert_or_assign(nca->GetTitleId(), nca);
  471. }
  472. return true;
  473. };
  474. FileUtil::ForeachDirectoryEntry(nullptr, dir_path, nca_control_callback);
  475. }
  476. void GameListWorker::AddFstEntriesToGameList(const std::string& dir_path, unsigned int recursion) {
  477. const auto callback = [this, recursion](u64* num_entries_out, const std::string& directory,
  478. const std::string& virtual_name) -> bool {
  479. std::string physical_name = directory + DIR_SEP + virtual_name;
  480. if (stop_processing)
  481. return false; // Breaks the callback loop.
  482. bool is_dir = FileUtil::IsDirectory(physical_name);
  483. if (!is_dir &&
  484. (HasSupportedFileExtension(physical_name) || IsExtractedNCAMain(physical_name))) {
  485. std::unique_ptr<Loader::AppLoader> loader =
  486. Loader::GetLoader(vfs->OpenFile(physical_name, FileSys::Mode::Read));
  487. if (!loader || ((loader->GetFileType() == Loader::FileType::Unknown ||
  488. loader->GetFileType() == Loader::FileType::Error) &&
  489. !UISettings::values.show_unknown))
  490. return true;
  491. std::vector<u8> icon;
  492. const auto res1 = loader->ReadIcon(icon);
  493. u64 program_id = 0;
  494. const auto res2 = loader->ReadProgramId(program_id);
  495. std::string name = " ";
  496. const auto res3 = loader->ReadTitle(name);
  497. if (res1 != Loader::ResultStatus::Success && res3 != Loader::ResultStatus::Success &&
  498. res2 == Loader::ResultStatus::Success) {
  499. // Use from metadata pool.
  500. if (nca_control_map.find(program_id) != nca_control_map.end()) {
  501. const auto nca = nca_control_map[program_id];
  502. GetMetadataFromControlNCA(nca, icon, name);
  503. }
  504. }
  505. auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  506. // The game list uses this as compatibility number for untested games
  507. QString compatibility("99");
  508. if (it != compatibility_list.end())
  509. compatibility = it->second.first;
  510. emit EntryReady({
  511. new GameListItemPath(
  512. FormatGameName(physical_name), icon, QString::fromStdString(name),
  513. QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType())),
  514. program_id),
  515. new GameListItemCompat(compatibility),
  516. new GameListItem(
  517. QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType()))),
  518. new GameListItemSize(FileUtil::GetSize(physical_name)),
  519. });
  520. } else if (is_dir && recursion > 0) {
  521. watch_list.append(QString::fromStdString(physical_name));
  522. AddFstEntriesToGameList(physical_name, recursion - 1);
  523. }
  524. return true;
  525. };
  526. FileUtil::ForeachDirectoryEntry(nullptr, dir_path, callback);
  527. }
  528. void GameListWorker::run() {
  529. stop_processing = false;
  530. watch_list.append(dir_path);
  531. FillControlMap(dir_path.toStdString());
  532. AddInstalledTitlesToGameList(Service::FileSystem::GetUserNANDContents());
  533. AddInstalledTitlesToGameList(Service::FileSystem::GetSystemNANDContents());
  534. AddInstalledTitlesToGameList(Service::FileSystem::GetSDMCContents());
  535. AddFstEntriesToGameList(dir_path.toStdString(), deep_scan ? 256 : 0);
  536. nca_control_map.clear();
  537. emit Finished(watch_list);
  538. }
  539. void GameListWorker::Cancel() {
  540. this->disconnect();
  541. stop_processing = true;
  542. }