game_list.cpp 25 KB

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