game_list.cpp 21 KB

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