game_list.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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/logging/log.h"
  19. #include "core/file_sys/patch_manager.h"
  20. #include "core/file_sys/registered_cache.h"
  21. #include "yuzu/compatibility_list.h"
  22. #include "yuzu/game_list.h"
  23. #include "yuzu/game_list_p.h"
  24. #include "yuzu/game_list_worker.h"
  25. #include "yuzu/main.h"
  26. #include "yuzu/ui_settings.h"
  27. GameListSearchField::KeyReleaseEater::KeyReleaseEater(GameList* gamelist) : gamelist{gamelist} {}
  28. // EventFilter in order to process systemkeys while editing the searchfield
  29. bool GameListSearchField::KeyReleaseEater::eventFilter(QObject* obj, QEvent* event) {
  30. // If it isn't a KeyRelease event then continue with standard event processing
  31. if (event->type() != QEvent::KeyRelease)
  32. return QObject::eventFilter(obj, event);
  33. QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
  34. int rowCount = gamelist->tree_view->model()->rowCount();
  35. QString edit_filter_text = gamelist->search_field->edit_filter->text().toLower();
  36. // If the searchfield's text hasn't changed special function keys get checked
  37. // If no function key changes the searchfield's text the filter doesn't need to get reloaded
  38. if (edit_filter_text == edit_filter_text_old) {
  39. switch (keyEvent->key()) {
  40. // Escape: Resets the searchfield
  41. case Qt::Key_Escape: {
  42. if (edit_filter_text_old.isEmpty()) {
  43. return QObject::eventFilter(obj, event);
  44. } else {
  45. gamelist->search_field->edit_filter->clear();
  46. edit_filter_text = "";
  47. }
  48. break;
  49. }
  50. // Return and Enter
  51. // If the enter key gets pressed first checks how many and which entry is visible
  52. // If there is only one result launch this game
  53. case Qt::Key_Return:
  54. case Qt::Key_Enter: {
  55. QStandardItemModel* item_model = new QStandardItemModel(gamelist->tree_view);
  56. QModelIndex root_index = item_model->invisibleRootItem()->index();
  57. QStandardItem* child_file;
  58. QString file_path;
  59. int resultCount = 0;
  60. for (int i = 0; i < rowCount; ++i) {
  61. if (!gamelist->tree_view->isRowHidden(i, root_index)) {
  62. ++resultCount;
  63. child_file = gamelist->item_model->item(i, 0);
  64. file_path = child_file->data(GameListItemPath::FullPathRole).toString();
  65. }
  66. }
  67. if (resultCount == 1) {
  68. // To avoid loading error dialog loops while confirming them using enter
  69. // Also users usually want to run a diffrent game after closing one
  70. gamelist->search_field->edit_filter->setText("");
  71. edit_filter_text = "";
  72. emit gamelist->GameChosen(file_path);
  73. } else {
  74. return QObject::eventFilter(obj, event);
  75. }
  76. break;
  77. }
  78. default:
  79. return QObject::eventFilter(obj, event);
  80. }
  81. }
  82. edit_filter_text_old = edit_filter_text;
  83. return QObject::eventFilter(obj, event);
  84. }
  85. void GameListSearchField::setFilterResult(int visible, int total) {
  86. label_filter_result->setText(tr("%1 of %n result(s)", "", total).arg(visible));
  87. }
  88. void GameListSearchField::clear() {
  89. edit_filter->setText("");
  90. }
  91. void GameListSearchField::setFocus() {
  92. if (edit_filter->isVisible()) {
  93. edit_filter->setFocus();
  94. }
  95. }
  96. GameListSearchField::GameListSearchField(GameList* parent) : QWidget{parent} {
  97. KeyReleaseEater* keyReleaseEater = new KeyReleaseEater(parent);
  98. layout_filter = new QHBoxLayout;
  99. layout_filter->setMargin(8);
  100. label_filter = new QLabel;
  101. label_filter->setText(tr("Filter:"));
  102. edit_filter = new QLineEdit;
  103. edit_filter->setText("");
  104. edit_filter->setPlaceholderText(tr("Enter pattern to filter"));
  105. edit_filter->installEventFilter(keyReleaseEater);
  106. edit_filter->setClearButtonEnabled(true);
  107. connect(edit_filter, &QLineEdit::textChanged, parent, &GameList::onTextChanged);
  108. label_filter_result = new QLabel;
  109. button_filter_close = new QToolButton(this);
  110. button_filter_close->setText("X");
  111. button_filter_close->setCursor(Qt::ArrowCursor);
  112. button_filter_close->setStyleSheet("QToolButton{ border: none; padding: 0px; color: "
  113. "#000000; font-weight: bold; background: #F0F0F0; }"
  114. "QToolButton:hover{ border: none; padding: 0px; color: "
  115. "#EEEEEE; font-weight: bold; background: #E81123}");
  116. connect(button_filter_close, &QToolButton::clicked, parent, &GameList::onFilterCloseClicked);
  117. layout_filter->setSpacing(10);
  118. layout_filter->addWidget(label_filter);
  119. layout_filter->addWidget(edit_filter);
  120. layout_filter->addWidget(label_filter_result);
  121. layout_filter->addWidget(button_filter_close);
  122. setLayout(layout_filter);
  123. }
  124. /**
  125. * Checks if all words separated by spaces are contained in another string
  126. * This offers a word order insensitive search function
  127. *
  128. * @param haystack String that gets checked if it contains all words of the userinput string
  129. * @param userinput String containing all words getting checked
  130. * @return true if the haystack contains all words of userinput
  131. */
  132. static bool ContainsAllWords(const QString& haystack, const QString& userinput) {
  133. const QStringList userinput_split =
  134. userinput.split(' ', QString::SplitBehavior::SkipEmptyParts);
  135. return std::all_of(userinput_split.begin(), userinput_split.end(),
  136. [&haystack](const QString& s) { return haystack.contains(s); });
  137. }
  138. // Event in order to filter the gamelist after editing the searchfield
  139. void GameList::onTextChanged(const QString& newText) {
  140. int rowCount = tree_view->model()->rowCount();
  141. QString edit_filter_text = newText.toLower();
  142. QModelIndex root_index = item_model->invisibleRootItem()->index();
  143. // If the searchfield is empty every item is visible
  144. // Otherwise the filter gets applied
  145. if (edit_filter_text.isEmpty()) {
  146. for (int i = 0; i < rowCount; ++i) {
  147. tree_view->setRowHidden(i, root_index, false);
  148. }
  149. search_field->setFilterResult(rowCount, rowCount);
  150. } else {
  151. int result_count = 0;
  152. for (int i = 0; i < rowCount; ++i) {
  153. const QStandardItem* child_file = item_model->item(i, 0);
  154. const QString file_path =
  155. child_file->data(GameListItemPath::FullPathRole).toString().toLower();
  156. QString file_name = file_path.mid(file_path.lastIndexOf('/') + 1);
  157. const QString file_title =
  158. child_file->data(GameListItemPath::TitleRole).toString().toLower();
  159. const QString file_programmid =
  160. child_file->data(GameListItemPath::ProgramIdRole).toString().toLower();
  161. // Only items which filename in combination with its title contains all words
  162. // that are in the searchfield will be visible in the gamelist
  163. // The search is case insensitive because of toLower()
  164. // I decided not to use Qt::CaseInsensitive in containsAllWords to prevent
  165. // multiple conversions of edit_filter_text for each game in the gamelist
  166. if (ContainsAllWords(file_name.append(' ').append(file_title), edit_filter_text) ||
  167. (file_programmid.count() == 16 && edit_filter_text.contains(file_programmid))) {
  168. tree_view->setRowHidden(i, root_index, false);
  169. ++result_count;
  170. } else {
  171. tree_view->setRowHidden(i, root_index, true);
  172. }
  173. search_field->setFilterResult(result_count, rowCount);
  174. }
  175. }
  176. }
  177. void GameList::onFilterCloseClicked() {
  178. main_window->filterBarSetChecked(false);
  179. }
  180. GameList::GameList(FileSys::VirtualFilesystem vfs, FileSys::ManualContentProvider* provider,
  181. GMainWindow* parent)
  182. : QWidget{parent}, vfs(std::move(vfs)), provider(provider) {
  183. watcher = new QFileSystemWatcher(this);
  184. connect(watcher, &QFileSystemWatcher::directoryChanged, this, &GameList::RefreshGameDirectory);
  185. this->main_window = parent;
  186. layout = new QVBoxLayout;
  187. tree_view = new QTreeView;
  188. search_field = new GameListSearchField(this);
  189. item_model = new QStandardItemModel(tree_view);
  190. tree_view->setModel(item_model);
  191. tree_view->setAlternatingRowColors(true);
  192. tree_view->setSelectionMode(QHeaderView::SingleSelection);
  193. tree_view->setSelectionBehavior(QHeaderView::SelectRows);
  194. tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel);
  195. tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel);
  196. tree_view->setSortingEnabled(true);
  197. tree_view->setEditTriggers(QHeaderView::NoEditTriggers);
  198. tree_view->setUniformRowHeights(true);
  199. tree_view->setContextMenuPolicy(Qt::CustomContextMenu);
  200. tree_view->setStyleSheet("QTreeView{ border: none; }");
  201. item_model->insertColumns(0, UISettings::values.show_add_ons ? COLUMN_COUNT : COLUMN_COUNT - 1);
  202. item_model->setHeaderData(COLUMN_NAME, Qt::Horizontal, tr("Name"));
  203. item_model->setHeaderData(COLUMN_COMPATIBILITY, Qt::Horizontal, tr("Compatibility"));
  204. if (UISettings::values.show_add_ons) {
  205. item_model->setHeaderData(COLUMN_ADD_ONS, Qt::Horizontal, tr("Add-ons"));
  206. item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, tr("File type"));
  207. item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, tr("Size"));
  208. } else {
  209. item_model->setHeaderData(COLUMN_FILE_TYPE - 1, Qt::Horizontal, tr("File type"));
  210. item_model->setHeaderData(COLUMN_SIZE - 1, Qt::Horizontal, tr("Size"));
  211. }
  212. connect(tree_view, &QTreeView::activated, this, &GameList::ValidateEntry);
  213. connect(tree_view, &QTreeView::customContextMenuRequested, this, &GameList::PopupContextMenu);
  214. // We must register all custom types with the Qt Automoc system so that we are able to use it
  215. // with signals/slots. In this case, QList falls under the umbrells of custom types.
  216. qRegisterMetaType<QList<QStandardItem*>>("QList<QStandardItem*>");
  217. layout->setContentsMargins(0, 0, 0, 0);
  218. layout->setSpacing(0);
  219. layout->addWidget(tree_view);
  220. layout->addWidget(search_field);
  221. setLayout(layout);
  222. }
  223. GameList::~GameList() {
  224. emit ShouldCancelWorker();
  225. }
  226. void GameList::setFilterFocus() {
  227. if (tree_view->model()->rowCount() > 0) {
  228. search_field->setFocus();
  229. }
  230. }
  231. void GameList::setFilterVisible(bool visibility) {
  232. search_field->setVisible(visibility);
  233. }
  234. void GameList::clearFilter() {
  235. search_field->clear();
  236. }
  237. void GameList::AddEntry(const QList<QStandardItem*>& entry_items) {
  238. item_model->invisibleRootItem()->appendRow(entry_items);
  239. }
  240. void GameList::ValidateEntry(const QModelIndex& item) {
  241. // We don't care about the individual QStandardItem that was selected, but its row.
  242. const int row = item_model->itemFromIndex(item)->row();
  243. const QStandardItem* child_file = item_model->invisibleRootItem()->child(row, COLUMN_NAME);
  244. const QString file_path = child_file->data(GameListItemPath::FullPathRole).toString();
  245. if (file_path.isEmpty())
  246. return;
  247. if (!QFileInfo::exists(file_path))
  248. return;
  249. const QFileInfo file_info{file_path};
  250. if (file_info.isDir()) {
  251. const QDir dir{file_path};
  252. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  253. if (matching_main.size() == 1) {
  254. emit GameChosen(dir.path() + DIR_SEP + matching_main[0]);
  255. }
  256. return;
  257. }
  258. // Users usually want to run a diffrent game after closing one
  259. search_field->clear();
  260. emit GameChosen(file_path);
  261. }
  262. void GameList::DonePopulating(QStringList watch_list) {
  263. // Clear out the old directories to watch for changes and add the new ones
  264. auto watch_dirs = watcher->directories();
  265. if (!watch_dirs.isEmpty()) {
  266. watcher->removePaths(watch_dirs);
  267. }
  268. // Workaround: Add the watch paths in chunks to allow the gui to refresh
  269. // This prevents the UI from stalling when a large number of watch paths are added
  270. // Also artificially caps the watcher to a certain number of directories
  271. constexpr int LIMIT_WATCH_DIRECTORIES = 5000;
  272. constexpr int SLICE_SIZE = 25;
  273. int len = std::min(watch_list.length(), LIMIT_WATCH_DIRECTORIES);
  274. for (int i = 0; i < len; i += SLICE_SIZE) {
  275. watcher->addPaths(watch_list.mid(i, i + SLICE_SIZE));
  276. QCoreApplication::processEvents();
  277. }
  278. tree_view->setEnabled(true);
  279. int rowCount = tree_view->model()->rowCount();
  280. search_field->setFilterResult(rowCount, rowCount);
  281. if (rowCount > 0) {
  282. search_field->setFocus();
  283. }
  284. }
  285. void GameList::PopupContextMenu(const QPoint& menu_location) {
  286. QModelIndex item = tree_view->indexAt(menu_location);
  287. if (!item.isValid())
  288. return;
  289. int row = item_model->itemFromIndex(item)->row();
  290. QStandardItem* child_file = item_model->invisibleRootItem()->child(row, COLUMN_NAME);
  291. u64 program_id = child_file->data(GameListItemPath::ProgramIdRole).toULongLong();
  292. std::string path = child_file->data(GameListItemPath::FullPathRole).toString().toStdString();
  293. QMenu context_menu;
  294. QAction* open_save_location = context_menu.addAction(tr("Open Save Data Location"));
  295. QAction* open_lfs_location = context_menu.addAction(tr("Open Mod Data Location"));
  296. QAction* open_transferable_shader_cache =
  297. context_menu.addAction(tr("Open Transferable Shader Cache"));
  298. context_menu.addSeparator();
  299. QAction* dump_romfs = context_menu.addAction(tr("Dump RomFS"));
  300. QAction* copy_tid = context_menu.addAction(tr("Copy Title ID to Clipboard"));
  301. QAction* navigate_to_gamedb_entry = context_menu.addAction(tr("Navigate to GameDB entry"));
  302. context_menu.addSeparator();
  303. QAction* properties = context_menu.addAction(tr("Properties"));
  304. open_save_location->setEnabled(program_id != 0);
  305. auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  306. navigate_to_gamedb_entry->setVisible(it != compatibility_list.end() && program_id != 0);
  307. connect(open_save_location, &QAction::triggered,
  308. [&]() { emit OpenFolderRequested(program_id, GameListOpenTarget::SaveData); });
  309. connect(open_lfs_location, &QAction::triggered,
  310. [&]() { emit OpenFolderRequested(program_id, GameListOpenTarget::ModData); });
  311. connect(open_transferable_shader_cache, &QAction::triggered,
  312. [&]() { emit OpenTransferableShaderCacheRequested(program_id); });
  313. connect(dump_romfs, &QAction::triggered, [&]() { emit DumpRomFSRequested(program_id, path); });
  314. connect(copy_tid, &QAction::triggered, [&]() { emit CopyTIDRequested(program_id); });
  315. connect(navigate_to_gamedb_entry, &QAction::triggered,
  316. [&]() { emit NavigateToGamedbEntryRequested(program_id, compatibility_list); });
  317. connect(properties, &QAction::triggered, [&]() { emit OpenPerGameGeneralRequested(path); });
  318. context_menu.exec(tree_view->viewport()->mapToGlobal(menu_location));
  319. }
  320. void GameList::LoadCompatibilityList() {
  321. QFile compat_list{":compatibility_list/compatibility_list.json"};
  322. if (!compat_list.open(QFile::ReadOnly | QFile::Text)) {
  323. LOG_ERROR(Frontend, "Unable to open game compatibility list");
  324. return;
  325. }
  326. if (compat_list.size() == 0) {
  327. LOG_WARNING(Frontend, "Game compatibility list is empty");
  328. return;
  329. }
  330. const QByteArray content = compat_list.readAll();
  331. if (content.isEmpty()) {
  332. LOG_ERROR(Frontend, "Unable to completely read game compatibility list");
  333. return;
  334. }
  335. const QString string_content = content;
  336. QJsonDocument json = QJsonDocument::fromJson(string_content.toUtf8());
  337. QJsonArray arr = json.array();
  338. for (const QJsonValueRef value : arr) {
  339. QJsonObject game = value.toObject();
  340. if (game.contains("compatibility") && game["compatibility"].isDouble()) {
  341. int compatibility = game["compatibility"].toInt();
  342. QString directory = game["directory"].toString();
  343. QJsonArray ids = game["releases"].toArray();
  344. for (const QJsonValueRef id_ref : ids) {
  345. QJsonObject id_object = id_ref.toObject();
  346. QString id = id_object["id"].toString();
  347. compatibility_list.emplace(
  348. id.toUpper().toStdString(),
  349. std::make_pair(QString::number(compatibility), directory));
  350. }
  351. }
  352. }
  353. }
  354. void GameList::PopulateAsync(const QString& dir_path, bool deep_scan) {
  355. const QFileInfo dir_info{dir_path};
  356. if (!dir_info.exists() || !dir_info.isDir()) {
  357. LOG_ERROR(Frontend, "Could not find game list folder at {}", dir_path.toStdString());
  358. search_field->setFilterResult(0, 0);
  359. return;
  360. }
  361. tree_view->setEnabled(false);
  362. // Update the columns in case UISettings has changed
  363. item_model->removeColumns(0, item_model->columnCount());
  364. item_model->insertColumns(0, UISettings::values.show_add_ons ? COLUMN_COUNT : COLUMN_COUNT - 1);
  365. item_model->setHeaderData(COLUMN_NAME, Qt::Horizontal, tr("Name"));
  366. item_model->setHeaderData(COLUMN_COMPATIBILITY, Qt::Horizontal, tr("Compatibility"));
  367. if (UISettings::values.show_add_ons) {
  368. item_model->setHeaderData(COLUMN_ADD_ONS, Qt::Horizontal, tr("Add-ons"));
  369. item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, tr("File type"));
  370. item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, tr("Size"));
  371. } else {
  372. item_model->setHeaderData(COLUMN_FILE_TYPE - 1, Qt::Horizontal, tr("File type"));
  373. item_model->setHeaderData(COLUMN_SIZE - 1, Qt::Horizontal, tr("Size"));
  374. item_model->removeColumns(COLUMN_COUNT - 1, 1);
  375. }
  376. LoadInterfaceLayout();
  377. // Delete any rows that might already exist if we're repopulating
  378. item_model->removeRows(0, item_model->rowCount());
  379. emit ShouldCancelWorker();
  380. GameListWorker* worker =
  381. new GameListWorker(vfs, provider, dir_path, deep_scan, compatibility_list);
  382. connect(worker, &GameListWorker::EntryReady, this, &GameList::AddEntry, Qt::QueuedConnection);
  383. connect(worker, &GameListWorker::Finished, this, &GameList::DonePopulating,
  384. Qt::QueuedConnection);
  385. // Use DirectConnection here because worker->Cancel() is thread-safe and we want it to cancel
  386. // without delay.
  387. connect(this, &GameList::ShouldCancelWorker, worker, &GameListWorker::Cancel,
  388. Qt::DirectConnection);
  389. QThreadPool::globalInstance()->start(worker);
  390. current_worker = std::move(worker);
  391. }
  392. void GameList::SaveInterfaceLayout() {
  393. UISettings::values.gamelist_header_state = tree_view->header()->saveState();
  394. }
  395. void GameList::LoadInterfaceLayout() {
  396. auto header = tree_view->header();
  397. if (!header->restoreState(UISettings::values.gamelist_header_state)) {
  398. // We are using the name column to display icons and titles
  399. // so make it as large as possible as default.
  400. header->resizeSection(COLUMN_NAME, header->width());
  401. }
  402. item_model->sort(header->sortIndicatorSection(), header->sortIndicatorOrder());
  403. }
  404. const QStringList GameList::supported_file_extensions = {"nso", "nro", "nca", "xci", "nsp"};
  405. void GameList::RefreshGameDirectory() {
  406. if (!UISettings::values.game_directory_path.isEmpty() && current_worker != nullptr) {
  407. LOG_INFO(Frontend, "Change detected in the games directory. Reloading game list.");
  408. search_field->clear();
  409. PopulateAsync(UISettings::values.game_directory_path, UISettings::values.game_directory_deepscan);
  410. }
  411. }