game_list.cpp 36 KB

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