game_list.cpp 36 KB

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