Debian Codegraph @

Source/Core/DolphinQt/GameList/GameList.cpp

raw symbols SCIP
1 // Copyright 2015 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #ifdef _WIN32
5 #include <QCoreApplication>
6 #include <shlobj.h>
7 #include <wil/com.h>
8
9 // This file uses some identifiers which are defined as macros in Windows headers.
10 // Include and undefine the macros first thing we do to solve build errors.
11 #ifdef DeleteFile
12 #undef DeleteFile
13 #endif
14 #ifdef interface
15 #undef interface
16 #endif
17 #endif
18
19 #include "DolphinQt/GameList/GameList.h"
20
21 #include <algorithm>
22 #include <cmath>
23 #include <utility>
24
25 #include <QDesktopServices>
26 #include <QDir>
27 #include <QErrorMessage>
28 #include <QFileDialog>
29 #include <QFileInfo>
30 #include <QFrame>
31 #include <QHeaderView>
32 #include <QInputDialog>
33 #include <QKeyEvent>
34 #include <QLabel>
35 #include <QListView>
36 #include <QMap>
37 #include <QMenu>
38 #include <QShortcut>
39 #include <QSortFilterProxyModel>
40 #include <QTableView>
41 #include <QUrl>
42
43 #ifdef _WIN32
44 #include "Common/Contains.h"
45 #endif
46 #include "Common/FileUtil.h"
47
48 #include "Core/Config/MainSettings.h"
49 #include "Core/Core.h"
50 #include "Core/HW/DVD/DVDInterface.h"
51 #include "Core/HW/EXI/EXI.h"
52 #include "Core/HW/EXI/EXI_Device.h"
53 #include "Core/HW/WiiSave.h"
54 #include "Core/System.h"
55 #include "Core/WiiUtils.h"
56
57 #include "DiscIO/Enums.h"
58
59 #include "DolphinQt/Config/PropertiesDialog.h"
60 #include "DolphinQt/ConvertDialog.h"
61 #include "DolphinQt/GameList/GridProxyModel.h"
62 #include "DolphinQt/GameList/ListProxyModel.h"
63 #include "DolphinQt/MenuBar.h"
64 #include "DolphinQt/QtUtils/DolphinFileDialog.h"
65 #include "DolphinQt/QtUtils/DoubleClickEventFilter.h"
66 #include "DolphinQt/QtUtils/ModalMessageBox.h"
67 #include "DolphinQt/QtUtils/NonAutodismissibleMenu.h"
68 #include "DolphinQt/QtUtils/QtUtils.h"
69 #include "DolphinQt/Resources.h"
70 #include "DolphinQt/Settings.h"
71 #include "DolphinQt/WiiUpdate.h"
72
73 #include "UICommon/GameFile.h"
74
75 namespace
76 {
77 class GameListTableView : public QTableView
78 {
79 public:
80 explicit GameListTableView(QWidget* parent = nullptr) : QTableView(parent) {}
81
82 protected:
83 QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) override
84 {
85 // QTableView::moveCursor handles home by moving to the first column and end by moving to the
86 // last column, unless control is held in which case it ALSO moves to the first/last row.
87 // Columns are irrelevant for the game list, so treat the home/end press as if control were
88 // held.
89 if (cursorAction == CursorAction::MoveHome || cursorAction == CursorAction::MoveEnd)
90 return QTableView::moveCursor(cursorAction, modifiers | Qt::ControlModifier);
91 else
92 return QTableView::moveCursor(cursorAction, modifiers);
93 }
94
95 virtual void mouseDoubleClickEvent(QMouseEvent* const event) override
96 {
97 if (event->button() == Qt::LeftButton)
98 QTableView::mouseDoubleClickEvent(event);
99 }
100 };
101
102 class GameListListView : public QListView
103 {
104 public:
105 explicit GameListListView(QWidget* parent = nullptr) : QListView(parent) {}
106
107 protected:
108 virtual void mouseDoubleClickEvent(QMouseEvent* const event) override
109 {
110 if (event->button() == Qt::LeftButton)
111 QListView::mouseDoubleClickEvent(event);
112 }
113 };
114 } // namespace
115
116 GameList::GameList(QWidget* parent) : QStackedWidget(parent), m_model(this)
117 {
118 m_list_proxy = new ListProxyModel(this);
119 m_list_proxy->setSortCaseSensitivity(Qt::CaseInsensitive);
120 m_list_proxy->setSortRole(GameListModel::SORT_ROLE);
121 m_list_proxy->setSourceModel(&m_model);
122 m_grid_proxy = new GridProxyModel(this);
123 m_grid_proxy->setSortCaseSensitivity(Qt::CaseInsensitive);
124 m_grid_proxy->setSortRole(GameListModel::SORT_ROLE);
125 m_grid_proxy->setSourceModel(&m_model);
126
127 MakeListView();
128 MakeGridView();
129 MakeEmptyView();
130
131 // Use List View's sorting for Grid View too.
132 m_grid_proxy->sort(m_list_proxy->sortColumn(), m_list_proxy->sortOrder());
133 connect(m_list->horizontalHeader(), &QHeaderView::sortIndicatorChanged, m_grid_proxy,
134 &GridProxyModel::sort);
135
136 if (Settings::GetQSettings().contains(QStringLiteral("gridview/scale")))
137 m_model.SetScale(Settings::GetQSettings().value(QStringLiteral("gridview/scale")).toFloat());
138
139 connect(m_list, &QTableView::doubleClicked, this, &GameList::GameSelected);
140 connect(m_grid, &QListView::doubleClicked, this, &GameList::GameSelected);
141 connect(&m_model, &QAbstractItemModel::rowsInserted, this, &GameList::ConsiderViewChange);
142 connect(&m_model, &QAbstractItemModel::rowsRemoved, this, &GameList::ConsiderViewChange);
143 connect(&m_model, &QAbstractItemModel::rowsInserted, this, &GameList::UpdateGameCount);
144 connect(&m_model, &QAbstractItemModel::rowsRemoved, this, &GameList::UpdateGameCount);
145
146 addWidget(m_list);
147 addWidget(m_grid);
148 addWidget(m_empty);
149 m_prefer_list = Settings::Instance().GetPreferredView();
150 ConsiderViewChange();
151
152 auto* zoom_in = new QShortcut(QKeySequence::ZoomIn, this);
153 auto* zoom_out = new QShortcut(QKeySequence::ZoomOut, this);
154 zoom_in->setContext(Qt::WidgetWithChildrenShortcut);
155 zoom_out->setContext(Qt::WidgetWithChildrenShortcut);
156
157 connect(zoom_in, &QShortcut::activated, this, &GameList::ZoomIn);
158 connect(zoom_out, &QShortcut::activated, this, &GameList::ZoomOut);
159
160 // On most keyboards the key to the left of the primary delete key represents 'plus' when shift is
161 // held and 'equal' when it isn't. By common convention, pressing control and that key is treated
162 // conceptually as 'control plus' (which is then interpreted as an appropriate zooming action)
163 // instead of the technically correct 'control equal'. Qt doesn't account for this convention so
164 // an alternate shortcut is needed to avoid counterintuitive behavior.
165 const auto* zoom_in_alternate = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Equal), this);
166 connect(zoom_in_alternate, &QShortcut::activated, this, &GameList::ZoomIn);
167
168 // The above correction introduces a different inconsistency: now zooming in can be done using
169 // conceptual 'control plus' or 'control shift plus', while zooming out can only be done using
170 // 'control minus'. Adding an alternate shortcut representing 'control shift minus' restores
171 // consistency.
172 const auto* zoom_out_alternate = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Underscore), this);
173 connect(zoom_out_alternate, &QShortcut::activated, this, &GameList::ZoomOut);
174
175 connect(&Settings::Instance(), &Settings::MetadataRefreshCompleted, this,
176 [this] { m_grid_proxy->invalidate(); });
177 }
178
179 void GameList::PurgeCache()
180 {
181 m_model.PurgeCache();
182 }
183
184 void GameList::MakeListView()
185 {
186 m_list = new GameListTableView(this);
187 m_list->setModel(m_list_proxy);
188
189 m_list->setTabKeyNavigation(false);
190 m_list->setSelectionMode(QAbstractItemView::ExtendedSelection);
191 m_list->setSelectionBehavior(QAbstractItemView::SelectRows);
192 m_list->setAlternatingRowColors(true);
193 m_list->setShowGrid(false);
194 m_list->setSortingEnabled(true);
195 m_list->setCurrentIndex(QModelIndex());
196 m_list->setContextMenuPolicy(Qt::CustomContextMenu);
197 m_list->setWordWrap(false);
198 // Have 1 pixel of padding above and below the 32 pixel banners.
199 m_list->verticalHeader()->setDefaultSectionSize(32 + 2);
200
201 QHeaderView* hor_header = m_list->horizontalHeader();
202
203 hor_header->restoreState(
204 Settings::GetQSettings().value(QStringLiteral("tableheader/state")).toByteArray());
205
206 hor_header->setContextMenuPolicy(Qt::CustomContextMenu);
207 connect(hor_header, &QWidget::customContextMenuRequested, this, &GameList::ShowHeaderContextMenu);
208
209 connect(hor_header, &QHeaderView::sortIndicatorChanged, this, &GameList::OnHeaderViewChanged);
210 connect(hor_header, &QHeaderView::sectionCountChanged, this, &GameList::OnHeaderViewChanged);
211 connect(hor_header, &QHeaderView::sectionMoved, this, &GameList::OnHeaderViewChanged);
212 connect(hor_header, &QHeaderView::sectionResized, this, &GameList::OnSectionResized);
213
214 if (!Settings::GetQSettings().contains(QStringLiteral("tableheader/state")))
215 m_list->sortByColumn(static_cast<int>(GameListModel::Column::Title), Qt::AscendingOrder);
216 {
217 const auto SetResizeMode = [&hor_header](const GameListModel::Column column,
218 const QHeaderView::ResizeMode mode) {
219 hor_header->setSectionResizeMode(static_cast<int>(column), mode);
220 };
221 using Column = GameListModel::Column;
222 using Mode = QHeaderView::ResizeMode;
223 SetResizeMode(Column::Platform, Mode::Fixed);
224 SetResizeMode(Column::Banner, Mode::Fixed);
225 SetResizeMode(Column::Title, Mode::Interactive);
226 SetResizeMode(Column::Description, Mode::Interactive);
227 SetResizeMode(Column::Maker, Mode::Interactive);
228 SetResizeMode(Column::ID, Mode::Fixed);
229 SetResizeMode(Column::Country, Mode::Fixed);
230 SetResizeMode(Column::Size, Mode::Fixed);
231 SetResizeMode(Column::FileName, Mode::Interactive);
232 SetResizeMode(Column::FilePath, Mode::Interactive);
233 SetResizeMode(Column::FileFormat, Mode::Fixed);
234 SetResizeMode(Column::BlockSize, Mode::Fixed);
235 SetResizeMode(Column::Compression, Mode::Fixed);
236 SetResizeMode(Column::TimePlayed, Mode::Interactive);
237 SetResizeMode(Column::Tags, Mode::Interactive);
238
239 // Cells have 3 pixels of padding, so the width of these needs to be image width + 6. Banners
240 // are 96 pixels wide, platform and country icons are 32 pixels wide.
241 m_list->setColumnWidth(static_cast<int>(Column::Banner), 102);
242 m_list->setColumnWidth(static_cast<int>(Column::Platform), 38);
243 m_list->setColumnWidth(static_cast<int>(Column::Country), 38);
244 m_list->setColumnWidth(static_cast<int>(Column::Size), 85);
245 m_list->setColumnWidth(static_cast<int>(Column::ID), 70);
246 }
247
248 // There's some odd platform-specific behavior with default minimum section size
249 hor_header->setMinimumSectionSize(38);
250
251 UpdateColumnVisibility();
252
253 m_list->verticalHeader()->hide();
254 m_list->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
255 m_list->setFrameStyle(QFrame::NoFrame);
256
257 hor_header->setSectionsMovable(true);
258 hor_header->setHighlightSections(false);
259
260 // Work around a Qt bug where clicking in the background (below the last game) as the first
261 // action and then pressing a key (e.g. page down or end) selects the first entry in the list
262 // instead of performing that key's action. This workaround does not work if there are no games
263 // when the view first appears, but then games are added (e.g. due to no game folders being
264 // present, and then the user adding one), but that is an infrequent situation.
265 m_list->selectRow(0);
266 m_list->clearSelection();
267
268 connect(m_list, &QTableView::customContextMenuRequested, this, &GameList::ShowContextMenu);
269 connect(m_list->selectionModel(), &QItemSelectionModel::selectionChanged,
270 [this](const QItemSelection&, const QItemSelection&) {
271 emit SelectionChanged(GetSelectedGame());
272 });
273 }
274
275 GameList::~GameList()
276 {
277 Settings::GetQSettings().setValue(QStringLiteral("tableheader/state"),
278 m_list->horizontalHeader()->saveState());
279 Settings::GetQSettings().setValue(QStringLiteral("gridview/scale"), m_model.GetScale());
280 }
281
282 void GameList::UpdateColumnVisibility()
283 {
284 const auto SetVisiblity = [this](const GameListModel::Column column, const bool is_visible) {
285 m_list->setColumnHidden(static_cast<int>(column), !is_visible);
286 };
287
288 using Column = GameListModel::Column;
289 SetVisiblity(Column::Platform, Config::Get(Config::MAIN_GAMELIST_COLUMN_PLATFORM));
290 SetVisiblity(Column::Banner, Config::Get(Config::MAIN_GAMELIST_COLUMN_BANNER));
291 SetVisiblity(Column::Title, Config::Get(Config::MAIN_GAMELIST_COLUMN_TITLE));
292 SetVisiblity(Column::Description, Config::Get(Config::MAIN_GAMELIST_COLUMN_DESCRIPTION));
293 SetVisiblity(Column::Maker, Config::Get(Config::MAIN_GAMELIST_COLUMN_MAKER));
294 SetVisiblity(Column::ID, Config::Get(Config::MAIN_GAMELIST_COLUMN_GAME_ID));
295 SetVisiblity(Column::Country, Config::Get(Config::MAIN_GAMELIST_COLUMN_REGION));
296 SetVisiblity(Column::Size, Config::Get(Config::MAIN_GAMELIST_COLUMN_FILE_SIZE));
297 SetVisiblity(Column::FileName, Config::Get(Config::MAIN_GAMELIST_COLUMN_FILE_NAME));
298 SetVisiblity(Column::FilePath, Config::Get(Config::MAIN_GAMELIST_COLUMN_FILE_PATH));
299 SetVisiblity(Column::FileFormat, Config::Get(Config::MAIN_GAMELIST_COLUMN_FILE_FORMAT));
300 SetVisiblity(Column::BlockSize, Config::Get(Config::MAIN_GAMELIST_COLUMN_BLOCK_SIZE));
301 SetVisiblity(Column::Compression, Config::Get(Config::MAIN_GAMELIST_COLUMN_COMPRESSION));
302 SetVisiblity(Column::TimePlayed, Config::Get(Config::MAIN_GAMELIST_COLUMN_TIME_PLAYED));
303 SetVisiblity(Column::Tags, Config::Get(Config::MAIN_GAMELIST_COLUMN_TAGS));
304 }
305
306 void GameList::MakeEmptyView()
307 {
308 const QString refreshing_msg = tr("Refreshing...");
309 const QString empty_msg = tr("Dolphin could not find any GameCube/Wii ISOs or WADs.\n"
310 "Double-click here to set a games directory...");
311
312 m_empty = new QLabel(this);
313 m_empty->setText(refreshing_msg);
314 m_empty->setEnabled(false);
315 m_empty->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
316
317 auto event_filter = new DoubleClickEventFilter{m_empty};
318 m_empty->installEventFilter(event_filter);
319 connect(event_filter, &DoubleClickEventFilter::doubleClicked, [this] {
320 auto current_dir = QDir::currentPath();
321 auto dir = DolphinFileDialog::getExistingDirectory(this, tr("Select a Directory"), current_dir);
322 if (!dir.isEmpty())
323 Settings::Instance().AddPath(dir);
324 });
325
326 QSizePolicy size_policy{m_empty->sizePolicy()};
327 size_policy.setRetainSizeWhenHidden(true);
328 m_empty->setSizePolicy(size_policy);
329
330 connect(&Settings::Instance(), &Settings::GameListRefreshRequested, this, [this, refreshing_msg] {
331 m_empty->setText(refreshing_msg);
332 m_empty->setEnabled(false);
333 });
334 connect(&Settings::Instance(), &Settings::GameListRefreshCompleted, this, [this, empty_msg] {
335 m_empty->setText(empty_msg);
336 m_empty->setEnabled(true);
337 });
338 }
339
340 void GameList::resizeEvent(QResizeEvent* event)
341 {
342 OnHeaderViewChanged();
343 }
344
345 void GameList::MakeGridView()
346 {
347 m_grid = new GameListListView(this);
348 m_grid->setModel(m_grid_proxy);
349 m_grid->setSelectionMode(QAbstractItemView::ExtendedSelection);
350
351 // Row in this context refers to the full set of columns (banner, title, region, etc.) associated
352 // with a single game rather than multiple games presented visually on the same row. Even though
353 // most of these elements are hidden in grid view selecting all of them allows us to use
354 // selectedRow() which only returns rows where all elements are selected. In addition to improving
355 // consistency with list view this avoids an edge case where clicking a game in grid mode selected
356 // only the first element of the row but ctrl+a selected every element of the row, making a bunch
357 // of duplicate selections for each game.
358 m_grid->setSelectionBehavior(QAbstractItemView::SelectRows);
359
360 m_grid->setViewMode(QListView::IconMode);
361 m_grid->setResizeMode(QListView::Adjust);
362 m_grid->setUniformItemSizes(true);
363 m_grid->setContextMenuPolicy(Qt::CustomContextMenu);
364 m_grid->setFrameStyle(QFrame::NoFrame);
365
366 // Work around a Qt bug where clicking in the background (below the last game) as the first action
367 // and then pressing a key (e.g. page down or end) selects the first entry in the list instead of
368 // performing that key's action. This workaround does not work if there are no games when the
369 // view first appears, but then games are added (e.g. due to no game folders being present,
370 // and then the user adding one), but that is an infrequent situation.
371 m_grid->setCurrentIndex(m_grid->indexAt(QPoint(0, 0)));
372 m_grid->clearSelection();
373
374 connect(m_grid, &QTableView::customContextMenuRequested, this, &GameList::ShowContextMenu);
375 connect(m_grid->selectionModel(), &QItemSelectionModel::selectionChanged,
376 [this](const QItemSelection&, const QItemSelection&) {
377 emit SelectionChanged(GetSelectedGame());
378 });
379 }
380
381 void GameList::ShowHeaderContextMenu(const QPoint& pos)
382 {
383 const MenuBar* const menu_bar = MenuBar::GetMenuBar();
384 if (!menu_bar)
385 return;
386
387 QMenu* const list_columns_menu = menu_bar->GetListColumnsMenu();
388 if (!list_columns_menu)
389 return;
390
391 const QWidget* const widget = qobject_cast<QWidget*>(sender());
392 list_columns_menu->exec(widget ? widget->mapToGlobal(pos) : pos);
393 }
394
395 void GameList::ShowContextMenu(const QPoint&)
396 {
397 if (!GetSelectedGame())
398 return;
399 auto& system = Core::System::GetInstance();
400
401 QMenu* menu = new QMenu(this);
402 menu->setAttribute(Qt::WA_DeleteOnClose, true);
403
404 if (HasMultipleSelected())
405 {
406 const auto selected_games = GetSelectedGames();
407
408 if (std::ranges::all_of(selected_games,
409 [](const auto& game) { return game->ShouldAllowConversion(); }))
410 {
411 menu->addAction(tr("Convert Selected Files..."), this, &GameList::ConvertFile);
412 menu->addSeparator();
413 }
414
415 if (std::ranges::all_of(selected_games,
416 [](const auto& game) { return DiscIO::IsWii(game->GetPlatform()); }))
417 {
418 menu->addAction(tr("Export Wii Saves"), this, &GameList::ExportWiiSave);
419 menu->addSeparator();
420 }
421
422 menu->addAction(tr("Delete Selected Files..."), this, &GameList::DeleteFile);
423 }
424 else
425 {
426 const auto game = GetSelectedGame();
427 const bool is_mod_descriptor = game->IsModDescriptor();
428 DiscIO::Platform platform = game->GetPlatform();
429 menu->addAction(tr("&Properties"), this, &GameList::OpenProperties);
430 if (!is_mod_descriptor && platform != DiscIO::Platform::ELFOrDOL)
431 {
432 menu->addAction(tr("&Wiki"), this, &GameList::OpenWiki);
433 }
434
435 menu->addSeparator();
436
437 if (!is_mod_descriptor && DiscIO::IsDisc(platform))
438 {
439 menu->addAction(tr("Start with Riivolution Patches..."), this,
440 &GameList::StartWithRiivolution);
441
442 menu->addSeparator();
443
444 menu->addAction(tr("Set as &Default ISO"), this, &GameList::SetDefaultISO);
445
446 if (game->ShouldAllowConversion())
447 menu->addAction(tr("Convert File..."), this, &GameList::ConvertFile);
448
449 QAction* change_disc = menu->addAction(tr("Change &Disc"), this, &GameList::ChangeDisc);
450
451 connect(&Settings::Instance(), &Settings::EmulationStateChanged, change_disc,
452 [&system, change_disc] { change_disc->setEnabled(Core::IsRunning(system)); });
453 change_disc->setEnabled(Core::IsRunning(system));
454
455 menu->addSeparator();
456 }
457
458 if (!is_mod_descriptor && platform == DiscIO::Platform::WiiDisc)
459 {
460 auto* perform_disc_update = menu->addAction(tr("Perform System Update"), this,
461 [this, file_path = game->GetFilePath()] {
462 WiiUpdate::PerformDiscUpdate(file_path, this);
463 // Since the update may have installed a newer
464 // system menu, trigger a refresh.
465 Settings::Instance().NANDRefresh();
466 });
467 perform_disc_update->setEnabled(Core::IsUninitialized(system) || !system.IsWii());
468 }
469
470 if (!is_mod_descriptor && platform == DiscIO::Platform::WiiWAD)
471 {
472 QAction* wad_install_action = new QAction(tr("Install to the NAND"), menu);
473 QAction* wad_uninstall_action = new QAction(tr("Uninstall from the NAND"), menu);
474
475 connect(wad_install_action, &QAction::triggered, this, &GameList::InstallWAD);
476 connect(wad_uninstall_action, &QAction::triggered, this, &GameList::UninstallWAD);
477
478 for (QAction* a : {wad_install_action, wad_uninstall_action})
479 {
480 a->setEnabled(Core::IsUninitialized(system));
481 menu->addAction(a);
482 }
483 if (Core::IsUninitialized(system))
484 wad_uninstall_action->setEnabled(WiiUtils::IsTitleInstalled(game->GetTitleID()));
485
486 connect(&Settings::Instance(), &Settings::EmulationStateChanged, menu,
487 [=](Core::State state) {
488 wad_install_action->setEnabled(state == Core::State::Uninitialized);
489 wad_uninstall_action->setEnabled(state == Core::State::Uninitialized &&
490 WiiUtils::IsTitleInstalled(game->GetTitleID()));
491 });
492
493 menu->addSeparator();
494 }
495
496 if (!is_mod_descriptor &&
497 (platform == DiscIO::Platform::WiiWAD || platform == DiscIO::Platform::WiiDisc))
498 {
499 QAction* open_wii_save_folder =
500 menu->addAction(tr("Open Wii &Save Folder"), this, &GameList::OpenWiiSaveFolder);
501 QAction* export_wii_save =
502 menu->addAction(tr("Export Wii Save"), this, &GameList::ExportWiiSave);
503
504 open_wii_save_folder->setEnabled(Core::IsUninitialized(system));
505 export_wii_save->setEnabled(Core::IsUninitialized(system));
506
507 menu->addSeparator();
508 }
509
510 if (!is_mod_descriptor && platform == DiscIO::Platform::GameCubeDisc)
511 {
512 menu->addAction(tr("Open GameCube &Save Folder"), this, &GameList::OpenGCSaveFolder);
513 menu->addSeparator();
514 }
515
516 menu->addAction(tr("Open &Containing Folder"), this, &GameList::OpenContainingFolder);
517 menu->addAction(tr("Delete File..."), this, &GameList::DeleteFile);
518 #ifdef _WIN32
519 menu->addAction(tr("Add Shortcut to Desktop"), this, [this] {
520 if (!AddShortcutToDesktop())
521 {
522 ModalMessageBox::critical(this, tr("Add Shortcut to Desktop"),
523 tr("There was an issue adding a shortcut to the desktop"));
524 }
525 });
526 #endif
527
528 menu->addSeparator();
529
530 auto* const tags_menu{new QtUtils::NonAutodismissibleMenu(tr("Tags"), menu)};
531 menu->addMenu(tags_menu);
532
533 auto path = game->GetFilePath();
534 auto game_tags = m_model.GetGameTags(path);
535
536 for (const auto& tag : m_model.GetAllTags())
537 {
538 auto* tag_action = tags_menu->addAction(tag);
539
540 tag_action->setCheckable(true);
541 tag_action->setChecked(game_tags.contains(tag));
542
543 connect(tag_action, &QAction::toggled, [path, tag, model = &m_model](bool checked) {
544 if (!checked)
545 model->RemoveGameTag(path, tag);
546 else
547 model->AddGameTag(path, tag);
548 });
549 }
550
551 menu->addAction(tr("New Tag..."), this, &GameList::NewTag);
552 menu->addAction(tr("Remove Tag..."), this, &GameList::DeleteTag);
553
554 menu->addSeparator();
555
556 QAction* netplay_host = new QAction(tr("Host with NetPlay"), menu);
557
558 connect(netplay_host, &QAction::triggered, [this, game] { emit NetPlayHost(*game); });
559
560 connect(&Settings::Instance(), &Settings::EmulationStateChanged, menu, [=](Core::State state) {
561 netplay_host->setEnabled(state == Core::State::Uninitialized);
562 });
563 netplay_host->setEnabled(Core::IsUninitialized(system));
564
565 menu->addAction(netplay_host);
566 }
567
568 menu->exec(QCursor::pos());
569 }
570
571 void GameList::OpenProperties()
572 {
573 const auto game = GetSelectedGame();
574 if (!game)
575 return;
576
577 auto property_windows = this->findChildren<PropertiesDialog*>();
578 auto it =
579 std::ranges::find(property_windows, game->GetFilePath(), &PropertiesDialog::GetFilePath);
580 if (it != property_windows.end())
581 {
582 (*it)->raise();
583 return;
584 }
585
586 PropertiesDialog* properties = new PropertiesDialog(this, *game);
587
588 connect(properties, &PropertiesDialog::OpenGeneralSettings, this, &GameList::OpenGeneralSettings);
589 connect(properties, &PropertiesDialog::OpenGraphicsSettings, this,
590 &GameList::OpenGraphicsSettings);
591 connect(properties, &PropertiesDialog::finished, this,
592 [properties] { properties->deleteLater(); });
593
594 #ifdef USE_RETRO_ACHIEVEMENTS
595 connect(properties, &PropertiesDialog::OpenAchievementSettings, this,
596 &GameList::OpenAchievementSettings);
597 #endif // USE_RETRO_ACHIEVEMENTS
598
599 properties->show();
600 }
601
602 void GameList::ExportWiiSave()
603 {
604 const QString export_dir = DolphinFileDialog::getExistingDirectory(
605 this, tr("Select Export Directory"), QString::fromStdString(File::GetUserPath(D_USER_IDX)),
606 QFileDialog::ShowDirsOnly);
607 if (export_dir.isEmpty())
608 return;
609
610 QList<std::string> failed;
611 for (const auto& game : GetSelectedGames())
612 {
613 if (WiiSave::Export(game->GetTitleID(), export_dir.toStdString()) !=
614 WiiSave::CopyResult::Success)
615 {
616 failed.push_back(game->GetName(UICommon::GameFile::Variant::LongAndPossiblyCustom));
617 }
618 }
619
620 if (!failed.isEmpty())
621 {
622 QString failed_str;
623 for (const std::string& str : failed)
624 failed_str.append(QLatin1Char{'\n'}).append(QString::fromStdString(str));
625 ModalMessageBox::critical(this, tr("Save Export"),
626 tr("Failed to export the following save files:") + failed_str);
627 }
628 else
629 {
630 ModalMessageBox::information(this, tr("Save Export"), tr("Successfully exported save files"));
631 }
632 }
633
634 void GameList::OpenWiki()
635 {
636 const auto game = GetSelectedGame();
637 if (!game)
638 return;
639
640 QString game_id = QString::fromStdString(game->GetGameID());
641 QString url =
642 QStringLiteral("https://wiki.dolphin-emu.org/dolphin-redirect.php?gameid=").append(game_id);
643 QDesktopServices::openUrl(QUrl(url));
644 }
645
646 void GameList::ConvertFile()
647 {
648 auto games = GetSelectedGames();
649 if (games.empty())
650 return;
651
652 ConvertDialog dialog{std::move(games), this};
653 dialog.exec();
654 }
655
656 void GameList::InstallWAD()
657 {
658 const auto game = GetSelectedGame();
659 if (!game)
660 return;
661
662 ModalMessageBox result_dialog(this);
663
664 const bool success = WiiUtils::InstallWAD(game->GetFilePath());
665
666 result_dialog.setIcon(success ? QMessageBox::Information : QMessageBox::Critical);
667 result_dialog.setWindowTitle(success ? tr("Success") : tr("Failure"));
668 result_dialog.setText(success ? tr("Successfully installed this title to the NAND.") :
669 tr("Failed to install this title to the NAND."));
670 result_dialog.exec();
671 }
672
673 void GameList::UninstallWAD()
674 {
675 const auto game = GetSelectedGame();
676 if (!game)
677 return;
678
679 ModalMessageBox warning_dialog(this);
680
681 warning_dialog.setIcon(QMessageBox::Information);
682 warning_dialog.setWindowTitle(tr("Confirm"));
683 warning_dialog.setText(tr("Uninstalling the WAD will remove the currently installed version of "
684 "this title from the NAND without deleting its save data. Continue?"));
685 warning_dialog.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
686
687 if (warning_dialog.exec() == QMessageBox::No)
688 return;
689
690 ModalMessageBox result_dialog(this);
691
692 const bool success = WiiUtils::UninstallTitle(game->GetTitleID());
693
694 result_dialog.setIcon(success ? QMessageBox::Information : QMessageBox::Critical);
695 result_dialog.setWindowTitle(success ? tr("Success") : tr("Failure"));
696 result_dialog.setText(success ? tr("Successfully removed this title from the NAND.") :
697 tr("Failed to remove this title from the NAND."));
698 result_dialog.exec();
699 }
700
701 void GameList::StartWithRiivolution()
702 {
703 const auto game = GetSelectedGame();
704 if (!game)
705 return;
706
707 emit OnStartWithRiivolution(*game);
708 }
709
710 void GameList::SetDefaultISO()
711 {
712 const auto game = GetSelectedGame();
713 if (!game)
714 return;
715
716 Settings::Instance().SetDefaultGame(
717 QDir::toNativeSeparators(QString::fromStdString(game->GetFilePath())));
718 }
719
720 void GameList::OpenContainingFolder()
721 {
722 const auto game = GetSelectedGame();
723 if (!game)
724 return;
725
726 QtUtils::ShowFileInFolder(game->GetFilePath());
727 }
728
729 void GameList::OpenWiiSaveFolder()
730 {
731 const auto game = GetSelectedGame();
732 if (!game)
733 return;
734
735 const std::string path = game->GetWiiFSPath();
736 if (!File::Exists(path))
737 {
738 ModalMessageBox::information(this, tr("Information"), tr("No save data found."));
739 return;
740 }
741
742 const QUrl url = QUrl::fromLocalFile(QString::fromStdString(path));
743 QDesktopServices::openUrl(url);
744 }
745
746 void GameList::OpenGCSaveFolder()
747 {
748 const auto game = GetSelectedGame();
749 if (!game)
750 return;
751
752 bool found = false;
753
754 using ExpansionInterface::Slot;
755
756 for (Slot slot : ExpansionInterface::MEMCARD_SLOTS)
757 {
758 const ExpansionInterface::EXIDeviceType current_exi_device =
759 Config::Get(Config::GetInfoForEXIDevice(slot));
760 switch (current_exi_device)
761 {
762 case ExpansionInterface::EXIDeviceType::MemoryCardFolder:
763 {
764 namespace fs = std::filesystem;
765
766 std::string override_path = Config::Get(Config::GetInfoForGCIPathOverride(slot));
767 const auto dir =
768 override_path.empty() ? Config::GetGCIFolderPath(slot, game->GetRegion()) : override_path;
769
770 const auto gci_filename_prefix =
771 fs::path{fmt::format("{}-{}-", game->GetMakerID(), game->GetGameID().substr(0, 4))}
772 .native();
773 const auto gci_extension = fs::path{".gci"}.native();
774
775 for (const auto& entry : fs::directory_iterator(dir))
776 {
777 if (entry.path().filename().native().starts_with(gci_filename_prefix) &&
778 entry.path().extension() == gci_extension)
779 {
780 QtUtils::ShowFileInFolder(entry.path().generic_string());
781 found = true;
782 break;
783 }
784 }
785 break;
786 }
787 case ExpansionInterface::EXIDeviceType::MemoryCard:
788 {
789 QtUtils::ShowFileInFolder(Config::GetMemcardPath(slot, game->GetRegion()));
790 found = true;
791 break;
792 }
793 default:
794 break;
795 }
796 }
797
798 if (!found)
799 ModalMessageBox::information(this, tr("Information"), tr("No save data found."));
800 }
801
802 #ifdef _WIN32
803 bool GameList::AddShortcutToDesktop()
804 {
805 auto init = wil::CoInitializeEx_failfast(COINIT_APARTMENTTHREADED);
806 auto shell_link = wil::CoCreateInstanceNoThrow<ShellLink, IShellLink>();
807 if (!shell_link)
808 return false;
809
810 std::wstring dolphin_path = QCoreApplication::applicationFilePath().toStdWString();
811 if (FAILED(shell_link->SetPath(dolphin_path.c_str())))
812 return false;
813
814 const auto game = GetSelectedGame();
815 const auto& file_path = game->GetFilePath();
816 std::wstring args = UTF8ToTStr("-e \"" + file_path + "\"");
817 if (FAILED(shell_link->SetArguments(args.c_str())))
818 return false;
819
820 wil::unique_cotaskmem_string desktop;
821 if (FAILED(SHGetKnownFolderPath(FOLDERID_Desktop, KF_FLAG_NO_ALIAS, nullptr, &desktop)))
822 return false;
823
824 std::string game_name = game->GetName(Core::TitleDatabase());
825 // Sanitize the string by removing all characters that cannot be used in NTFS file names
826 std::erase_if(game_name, [](char ch) {
827 static constexpr char illegal_characters[] = {'<', '>', ':', '\"', '/', '\\', '|', '?', '*'};
828 return Common::Contains(illegal_characters, ch);
829 });
830
831 std::wstring desktop_path = std::wstring(desktop.get()) + UTF8ToTStr("\\" + game_name + ".lnk");
832 auto persist_file = shell_link.try_query<IPersistFile>();
833 if (!persist_file)
834 return false;
835
836 if (FAILED(persist_file->Save(desktop_path.c_str(), TRUE)))
837 return false;
838
839 return true;
840 }
841 #endif
842
843 void GameList::DeleteFile()
844 {
845 ModalMessageBox confirm_dialog(this);
846
847 confirm_dialog.setIcon(QMessageBox::Warning);
848 confirm_dialog.setWindowTitle(tr("Confirm"));
849 confirm_dialog.setText(tr("Are you sure you want to delete this file?"));
850 confirm_dialog.setInformativeText(tr("This cannot be undone!"));
851 confirm_dialog.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
852
853 if (confirm_dialog.exec() == QMessageBox::Yes)
854 {
855 for (const auto& game : GetSelectedGames())
856 {
857 bool deletion_successful = false;
858
859 while (!deletion_successful)
860 {
861 deletion_successful = File::Delete(game->GetFilePath());
862
863 if (deletion_successful)
864 {
865 m_model.RemoveGame(game->GetFilePath());
866 }
867 else
868 {
869 ModalMessageBox error_dialog(this);
870
871 error_dialog.setIcon(QMessageBox::Critical);
872 error_dialog.setWindowTitle(tr("Failure"));
873 error_dialog.setText(tr("Failed to delete the selected file."));
874 error_dialog.setInformativeText(tr("Check whether you have the permissions required to "
875 "delete the file or whether it's still in use."));
876 error_dialog.setStandardButtons(QMessageBox::Retry | QMessageBox::Abort);
877
878 if (error_dialog.exec() == QMessageBox::Abort)
879 break;
880 }
881 }
882
883 if (!deletion_successful)
884 break; // Something is wrong, so we should abort the whole thing
885 }
886 }
887 }
888
889 void GameList::ChangeDisc()
890 {
891 const auto game = GetSelectedGame();
892 if (!game)
893 return;
894
895 auto& system = Core::System::GetInstance();
896 system.GetDVDInterface().ChangeDisc(Core::CPUThreadGuard{system}, game->GetFilePath());
897 }
898
899 QAbstractItemView* GameList::GetActiveView() const
900 {
901 if (currentWidget() == m_list)
902 {
903 return m_list;
904 }
905 return m_grid;
906 }
907
908 QSortFilterProxyModel* GameList::GetActiveProxyModel() const
909 {
910 if (currentWidget() == m_list)
911 {
912 return m_list_proxy;
913 }
914 return m_grid_proxy;
915 }
916
917 std::shared_ptr<const UICommon::GameFile> GameList::GetSelectedGame() const
918 {
919 QItemSelectionModel* const sel_model = GetActiveView()->selectionModel();
920 if (sel_model->hasSelection())
921 {
922 QSortFilterProxyModel* const proxy = GetActiveProxyModel();
923 QModelIndex model_index = proxy->mapToSource(sel_model->selectedIndexes()[0]);
924 return m_model.GetGameFile(model_index.row());
925 }
926 return {};
927 }
928
929 QList<std::shared_ptr<const UICommon::GameFile>> GameList::GetSelectedGames() const
930 {
931 QList<std::shared_ptr<const UICommon::GameFile>> selected_list;
932 QItemSelectionModel* const sel_model = GetActiveView()->selectionModel();
933
934 if (sel_model->hasSelection())
935 {
936 const QModelIndexList index_list = sel_model->selectedRows();
937 for (const auto& index : index_list)
938 {
939 const QModelIndex model_index = GetActiveProxyModel()->mapToSource(index);
940 selected_list.push_back(m_model.GetGameFile(model_index.row()));
941 }
942 }
943 return selected_list;
944 }
945
946 bool GameList::HasMultipleSelected() const
947 {
948 return GetActiveView()->selectionModel()->selectedRows().size() > 1;
949 }
950
951 std::shared_ptr<const UICommon::GameFile> GameList::FindGame(const std::string& path) const
952 {
953 return m_model.FindGame(path);
954 }
955
956 std::shared_ptr<const UICommon::GameFile>
957 GameList::FindSecondDisc(const UICommon::GameFile& game) const
958 {
959 return m_model.FindSecondDisc(game);
960 }
961
962 std::string GameList::GetNetPlayName(const UICommon::GameFile& game) const
963 {
964 return m_model.GetNetPlayName(game);
965 }
966
967 void GameList::SetViewColumn(int col, bool view)
968 {
969 m_list->setColumnHidden(col, !view);
970 }
971
972 void GameList::SetPreferredView(bool list)
973 {
974 m_prefer_list = list;
975 Settings::Instance().SetPreferredView(list);
976 ConsiderViewChange();
977 }
978
979 void GameList::ConsiderViewChange()
980 {
981 if (m_model.rowCount(QModelIndex()) > 0)
982 {
983 if (m_prefer_list)
984 setCurrentWidget(m_list);
985 else
986 setCurrentWidget(m_grid);
987 }
988 else
989 {
990 setCurrentWidget(m_empty);
991 }
992 }
993 void GameList::keyPressEvent(QKeyEvent* event)
994 {
995 if (event->key() == Qt::Key_Return && GetSelectedGame() != nullptr)
996 {
997 if (event->modifiers() == Qt::AltModifier)
998 OpenProperties();
999 else
1000 emit GameSelected();
1001 }
1002 else
1003 {
1004 QStackedWidget::keyPressEvent(event);
1005 }
1006 }
1007
1008 void GameList::OnColumnVisibilityToggled(const QString& row, bool visible)
1009 {
1010 using Column = GameListModel::Column;
1011 static const QMap<QString, Column> rowname_to_column = {
1012 {tr("Platform"), Column::Platform},
1013 {tr("Banner"), Column::Banner},
1014 {tr("Title"), Column::Title},
1015 {tr("Description"), Column::Description},
1016 {tr("Maker"), Column::Maker},
1017 {tr("File Name"), Column::FileName},
1018 {tr("File Path"), Column::FilePath},
1019 {tr("Game ID"), Column::ID},
1020 {tr("Region"), Column::Country},
1021 {tr("File Size"), Column::Size},
1022 {tr("File Format"), Column::FileFormat},
1023 {tr("Block Size"), Column::BlockSize},
1024 {tr("Compression"), Column::Compression},
1025 {tr("Time Played"), Column::TimePlayed},
1026 {tr("Tags"), Column::Tags},
1027 };
1028
1029 m_list->setColumnHidden(static_cast<int>(rowname_to_column[row]), !visible);
1030 }
1031
1032 void GameList::OnGameListVisibilityChanged()
1033 {
1034 m_list_proxy->invalidate();
1035 m_grid_proxy->invalidate();
1036
1037 UpdateGameCount();
1038 }
1039
1040 void GameList::OnSectionResized(int index, int, int)
1041 {
1042 auto* hor_header = m_list->horizontalHeader();
1043
1044 const int vis_index = hor_header->visualIndex(index);
1045 const int col_count = hor_header->count() - hor_header->hiddenSectionCount();
1046
1047 bool last = true;
1048
1049 for (int i = vis_index + 1; i < col_count; i++)
1050 {
1051 const int logical_index = hor_header->logicalIndex(i);
1052 if (hor_header->sectionResizeMode(logical_index) != QHeaderView::Interactive)
1053 continue;
1054
1055 last = false;
1056 break;
1057 }
1058
1059 if (!last)
1060 {
1061 std::vector<int> sections;
1062 for (int i = 0; i < vis_index; i++)
1063 {
1064 const int logical_index = hor_header->logicalIndex(i);
1065 if (hor_header->sectionResizeMode(logical_index) != QHeaderView::Interactive)
1066 continue;
1067
1068 hor_header->setSectionResizeMode(logical_index, QHeaderView::Fixed);
1069 sections.push_back(i);
1070 }
1071
1072 OnHeaderViewChanged();
1073
1074 for (int i : sections)
1075 {
1076 hor_header->setSectionResizeMode(hor_header->logicalIndex(i), QHeaderView::Interactive);
1077 }
1078 }
1079 else
1080 {
1081 OnHeaderViewChanged();
1082 }
1083 }
1084
1085 void GameList::OnHeaderViewChanged()
1086 {
1087 static bool block = false;
1088
1089 if (block)
1090 return;
1091
1092 block = true;
1093
1094 UpdateColumnVisibility();
1095
1096 // So here's the deal: Qt's way of resizing stuff around stretched columns sucks ass
1097 // That's why instead of using Stretch, we'll just make resizable columns take all the available
1098 // space ourselves!
1099
1100 int available_width = width() - style()->pixelMetric(QStyle::PM_ScrollBarExtent);
1101 int previous_width = 0;
1102
1103 std::vector<int> candidate_columns;
1104
1105 // Iterate through all columns
1106 for (int i = 0; i < static_cast<int>(GameListModel::Column::Count); i++)
1107 {
1108 if (m_list->isColumnHidden(i))
1109 continue;
1110
1111 if (m_list->horizontalHeader()->sectionResizeMode(i) == QHeaderView::Fixed)
1112 {
1113 available_width -= m_list->columnWidth(i);
1114 }
1115 else
1116 {
1117 candidate_columns.push_back(i);
1118 previous_width += m_list->columnWidth(i);
1119 }
1120 }
1121
1122 for (int column : candidate_columns)
1123 {
1124 int column_width = static_cast<int>(
1125 std::max(5.f, std::ceil(available_width * (static_cast<float>(m_list->columnWidth(column)) /
1126 previous_width))));
1127
1128 m_list->setColumnWidth(column, column_width);
1129 }
1130
1131 block = false;
1132 }
1133
1134 void GameList::NewTag()
1135 {
1136 const auto tag =
1137 QInputDialog::getText(this, tr("New tag"), tr("Name for a new tag:"), QLineEdit::Normal,
1138 QString{}, nullptr, Qt::WindowCloseButtonHint);
1139
1140 if (tag.isEmpty())
1141 return;
1142
1143 m_model.NewTag(tag);
1144 }
1145
1146 void GameList::DeleteTag()
1147 {
1148 const auto tag =
1149 QInputDialog::getText(this, tr("Remove tag"), tr("Name of the tag to remove:"),
1150 QLineEdit::Normal, QString{}, nullptr, Qt::WindowCloseButtonHint);
1151
1152 if (tag.isEmpty())
1153 return;
1154
1155 m_model.DeleteTag(tag);
1156 }
1157
1158 void GameList::SetSearchTerm(const QString& term)
1159 {
1160 m_model.SetSearchTerm(term);
1161
1162 m_list_proxy->invalidate();
1163 m_grid_proxy->invalidate();
1164
1165 UpdateColumnVisibility();
1166 UpdateGameCount();
1167 }
1168
1169 void GameList::UpdateGameCount() const
1170 {
1171 const int total_games = m_model.rowCount(QModelIndex{});
1172 const int visible_games = m_list_proxy->rowCount();
1173
1174 emit GameCountUpdated(total_games, visible_games);
1175 }
1176
1177 void GameList::ZoomIn()
1178 {
1179 m_model.SetScale(m_model.GetScale() + 0.1);
1180
1181 m_list_proxy->invalidate();
1182 m_grid_proxy->invalidate();
1183
1184 UpdateFont();
1185 }
1186
1187 void GameList::ZoomOut()
1188 {
1189 if (m_model.GetScale() <= 0.1)
1190 return;
1191
1192 m_model.SetScale(m_model.GetScale() - 0.1);
1193
1194 m_list_proxy->invalidate();
1195 m_grid_proxy->invalidate();
1196
1197 UpdateFont();
1198 }
1199
1200 void GameList::UpdateFont()
1201 {
1202 QFont f;
1203
1204 f.setPointSizeF(m_model.GetScale() * f.pointSize());
1205
1206 m_grid->setFont(f);
1207 }