game_list.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. // Users usually want to run a different game after closing one
  362. search_field->clear();
  363. emit GameChosen(file_path);
  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_shader_cache = remove_menu->addAction(tr("Remove Shader Cache"));
  467. QAction* remove_custom_config = remove_menu->addAction(tr("Remove Custom Configuration"));
  468. remove_menu->addSeparator();
  469. QAction* remove_all_content = remove_menu->addAction(tr("Remove All Installed Contents"));
  470. QMenu* dump_romfs_menu = context_menu.addMenu(tr("Dump RomFS"));
  471. QAction* dump_romfs = dump_romfs_menu->addAction(tr("Dump RomFS"));
  472. QAction* dump_romfs_sdmc = dump_romfs_menu->addAction(tr("Dump RomFS to SDMC"));
  473. QAction* copy_tid = context_menu.addAction(tr("Copy Title ID to Clipboard"));
  474. QAction* navigate_to_gamedb_entry = context_menu.addAction(tr("Navigate to GameDB entry"));
  475. context_menu.addSeparator();
  476. QAction* properties = context_menu.addAction(tr("Properties"));
  477. favorite->setVisible(program_id != 0);
  478. favorite->setCheckable(true);
  479. favorite->setChecked(UISettings::values.favorited_ids.contains(program_id));
  480. open_save_location->setVisible(program_id != 0);
  481. open_mod_location->setVisible(program_id != 0);
  482. open_transferable_shader_cache->setVisible(program_id != 0);
  483. remove_update->setVisible(program_id != 0);
  484. remove_dlc->setVisible(program_id != 0);
  485. remove_shader_cache->setVisible(program_id != 0);
  486. remove_all_content->setVisible(program_id != 0);
  487. auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  488. navigate_to_gamedb_entry->setVisible(it != compatibility_list.end() && program_id != 0);
  489. connect(favorite, &QAction::triggered, [this, program_id]() { ToggleFavorite(program_id); });
  490. connect(open_save_location, &QAction::triggered, [this, program_id, path]() {
  491. emit OpenFolderRequested(program_id, GameListOpenTarget::SaveData, path);
  492. });
  493. connect(start_game, &QAction::triggered, [this, path]() {
  494. emit BootGame(QString::fromStdString(path), 0, StartGameType::Normal);
  495. });
  496. connect(start_game_global, &QAction::triggered, [this, path]() {
  497. emit BootGame(QString::fromStdString(path), 0, StartGameType::Global);
  498. });
  499. connect(open_mod_location, &QAction::triggered, [this, program_id, path]() {
  500. emit OpenFolderRequested(program_id, GameListOpenTarget::ModData, path);
  501. });
  502. connect(open_transferable_shader_cache, &QAction::triggered,
  503. [this, program_id]() { emit OpenTransferableShaderCacheRequested(program_id); });
  504. connect(remove_all_content, &QAction::triggered, [this, program_id]() {
  505. emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::Game);
  506. });
  507. connect(remove_update, &QAction::triggered, [this, program_id]() {
  508. emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::Update);
  509. });
  510. connect(remove_dlc, &QAction::triggered, [this, program_id]() {
  511. emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::AddOnContent);
  512. });
  513. connect(remove_shader_cache, &QAction::triggered, [this, program_id, path]() {
  514. emit RemoveFileRequested(program_id, GameListRemoveTarget::ShaderCache, path);
  515. });
  516. connect(remove_custom_config, &QAction::triggered, [this, program_id, path]() {
  517. emit RemoveFileRequested(program_id, GameListRemoveTarget::CustomConfiguration, path);
  518. });
  519. connect(dump_romfs, &QAction::triggered, [this, program_id, path]() {
  520. emit DumpRomFSRequested(program_id, path, DumpRomFSTarget::Normal);
  521. });
  522. connect(dump_romfs_sdmc, &QAction::triggered, [this, program_id, path]() {
  523. emit DumpRomFSRequested(program_id, path, DumpRomFSTarget::SDMC);
  524. });
  525. connect(copy_tid, &QAction::triggered,
  526. [this, program_id]() { emit CopyTIDRequested(program_id); });
  527. connect(navigate_to_gamedb_entry, &QAction::triggered, [this, program_id]() {
  528. emit NavigateToGamedbEntryRequested(program_id, compatibility_list);
  529. });
  530. connect(properties, &QAction::triggered,
  531. [this, path]() { emit OpenPerGameGeneralRequested(path); });
  532. };
  533. void GameList::AddCustomDirPopup(QMenu& context_menu, QModelIndex selected) {
  534. UISettings::GameDir& game_dir =
  535. UISettings::values.game_dirs[selected.data(GameListDir::GameDirRole).toInt()];
  536. QAction* deep_scan = context_menu.addAction(tr("Scan Subfolders"));
  537. QAction* delete_dir = context_menu.addAction(tr("Remove Game Directory"));
  538. deep_scan->setCheckable(true);
  539. deep_scan->setChecked(game_dir.deep_scan);
  540. connect(deep_scan, &QAction::triggered, [this, &game_dir] {
  541. game_dir.deep_scan = !game_dir.deep_scan;
  542. PopulateAsync(UISettings::values.game_dirs);
  543. });
  544. connect(delete_dir, &QAction::triggered, [this, &game_dir, selected] {
  545. UISettings::values.game_dirs.removeOne(game_dir);
  546. item_model->invisibleRootItem()->removeRow(selected.row());
  547. OnTextChanged(search_field->filterText());
  548. });
  549. }
  550. void GameList::AddPermDirPopup(QMenu& context_menu, QModelIndex selected) {
  551. const int game_dir_index = selected.data(GameListDir::GameDirRole).toInt();
  552. QAction* move_up = context_menu.addAction(tr("\u25B2 Move Up"));
  553. QAction* move_down = context_menu.addAction(tr("\u25bc Move Down"));
  554. QAction* open_directory_location = context_menu.addAction(tr("Open Directory Location"));
  555. const int row = selected.row();
  556. move_up->setEnabled(row > 1);
  557. move_down->setEnabled(row < item_model->rowCount() - 2);
  558. connect(move_up, &QAction::triggered, [this, selected, row, game_dir_index] {
  559. const int other_index = selected.sibling(row - 1, 0).data(GameListDir::GameDirRole).toInt();
  560. // swap the items in the settings
  561. std::swap(UISettings::values.game_dirs[game_dir_index],
  562. UISettings::values.game_dirs[other_index]);
  563. // swap the indexes held by the QVariants
  564. item_model->setData(selected, QVariant(other_index), GameListDir::GameDirRole);
  565. item_model->setData(selected.sibling(row - 1, 0), QVariant(game_dir_index),
  566. GameListDir::GameDirRole);
  567. // move the treeview items
  568. QList<QStandardItem*> item = item_model->takeRow(row);
  569. item_model->invisibleRootItem()->insertRow(row - 1, item);
  570. tree_view->setExpanded(selected.sibling(row - 1, 0),
  571. UISettings::values.game_dirs[other_index].expanded);
  572. });
  573. connect(move_down, &QAction::triggered, [this, selected, row, game_dir_index] {
  574. const int other_index = selected.sibling(row + 1, 0).data(GameListDir::GameDirRole).toInt();
  575. // swap the items in the settings
  576. std::swap(UISettings::values.game_dirs[game_dir_index],
  577. UISettings::values.game_dirs[other_index]);
  578. // swap the indexes held by the QVariants
  579. item_model->setData(selected, QVariant(other_index), GameListDir::GameDirRole);
  580. item_model->setData(selected.sibling(row + 1, 0), QVariant(game_dir_index),
  581. GameListDir::GameDirRole);
  582. // move the treeview items
  583. const QList<QStandardItem*> item = item_model->takeRow(row);
  584. item_model->invisibleRootItem()->insertRow(row + 1, item);
  585. tree_view->setExpanded(selected.sibling(row + 1, 0),
  586. UISettings::values.game_dirs[other_index].expanded);
  587. });
  588. connect(open_directory_location, &QAction::triggered, [this, game_dir_index] {
  589. emit OpenDirectory(UISettings::values.game_dirs[game_dir_index].path);
  590. });
  591. }
  592. void GameList::AddFavoritesPopup(QMenu& context_menu) {
  593. QAction* clear = context_menu.addAction(tr("Clear"));
  594. connect(clear, &QAction::triggered, [this] {
  595. for (const auto id : UISettings::values.favorited_ids) {
  596. RemoveFavorite(id);
  597. }
  598. UISettings::values.favorited_ids.clear();
  599. tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), true);
  600. });
  601. }
  602. void GameList::LoadCompatibilityList() {
  603. QFile compat_list{QStringLiteral(":compatibility_list/compatibility_list.json")};
  604. if (!compat_list.open(QFile::ReadOnly | QFile::Text)) {
  605. LOG_ERROR(Frontend, "Unable to open game compatibility list");
  606. return;
  607. }
  608. if (compat_list.size() == 0) {
  609. LOG_WARNING(Frontend, "Game compatibility list is empty");
  610. return;
  611. }
  612. const QByteArray content = compat_list.readAll();
  613. if (content.isEmpty()) {
  614. LOG_ERROR(Frontend, "Unable to completely read game compatibility list");
  615. return;
  616. }
  617. const QJsonDocument json = QJsonDocument::fromJson(content);
  618. const QJsonArray arr = json.array();
  619. for (const QJsonValue value : arr) {
  620. const QJsonObject game = value.toObject();
  621. const QString compatibility_key = QStringLiteral("compatibility");
  622. if (!game.contains(compatibility_key) || !game[compatibility_key].isDouble()) {
  623. continue;
  624. }
  625. const int compatibility = game[compatibility_key].toInt();
  626. const QString directory = game[QStringLiteral("directory")].toString();
  627. const QJsonArray ids = game[QStringLiteral("releases")].toArray();
  628. for (const QJsonValue id_ref : ids) {
  629. const QJsonObject id_object = id_ref.toObject();
  630. const QString id = id_object[QStringLiteral("id")].toString();
  631. compatibility_list.emplace(id.toUpper().toStdString(),
  632. std::make_pair(QString::number(compatibility), directory));
  633. }
  634. }
  635. }
  636. void GameList::PopulateAsync(QVector<UISettings::GameDir>& game_dirs) {
  637. tree_view->setEnabled(false);
  638. // Update the columns in case UISettings has changed
  639. tree_view->setColumnHidden(COLUMN_ADD_ONS, !UISettings::values.show_add_ons);
  640. // Delete any rows that might already exist if we're repopulating
  641. item_model->removeRows(0, item_model->rowCount());
  642. search_field->clear();
  643. emit ShouldCancelWorker();
  644. GameListWorker* worker = new GameListWorker(vfs, provider, game_dirs, compatibility_list);
  645. connect(worker, &GameListWorker::EntryReady, this, &GameList::AddEntry, Qt::QueuedConnection);
  646. connect(worker, &GameListWorker::DirEntryReady, this, &GameList::AddDirEntry,
  647. Qt::QueuedConnection);
  648. connect(worker, &GameListWorker::Finished, this, &GameList::DonePopulating,
  649. Qt::QueuedConnection);
  650. // Use DirectConnection here because worker->Cancel() is thread-safe and we want it to
  651. // cancel without delay.
  652. connect(this, &GameList::ShouldCancelWorker, worker, &GameListWorker::Cancel,
  653. Qt::DirectConnection);
  654. QThreadPool::globalInstance()->start(worker);
  655. current_worker = std::move(worker);
  656. }
  657. void GameList::SaveInterfaceLayout() {
  658. UISettings::values.gamelist_header_state = tree_view->header()->saveState();
  659. }
  660. void GameList::LoadInterfaceLayout() {
  661. auto* header = tree_view->header();
  662. if (header->restoreState(UISettings::values.gamelist_header_state)) {
  663. return;
  664. }
  665. // We are using the name column to display icons and titles
  666. // so make it as large as possible as default.
  667. header->resizeSection(COLUMN_NAME, header->width());
  668. }
  669. const QStringList GameList::supported_file_extensions = {
  670. QStringLiteral("nso"), QStringLiteral("nro"), QStringLiteral("nca"),
  671. QStringLiteral("xci"), QStringLiteral("nsp"), QStringLiteral("kip")};
  672. void GameList::RefreshGameDirectory() {
  673. if (!UISettings::values.game_dirs.isEmpty() && current_worker != nullptr) {
  674. LOG_INFO(Frontend, "Change detected in the games directory. Reloading game list.");
  675. PopulateAsync(UISettings::values.game_dirs);
  676. }
  677. }
  678. void GameList::ToggleFavorite(u64 program_id) {
  679. if (!UISettings::values.favorited_ids.contains(program_id)) {
  680. tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(),
  681. !search_field->filterText().isEmpty());
  682. UISettings::values.favorited_ids.append(program_id);
  683. AddFavorite(program_id);
  684. item_model->sort(tree_view->header()->sortIndicatorSection(),
  685. tree_view->header()->sortIndicatorOrder());
  686. } else {
  687. UISettings::values.favorited_ids.removeOne(program_id);
  688. RemoveFavorite(program_id);
  689. if (UISettings::values.favorited_ids.size() == 0) {
  690. tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), true);
  691. }
  692. }
  693. }
  694. void GameList::AddFavorite(u64 program_id) {
  695. auto* favorites_row = item_model->item(0);
  696. for (int i = 1; i < item_model->rowCount() - 1; i++) {
  697. const auto* folder = item_model->item(i);
  698. for (int j = 0; j < folder->rowCount(); j++) {
  699. if (folder->child(j)->data(GameListItemPath::ProgramIdRole).toULongLong() ==
  700. program_id) {
  701. QList<QStandardItem*> list;
  702. for (int k = 0; k < COLUMN_COUNT; k++) {
  703. list.append(folder->child(j, k)->clone());
  704. }
  705. list[0]->setData(folder->child(j)->data(GameListItem::SortRole),
  706. GameListItem::SortRole);
  707. list[0]->setText(folder->child(j)->data(Qt::DisplayRole).toString());
  708. favorites_row->appendRow(list);
  709. return;
  710. }
  711. }
  712. }
  713. }
  714. void GameList::RemoveFavorite(u64 program_id) {
  715. auto* favorites_row = item_model->item(0);
  716. for (int i = 0; i < favorites_row->rowCount(); i++) {
  717. const auto* game = favorites_row->child(i);
  718. if (game->data(GameListItemPath::ProgramIdRole).toULongLong() == program_id) {
  719. favorites_row->removeRow(i);
  720. return;
  721. }
  722. }
  723. }
  724. GameListPlaceholder::GameListPlaceholder(GMainWindow* parent) : QWidget{parent} {
  725. connect(parent, &GMainWindow::UpdateThemedIcons, this,
  726. &GameListPlaceholder::onUpdateThemedIcons);
  727. layout = new QVBoxLayout;
  728. image = new QLabel;
  729. text = new QLabel;
  730. layout->setAlignment(Qt::AlignCenter);
  731. image->setPixmap(QIcon::fromTheme(QStringLiteral("plus_folder")).pixmap(200));
  732. text->setText(tr("Double-click to add a new folder to the game list"));
  733. QFont font = text->font();
  734. font.setPointSize(20);
  735. text->setFont(font);
  736. text->setAlignment(Qt::AlignHCenter);
  737. image->setAlignment(Qt::AlignHCenter);
  738. layout->addWidget(image);
  739. layout->addWidget(text);
  740. setLayout(layout);
  741. }
  742. GameListPlaceholder::~GameListPlaceholder() = default;
  743. void GameListPlaceholder::onUpdateThemedIcons() {
  744. image->setPixmap(QIcon::fromTheme(QStringLiteral("plus_folder")).pixmap(200));
  745. }
  746. void GameListPlaceholder::mouseDoubleClickEvent(QMouseEvent* event) {
  747. emit GameListPlaceholder::AddDirectory();
  748. }