game_list.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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 <QList>
  14. #include <QMenu>
  15. #include <QThreadPool>
  16. #include <fmt/format.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/uisettings.h"
  27. GameListSearchField::KeyReleaseEater::KeyReleaseEater(GameList* gamelist, QObject* parent)
  28. : QObject(parent), gamelist{gamelist} {}
  29. // EventFilter in order to process systemkeys while editing the searchfield
  30. bool GameListSearchField::KeyReleaseEater::eventFilter(QObject* obj, QEvent* event) {
  31. // If it isn't a KeyRelease event then continue with standard event processing
  32. if (event->type() != QEvent::KeyRelease)
  33. return QObject::eventFilter(obj, event);
  34. QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
  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.clear();
  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. if (gamelist->search_field->visible == 1) {
  56. const QString file_path = gamelist->GetLastFilterResultItem();
  57. // To avoid loading error dialog loops while confirming them using enter
  58. // Also users usually want to run a different game after closing one
  59. gamelist->search_field->edit_filter->clear();
  60. edit_filter_text.clear();
  61. emit gamelist->GameChosen(file_path);
  62. } else {
  63. return QObject::eventFilter(obj, event);
  64. }
  65. break;
  66. }
  67. default:
  68. return QObject::eventFilter(obj, event);
  69. }
  70. }
  71. edit_filter_text_old = edit_filter_text;
  72. return QObject::eventFilter(obj, event);
  73. }
  74. void GameListSearchField::setFilterResult(int visible, int total) {
  75. this->visible = visible;
  76. this->total = total;
  77. label_filter_result->setText(tr("%1 of %n result(s)", "", total).arg(visible));
  78. }
  79. QString GameListSearchField::filterText() const {
  80. return edit_filter->text();
  81. }
  82. QString GameList::GetLastFilterResultItem() const {
  83. QString file_path;
  84. for (int i = 1; i < item_model->rowCount() - 1; ++i) {
  85. const QStandardItem* folder = item_model->item(i, 0);
  86. const QModelIndex folder_index = folder->index();
  87. const int children_count = folder->rowCount();
  88. for (int j = 0; j < children_count; ++j) {
  89. if (tree_view->isRowHidden(j, folder_index)) {
  90. continue;
  91. }
  92. const QStandardItem* child = folder->child(j, 0);
  93. file_path = child->data(GameListItemPath::FullPathRole).toString();
  94. }
  95. }
  96. return file_path;
  97. }
  98. void GameListSearchField::clear() {
  99. edit_filter->clear();
  100. }
  101. void GameListSearchField::setFocus() {
  102. if (edit_filter->isVisible()) {
  103. edit_filter->setFocus();
  104. }
  105. }
  106. GameListSearchField::GameListSearchField(GameList* parent) : QWidget{parent} {
  107. auto* const key_release_eater = new KeyReleaseEater(parent, this);
  108. layout_filter = new QHBoxLayout;
  109. layout_filter->setContentsMargins(8, 8, 8, 8);
  110. label_filter = new QLabel;
  111. label_filter->setText(tr("Filter:"));
  112. edit_filter = new QLineEdit;
  113. edit_filter->clear();
  114. edit_filter->setPlaceholderText(tr("Enter pattern to filter"));
  115. edit_filter->installEventFilter(key_release_eater);
  116. edit_filter->setClearButtonEnabled(true);
  117. connect(edit_filter, &QLineEdit::textChanged, parent, &GameList::OnTextChanged);
  118. label_filter_result = new QLabel;
  119. button_filter_close = new QToolButton(this);
  120. button_filter_close->setText(QStringLiteral("X"));
  121. button_filter_close->setCursor(Qt::ArrowCursor);
  122. button_filter_close->setStyleSheet(
  123. QStringLiteral("QToolButton{ border: none; padding: 0px; color: "
  124. "#000000; font-weight: bold; background: #F0F0F0; }"
  125. "QToolButton:hover{ border: none; padding: 0px; color: "
  126. "#EEEEEE; font-weight: bold; background: #E81123}"));
  127. connect(button_filter_close, &QToolButton::clicked, parent, &GameList::OnFilterCloseClicked);
  128. layout_filter->setSpacing(10);
  129. layout_filter->addWidget(label_filter);
  130. layout_filter->addWidget(edit_filter);
  131. layout_filter->addWidget(label_filter_result);
  132. layout_filter->addWidget(button_filter_close);
  133. setLayout(layout_filter);
  134. }
  135. /**
  136. * Checks if all words separated by spaces are contained in another string
  137. * This offers a word order insensitive search function
  138. *
  139. * @param haystack String that gets checked if it contains all words of the userinput string
  140. * @param userinput String containing all words getting checked
  141. * @return true if the haystack contains all words of userinput
  142. */
  143. static bool ContainsAllWords(const QString& haystack, const QString& userinput) {
  144. const QStringList userinput_split = userinput.split(QLatin1Char{' '}, Qt::SkipEmptyParts);
  145. return std::all_of(userinput_split.begin(), userinput_split.end(),
  146. [&haystack](const QString& s) { return haystack.contains(s); });
  147. }
  148. // Syncs the expanded state of Game Directories with settings to persist across sessions
  149. void GameList::OnItemExpanded(const QModelIndex& item) {
  150. const auto type = item.data(GameListItem::TypeRole).value<GameListItemType>();
  151. const bool is_dir = type == GameListItemType::CustomDir || type == GameListItemType::SdmcDir ||
  152. type == GameListItemType::UserNandDir ||
  153. type == GameListItemType::SysNandDir;
  154. if (!is_dir) {
  155. return;
  156. }
  157. UISettings::values.game_dirs[item.data(GameListDir::GameDirRole).toInt()].expanded =
  158. tree_view->isExpanded(item);
  159. }
  160. // Event in order to filter the gamelist after editing the searchfield
  161. void GameList::OnTextChanged(const QString& new_text) {
  162. QString edit_filter_text = new_text.toLower();
  163. QStandardItem* folder;
  164. int children_total = 0;
  165. // If the searchfield is empty every item is visible
  166. // Otherwise the filter gets applied
  167. if (edit_filter_text.isEmpty()) {
  168. tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(),
  169. UISettings::values.favorited_ids.size() == 0);
  170. for (int i = 1; i < item_model->rowCount() - 1; ++i) {
  171. folder = item_model->item(i, 0);
  172. const QModelIndex folder_index = folder->index();
  173. const int children_count = folder->rowCount();
  174. for (int j = 0; j < children_count; ++j) {
  175. ++children_total;
  176. tree_view->setRowHidden(j, folder_index, false);
  177. }
  178. }
  179. search_field->setFilterResult(children_total, children_total);
  180. } else {
  181. tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), true);
  182. int result_count = 0;
  183. for (int i = 1; i < item_model->rowCount() - 1; ++i) {
  184. folder = item_model->item(i, 0);
  185. const QModelIndex folder_index = folder->index();
  186. const int children_count = folder->rowCount();
  187. for (int j = 0; j < children_count; ++j) {
  188. ++children_total;
  189. const QStandardItem* child = folder->child(j, 0);
  190. const QString file_path =
  191. child->data(GameListItemPath::FullPathRole).toString().toLower();
  192. const QString file_title =
  193. child->data(GameListItemPath::TitleRole).toString().toLower();
  194. const QString file_program_id =
  195. child->data(GameListItemPath::ProgramIdRole).toString().toLower();
  196. // Only items which filename in combination with its title contains all words
  197. // that are in the searchfield will be visible in the gamelist
  198. // The search is case insensitive because of toLower()
  199. // I decided not to use Qt::CaseInsensitive in containsAllWords to prevent
  200. // multiple conversions of edit_filter_text for each game in the gamelist
  201. const QString file_name =
  202. file_path.mid(file_path.lastIndexOf(QLatin1Char{'/'}) + 1) + QLatin1Char{' '} +
  203. file_title;
  204. if (ContainsAllWords(file_name, edit_filter_text) ||
  205. (file_program_id.count() == 16 && edit_filter_text.contains(file_program_id))) {
  206. tree_view->setRowHidden(j, folder_index, false);
  207. ++result_count;
  208. } else {
  209. tree_view->setRowHidden(j, folder_index, true);
  210. }
  211. }
  212. }
  213. search_field->setFilterResult(result_count, children_total);
  214. }
  215. }
  216. void GameList::OnUpdateThemedIcons() {
  217. for (int i = 0; i < item_model->invisibleRootItem()->rowCount(); i++) {
  218. QStandardItem* child = item_model->invisibleRootItem()->child(i);
  219. const int icon_size = UISettings::values.folder_icon_size.GetValue();
  220. switch (child->data(GameListItem::TypeRole).value<GameListItemType>()) {
  221. case GameListItemType::SdmcDir:
  222. child->setData(
  223. QIcon::fromTheme(QStringLiteral("sd_card"))
  224. .pixmap(icon_size)
  225. .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation),
  226. Qt::DecorationRole);
  227. break;
  228. case GameListItemType::UserNandDir:
  229. child->setData(
  230. QIcon::fromTheme(QStringLiteral("chip"))
  231. .pixmap(icon_size)
  232. .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation),
  233. Qt::DecorationRole);
  234. break;
  235. case GameListItemType::SysNandDir:
  236. child->setData(
  237. QIcon::fromTheme(QStringLiteral("chip"))
  238. .pixmap(icon_size)
  239. .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation),
  240. Qt::DecorationRole);
  241. break;
  242. case GameListItemType::CustomDir: {
  243. const UISettings::GameDir& game_dir =
  244. UISettings::values.game_dirs[child->data(GameListDir::GameDirRole).toInt()];
  245. const QString icon_name = QFileInfo::exists(game_dir.path)
  246. ? QStringLiteral("folder")
  247. : QStringLiteral("bad_folder");
  248. child->setData(
  249. QIcon::fromTheme(icon_name).pixmap(icon_size).scaled(
  250. icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation),
  251. Qt::DecorationRole);
  252. break;
  253. }
  254. case GameListItemType::AddDir:
  255. child->setData(
  256. QIcon::fromTheme(QStringLiteral("plus"))
  257. .pixmap(icon_size)
  258. .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation),
  259. Qt::DecorationRole);
  260. break;
  261. case GameListItemType::Favorites:
  262. child->setData(
  263. QIcon::fromTheme(QStringLiteral("star"))
  264. .pixmap(icon_size)
  265. .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation),
  266. Qt::DecorationRole);
  267. break;
  268. default:
  269. break;
  270. }
  271. }
  272. }
  273. void GameList::OnFilterCloseClicked() {
  274. main_window->filterBarSetChecked(false);
  275. }
  276. GameList::GameList(FileSys::VirtualFilesystem vfs, FileSys::ManualContentProvider* provider,
  277. GMainWindow* parent)
  278. : QWidget{parent}, vfs(std::move(vfs)), provider(provider) {
  279. watcher = new QFileSystemWatcher(this);
  280. connect(watcher, &QFileSystemWatcher::directoryChanged, this, &GameList::RefreshGameDirectory);
  281. this->main_window = parent;
  282. layout = new QVBoxLayout;
  283. tree_view = new QTreeView;
  284. search_field = new GameListSearchField(this);
  285. item_model = new QStandardItemModel(tree_view);
  286. tree_view->setModel(item_model);
  287. tree_view->setAlternatingRowColors(true);
  288. tree_view->setSelectionMode(QHeaderView::SingleSelection);
  289. tree_view->setSelectionBehavior(QHeaderView::SelectRows);
  290. tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel);
  291. tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel);
  292. tree_view->setSortingEnabled(true);
  293. tree_view->setEditTriggers(QHeaderView::NoEditTriggers);
  294. tree_view->setContextMenuPolicy(Qt::CustomContextMenu);
  295. tree_view->setStyleSheet(QStringLiteral("QTreeView{ border: none; }"));
  296. item_model->insertColumns(0, COLUMN_COUNT);
  297. item_model->setHeaderData(COLUMN_NAME, Qt::Horizontal, tr("Name"));
  298. item_model->setHeaderData(COLUMN_COMPATIBILITY, Qt::Horizontal, tr("Compatibility"));
  299. item_model->setHeaderData(COLUMN_ADD_ONS, Qt::Horizontal, tr("Add-ons"));
  300. tree_view->setColumnHidden(COLUMN_ADD_ONS, !UISettings::values.show_add_ons);
  301. item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, tr("File type"));
  302. item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, tr("Size"));
  303. item_model->setSortRole(GameListItemPath::SortRole);
  304. connect(main_window, &GMainWindow::UpdateThemedIcons, this, &GameList::OnUpdateThemedIcons);
  305. connect(tree_view, &QTreeView::activated, this, &GameList::ValidateEntry);
  306. connect(tree_view, &QTreeView::customContextMenuRequested, this, &GameList::PopupContextMenu);
  307. connect(tree_view, &QTreeView::expanded, this, &GameList::OnItemExpanded);
  308. connect(tree_view, &QTreeView::collapsed, this, &GameList::OnItemExpanded);
  309. // We must register all custom types with the Qt Automoc system so that we are able to use
  310. // it with signals/slots. In this case, QList falls under the umbrells of custom types.
  311. qRegisterMetaType<QList<QStandardItem*>>("QList<QStandardItem*>");
  312. layout->setContentsMargins(0, 0, 0, 0);
  313. layout->setSpacing(0);
  314. layout->addWidget(tree_view);
  315. layout->addWidget(search_field);
  316. setLayout(layout);
  317. }
  318. GameList::~GameList() {
  319. emit ShouldCancelWorker();
  320. }
  321. void GameList::SetFilterFocus() {
  322. if (tree_view->model()->rowCount() > 0) {
  323. search_field->setFocus();
  324. }
  325. }
  326. void GameList::SetFilterVisible(bool visibility) {
  327. search_field->setVisible(visibility);
  328. }
  329. void GameList::ClearFilter() {
  330. search_field->clear();
  331. }
  332. void GameList::AddDirEntry(GameListDir* entry_items) {
  333. item_model->invisibleRootItem()->appendRow(entry_items);
  334. tree_view->setExpanded(
  335. entry_items->index(),
  336. UISettings::values.game_dirs[entry_items->data(GameListDir::GameDirRole).toInt()].expanded);
  337. }
  338. void GameList::AddEntry(const QList<QStandardItem*>& entry_items, GameListDir* parent) {
  339. parent->appendRow(entry_items);
  340. }
  341. void GameList::ValidateEntry(const QModelIndex& item) {
  342. const auto selected = item.sibling(item.row(), 0);
  343. switch (selected.data(GameListItem::TypeRole).value<GameListItemType>()) {
  344. case GameListItemType::Game: {
  345. const QString file_path = selected.data(GameListItemPath::FullPathRole).toString();
  346. if (file_path.isEmpty())
  347. return;
  348. const QFileInfo file_info(file_path);
  349. if (!file_info.exists())
  350. return;
  351. if (file_info.isDir()) {
  352. const QDir dir{file_path};
  353. const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files);
  354. if (matching_main.size() == 1) {
  355. emit GameChosen(dir.path() + QDir::separator() + matching_main[0]);
  356. }
  357. return;
  358. }
  359. const auto title_id = selected.data(GameListItemPath::ProgramIdRole).toULongLong();
  360. // Users usually want to run a different game after closing one
  361. search_field->clear();
  362. emit GameChosen(file_path, title_id);
  363. break;
  364. }
  365. case GameListItemType::AddDir:
  366. emit AddDirectory();
  367. break;
  368. default:
  369. break;
  370. }
  371. }
  372. bool GameList::IsEmpty() const {
  373. for (int i = 0; i < item_model->rowCount(); i++) {
  374. const QStandardItem* child = item_model->invisibleRootItem()->child(i);
  375. const auto type = static_cast<GameListItemType>(child->type());
  376. if (!child->hasChildren() &&
  377. (type == GameListItemType::SdmcDir || type == GameListItemType::UserNandDir ||
  378. type == GameListItemType::SysNandDir)) {
  379. item_model->invisibleRootItem()->removeRow(child->row());
  380. i--;
  381. }
  382. }
  383. return !item_model->invisibleRootItem()->hasChildren();
  384. }
  385. void GameList::DonePopulating(const QStringList& watch_list) {
  386. emit ShowList(!IsEmpty());
  387. item_model->invisibleRootItem()->appendRow(new GameListAddDir());
  388. item_model->invisibleRootItem()->insertRow(0, new GameListFavorites());
  389. tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(),
  390. UISettings::values.favorited_ids.size() == 0);
  391. tree_view->expand(item_model->invisibleRootItem()->child(0)->index());
  392. for (const auto id : UISettings::values.favorited_ids) {
  393. AddFavorite(id);
  394. }
  395. // Clear out the old directories to watch for changes and add the new ones
  396. auto watch_dirs = watcher->directories();
  397. if (!watch_dirs.isEmpty()) {
  398. watcher->removePaths(watch_dirs);
  399. }
  400. // Workaround: Add the watch paths in chunks to allow the gui to refresh
  401. // This prevents the UI from stalling when a large number of watch paths are added
  402. // Also artificially caps the watcher to a certain number of directories
  403. constexpr int LIMIT_WATCH_DIRECTORIES = 5000;
  404. constexpr int SLICE_SIZE = 25;
  405. int len = std::min(watch_list.length(), LIMIT_WATCH_DIRECTORIES);
  406. for (int i = 0; i < len; i += SLICE_SIZE) {
  407. watcher->addPaths(watch_list.mid(i, i + SLICE_SIZE));
  408. QCoreApplication::processEvents();
  409. }
  410. tree_view->setEnabled(true);
  411. int children_total = 0;
  412. for (int i = 1; i < item_model->rowCount() - 1; ++i) {
  413. children_total += item_model->item(i, 0)->rowCount();
  414. }
  415. search_field->setFilterResult(children_total, children_total);
  416. if (children_total > 0) {
  417. search_field->setFocus();
  418. }
  419. item_model->sort(tree_view->header()->sortIndicatorSection(),
  420. tree_view->header()->sortIndicatorOrder());
  421. }
  422. void GameList::PopupContextMenu(const QPoint& menu_location) {
  423. QModelIndex item = tree_view->indexAt(menu_location);
  424. if (!item.isValid())
  425. return;
  426. const auto selected = item.sibling(item.row(), 0);
  427. QMenu context_menu;
  428. switch (selected.data(GameListItem::TypeRole).value<GameListItemType>()) {
  429. case GameListItemType::Game:
  430. AddGamePopup(context_menu, selected.data(GameListItemPath::ProgramIdRole).toULongLong(),
  431. selected.data(GameListItemPath::FullPathRole).toString().toStdString());
  432. break;
  433. case GameListItemType::CustomDir:
  434. AddPermDirPopup(context_menu, selected);
  435. AddCustomDirPopup(context_menu, selected);
  436. break;
  437. case GameListItemType::SdmcDir:
  438. case GameListItemType::UserNandDir:
  439. case GameListItemType::SysNandDir:
  440. AddPermDirPopup(context_menu, selected);
  441. break;
  442. case GameListItemType::Favorites:
  443. AddFavoritesPopup(context_menu);
  444. break;
  445. default:
  446. break;
  447. }
  448. context_menu.exec(tree_view->viewport()->mapToGlobal(menu_location));
  449. }
  450. void GameList::AddGamePopup(QMenu& context_menu, u64 program_id, const std::string& path) {
  451. QAction* favorite = context_menu.addAction(tr("Favorite"));
  452. context_menu.addSeparator();
  453. QAction* start_game = context_menu.addAction(tr("Start Game"));
  454. QAction* start_game_global =
  455. context_menu.addAction(tr("Start Game without Custom Configuration"));
  456. context_menu.addSeparator();
  457. QAction* open_save_location = context_menu.addAction(tr("Open Save Data Location"));
  458. QAction* open_mod_location = context_menu.addAction(tr("Open Mod Data Location"));
  459. QAction* open_transferable_shader_cache =
  460. context_menu.addAction(tr("Open Transferable Pipeline Cache"));
  461. context_menu.addSeparator();
  462. QMenu* remove_menu = context_menu.addMenu(tr("Remove"));
  463. QAction* remove_update = remove_menu->addAction(tr("Remove Installed Update"));
  464. QAction* remove_dlc = remove_menu->addAction(tr("Remove All Installed DLC"));
  465. QAction* remove_custom_config = remove_menu->addAction(tr("Remove Custom Configuration"));
  466. QAction* remove_gl_shader_cache = remove_menu->addAction(tr("Remove OpenGL Pipeline Cache"));
  467. QAction* remove_vk_shader_cache = remove_menu->addAction(tr("Remove Vulkan Pipeline Cache"));
  468. remove_menu->addSeparator();
  469. QAction* remove_shader_cache = remove_menu->addAction(tr("Remove All Pipeline Caches"));
  470. QAction* remove_all_content = remove_menu->addAction(tr("Remove All Installed Contents"));
  471. QMenu* dump_romfs_menu = context_menu.addMenu(tr("Dump RomFS"));
  472. QAction* dump_romfs = dump_romfs_menu->addAction(tr("Dump RomFS"));
  473. QAction* dump_romfs_sdmc = dump_romfs_menu->addAction(tr("Dump RomFS to SDMC"));
  474. QAction* copy_tid = context_menu.addAction(tr("Copy Title ID to Clipboard"));
  475. QAction* navigate_to_gamedb_entry = context_menu.addAction(tr("Navigate to GameDB entry"));
  476. context_menu.addSeparator();
  477. QAction* properties = context_menu.addAction(tr("Properties"));
  478. favorite->setVisible(program_id != 0);
  479. favorite->setCheckable(true);
  480. favorite->setChecked(UISettings::values.favorited_ids.contains(program_id));
  481. open_save_location->setVisible(program_id != 0);
  482. open_mod_location->setVisible(program_id != 0);
  483. open_transferable_shader_cache->setVisible(program_id != 0);
  484. remove_update->setVisible(program_id != 0);
  485. remove_dlc->setVisible(program_id != 0);
  486. remove_gl_shader_cache->setVisible(program_id != 0);
  487. remove_vk_shader_cache->setVisible(program_id != 0);
  488. remove_shader_cache->setVisible(program_id != 0);
  489. remove_all_content->setVisible(program_id != 0);
  490. auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  491. navigate_to_gamedb_entry->setVisible(it != compatibility_list.end() && program_id != 0);
  492. connect(favorite, &QAction::triggered, [this, program_id]() { ToggleFavorite(program_id); });
  493. connect(open_save_location, &QAction::triggered, [this, program_id, path]() {
  494. emit OpenFolderRequested(program_id, GameListOpenTarget::SaveData, path);
  495. });
  496. connect(start_game, &QAction::triggered, [this, path]() {
  497. emit BootGame(QString::fromStdString(path), 0, 0, StartGameType::Normal);
  498. });
  499. connect(start_game_global, &QAction::triggered, [this, path]() {
  500. emit BootGame(QString::fromStdString(path), 0, 0, StartGameType::Global);
  501. });
  502. connect(open_mod_location, &QAction::triggered, [this, program_id, path]() {
  503. emit OpenFolderRequested(program_id, GameListOpenTarget::ModData, path);
  504. });
  505. connect(open_transferable_shader_cache, &QAction::triggered,
  506. [this, program_id]() { emit OpenTransferableShaderCacheRequested(program_id); });
  507. connect(remove_all_content, &QAction::triggered, [this, program_id]() {
  508. emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::Game);
  509. });
  510. connect(remove_update, &QAction::triggered, [this, program_id]() {
  511. emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::Update);
  512. });
  513. connect(remove_dlc, &QAction::triggered, [this, program_id]() {
  514. emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::AddOnContent);
  515. });
  516. connect(remove_gl_shader_cache, &QAction::triggered, [this, program_id, path]() {
  517. emit RemoveFileRequested(program_id, GameListRemoveTarget::GlShaderCache, path);
  518. });
  519. connect(remove_vk_shader_cache, &QAction::triggered, [this, program_id, path]() {
  520. emit RemoveFileRequested(program_id, GameListRemoveTarget::VkShaderCache, path);
  521. });
  522. connect(remove_shader_cache, &QAction::triggered, [this, program_id, path]() {
  523. emit RemoveFileRequested(program_id, GameListRemoveTarget::AllShaderCache, path);
  524. });
  525. connect(remove_custom_config, &QAction::triggered, [this, program_id, path]() {
  526. emit RemoveFileRequested(program_id, GameListRemoveTarget::CustomConfiguration, path);
  527. });
  528. connect(dump_romfs, &QAction::triggered, [this, program_id, path]() {
  529. emit DumpRomFSRequested(program_id, path, DumpRomFSTarget::Normal);
  530. });
  531. connect(dump_romfs_sdmc, &QAction::triggered, [this, program_id, path]() {
  532. emit DumpRomFSRequested(program_id, path, DumpRomFSTarget::SDMC);
  533. });
  534. connect(copy_tid, &QAction::triggered,
  535. [this, program_id]() { emit CopyTIDRequested(program_id); });
  536. connect(navigate_to_gamedb_entry, &QAction::triggered, [this, program_id]() {
  537. emit NavigateToGamedbEntryRequested(program_id, compatibility_list);
  538. });
  539. connect(properties, &QAction::triggered,
  540. [this, path]() { emit OpenPerGameGeneralRequested(path); });
  541. };
  542. void GameList::AddCustomDirPopup(QMenu& context_menu, QModelIndex selected) {
  543. UISettings::GameDir& game_dir =
  544. UISettings::values.game_dirs[selected.data(GameListDir::GameDirRole).toInt()];
  545. QAction* deep_scan = context_menu.addAction(tr("Scan Subfolders"));
  546. QAction* delete_dir = context_menu.addAction(tr("Remove Game Directory"));
  547. deep_scan->setCheckable(true);
  548. deep_scan->setChecked(game_dir.deep_scan);
  549. connect(deep_scan, &QAction::triggered, [this, &game_dir] {
  550. game_dir.deep_scan = !game_dir.deep_scan;
  551. PopulateAsync(UISettings::values.game_dirs);
  552. });
  553. connect(delete_dir, &QAction::triggered, [this, &game_dir, selected] {
  554. UISettings::values.game_dirs.removeOne(game_dir);
  555. item_model->invisibleRootItem()->removeRow(selected.row());
  556. OnTextChanged(search_field->filterText());
  557. });
  558. }
  559. void GameList::AddPermDirPopup(QMenu& context_menu, QModelIndex selected) {
  560. const int game_dir_index = selected.data(GameListDir::GameDirRole).toInt();
  561. QAction* move_up = context_menu.addAction(tr("\u25B2 Move Up"));
  562. QAction* move_down = context_menu.addAction(tr("\u25bc Move Down"));
  563. QAction* open_directory_location = context_menu.addAction(tr("Open Directory Location"));
  564. const int row = selected.row();
  565. move_up->setEnabled(row > 1);
  566. move_down->setEnabled(row < item_model->rowCount() - 2);
  567. connect(move_up, &QAction::triggered, [this, selected, row, game_dir_index] {
  568. const int other_index = selected.sibling(row - 1, 0).data(GameListDir::GameDirRole).toInt();
  569. // swap the items in the settings
  570. std::swap(UISettings::values.game_dirs[game_dir_index],
  571. UISettings::values.game_dirs[other_index]);
  572. // swap the indexes held by the QVariants
  573. item_model->setData(selected, QVariant(other_index), GameListDir::GameDirRole);
  574. item_model->setData(selected.sibling(row - 1, 0), QVariant(game_dir_index),
  575. GameListDir::GameDirRole);
  576. // move the treeview items
  577. QList<QStandardItem*> item = item_model->takeRow(row);
  578. item_model->invisibleRootItem()->insertRow(row - 1, item);
  579. tree_view->setExpanded(selected.sibling(row - 1, 0),
  580. UISettings::values.game_dirs[other_index].expanded);
  581. });
  582. connect(move_down, &QAction::triggered, [this, selected, row, game_dir_index] {
  583. const int other_index = selected.sibling(row + 1, 0).data(GameListDir::GameDirRole).toInt();
  584. // swap the items in the settings
  585. std::swap(UISettings::values.game_dirs[game_dir_index],
  586. UISettings::values.game_dirs[other_index]);
  587. // swap the indexes held by the QVariants
  588. item_model->setData(selected, QVariant(other_index), GameListDir::GameDirRole);
  589. item_model->setData(selected.sibling(row + 1, 0), QVariant(game_dir_index),
  590. GameListDir::GameDirRole);
  591. // move the treeview items
  592. const QList<QStandardItem*> item = item_model->takeRow(row);
  593. item_model->invisibleRootItem()->insertRow(row + 1, item);
  594. tree_view->setExpanded(selected.sibling(row + 1, 0),
  595. UISettings::values.game_dirs[other_index].expanded);
  596. });
  597. connect(open_directory_location, &QAction::triggered, [this, game_dir_index] {
  598. emit OpenDirectory(UISettings::values.game_dirs[game_dir_index].path);
  599. });
  600. }
  601. void GameList::AddFavoritesPopup(QMenu& context_menu) {
  602. QAction* clear = context_menu.addAction(tr("Clear"));
  603. connect(clear, &QAction::triggered, [this] {
  604. for (const auto id : UISettings::values.favorited_ids) {
  605. RemoveFavorite(id);
  606. }
  607. UISettings::values.favorited_ids.clear();
  608. tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), true);
  609. });
  610. }
  611. void GameList::LoadCompatibilityList() {
  612. QFile compat_list{QStringLiteral(":compatibility_list/compatibility_list.json")};
  613. if (!compat_list.open(QFile::ReadOnly | QFile::Text)) {
  614. LOG_ERROR(Frontend, "Unable to open game compatibility list");
  615. return;
  616. }
  617. if (compat_list.size() == 0) {
  618. LOG_WARNING(Frontend, "Game compatibility list is empty");
  619. return;
  620. }
  621. const QByteArray content = compat_list.readAll();
  622. if (content.isEmpty()) {
  623. LOG_ERROR(Frontend, "Unable to completely read game compatibility list");
  624. return;
  625. }
  626. const QJsonDocument json = QJsonDocument::fromJson(content);
  627. const QJsonArray arr = json.array();
  628. for (const QJsonValue value : arr) {
  629. const QJsonObject game = value.toObject();
  630. const QString compatibility_key = QStringLiteral("compatibility");
  631. if (!game.contains(compatibility_key) || !game[compatibility_key].isDouble()) {
  632. continue;
  633. }
  634. const int compatibility = game[compatibility_key].toInt();
  635. const QString directory = game[QStringLiteral("directory")].toString();
  636. const QJsonArray ids = game[QStringLiteral("releases")].toArray();
  637. for (const QJsonValue id_ref : ids) {
  638. const QJsonObject id_object = id_ref.toObject();
  639. const QString id = id_object[QStringLiteral("id")].toString();
  640. compatibility_list.emplace(id.toUpper().toStdString(),
  641. std::make_pair(QString::number(compatibility), directory));
  642. }
  643. }
  644. }
  645. void GameList::PopulateAsync(QVector<UISettings::GameDir>& game_dirs) {
  646. tree_view->setEnabled(false);
  647. // Update the columns in case UISettings has changed
  648. tree_view->setColumnHidden(COLUMN_ADD_ONS, !UISettings::values.show_add_ons);
  649. // Delete any rows that might already exist if we're repopulating
  650. item_model->removeRows(0, item_model->rowCount());
  651. search_field->clear();
  652. emit ShouldCancelWorker();
  653. GameListWorker* worker = new GameListWorker(vfs, provider, game_dirs, compatibility_list);
  654. connect(worker, &GameListWorker::EntryReady, this, &GameList::AddEntry, Qt::QueuedConnection);
  655. connect(worker, &GameListWorker::DirEntryReady, this, &GameList::AddDirEntry,
  656. Qt::QueuedConnection);
  657. connect(worker, &GameListWorker::Finished, this, &GameList::DonePopulating,
  658. Qt::QueuedConnection);
  659. // Use DirectConnection here because worker->Cancel() is thread-safe and we want it to
  660. // cancel without delay.
  661. connect(this, &GameList::ShouldCancelWorker, worker, &GameListWorker::Cancel,
  662. Qt::DirectConnection);
  663. QThreadPool::globalInstance()->start(worker);
  664. current_worker = std::move(worker);
  665. }
  666. void GameList::SaveInterfaceLayout() {
  667. UISettings::values.gamelist_header_state = tree_view->header()->saveState();
  668. }
  669. void GameList::LoadInterfaceLayout() {
  670. auto* header = tree_view->header();
  671. if (header->restoreState(UISettings::values.gamelist_header_state)) {
  672. return;
  673. }
  674. // We are using the name column to display icons and titles
  675. // so make it as large as possible as default.
  676. header->resizeSection(COLUMN_NAME, header->width());
  677. }
  678. const QStringList GameList::supported_file_extensions = {
  679. QStringLiteral("nso"), QStringLiteral("nro"), QStringLiteral("nca"),
  680. QStringLiteral("xci"), QStringLiteral("nsp"), QStringLiteral("kip")};
  681. void GameList::RefreshGameDirectory() {
  682. if (!UISettings::values.game_dirs.isEmpty() && current_worker != nullptr) {
  683. LOG_INFO(Frontend, "Change detected in the games directory. Reloading game list.");
  684. PopulateAsync(UISettings::values.game_dirs);
  685. }
  686. }
  687. void GameList::ToggleFavorite(u64 program_id) {
  688. if (!UISettings::values.favorited_ids.contains(program_id)) {
  689. tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(),
  690. !search_field->filterText().isEmpty());
  691. UISettings::values.favorited_ids.append(program_id);
  692. AddFavorite(program_id);
  693. item_model->sort(tree_view->header()->sortIndicatorSection(),
  694. tree_view->header()->sortIndicatorOrder());
  695. } else {
  696. UISettings::values.favorited_ids.removeOne(program_id);
  697. RemoveFavorite(program_id);
  698. if (UISettings::values.favorited_ids.size() == 0) {
  699. tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), true);
  700. }
  701. }
  702. }
  703. void GameList::AddFavorite(u64 program_id) {
  704. auto* favorites_row = item_model->item(0);
  705. for (int i = 1; i < item_model->rowCount() - 1; i++) {
  706. const auto* folder = item_model->item(i);
  707. for (int j = 0; j < folder->rowCount(); j++) {
  708. if (folder->child(j)->data(GameListItemPath::ProgramIdRole).toULongLong() ==
  709. program_id) {
  710. QList<QStandardItem*> list;
  711. for (int k = 0; k < COLUMN_COUNT; k++) {
  712. list.append(folder->child(j, k)->clone());
  713. }
  714. list[0]->setData(folder->child(j)->data(GameListItem::SortRole),
  715. GameListItem::SortRole);
  716. list[0]->setText(folder->child(j)->data(Qt::DisplayRole).toString());
  717. favorites_row->appendRow(list);
  718. return;
  719. }
  720. }
  721. }
  722. }
  723. void GameList::RemoveFavorite(u64 program_id) {
  724. auto* favorites_row = item_model->item(0);
  725. for (int i = 0; i < favorites_row->rowCount(); i++) {
  726. const auto* game = favorites_row->child(i);
  727. if (game->data(GameListItemPath::ProgramIdRole).toULongLong() == program_id) {
  728. favorites_row->removeRow(i);
  729. return;
  730. }
  731. }
  732. }
  733. GameListPlaceholder::GameListPlaceholder(GMainWindow* parent) : QWidget{parent} {
  734. connect(parent, &GMainWindow::UpdateThemedIcons, this,
  735. &GameListPlaceholder::onUpdateThemedIcons);
  736. layout = new QVBoxLayout;
  737. image = new QLabel;
  738. text = new QLabel;
  739. layout->setAlignment(Qt::AlignCenter);
  740. image->setPixmap(QIcon::fromTheme(QStringLiteral("plus_folder")).pixmap(200));
  741. text->setText(tr("Double-click to add a new folder to the game list"));
  742. QFont font = text->font();
  743. font.setPointSize(20);
  744. text->setFont(font);
  745. text->setAlignment(Qt::AlignHCenter);
  746. image->setAlignment(Qt::AlignHCenter);
  747. layout->addWidget(image);
  748. layout->addWidget(text);
  749. setLayout(layout);
  750. }
  751. GameListPlaceholder::~GameListPlaceholder() = default;
  752. void GameListPlaceholder::onUpdateThemedIcons() {
  753. image->setPixmap(QIcon::fromTheme(QStringLiteral("plus_folder")).pixmap(200));
  754. }
  755. void GameListPlaceholder::mouseDoubleClickEvent(QMouseEvent* event) {
  756. emit GameListPlaceholder::AddDirectory();
  757. }