game_list.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 <QFileInfo>
  6. #include <QHeaderView>
  7. #include <QKeyEvent>
  8. #include <QMenu>
  9. #include <QThreadPool>
  10. #include "common/common_paths.h"
  11. #include "common/logging/log.h"
  12. #include "common/string_util.h"
  13. #include "core/loader/loader.h"
  14. #include "game_list.h"
  15. #include "game_list_p.h"
  16. #include "ui_settings.h"
  17. GameList::SearchField::KeyReleaseEater::KeyReleaseEater(GameList* gamelist) {
  18. this->gamelist = gamelist;
  19. edit_filter_text_old = "";
  20. }
  21. // EventFilter in order to process systemkeys while editing the searchfield
  22. bool GameList::SearchField::KeyReleaseEater::eventFilter(QObject* obj, QEvent* event) {
  23. // If it isn't a KeyRelease event then continue with standard event processing
  24. if (event->type() != QEvent::KeyRelease)
  25. return QObject::eventFilter(obj, event);
  26. QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
  27. int rowCount = gamelist->tree_view->model()->rowCount();
  28. QString edit_filter_text = gamelist->search_field->edit_filter->text().toLower();
  29. // If the searchfield's text hasn't changed special function keys get checked
  30. // If no function key changes the searchfield's text the filter doesn't need to get reloaded
  31. if (edit_filter_text == edit_filter_text_old) {
  32. switch (keyEvent->key()) {
  33. // Escape: Resets the searchfield
  34. case Qt::Key_Escape: {
  35. if (edit_filter_text_old.isEmpty()) {
  36. return QObject::eventFilter(obj, event);
  37. } else {
  38. gamelist->search_field->edit_filter->clear();
  39. edit_filter_text = "";
  40. }
  41. break;
  42. }
  43. // Return and Enter
  44. // If the enter key gets pressed first checks how many and which entry is visible
  45. // If there is only one result launch this game
  46. case Qt::Key_Return:
  47. case Qt::Key_Enter: {
  48. QStandardItemModel* item_model = new QStandardItemModel(gamelist->tree_view);
  49. QModelIndex root_index = item_model->invisibleRootItem()->index();
  50. QStandardItem* child_file;
  51. QString file_path;
  52. int resultCount = 0;
  53. for (int i = 0; i < rowCount; ++i) {
  54. if (!gamelist->tree_view->isRowHidden(i, root_index)) {
  55. ++resultCount;
  56. child_file = gamelist->item_model->item(i, 0);
  57. file_path = child_file->data(GameListItemPath::FullPathRole).toString();
  58. }
  59. }
  60. if (resultCount == 1) {
  61. // To avoid loading error dialog loops while confirming them using enter
  62. // Also users usually want to run a diffrent game after closing one
  63. gamelist->search_field->edit_filter->setText("");
  64. edit_filter_text = "";
  65. emit gamelist->GameChosen(file_path);
  66. } else {
  67. return QObject::eventFilter(obj, event);
  68. }
  69. break;
  70. }
  71. default:
  72. return QObject::eventFilter(obj, event);
  73. }
  74. }
  75. edit_filter_text_old = edit_filter_text;
  76. return QObject::eventFilter(obj, event);
  77. }
  78. void GameList::SearchField::setFilterResult(int visible, int total) {
  79. QString result_of_text = tr("of");
  80. QString result_text;
  81. if (total == 1) {
  82. result_text = tr("result");
  83. } else {
  84. result_text = tr("results");
  85. }
  86. label_filter_result->setText(
  87. QString("%1 %2 %3 %4").arg(visible).arg(result_of_text).arg(total).arg(result_text));
  88. }
  89. void GameList::SearchField::clear() {
  90. edit_filter->setText("");
  91. }
  92. void GameList::SearchField::setFocus() {
  93. if (edit_filter->isVisible()) {
  94. edit_filter->setFocus();
  95. }
  96. }
  97. GameList::SearchField::SearchField(GameList* parent) : QWidget{parent} {
  98. KeyReleaseEater* keyReleaseEater = new KeyReleaseEater(parent);
  99. layout_filter = new QHBoxLayout;
  100. layout_filter->setMargin(8);
  101. label_filter = new QLabel;
  102. label_filter->setText(tr("Filter:"));
  103. edit_filter = new QLineEdit;
  104. edit_filter->setText("");
  105. edit_filter->setPlaceholderText(tr("Enter pattern to filter"));
  106. edit_filter->installEventFilter(keyReleaseEater);
  107. edit_filter->setClearButtonEnabled(true);
  108. connect(edit_filter, SIGNAL(textChanged(const QString&)), parent,
  109. SLOT(onTextChanged(const QString&)));
  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, SIGNAL(clicked()), parent, SLOT(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 String that gets checked if it contains all words of the userinput string
  131. * @param 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 searchfiel 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) || FileUtil::IsDirectory(std_file_path))
  240. return;
  241. // Users usually want to run a diffrent game after closing one
  242. search_field->clear();
  243. emit GameChosen(file_path);
  244. }
  245. void GameList::DonePopulating(QStringList watch_list) {
  246. // Clear out the old directories to watch for changes and add the new ones
  247. auto watch_dirs = watcher->directories();
  248. if (!watch_dirs.isEmpty()) {
  249. watcher->removePaths(watch_dirs);
  250. }
  251. // Workaround: Add the watch paths in chunks to allow the gui to refresh
  252. // This prevents the UI from stalling when a large number of watch paths are added
  253. // Also artificially caps the watcher to a certain number of directories
  254. constexpr int LIMIT_WATCH_DIRECTORIES = 5000;
  255. constexpr int SLICE_SIZE = 25;
  256. int len = std::min(watch_list.length(), LIMIT_WATCH_DIRECTORIES);
  257. for (int i = 0; i < len; i += SLICE_SIZE) {
  258. watcher->addPaths(watch_list.mid(i, i + SLICE_SIZE));
  259. QCoreApplication::processEvents();
  260. }
  261. tree_view->setEnabled(true);
  262. int rowCount = tree_view->model()->rowCount();
  263. search_field->setFilterResult(rowCount, rowCount);
  264. if (rowCount > 0) {
  265. search_field->setFocus();
  266. }
  267. }
  268. void GameList::PopupContextMenu(const QPoint& menu_location) {
  269. QModelIndex item = tree_view->indexAt(menu_location);
  270. if (!item.isValid())
  271. return;
  272. int row = item_model->itemFromIndex(item)->row();
  273. QStandardItem* child_file = item_model->invisibleRootItem()->child(row, COLUMN_NAME);
  274. u64 program_id = child_file->data(GameListItemPath::ProgramIdRole).toULongLong();
  275. QMenu context_menu;
  276. QAction* open_save_location = context_menu.addAction(tr("Open Save Data Location"));
  277. open_save_location->setEnabled(program_id != 0);
  278. connect(open_save_location, &QAction::triggered,
  279. [&]() { emit OpenSaveFolderRequested(program_id); });
  280. context_menu.exec(tree_view->viewport()->mapToGlobal(menu_location));
  281. }
  282. void GameList::PopulateAsync(const QString& dir_path, bool deep_scan) {
  283. if (!FileUtil::Exists(dir_path.toStdString()) ||
  284. !FileUtil::IsDirectory(dir_path.toStdString())) {
  285. LOG_ERROR(Frontend, "Could not find game list folder at %s", dir_path.toLocal8Bit().data());
  286. search_field->setFilterResult(0, 0);
  287. return;
  288. }
  289. tree_view->setEnabled(false);
  290. // Delete any rows that might already exist if we're repopulating
  291. item_model->removeRows(0, item_model->rowCount());
  292. emit ShouldCancelWorker();
  293. GameListWorker* worker = new GameListWorker(dir_path, deep_scan);
  294. connect(worker, &GameListWorker::EntryReady, this, &GameList::AddEntry, Qt::QueuedConnection);
  295. connect(worker, &GameListWorker::Finished, this, &GameList::DonePopulating,
  296. Qt::QueuedConnection);
  297. // Use DirectConnection here because worker->Cancel() is thread-safe and we want it to cancel
  298. // without delay.
  299. connect(this, &GameList::ShouldCancelWorker, worker, &GameListWorker::Cancel,
  300. Qt::DirectConnection);
  301. QThreadPool::globalInstance()->start(worker);
  302. current_worker = std::move(worker);
  303. }
  304. void GameList::SaveInterfaceLayout() {
  305. UISettings::values.gamelist_header_state = tree_view->header()->saveState();
  306. }
  307. void GameList::LoadInterfaceLayout() {
  308. auto header = tree_view->header();
  309. if (!header->restoreState(UISettings::values.gamelist_header_state)) {
  310. // We are using the name column to display icons and titles
  311. // so make it as large as possible as default.
  312. header->resizeSection(COLUMN_NAME, header->width());
  313. }
  314. item_model->sort(header->sortIndicatorSection(), header->sortIndicatorOrder());
  315. }
  316. const QStringList GameList::supported_file_extensions = {"nso", "nro"};
  317. static bool HasSupportedFileExtension(const std::string& file_name) {
  318. QFileInfo file = QFileInfo(file_name.c_str());
  319. return GameList::supported_file_extensions.contains(file.suffix(), Qt::CaseInsensitive);
  320. }
  321. void GameList::RefreshGameDirectory() {
  322. if (!UISettings::values.gamedir.isEmpty() && current_worker != nullptr) {
  323. LOG_INFO(Frontend, "Change detected in the games directory. Reloading game list.");
  324. search_field->clear();
  325. PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  326. }
  327. }
  328. void GameListWorker::AddFstEntriesToGameList(const std::string& dir_path, unsigned int recursion) {
  329. const auto callback = [this, recursion](unsigned* num_entries_out, const std::string& directory,
  330. const std::string& virtual_name) -> bool {
  331. std::string physical_name = directory + DIR_SEP + virtual_name;
  332. if (stop_processing)
  333. return false; // Breaks the callback loop.
  334. bool is_dir = FileUtil::IsDirectory(physical_name);
  335. if (!is_dir && HasSupportedFileExtension(physical_name)) {
  336. std::unique_ptr<Loader::AppLoader> loader = Loader::GetLoader(physical_name);
  337. if (!loader)
  338. return true;
  339. std::vector<u8> smdh;
  340. loader->ReadIcon(smdh);
  341. u64 program_id = 0;
  342. loader->ReadProgramId(program_id);
  343. emit EntryReady({
  344. new GameListItemPath(QString::fromStdString(physical_name), smdh, program_id),
  345. new GameListItem(
  346. QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType()))),
  347. new GameListItemSize(FileUtil::GetSize(physical_name)),
  348. });
  349. } else if (is_dir && recursion > 0) {
  350. watch_list.append(QString::fromStdString(physical_name));
  351. AddFstEntriesToGameList(physical_name, recursion - 1);
  352. }
  353. return true;
  354. };
  355. FileUtil::ForeachDirectoryEntry(nullptr, dir_path, callback);
  356. }
  357. void GameListWorker::run() {
  358. stop_processing = false;
  359. watch_list.append(dir_path);
  360. AddFstEntriesToGameList(dir_path.toStdString(), deep_scan ? 256 : 0);
  361. emit Finished(watch_list);
  362. }
  363. void GameListWorker::Cancel() {
  364. this->disconnect();
  365. stop_processing = true;
  366. }