/
GameList.cpp
1096 lines (902 loc) · 34.6 KB
/
GameList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#ifdef _WIN32
#include <QCoreApplication>
#include <shlobj.h>
#include <wil/com.h>
// This file uses some identifiers which are defined as macros in Windows headers.
// Include and undefine the macros first thing we do to solve build errors.
#ifdef DeleteFile
#undef DeleteFile
#endif
#ifdef interface
#undef interface
#endif
#endif
#include "DolphinQt/GameList/GameList.h"
#include <algorithm>
#include <cmath>
#include <utility>
#include <QDesktopServices>
#include <QDir>
#include <QErrorMessage>
#include <QFileDialog>
#include <QFileInfo>
#include <QFrame>
#include <QHeaderView>
#include <QInputDialog>
#include <QKeyEvent>
#include <QLabel>
#include <QListView>
#include <QMap>
#include <QMenu>
#include <QShortcut>
#include <QSortFilterProxyModel>
#include <QTableView>
#include <QUrl>
#include "Common/CommonPaths.h"
#include "Common/FileUtil.h"
#include "Core/Config/MainSettings.h"
#include "Core/ConfigManager.h"
#include "Core/Core.h"
#include "Core/HW/DVD/DVDInterface.h"
#include "Core/HW/EXI/EXI_Device.h"
#include "Core/HW/WiiSave.h"
#include "Core/WiiUtils.h"
#include "DiscIO/Blob.h"
#include "DiscIO/Enums.h"
#include "DolphinQt/Config/PropertiesDialog.h"
#include "DolphinQt/ConvertDialog.h"
#include "DolphinQt/GameList/GridProxyModel.h"
#include "DolphinQt/GameList/ListProxyModel.h"
#include "DolphinQt/MenuBar.h"
#include "DolphinQt/QtUtils/DolphinFileDialog.h"
#include "DolphinQt/QtUtils/DoubleClickEventFilter.h"
#include "DolphinQt/QtUtils/ModalMessageBox.h"
#include "DolphinQt/QtUtils/ParallelProgressDialog.h"
#include "DolphinQt/Resources.h"
#include "DolphinQt/Settings.h"
#include "DolphinQt/WiiUpdate.h"
#include "UICommon/GameFile.h"
GameList::GameList(QWidget* parent) : QStackedWidget(parent), m_model(this)
{
m_list_proxy = new ListProxyModel(this);
m_list_proxy->setSortCaseSensitivity(Qt::CaseInsensitive);
m_list_proxy->setSortRole(GameListModel::SORT_ROLE);
m_list_proxy->setSourceModel(&m_model);
m_grid_proxy = new GridProxyModel(this);
m_grid_proxy->setSourceModel(&m_model);
MakeListView();
MakeGridView();
MakeEmptyView();
if (Settings::GetQSettings().contains(QStringLiteral("gridview/scale")))
m_model.SetScale(Settings::GetQSettings().value(QStringLiteral("gridview/scale")).toFloat());
connect(m_list, &QTableView::doubleClicked, this, &GameList::GameSelected);
connect(m_grid, &QListView::doubleClicked, this, &GameList::GameSelected);
connect(&m_model, &QAbstractItemModel::rowsInserted, this, &GameList::ConsiderViewChange);
connect(&m_model, &QAbstractItemModel::rowsRemoved, this, &GameList::ConsiderViewChange);
addWidget(m_list);
addWidget(m_grid);
addWidget(m_empty);
m_prefer_list = Settings::Instance().GetPreferredView();
ConsiderViewChange();
const auto* zoom_in = new QShortcut(QKeySequence::ZoomIn, this);
const auto* zoom_out = new QShortcut(QKeySequence::ZoomOut, this);
connect(zoom_in, &QShortcut::activated, this, &GameList::ZoomIn);
connect(zoom_out, &QShortcut::activated, this, &GameList::ZoomOut);
// On most keyboards the key to the left of the primary delete key represents 'plus' when shift is
// held and 'equal' when it isn't. By common convention, pressing control and that key is treated
// conceptually as 'control plus' (which is then interpreted as an appropriate zooming action)
// instead of the technically correct 'control equal'. Qt doesn't account for this convention so
// an alternate shortcut is needed to avoid counterintuitive behavior.
const auto* zoom_in_alternate = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Equal), this);
connect(zoom_in_alternate, &QShortcut::activated, this, &GameList::ZoomIn);
// The above correction introduces a different inconsistency: now zooming in can be done using
// conceptual 'control plus' or 'control shift plus', while zooming out can only be done using
// 'control minus'. Adding an alternate shortcut representing 'control shift minus' restores
// consistency.
const auto* zoom_out_alternate = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Underscore), this);
connect(zoom_out_alternate, &QShortcut::activated, this, &GameList::ZoomOut);
connect(&Settings::Instance(), &Settings::MetadataRefreshCompleted, this,
[this] { m_grid_proxy->invalidate(); });
}
void GameList::PurgeCache()
{
m_model.PurgeCache();
}
void GameList::MakeListView()
{
m_list = new QTableView(this);
m_list->setModel(m_list_proxy);
m_list->setTabKeyNavigation(false);
m_list->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_list->setSelectionBehavior(QAbstractItemView::SelectRows);
m_list->setAlternatingRowColors(true);
m_list->setShowGrid(false);
m_list->setSortingEnabled(true);
m_list->setCurrentIndex(QModelIndex());
m_list->setContextMenuPolicy(Qt::CustomContextMenu);
m_list->setWordWrap(false);
// Have 1 pixel of padding above and below the 32 pixel banners.
m_list->verticalHeader()->setDefaultSectionSize(32 + 2);
connect(m_list, &QTableView::customContextMenuRequested, this, &GameList::ShowContextMenu);
connect(m_list->selectionModel(), &QItemSelectionModel::selectionChanged,
[this](const QItemSelection&, const QItemSelection&) {
emit SelectionChanged(GetSelectedGame());
});
QHeaderView* hor_header = m_list->horizontalHeader();
hor_header->restoreState(
Settings::GetQSettings().value(QStringLiteral("tableheader/state")).toByteArray());
hor_header->setContextMenuPolicy(Qt::CustomContextMenu);
connect(hor_header, &QWidget::customContextMenuRequested, this, &GameList::ShowHeaderContextMenu);
connect(hor_header, &QHeaderView::sortIndicatorChanged, this, &GameList::OnHeaderViewChanged);
connect(hor_header, &QHeaderView::sectionCountChanged, this, &GameList::OnHeaderViewChanged);
connect(hor_header, &QHeaderView::sectionMoved, this, &GameList::OnHeaderViewChanged);
connect(hor_header, &QHeaderView::sectionResized, this, &GameList::OnSectionResized);
if (!Settings::GetQSettings().contains(QStringLiteral("tableheader/state")))
m_list->sortByColumn(static_cast<int>(GameListModel::Column::Title), Qt::AscendingOrder);
const auto SetResizeMode = [&hor_header](const GameListModel::Column column,
const QHeaderView::ResizeMode mode) {
hor_header->setSectionResizeMode(static_cast<int>(column), mode);
};
{
using Column = GameListModel::Column;
using Mode = QHeaderView::ResizeMode;
SetResizeMode(Column::Platform, Mode::Fixed);
SetResizeMode(Column::Banner, Mode::Fixed);
SetResizeMode(Column::Title, Mode::Interactive);
SetResizeMode(Column::Description, Mode::Interactive);
SetResizeMode(Column::Maker, Mode::Interactive);
SetResizeMode(Column::ID, Mode::Fixed);
SetResizeMode(Column::Country, Mode::Fixed);
SetResizeMode(Column::Size, Mode::Fixed);
SetResizeMode(Column::FileName, Mode::Interactive);
SetResizeMode(Column::FilePath, Mode::Interactive);
SetResizeMode(Column::FileFormat, Mode::Fixed);
SetResizeMode(Column::BlockSize, Mode::Fixed);
SetResizeMode(Column::Compression, Mode::Fixed);
SetResizeMode(Column::Tags, Mode::Interactive);
// Cells have 3 pixels of padding, so the width of these needs to be image width + 6. Banners
// are 96 pixels wide, platform and country icons are 32 pixels wide.
m_list->setColumnWidth(static_cast<int>(Column::Banner), 102);
m_list->setColumnWidth(static_cast<int>(Column::Platform), 38);
m_list->setColumnWidth(static_cast<int>(Column::Country), 38);
m_list->setColumnWidth(static_cast<int>(Column::Size), 85);
m_list->setColumnWidth(static_cast<int>(Column::ID), 70);
}
// There's some odd platform-specific behavior with default minimum section size
hor_header->setMinimumSectionSize(38);
UpdateColumnVisibility();
m_list->verticalHeader()->hide();
m_list->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_list->setFrameStyle(QFrame::NoFrame);
hor_header->setSectionsMovable(true);
hor_header->setHighlightSections(false);
}
GameList::~GameList()
{
Settings::GetQSettings().setValue(QStringLiteral("tableheader/state"),
m_list->horizontalHeader()->saveState());
Settings::GetQSettings().setValue(QStringLiteral("gridview/scale"), m_model.GetScale());
}
void GameList::UpdateColumnVisibility()
{
const auto& config = SConfig::GetInstance();
const auto SetVisiblity = [this](const GameListModel::Column column, const bool is_visible) {
m_list->setColumnHidden(static_cast<int>(column), !is_visible);
};
using Column = GameListModel::Column;
SetVisiblity(Column::Platform, config.m_showSystemColumn);
SetVisiblity(Column::Banner, config.m_showBannerColumn);
SetVisiblity(Column::Title, config.m_showTitleColumn);
SetVisiblity(Column::Description, config.m_showDescriptionColumn);
SetVisiblity(Column::Maker, config.m_showMakerColumn);
SetVisiblity(Column::ID, config.m_showIDColumn);
SetVisiblity(Column::Country, config.m_showRegionColumn);
SetVisiblity(Column::Size, config.m_showSizeColumn);
SetVisiblity(Column::FileName, config.m_showFileNameColumn);
SetVisiblity(Column::FilePath, config.m_showFilePathColumn);
SetVisiblity(Column::FileFormat, config.m_showFileFormatColumn);
SetVisiblity(Column::BlockSize, config.m_showBlockSizeColumn);
SetVisiblity(Column::Compression, config.m_showCompressionColumn);
SetVisiblity(Column::Tags, config.m_showTagsColumn);
}
void GameList::MakeEmptyView()
{
const QString refreshing_msg = tr("Refreshing...");
const QString empty_msg = tr("Dolphin could not find any GameCube/Wii ISOs or WADs.\n"
"Double-click here to set a games directory...");
m_empty = new QLabel(this);
m_empty->setText(refreshing_msg);
m_empty->setEnabled(false);
m_empty->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
auto event_filter = new DoubleClickEventFilter{m_empty};
m_empty->installEventFilter(event_filter);
connect(event_filter, &DoubleClickEventFilter::doubleClicked, [this] {
auto current_dir = QDir::currentPath();
auto dir = DolphinFileDialog::getExistingDirectory(this, tr("Select a Directory"), current_dir);
if (!dir.isEmpty())
Settings::Instance().AddPath(dir);
});
QSizePolicy size_policy{m_empty->sizePolicy()};
size_policy.setRetainSizeWhenHidden(true);
m_empty->setSizePolicy(size_policy);
connect(&Settings::Instance(), &Settings::GameListRefreshRequested, this,
[this, refreshing_msg = refreshing_msg] {
m_empty->setText(refreshing_msg);
m_empty->setEnabled(false);
});
connect(&Settings::Instance(), &Settings::GameListRefreshCompleted, this,
[this, empty_msg = empty_msg] {
m_empty->setText(empty_msg);
m_empty->setEnabled(true);
});
}
void GameList::resizeEvent(QResizeEvent* event)
{
OnHeaderViewChanged();
}
void GameList::MakeGridView()
{
m_grid = new QListView(this);
m_grid->setModel(m_grid_proxy);
m_grid->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_grid->setViewMode(QListView::IconMode);
m_grid->setResizeMode(QListView::Adjust);
m_grid->setUniformItemSizes(true);
m_grid->setContextMenuPolicy(Qt::CustomContextMenu);
m_grid->setFrameStyle(QFrame::NoFrame);
connect(m_grid, &QTableView::customContextMenuRequested, this, &GameList::ShowContextMenu);
connect(m_grid->selectionModel(), &QItemSelectionModel::selectionChanged,
[this](const QItemSelection&, const QItemSelection&) {
emit SelectionChanged(GetSelectedGame());
});
}
void GameList::ShowHeaderContextMenu(const QPoint& pos)
{
const MenuBar* const menu_bar = MenuBar::GetMenuBar();
if (!menu_bar)
return;
QMenu* const list_columns_menu = menu_bar->GetListColumnsMenu();
if (!list_columns_menu)
return;
const QWidget* const widget = qobject_cast<QWidget*>(sender());
list_columns_menu->exec(widget ? widget->mapToGlobal(pos) : pos);
}
void GameList::ShowContextMenu(const QPoint&)
{
if (!GetSelectedGame())
return;
QMenu* menu = new QMenu(this);
if (HasMultipleSelected())
{
const auto selected_games = GetSelectedGames();
if (std::all_of(selected_games.begin(), selected_games.end(),
[](const auto& game) { return game->ShouldAllowConversion(); }))
{
menu->addAction(tr("Convert Selected Files..."), this, &GameList::ConvertFile);
menu->addSeparator();
}
if (std::all_of(selected_games.begin(), selected_games.end(),
[](const auto& game) { return DiscIO::IsWii(game->GetPlatform()); }))
{
menu->addAction(tr("Export Wii Saves"), this, &GameList::ExportWiiSave);
menu->addSeparator();
}
menu->addAction(tr("Delete Selected Files..."), this, &GameList::DeleteFile);
}
else
{
const auto game = GetSelectedGame();
DiscIO::Platform platform = game->GetPlatform();
menu->addAction(tr("&Properties"), this, &GameList::OpenProperties);
if (platform != DiscIO::Platform::ELFOrDOL)
{
menu->addAction(tr("&Wiki"), this, &GameList::OpenWiki);
}
menu->addSeparator();
if (DiscIO::IsDisc(platform))
{
menu->addAction(tr("Set as &Default ISO"), this, &GameList::SetDefaultISO);
if (game->ShouldAllowConversion())
menu->addAction(tr("Convert File..."), this, &GameList::ConvertFile);
QAction* change_disc = menu->addAction(tr("Change &Disc"), this, &GameList::ChangeDisc);
connect(&Settings::Instance(), &Settings::EmulationStateChanged, change_disc,
[change_disc] { change_disc->setEnabled(Core::IsRunning()); });
change_disc->setEnabled(Core::IsRunning());
menu->addSeparator();
}
if (platform == DiscIO::Platform::WiiDisc)
{
auto* perform_disc_update = menu->addAction(tr("Perform System Update"), this,
[this, file_path = game->GetFilePath()] {
WiiUpdate::PerformDiscUpdate(file_path, this);
// Since the update may have installed a newer
// system menu, trigger a refresh.
Settings::Instance().NANDRefresh();
});
perform_disc_update->setEnabled(!Core::IsRunning() || !SConfig::GetInstance().bWii);
}
if (platform == DiscIO::Platform::WiiWAD)
{
QAction* wad_install_action = new QAction(tr("Install to the NAND"), menu);
QAction* wad_uninstall_action = new QAction(tr("Uninstall from the NAND"), menu);
connect(wad_install_action, &QAction::triggered, this, &GameList::InstallWAD);
connect(wad_uninstall_action, &QAction::triggered, this, &GameList::UninstallWAD);
for (QAction* a : {wad_install_action, wad_uninstall_action})
{
a->setEnabled(!Core::IsRunning());
menu->addAction(a);
}
if (!Core::IsRunning())
wad_uninstall_action->setEnabled(WiiUtils::IsTitleInstalled(game->GetTitleID()));
connect(&Settings::Instance(), &Settings::EmulationStateChanged, menu,
[=](Core::State state) {
wad_install_action->setEnabled(state == Core::State::Uninitialized);
wad_uninstall_action->setEnabled(state == Core::State::Uninitialized &&
WiiUtils::IsTitleInstalled(game->GetTitleID()));
});
menu->addSeparator();
}
if (platform == DiscIO::Platform::WiiWAD || platform == DiscIO::Platform::WiiDisc)
{
menu->addAction(tr("Open Wii &Save Folder"), this, &GameList::OpenWiiSaveFolder);
menu->addAction(tr("Export Wii Save"), this, &GameList::ExportWiiSave);
menu->addSeparator();
}
if (platform == DiscIO::Platform::GameCubeDisc)
{
menu->addAction(tr("Open GameCube &Save Folder"), this, &GameList::OpenGCSaveFolder);
menu->addSeparator();
}
menu->addAction(tr("Open &Containing Folder"), this, &GameList::OpenContainingFolder);
menu->addAction(tr("Delete File..."), this, &GameList::DeleteFile);
#ifdef _WIN32
menu->addAction(tr("Add Shortcut to Desktop"), this, [this] {
if (!AddShortcutToDesktop())
{
ModalMessageBox::critical(this, tr("Add Shortcut to Desktop"),
tr("There was an issue adding a shortcut to the desktop"));
}
});
#endif
menu->addSeparator();
auto* tags_menu = menu->addMenu(tr("Tags"));
auto path = game->GetFilePath();
auto game_tags = m_model.GetGameTags(path);
for (const auto& tag : m_model.GetAllTags())
{
auto* tag_action = tags_menu->addAction(tag);
tag_action->setCheckable(true);
tag_action->setChecked(game_tags.contains(tag));
connect(tag_action, &QAction::toggled, [path, tag, model = &m_model](bool checked) {
if (!checked)
model->RemoveGameTag(path, tag);
else
model->AddGameTag(path, tag);
});
}
menu->addAction(tr("New Tag..."), this, &GameList::NewTag);
menu->addAction(tr("Remove Tag..."), this, &GameList::DeleteTag);
menu->addSeparator();
QAction* netplay_host = new QAction(tr("Host with NetPlay"), menu);
connect(netplay_host, &QAction::triggered, [this, game] { emit NetPlayHost(*game); });
connect(&Settings::Instance(), &Settings::EmulationStateChanged, menu, [=](Core::State state) {
netplay_host->setEnabled(state == Core::State::Uninitialized);
});
netplay_host->setEnabled(!Core::IsRunning());
menu->addAction(netplay_host);
}
menu->exec(QCursor::pos());
}
void GameList::OpenProperties()
{
const auto game = GetSelectedGame();
if (!game)
return;
PropertiesDialog* properties = new PropertiesDialog(this, *game);
// Since the properties dialog locks the game file, it's important to free it as soon as it's
// closed so that the file can be moved or deleted.
properties->setAttribute(Qt::WA_DeleteOnClose, true);
connect(properties, &PropertiesDialog::OpenGeneralSettings, this, &GameList::OpenGeneralSettings);
properties->show();
}
void GameList::ExportWiiSave()
{
const QString export_dir = DolphinFileDialog::getExistingDirectory(
this, tr("Select Export Directory"), QString::fromStdString(File::GetUserPath(D_USER_IDX)),
QFileDialog::ShowDirsOnly);
if (export_dir.isEmpty())
return;
QList<std::string> failed;
for (const auto& game : GetSelectedGames())
{
if (WiiSave::Export(game->GetTitleID(), export_dir.toStdString()) !=
WiiSave::CopyResult::Success)
{
failed.push_back(game->GetName(UICommon::GameFile::Variant::LongAndPossiblyCustom));
}
}
if (!failed.isEmpty())
{
QString failed_str;
for (const std::string& str : failed)
failed_str.append(QLatin1Char{'\n'}).append(QString::fromStdString(str));
ModalMessageBox::critical(this, tr("Save Export"),
tr("Failed to export the following save files:") + failed_str);
}
else
{
ModalMessageBox::information(this, tr("Save Export"), tr("Successfully exported save files"));
}
}
void GameList::OpenWiki()
{
const auto game = GetSelectedGame();
if (!game)
return;
QString game_id = QString::fromStdString(game->GetGameID());
QString url =
QStringLiteral("https://wiki.dolphin-emu.org/dolphin-redirect.php?gameid=").append(game_id);
QDesktopServices::openUrl(QUrl(url));
}
void GameList::ConvertFile()
{
auto games = GetSelectedGames();
if (games.empty())
return;
ConvertDialog dialog{std::move(games), this};
dialog.exec();
}
void GameList::InstallWAD()
{
const auto game = GetSelectedGame();
if (!game)
return;
ModalMessageBox result_dialog(this);
const bool success = WiiUtils::InstallWAD(game->GetFilePath());
result_dialog.setIcon(success ? QMessageBox::Information : QMessageBox::Critical);
result_dialog.setWindowTitle(success ? tr("Success") : tr("Failure"));
result_dialog.setText(success ? tr("Successfully installed this title to the NAND.") :
tr("Failed to install this title to the NAND."));
result_dialog.exec();
}
void GameList::UninstallWAD()
{
const auto game = GetSelectedGame();
if (!game)
return;
ModalMessageBox warning_dialog(this);
warning_dialog.setIcon(QMessageBox::Information);
warning_dialog.setWindowTitle(tr("Confirm"));
warning_dialog.setText(tr("Uninstalling the WAD will remove the currently installed version of "
"this title from the NAND without deleting its save data. Continue?"));
warning_dialog.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
if (warning_dialog.exec() == QMessageBox::No)
return;
ModalMessageBox result_dialog(this);
const bool success = WiiUtils::UninstallTitle(game->GetTitleID());
result_dialog.setIcon(success ? QMessageBox::Information : QMessageBox::Critical);
result_dialog.setWindowTitle(success ? tr("Success") : tr("Failure"));
result_dialog.setText(success ? tr("Successfully removed this title from the NAND.") :
tr("Failed to remove this title from the NAND."));
result_dialog.exec();
}
void GameList::SetDefaultISO()
{
const auto game = GetSelectedGame();
if (!game)
return;
Settings::Instance().SetDefaultGame(
QDir::toNativeSeparators(QString::fromStdString(game->GetFilePath())));
}
void GameList::OpenContainingFolder()
{
const auto game = GetSelectedGame();
if (!game)
return;
// Remove everything after the last separator in the game's path, resulting in the parent
// directory path with a trailing separator. Keeping the trailing separator prevents Windows from
// mistakenly opening a .bat or .exe file in the grandparent folder when that file has the same
// base name as the folder (See https://bugs.dolphin-emu.org/issues/12411).
std::string parent_directory_path;
SplitPath(game->GetFilePath(), &parent_directory_path, nullptr, nullptr);
if (parent_directory_path.empty())
{
return;
}
const QUrl url = QUrl::fromLocalFile(QString::fromStdString(parent_directory_path));
QDesktopServices::openUrl(url);
}
void GameList::OpenWiiSaveFolder()
{
const auto game = GetSelectedGame();
if (!game)
return;
QUrl url = QUrl::fromLocalFile(QString::fromStdString(game->GetWiiFSPath()));
QDesktopServices::openUrl(url);
}
void GameList::OpenGCSaveFolder()
{
const auto game = GetSelectedGame();
if (!game)
return;
bool found = false;
for (int i = 0; i < 2; i++)
{
QUrl url;
switch (SConfig::GetInstance().m_EXIDevice[i])
{
case ExpansionInterface::EXIDEVICE_MEMORYCARDFOLDER:
{
std::string path = StringFromFormat("%s/%s/%s", File::GetUserPath(D_GCUSER_IDX).c_str(),
SConfig::GetDirectoryForRegion(game->GetRegion()),
i == 0 ? "Card A" : "Card B");
std::string override_path = i == 0 ? Config::Get(Config::MAIN_GCI_FOLDER_A_PATH_OVERRIDE) :
Config::Get(Config::MAIN_GCI_FOLDER_B_PATH_OVERRIDE);
if (!override_path.empty())
path = override_path;
QDir dir(QString::fromStdString(path));
if (!dir.entryList({QStringLiteral("%1-%2-*.gci")
.arg(QString::fromStdString(game->GetMakerID()))
.arg(QString::fromStdString(game->GetGameID().substr(0, 4)))})
.empty())
{
url = QUrl::fromLocalFile(dir.absolutePath());
}
break;
}
case ExpansionInterface::EXIDEVICE_MEMORYCARD:
{
std::string memcard_path = i == 0 ? Config::Get(Config::MAIN_MEMCARD_A_PATH) :
Config::Get(Config::MAIN_MEMCARD_B_PATH);
std::string memcard_dir;
SplitPath(memcard_path, &memcard_dir, nullptr, nullptr);
url = QUrl::fromLocalFile(QString::fromStdString(memcard_dir));
break;
}
default:
break;
}
found |= !url.isEmpty();
if (!url.isEmpty())
QDesktopServices::openUrl(url);
}
if (!found)
ModalMessageBox::information(this, tr("Information"), tr("No save data found."));
}
#ifdef _WIN32
bool GameList::AddShortcutToDesktop()
{
auto init = wil::CoInitializeEx_failfast(COINIT_APARTMENTTHREADED);
auto shell_link = wil::CoCreateInstanceNoThrow<ShellLink, IShellLink>();
if (!shell_link)
return false;
std::wstring dolphin_path = QCoreApplication::applicationFilePath().toStdWString();
if (FAILED(shell_link->SetPath(dolphin_path.c_str())))
return false;
const auto game = GetSelectedGame();
const auto& file_path = game->GetFilePath();
std::wstring args = UTF8ToTStr("-e \"" + file_path + "\"");
if (FAILED(shell_link->SetArguments(args.c_str())))
return false;
wil::unique_cotaskmem_string desktop;
if (FAILED(SHGetKnownFolderPath(FOLDERID_Desktop, KF_FLAG_NO_ALIAS, nullptr, &desktop)))
return false;
std::string game_name = game->GetName(Core::TitleDatabase());
// Sanitize the string by removing all characters that cannot be used in NTFS file names
game_name.erase(std::remove_if(game_name.begin(), game_name.end(),
[](char ch) {
static constexpr char illegal_characters[] = {
'<', '>', ':', '\"', '/', '\\', '|', '?', '*'};
return std::find(std::begin(illegal_characters),
std::end(illegal_characters),
ch) != std::end(illegal_characters);
}),
game_name.end());
std::wstring desktop_path = std::wstring(desktop.get()) + UTF8ToTStr("\\" + game_name + ".lnk");
auto persist_file = shell_link.try_query<IPersistFile>();
if (!persist_file)
return false;
if (FAILED(persist_file->Save(desktop_path.c_str(), TRUE)))
return false;
return true;
}
#endif
void GameList::DeleteFile()
{
ModalMessageBox confirm_dialog(this);
confirm_dialog.setIcon(QMessageBox::Warning);
confirm_dialog.setWindowTitle(tr("Confirm"));
confirm_dialog.setText(tr("Are you sure you want to delete this file?"));
confirm_dialog.setInformativeText(tr("This cannot be undone!"));
confirm_dialog.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
if (confirm_dialog.exec() == QMessageBox::Yes)
{
for (const auto& game : GetSelectedGames())
{
bool deletion_successful = false;
while (!deletion_successful)
{
deletion_successful = File::Delete(game->GetFilePath());
if (deletion_successful)
{
m_model.RemoveGame(game->GetFilePath());
}
else
{
ModalMessageBox error_dialog(this);
error_dialog.setIcon(QMessageBox::Critical);
error_dialog.setWindowTitle(tr("Failure"));
error_dialog.setText(tr("Failed to delete the selected file."));
error_dialog.setInformativeText(tr("Check whether you have the permissions required to "
"delete the file or whether it's still in use."));
error_dialog.setStandardButtons(QMessageBox::Retry | QMessageBox::Abort);
if (error_dialog.exec() == QMessageBox::Abort)
break;
}
}
if (!deletion_successful)
break; // Something is wrong, so we should abort the whole thing
}
}
}
void GameList::ChangeDisc()
{
const auto game = GetSelectedGame();
if (!game)
return;
Core::RunAsCPUThread([file_path = game->GetFilePath()] { DVDInterface::ChangeDisc(file_path); });
}
std::shared_ptr<const UICommon::GameFile> GameList::GetSelectedGame() const
{
QAbstractItemView* view;
QSortFilterProxyModel* proxy;
if (currentWidget() == m_list)
{
view = m_list;
proxy = m_list_proxy;
}
else
{
view = m_grid;
proxy = m_grid_proxy;
}
QItemSelectionModel* sel_model = view->selectionModel();
if (sel_model->hasSelection())
{
QModelIndex model_index = proxy->mapToSource(sel_model->selectedIndexes()[0]);
return m_model.GetGameFile(model_index.row());
}
return {};
}
QList<std::shared_ptr<const UICommon::GameFile>> GameList::GetSelectedGames() const
{
QAbstractItemView* view;
QSortFilterProxyModel* proxy;
if (currentWidget() == m_list)
{
view = m_list;
proxy = m_list_proxy;
}
else
{
view = m_grid;
proxy = m_grid_proxy;
}
QList<std::shared_ptr<const UICommon::GameFile>> selected_list;
QItemSelectionModel* sel_model = view->selectionModel();
if (sel_model->hasSelection())
{
QModelIndexList index_list =
currentWidget() == m_list ? sel_model->selectedRows() : sel_model->selectedIndexes();
for (const auto& index : index_list)
{
QModelIndex model_index = proxy->mapToSource(index);
selected_list.push_back(m_model.GetGameFile(model_index.row()));
}
}
return selected_list;
}
bool GameList::HasMultipleSelected() const
{
return currentWidget() == m_list ? m_list->selectionModel()->selectedRows().size() > 1 :
m_grid->selectionModel()->selectedIndexes().size() > 1;
}
std::shared_ptr<const UICommon::GameFile> GameList::FindGame(const std::string& path) const
{
return m_model.FindGame(path);
}
std::shared_ptr<const UICommon::GameFile>
GameList::FindSecondDisc(const UICommon::GameFile& game) const
{
return m_model.FindSecondDisc(game);
}
std::string GameList::GetNetPlayName(const UICommon::GameFile& game) const
{
return m_model.GetNetPlayName(game);
}
void GameList::SetViewColumn(int col, bool view)
{
m_list->setColumnHidden(col, !view);
}
void GameList::SetPreferredView(bool list)
{
m_prefer_list = list;
Settings::Instance().SetPreferredView(list);
ConsiderViewChange();
}
void GameList::ConsiderViewChange()
{
if (m_model.rowCount(QModelIndex()) > 0)
{
if (m_prefer_list)
setCurrentWidget(m_list);
else
setCurrentWidget(m_grid);
}
else
{
setCurrentWidget(m_empty);
}
}
void GameList::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Return && GetSelectedGame() != nullptr)
{
if (event->modifiers() == Qt::AltModifier)
OpenProperties();
else
emit GameSelected();
}
else
{
QStackedWidget::keyPressEvent(event);
}
}
void GameList::OnColumnVisibilityToggled(const QString& row, bool visible)
{
using Column = GameListModel::Column;
static const QMap<QString, Column> rowname_to_column = {
{tr("Platform"), Column::Platform},
{tr("Banner"), Column::Banner},
{tr("Title"), Column::Title},
{tr("Description"), Column::Description},
{tr("Maker"), Column::Maker},
{tr("File Name"), Column::FileName},
{tr("File Path"), Column::FilePath},
{tr("Game ID"), Column::ID},
{tr("Region"), Column::Country},
{tr("File Size"), Column::Size},
{tr("File Format"), Column::FileFormat},
{tr("Block Size"), Column::BlockSize},
{tr("Compression"), Column::Compression},
{tr("Tags"), Column::Tags},
};
m_list->setColumnHidden(static_cast<int>(rowname_to_column[row]), !visible);
}
void GameList::OnGameListVisibilityChanged()
{
m_list_proxy->invalidate();
m_grid_proxy->invalidate();
}
void GameList::OnSectionResized(int index, int, int)
{
auto* hor_header = m_list->horizontalHeader();
std::vector<int> sections;
const int vis_index = hor_header->visualIndex(index);
const int col_count = hor_header->count() - hor_header->hiddenSectionCount();
bool last = true;
for (int i = vis_index + 1; i < col_count; i++)
{
const int logical_index = hor_header->logicalIndex(i);
if (hor_header->sectionResizeMode(logical_index) != QHeaderView::Interactive)
continue;
last = false;
break;
}
if (!last)
{
for (int i = 0; i < vis_index; i++)
{
const int logical_index = hor_header->logicalIndex(i);
if (hor_header->sectionResizeMode(logical_index) != QHeaderView::Interactive)
continue;
hor_header->setSectionResizeMode(logical_index, QHeaderView::Fixed);
sections.push_back(i);
}
OnHeaderViewChanged();
for (int i : sections)
{
hor_header->setSectionResizeMode(hor_header->logicalIndex(i), QHeaderView::Interactive);
}
}
else
{
OnHeaderViewChanged();
}
}
void GameList::OnHeaderViewChanged()
{
static bool block = false;
if (block)
return;
block = true;
UpdateColumnVisibility();
// So here's the deal: Qt's way of resizing stuff around stretched columns sucks ass
// That's why instead of using Stretch, we'll just make resizable columns take all the available
// space ourselves!
int available_width = width() - style()->pixelMetric(QStyle::PM_ScrollBarExtent);
int previous_width = 0;