game_list.cpp 40 KB

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