game_list.cpp 31 KB

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