game_list.cpp 29 KB

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