game_list.cpp 17 KB

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