game_list.cpp 18 KB

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