game_list.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <QApplication>
  5. #include <QDir>
  6. #include <QFileInfo>
  7. #include <QHeaderView>
  8. #include <QKeyEvent>
  9. #include <QMenu>
  10. #include <QThreadPool>
  11. #include <boost/container/flat_map.hpp>
  12. #include "common/common_paths.h"
  13. #include "common/logging/log.h"
  14. #include "common/string_util.h"
  15. #include "core/file_sys/content_archive.h"
  16. #include "core/file_sys/control_metadata.h"
  17. #include "core/file_sys/vfs_real.h"
  18. #include "core/loader/loader.h"
  19. #include "game_list.h"
  20. #include "game_list_p.h"
  21. #include "ui_settings.h"
  22. GameList::SearchField::KeyReleaseEater::KeyReleaseEater(GameList* gamelist) : gamelist{gamelist} {}
  23. // EventFilter in order to process systemkeys while editing the searchfield
  24. bool GameList::SearchField::KeyReleaseEater::eventFilter(QObject* obj, QEvent* event) {
  25. // If it isn't a KeyRelease event then continue with standard event processing
  26. if (event->type() != QEvent::KeyRelease)
  27. return QObject::eventFilter(obj, event);
  28. QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
  29. int rowCount = gamelist->tree_view->model()->rowCount();
  30. QString edit_filter_text = gamelist->search_field->edit_filter->text().toLower();
  31. // If the searchfield's text hasn't changed special function keys get checked
  32. // If no function key changes the searchfield's text the filter doesn't need to get reloaded
  33. if (edit_filter_text == edit_filter_text_old) {
  34. switch (keyEvent->key()) {
  35. // Escape: Resets the searchfield
  36. case Qt::Key_Escape: {
  37. if (edit_filter_text_old.isEmpty()) {
  38. return QObject::eventFilter(obj, event);
  39. } else {
  40. gamelist->search_field->edit_filter->clear();
  41. edit_filter_text = "";
  42. }
  43. break;
  44. }
  45. // Return and Enter
  46. // If the enter key gets pressed first checks how many and which entry is visible
  47. // If there is only one result launch this game
  48. case Qt::Key_Return:
  49. case Qt::Key_Enter: {
  50. QStandardItemModel* item_model = new QStandardItemModel(gamelist->tree_view);
  51. QModelIndex root_index = item_model->invisibleRootItem()->index();
  52. QStandardItem* child_file;
  53. QString file_path;
  54. int resultCount = 0;
  55. for (int i = 0; i < rowCount; ++i) {
  56. if (!gamelist->tree_view->isRowHidden(i, root_index)) {
  57. ++resultCount;
  58. child_file = gamelist->item_model->item(i, 0);
  59. file_path = child_file->data(GameListItemPath::FullPathRole).toString();
  60. }
  61. }
  62. if (resultCount == 1) {
  63. // To avoid loading error dialog loops while confirming them using enter
  64. // Also users usually want to run a diffrent game after closing one
  65. gamelist->search_field->edit_filter->setText("");
  66. edit_filter_text = "";
  67. emit gamelist->GameChosen(file_path);
  68. } else {
  69. return QObject::eventFilter(obj, event);
  70. }
  71. break;
  72. }
  73. default:
  74. return QObject::eventFilter(obj, event);
  75. }
  76. }
  77. edit_filter_text_old = edit_filter_text;
  78. return QObject::eventFilter(obj, event);
  79. }
  80. void GameList::SearchField::setFilterResult(int visible, int total) {
  81. QString result_of_text = tr("of");
  82. QString result_text;
  83. if (total == 1) {
  84. result_text = tr("result");
  85. } else {
  86. result_text = tr("results");
  87. }
  88. label_filter_result->setText(
  89. QString("%1 %2 %3 %4").arg(visible).arg(result_of_text).arg(total).arg(result_text));
  90. }
  91. void GameList::SearchField::clear() {
  92. edit_filter->setText("");
  93. }
  94. void GameList::SearchField::setFocus() {
  95. if (edit_filter->isVisible()) {
  96. edit_filter->setFocus();
  97. }
  98. }
  99. GameList::SearchField::SearchField(GameList* parent) : QWidget{parent} {
  100. KeyReleaseEater* keyReleaseEater = new KeyReleaseEater(parent);
  101. layout_filter = new QHBoxLayout;
  102. layout_filter->setMargin(8);
  103. label_filter = new QLabel;
  104. label_filter->setText(tr("Filter:"));
  105. edit_filter = new QLineEdit;
  106. edit_filter->setText("");
  107. edit_filter->setPlaceholderText(tr("Enter pattern to filter"));
  108. edit_filter->installEventFilter(keyReleaseEater);
  109. edit_filter->setClearButtonEnabled(true);
  110. connect(edit_filter, &QLineEdit::textChanged, parent, &GameList::onTextChanged);
  111. label_filter_result = new QLabel;
  112. button_filter_close = new QToolButton(this);
  113. button_filter_close->setText("X");
  114. button_filter_close->setCursor(Qt::ArrowCursor);
  115. button_filter_close->setStyleSheet("QToolButton{ border: none; padding: 0px; color: "
  116. "#000000; font-weight: bold; background: #F0F0F0; }"
  117. "QToolButton:hover{ border: none; padding: 0px; color: "
  118. "#EEEEEE; font-weight: bold; background: #E81123}");
  119. connect(button_filter_close, &QToolButton::clicked, parent, &GameList::onFilterCloseClicked);
  120. layout_filter->setSpacing(10);
  121. layout_filter->addWidget(label_filter);
  122. layout_filter->addWidget(edit_filter);
  123. layout_filter->addWidget(label_filter_result);
  124. layout_filter->addWidget(button_filter_close);
  125. setLayout(layout_filter);
  126. }
  127. /**
  128. * Checks if all words separated by spaces are contained in another string
  129. * This offers a word order insensitive search function
  130. *
  131. * @param haystack String that gets checked if it contains all words of the userinput string
  132. * @param userinput String containing all words getting checked
  133. * @return true if the haystack contains all words of userinput
  134. */
  135. static bool ContainsAllWords(const QString& haystack, const QString& userinput) {
  136. const QStringList userinput_split =
  137. userinput.split(' ', QString::SplitBehavior::SkipEmptyParts);
  138. return std::all_of(userinput_split.begin(), userinput_split.end(),
  139. [&haystack](const QString& s) { return haystack.contains(s); });
  140. }
  141. // Event in order to filter the gamelist after editing the searchfield
  142. void GameList::onTextChanged(const QString& newText) {
  143. int rowCount = tree_view->model()->rowCount();
  144. QString edit_filter_text = newText.toLower();
  145. QModelIndex root_index = item_model->invisibleRootItem()->index();
  146. // If the searchfield is empty every item is visible
  147. // Otherwise the filter gets applied
  148. if (edit_filter_text.isEmpty()) {
  149. for (int i = 0; i < rowCount; ++i) {
  150. tree_view->setRowHidden(i, root_index, false);
  151. }
  152. search_field->setFilterResult(rowCount, rowCount);
  153. } else {
  154. int result_count = 0;
  155. for (int i = 0; i < rowCount; ++i) {
  156. const QStandardItem* child_file = item_model->item(i, 0);
  157. const QString file_path =
  158. child_file->data(GameListItemPath::FullPathRole).toString().toLower();
  159. QString file_name = file_path.mid(file_path.lastIndexOf('/') + 1);
  160. const QString file_title =
  161. child_file->data(GameListItemPath::TitleRole).toString().toLower();
  162. const QString file_programmid =
  163. child_file->data(GameListItemPath::ProgramIdRole).toString().toLower();
  164. // Only items which filename in combination with its title contains all words
  165. // that are in the searchfield will be visible in the gamelist
  166. // The search is case insensitive because of toLower()
  167. // I decided not to use Qt::CaseInsensitive in containsAllWords to prevent
  168. // multiple conversions of edit_filter_text for each game in the gamelist
  169. if (ContainsAllWords(file_name.append(' ').append(file_title), edit_filter_text) ||
  170. (file_programmid.count() == 16 && edit_filter_text.contains(file_programmid))) {
  171. tree_view->setRowHidden(i, root_index, false);
  172. ++result_count;
  173. } else {
  174. tree_view->setRowHidden(i, root_index, true);
  175. }
  176. search_field->setFilterResult(result_count, rowCount);
  177. }
  178. }
  179. }
  180. void GameList::onFilterCloseClicked() {
  181. main_window->filterBarSetChecked(false);
  182. }
  183. GameList::GameList(FileSys::VirtualFilesystem vfs, GMainWindow* parent)
  184. : QWidget{parent}, vfs(std::move(vfs)) {
  185. watcher = new QFileSystemWatcher(this);
  186. connect(watcher, &QFileSystemWatcher::directoryChanged, this, &GameList::RefreshGameDirectory);
  187. this->main_window = parent;
  188. layout = new QVBoxLayout;
  189. tree_view = new QTreeView;
  190. search_field = new SearchField(this);
  191. item_model = new QStandardItemModel(tree_view);
  192. tree_view->setModel(item_model);
  193. tree_view->setAlternatingRowColors(true);
  194. tree_view->setSelectionMode(QHeaderView::SingleSelection);
  195. tree_view->setSelectionBehavior(QHeaderView::SelectRows);
  196. tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel);
  197. tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel);
  198. tree_view->setSortingEnabled(true);
  199. tree_view->setEditTriggers(QHeaderView::NoEditTriggers);
  200. tree_view->setUniformRowHeights(true);
  201. tree_view->setContextMenuPolicy(Qt::CustomContextMenu);
  202. item_model->insertColumns(0, COLUMN_COUNT);
  203. item_model->setHeaderData(COLUMN_NAME, Qt::Horizontal, "Name");
  204. item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, "File type");
  205. item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, "Size");
  206. connect(tree_view, &QTreeView::activated, this, &GameList::ValidateEntry);
  207. connect(tree_view, &QTreeView::customContextMenuRequested, this, &GameList::PopupContextMenu);
  208. // We must register all custom types with the Qt Automoc system so that we are able to use it
  209. // with signals/slots. In this case, QList falls under the umbrells of custom types.
  210. qRegisterMetaType<QList<QStandardItem*>>("QList<QStandardItem*>");
  211. layout->setContentsMargins(0, 0, 0, 0);
  212. layout->setSpacing(0);
  213. layout->addWidget(tree_view);
  214. layout->addWidget(search_field);
  215. setLayout(layout);
  216. }
  217. GameList::~GameList() {
  218. emit ShouldCancelWorker();
  219. }
  220. void GameList::setFilterFocus() {
  221. if (tree_view->model()->rowCount() > 0) {
  222. search_field->setFocus();
  223. }
  224. }
  225. void GameList::setFilterVisible(bool visibility) {
  226. search_field->setVisible(visibility);
  227. }
  228. void GameList::clearFilter() {
  229. search_field->clear();
  230. }
  231. void GameList::AddEntry(const QList<QStandardItem*>& entry_items) {
  232. item_model->invisibleRootItem()->appendRow(entry_items);
  233. }
  234. void GameList::ValidateEntry(const QModelIndex& item) {
  235. // We don't care about the individual QStandardItem that was selected, but its row.
  236. const int row = item_model->itemFromIndex(item)->row();
  237. const QStandardItem* child_file = item_model->invisibleRootItem()->child(row, COLUMN_NAME);
  238. const QString file_path = child_file->data(GameListItemPath::FullPathRole).toString();
  239. if (file_path.isEmpty())
  240. return;
  241. if (!QFileInfo::exists(file_path))
  242. return;
  243. const QFileInfo file_info{file_path};
  244. if (file_info.isDir()) {
  245. const QDir dir{file_path};
  246. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  247. if (matching_main.size() == 1) {
  248. emit GameChosen(dir.path() + DIR_SEP + matching_main[0]);
  249. }
  250. return;
  251. }
  252. // Users usually want to run a diffrent game after closing one
  253. search_field->clear();
  254. emit GameChosen(file_path);
  255. }
  256. void GameList::DonePopulating(QStringList watch_list) {
  257. // Clear out the old directories to watch for changes and add the new ones
  258. auto watch_dirs = watcher->directories();
  259. if (!watch_dirs.isEmpty()) {
  260. watcher->removePaths(watch_dirs);
  261. }
  262. // Workaround: Add the watch paths in chunks to allow the gui to refresh
  263. // This prevents the UI from stalling when a large number of watch paths are added
  264. // Also artificially caps the watcher to a certain number of directories
  265. constexpr int LIMIT_WATCH_DIRECTORIES = 5000;
  266. constexpr int SLICE_SIZE = 25;
  267. int len = std::min(watch_list.length(), LIMIT_WATCH_DIRECTORIES);
  268. for (int i = 0; i < len; i += SLICE_SIZE) {
  269. watcher->addPaths(watch_list.mid(i, i + SLICE_SIZE));
  270. QCoreApplication::processEvents();
  271. }
  272. tree_view->setEnabled(true);
  273. int rowCount = tree_view->model()->rowCount();
  274. search_field->setFilterResult(rowCount, rowCount);
  275. if (rowCount > 0) {
  276. search_field->setFocus();
  277. }
  278. }
  279. void GameList::PopupContextMenu(const QPoint& menu_location) {
  280. QModelIndex item = tree_view->indexAt(menu_location);
  281. if (!item.isValid())
  282. return;
  283. int row = item_model->itemFromIndex(item)->row();
  284. QStandardItem* child_file = item_model->invisibleRootItem()->child(row, COLUMN_NAME);
  285. u64 program_id = child_file->data(GameListItemPath::ProgramIdRole).toULongLong();
  286. QMenu context_menu;
  287. QAction* open_save_location = context_menu.addAction(tr("Open Save Data Location"));
  288. open_save_location->setEnabled(program_id != 0);
  289. connect(open_save_location, &QAction::triggered,
  290. [&]() { emit OpenSaveFolderRequested(program_id); });
  291. context_menu.exec(tree_view->viewport()->mapToGlobal(menu_location));
  292. }
  293. void GameList::PopulateAsync(const QString& dir_path, bool deep_scan) {
  294. if (!FileUtil::Exists(dir_path.toStdString()) ||
  295. !FileUtil::IsDirectory(dir_path.toStdString())) {
  296. LOG_ERROR(Frontend, "Could not find game list folder at {}", dir_path.toLocal8Bit().data());
  297. search_field->setFilterResult(0, 0);
  298. return;
  299. }
  300. tree_view->setEnabled(false);
  301. // Delete any rows that might already exist if we're repopulating
  302. item_model->removeRows(0, item_model->rowCount());
  303. emit ShouldCancelWorker();
  304. GameListWorker* worker = new GameListWorker(vfs, dir_path, deep_scan);
  305. connect(worker, &GameListWorker::EntryReady, this, &GameList::AddEntry, Qt::QueuedConnection);
  306. connect(worker, &GameListWorker::Finished, this, &GameList::DonePopulating,
  307. Qt::QueuedConnection);
  308. // Use DirectConnection here because worker->Cancel() is thread-safe and we want it to cancel
  309. // without delay.
  310. connect(this, &GameList::ShouldCancelWorker, worker, &GameListWorker::Cancel,
  311. Qt::DirectConnection);
  312. QThreadPool::globalInstance()->start(worker);
  313. current_worker = std::move(worker);
  314. }
  315. void GameList::SaveInterfaceLayout() {
  316. UISettings::values.gamelist_header_state = tree_view->header()->saveState();
  317. }
  318. void GameList::LoadInterfaceLayout() {
  319. auto header = tree_view->header();
  320. if (!header->restoreState(UISettings::values.gamelist_header_state)) {
  321. // We are using the name column to display icons and titles
  322. // so make it as large as possible as default.
  323. header->resizeSection(COLUMN_NAME, header->width());
  324. }
  325. item_model->sort(header->sortIndicatorSection(), header->sortIndicatorOrder());
  326. }
  327. const QStringList GameList::supported_file_extensions = {"nso", "nro", "nca", "xci"};
  328. static bool HasSupportedFileExtension(const std::string& file_name) {
  329. const QFileInfo file = QFileInfo(QString::fromStdString(file_name));
  330. return GameList::supported_file_extensions.contains(file.suffix(), Qt::CaseInsensitive);
  331. }
  332. static bool IsExtractedNCAMain(const std::string& file_name) {
  333. return QFileInfo(QString::fromStdString(file_name)).fileName() == "main";
  334. }
  335. static QString FormatGameName(const std::string& physical_name) {
  336. const QString physical_name_as_qstring = QString::fromStdString(physical_name);
  337. const QFileInfo file_info(physical_name_as_qstring);
  338. if (IsExtractedNCAMain(physical_name)) {
  339. return file_info.dir().path();
  340. }
  341. return physical_name_as_qstring;
  342. }
  343. void GameList::RefreshGameDirectory() {
  344. if (!UISettings::values.gamedir.isEmpty() && current_worker != nullptr) {
  345. LOG_INFO(Frontend, "Change detected in the games directory. Reloading game list.");
  346. search_field->clear();
  347. PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  348. }
  349. }
  350. void GameListWorker::AddFstEntriesToGameList(const std::string& dir_path, unsigned int recursion) {
  351. boost::container::flat_map<u64, std::shared_ptr<FileSys::NCA>> nca_control_map;
  352. const auto nca_control_callback =
  353. [this, &nca_control_map](u64* num_entries_out, const std::string& directory,
  354. const std::string& virtual_name) -> bool {
  355. std::string physical_name = directory + DIR_SEP + virtual_name;
  356. if (stop_processing)
  357. return false; // Breaks the callback loop.
  358. bool is_dir = FileUtil::IsDirectory(physical_name);
  359. QFileInfo file_info(physical_name.c_str());
  360. if (!is_dir && file_info.suffix().toStdString() == "nca") {
  361. auto nca = std::make_shared<FileSys::NCA>(
  362. std::make_shared<FileSys::RealVfsFile>(physical_name));
  363. if (nca->GetType() == FileSys::NCAContentType::Control)
  364. nca_control_map.insert_or_assign(nca->GetTitleId(), nca);
  365. }
  366. return true;
  367. };
  368. FileUtil::ForeachDirectoryEntry(nullptr, dir_path, nca_control_callback);
  369. const auto callback = [this, recursion,
  370. &nca_control_map](u64* num_entries_out, const std::string& directory,
  371. const std::string& virtual_name) -> bool {
  372. std::string physical_name = directory + DIR_SEP + virtual_name;
  373. if (stop_processing)
  374. return false; // Breaks the callback loop.
  375. bool is_dir = FileUtil::IsDirectory(physical_name);
  376. if (!is_dir &&
  377. (HasSupportedFileExtension(physical_name) || IsExtractedNCAMain(physical_name))) {
  378. std::unique_ptr<Loader::AppLoader> loader =
  379. Loader::GetLoader(vfs->OpenFile(physical_name, FileSys::Mode::Read));
  380. if (!loader || ((loader->GetFileType() == Loader::FileType::Unknown ||
  381. loader->GetFileType() == Loader::FileType::Error) &&
  382. !UISettings::values.show_unknown))
  383. return true;
  384. std::vector<u8> icon;
  385. const auto res1 = loader->ReadIcon(icon);
  386. u64 program_id;
  387. const auto res2 = loader->ReadProgramId(program_id);
  388. std::string name = " ";
  389. const auto res3 = loader->ReadTitle(name);
  390. if ((res1 == Loader::ResultStatus::ErrorNotUsed ||
  391. res1 == Loader::ResultStatus::ErrorNotImplemented) &&
  392. (res3 == Loader::ResultStatus::ErrorNotUsed ||
  393. res3 == Loader::ResultStatus::ErrorNotImplemented) &&
  394. res2 == Loader::ResultStatus::Success) {
  395. // Use from metadata pool.
  396. if (nca_control_map.find(program_id) != nca_control_map.end()) {
  397. const auto nca = nca_control_map[program_id];
  398. const auto control_dir = nca->GetSubdirectories()[0];
  399. const auto nacp_file = control_dir->GetFile("control.nacp");
  400. FileSys::NACP nacp(nacp_file);
  401. name = nacp.GetApplicationName();
  402. FileSys::VirtualFile icon_file = nullptr;
  403. for (const auto& language : FileSys::LANGUAGE_NAMES) {
  404. icon_file = control_dir->GetFile("icon_" + std::string(language) + ".dat");
  405. if (icon_file != nullptr) {
  406. icon = icon_file->ReadAllBytes();
  407. break;
  408. }
  409. }
  410. }
  411. }
  412. emit EntryReady({
  413. new GameListItemPath(
  414. FormatGameName(physical_name), icon, QString::fromStdString(name),
  415. QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType())),
  416. program_id),
  417. new GameListItem(
  418. QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType()))),
  419. new GameListItemSize(FileUtil::GetSize(physical_name)),
  420. });
  421. } else if (is_dir && recursion > 0) {
  422. watch_list.append(QString::fromStdString(physical_name));
  423. AddFstEntriesToGameList(physical_name, recursion - 1);
  424. }
  425. return true;
  426. };
  427. FileUtil::ForeachDirectoryEntry(nullptr, dir_path, callback);
  428. }
  429. void GameListWorker::run() {
  430. stop_processing = false;
  431. watch_list.append(dir_path);
  432. AddFstEntriesToGameList(dir_path.toStdString(), deep_scan ? 256 : 0);
  433. emit Finished(watch_list);
  434. }
  435. void GameListWorker::Cancel() {
  436. this->disconnect();
  437. stop_processing = true;
  438. }