game_list.cpp 39 KB

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