game_list.cpp 38 KB

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