game_list.cpp 40 KB

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