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