game_list.cpp 37 KB

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