Debian Codegraph @

Source/Core/DolphinQt/MainWindow.cpp

raw symbols SCIP
1 // Copyright 2015 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DolphinQt/MainWindow.h"
5
6 #include <QApplication>
7 #include <QCloseEvent>
8 #include <QDateTime>
9 #include <QDesktopServices>
10 #include <QDir>
11 #include <QDragEnterEvent>
12 #include <QDropEvent>
13 #include <QFileInfo>
14 #include <QIcon>
15 #include <QMimeData>
16 #include <QStackedWidget>
17 #include <QStyleHints>
18 #include <QVBoxLayout>
19 #include <QWindow>
20
21 #include <fmt/format.h>
22
23 #include <future>
24 #include <optional>
25 #include <utility>
26 #include <variant>
27
28 #if defined(__unix__) || defined(__unix) || defined(__APPLE__)
29 #include <signal.h>
30
31 #include "QtUtils/SignalDaemon.h"
32 #endif
33
34 #ifndef _WIN32
35 #include <qpa/qplatformnativeinterface.h>
36 #endif
37
38 #include "Common/Config/Config.h"
39 #include "Common/FileUtil.h"
40 #include "Common/ScopeGuard.h"
41 #include "Common/Version.h"
42 #include "Common/WindowSystemInfo.h"
43
44 #include "Core/AchievementManager.h"
45 #include "Core/Boot/Boot.h"
46 #include "Core/BootManager.h"
47 #include "Core/CommonTitles.h"
48 #include "Core/Config/AchievementSettings.h"
49 #include "Core/Config/MainSettings.h"
50 #include "Core/Config/NetplaySettings.h"
51 #include "Core/Config/UISettings.h"
52 #include "Core/Config/WiimoteSettings.h"
53 #include "Core/Core.h"
54 #include "Core/FreeLookManager.h"
55 #include "Core/HW/DVD/DVDInterface.h"
56 #include "Core/HW/GBAPad.h"
57 #include "Core/HW/GCKeyboard.h"
58 #include "Core/HW/GCPad.h"
59 #include "Core/HW/ProcessorInterface.h"
60 #include "Core/HW/SI/SI_Device.h"
61 #include "Core/HW/Wiimote.h"
62 #include "Core/HotkeyManager.h"
63 #include "Core/IOS/USB/Bluetooth/BTEmu.h"
64 #include "Core/Movie.h"
65 #include "Core/NetPlayClient.h"
66 #include "Core/NetPlayProto.h"
67 #include "Core/NetPlayServer.h"
68 #include "Core/State.h"
69 #include "Core/System.h"
70 #include "Core/WiiUtils.h"
71
72 #include "DiscIO/DirectoryBlob.h"
73 #include "DiscIO/NANDImporter.h"
74 #include "DiscIO/RiivolutionPatcher.h"
75
76 #include "DolphinQt/AboutDialog.h"
77 #include "DolphinQt/Achievements/AchievementsWindow.h"
78 #include "DolphinQt/CheatsManager.h"
79 #include "DolphinQt/Config/FreeLookWindow.h"
80 #include "DolphinQt/Config/LogConfigWidget.h"
81 #include "DolphinQt/Config/LogWidget.h"
82 #include "DolphinQt/Config/Mapping/MappingWindow.h"
83 #include "DolphinQt/Config/SettingsWindow.h"
84 #include "DolphinQt/Debugger/AssemblerWidget.h"
85 #include "DolphinQt/Debugger/BreakpointWidget.h"
86 #include "DolphinQt/Debugger/CodeViewWidget.h"
87 #include "DolphinQt/Debugger/CodeWidget.h"
88 #include "DolphinQt/Debugger/JITWidget.h"
89 #include "DolphinQt/Debugger/MemoryWidget.h"
90 #include "DolphinQt/Debugger/NetworkWidget.h"
91 #include "DolphinQt/Debugger/RegisterWidget.h"
92 #include "DolphinQt/Debugger/ThreadWidget.h"
93 #include "DolphinQt/Debugger/WatchWidget.h"
94 #include "DolphinQt/DiscordHandler.h"
95 #include "DolphinQt/EmulatedUSB/LogitechMicWindow.h"
96 #include "DolphinQt/EmulatedUSB/WiiSpeakWindow.h"
97 #include "DolphinQt/FIFO/FIFOPlayerWindow.h"
98 #include "DolphinQt/GCMemcardManager.h"
99 #include "DolphinQt/GameCount.h"
100 #include "DolphinQt/GameList/GameList.h"
101 #include "DolphinQt/Host.h"
102 #include "DolphinQt/HotkeyScheduler.h"
103 #include "DolphinQt/InfinityBase/InfinityBaseWindow.h"
104 #include "DolphinQt/MenuBar.h"
105 #include "DolphinQt/NKitWarningDialog.h"
106 #include "DolphinQt/NetPlay/NetPlayBrowser.h"
107 #include "DolphinQt/NetPlay/NetPlayDialog.h"
108 #include "DolphinQt/NetPlay/NetPlaySetupDialog.h"
109 #include "DolphinQt/QtUtils/DolphinFileDialog.h"
110 #include "DolphinQt/QtUtils/FileOpenEventFilter.h"
111 #include "DolphinQt/QtUtils/ModalMessageBox.h"
112 #include "DolphinQt/QtUtils/ParallelProgressDialog.h"
113 #include "DolphinQt/QtUtils/QueueOnObject.h"
114 #include "DolphinQt/QtUtils/RunOnObject.h"
115 #include "DolphinQt/QtUtils/WindowActivationEventFilter.h"
116 #include "DolphinQt/RenderWidget.h"
117 #include "DolphinQt/ResourcePackManager.h"
118 #include "DolphinQt/Resources.h"
119 #include "DolphinQt/RiivolutionBootWidget.h"
120 #include "DolphinQt/SearchBar.h"
121 #include "DolphinQt/Settings.h"
122 #include "DolphinQt/SkylanderPortal/SkylanderPortalWindow.h"
123 #include "DolphinQt/TAS/GBATASInputWindow.h"
124 #include "DolphinQt/TAS/GCTASInputWindow.h"
125 #include "DolphinQt/TAS/WiiTASInputWindow.h"
126 #include "DolphinQt/ToolBar.h"
127 #include "DolphinQt/WiiUpdate.h"
128
129 #include "UICommon/DiscordPresence.h"
130 #include "UICommon/GameFile.h"
131 #include "UICommon/ResourcePack/Manager.h"
132 #include "UICommon/ResourcePack/ResourcePack.h"
133
134 #include "UICommon/UICommon.h"
135
136 #include "VideoCommon/NetPlayChatUI.h"
137
138 #ifdef HAVE_XRANDR
139 #include "UICommon/X11Utils.h"
140 // This #define within X11/X.h conflicts with our WiimoteSource enum.
141 #undef None
142 #endif
143
144 #if defined(__unix__) || defined(__unix) || defined(__APPLE__)
145 void MainWindow::OnSignal()
146 {
147 close();
148 }
149
150 static void InstallSignalHandler()
151 {
152 struct sigaction sa;
153 sa.sa_handler = &SignalDaemon::HandleInterrupt;
154 sigemptyset(&sa.sa_mask);
155 sa.sa_flags = SA_RESTART | SA_RESETHAND;
156 sigaction(SIGINT, &sa, nullptr);
157 sigaction(SIGTERM, &sa, nullptr);
158 }
159 #endif
160
161 static WindowSystemType GetWindowSystemType()
162 {
163 // Determine WSI type based on Qt platform.
164 QString platform_name = QGuiApplication::platformName();
165 if (platform_name == QStringLiteral("windows"))
166 return WindowSystemType::Windows;
167 else if (platform_name == QStringLiteral("cocoa"))
168 return WindowSystemType::MacOS;
169 else if (platform_name == QStringLiteral("xcb"))
170 return WindowSystemType::X11;
171 else if (platform_name == QStringLiteral("wayland"))
172 return WindowSystemType::Wayland;
173 else if (platform_name == QStringLiteral("haiku"))
174 return WindowSystemType::Haiku;
175
176 ModalMessageBox::critical(
177 nullptr, QStringLiteral("Error"),
178 QString::asprintf("Unknown Qt platform: %s", platform_name.toStdString().c_str()));
179 return WindowSystemType::Headless;
180 }
181
182 static WindowSystemInfo GetWindowSystemInfo(QWindow* window)
183 {
184 WindowSystemInfo wsi;
185 wsi.type = GetWindowSystemType();
186
187 // Our Win32 Qt external doesn't have the private API.
188 #if defined(WIN32) || defined(__APPLE__) || defined(__HAIKU__)
189 wsi.render_window = window ? reinterpret_cast<void*>(window->winId()) : nullptr;
190 wsi.render_surface = wsi.render_window;
191 #else
192 QPlatformNativeInterface* pni = QGuiApplication::platformNativeInterface();
193 wsi.display_connection = pni->nativeResourceForWindow("display", window);
194 if (wsi.type == WindowSystemType::Wayland)
195 wsi.render_window = window ? pni->nativeResourceForWindow("surface", window) : nullptr;
196 else
197 wsi.render_window = window ? reinterpret_cast<void*>(window->winId()) : nullptr;
198 wsi.render_surface = wsi.render_window;
199 #endif
200 wsi.render_surface_scale = window ? static_cast<float>(window->devicePixelRatio()) : 1.0f;
201
202 return wsi;
203 }
204
205 static std::vector<std::string> StringListToStdVector(const QStringList& list)
206 {
207 std::vector<std::string> result;
208 result.reserve(list.size());
209
210 for (const QString& s : list)
211 result.push_back(s.toStdString());
212
213 return result;
214 }
215
216 MainWindow::MainWindow(Core::System& system, std::unique_ptr<BootParameters> boot_parameters,
217 const std::string& movie_path)
218 : QMainWindow(nullptr), m_system(system)
219 {
220 setWindowTitle(QString::fromStdString(Common::GetScmRevStr()));
221 setWindowIcon(Resources::GetAppIcon());
222 setUnifiedTitleAndToolBarOnMac(true);
223 setAcceptDrops(true);
224 setAttribute(Qt::WA_NativeWindow);
225
226 CreateComponents();
227
228 ConnectGameList();
229 ConnectHost();
230 ConnectToolBar();
231 ConnectRenderWidget();
232 ConnectStack();
233 ConnectMenuBar();
234
235 QSettings& settings = Settings::GetQSettings();
236 restoreState(settings.value(QStringLiteral("mainwindow/state")).toByteArray());
237 restoreGeometry(settings.value(QStringLiteral("mainwindow/geometry")).toByteArray());
238 if (!Settings::Instance().IsBatchModeEnabled())
239 {
240 show();
241 }
242
243 InitControllers();
244 ConnectHotkeys();
245
246 #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
247 connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged, this,
248 [this](Qt::ColorScheme colorScheme) {
249 Settings::Instance().ApplyStyle();
250 if (m_skylander_window)
251 m_skylander_window->RefreshList();
252 });
253 #endif
254
255 #ifdef USE_RETRO_ACHIEVEMENTS
256 connect(m_game_list, &GameList::OpenAchievementSettings, this,
257 &MainWindow::ShowAchievementSettings);
258 #endif // USE_RETRO_ACHIEVEMENTS
259
260 InitCoreCallbacks();
261
262 NetPlayInit();
263
264 #ifdef USE_RETRO_ACHIEVEMENTS
265 AchievementManager::GetInstance().Init(reinterpret_cast<void*>(winId()));
266 if (AchievementManager::GetInstance().IsHardcoreModeActive())
267 Settings::Instance().SetDebugModeEnabled(false);
268 // This needs to trigger on both RA_HARDCORE_ENABLED and RA_ENABLED
269 m_config_changed_callback_id = Config::AddConfigChangedCallback(
270 [this] { QueueOnObject(this, [this] { this->OnHardcoreChanged(); }); });
271 // If hardcore is enabled when the emulator starts, make sure it turns off what it needs to
272 if (Config::Get(Config::RA_HARDCORE_ENABLED))
273 OnHardcoreChanged();
274 #endif // USE_RETRO_ACHIEVEMENTS
275
276 #if defined(__unix__) || defined(__unix) || defined(__APPLE__)
277 auto* daemon = new SignalDaemon(this);
278
279 connect(daemon, &SignalDaemon::InterruptReceived, this, &MainWindow::OnSignal);
280
281 InstallSignalHandler();
282 #endif
283
284 if (boot_parameters)
285 {
286 m_pending_boot = std::move(boot_parameters);
287
288 if (!movie_path.empty())
289 {
290 std::optional<std::string> savestate_path;
291 if (m_system.GetMovie().PlayInput(movie_path, &savestate_path))
292 {
293 m_pending_boot->boot_session_data.SetSavestateData(std::move(savestate_path),
294 DeleteSavestateAfterBoot::No);
295 emit RecordingStatusChanged(true);
296 }
297 }
298 }
299
300 m_state_slot =
301 std::clamp(Settings::Instance().GetStateSlot(), 1, static_cast<int>(State::NUM_STATES));
302
303 m_render_widget_geometry = settings.value(QStringLiteral("renderwidget/geometry")).toByteArray();
304
305 // Restoring of window states can sometimes go wrong, resulting in widgets being visible when they
306 // shouldn't be so we have to reapply all our rules afterwards.
307 Settings::Instance().RefreshWidgetVisibility();
308
309 if (!ResourcePack::Init())
310 {
311 ModalMessageBox::critical(this, tr("Error"),
312 tr("Error occurred while loading some texture packs"));
313 }
314
315 for (auto& pack : ResourcePack::GetPacks())
316 {
317 if (!pack.IsValid())
318 {
319 ModalMessageBox::critical(this, tr("Error"),
320 tr("Invalid Pack %1 provided: %2")
321 .arg(QString::fromStdString(pack.GetPath()))
322 .arg(QString::fromStdString(pack.GetError())));
323 return;
324 }
325 }
326
327 Host::GetInstance()->SetMainWindowHandle(reinterpret_cast<void*>(winId()));
328
329 if (m_pending_boot != nullptr)
330 {
331 StartGame(std::move(m_pending_boot));
332 m_pending_boot.reset();
333 }
334 }
335
336 MainWindow::~MainWindow()
337 {
338 // Shut down NetPlay first to avoid race condition segfault
339 Settings::Instance().ResetNetPlayClient();
340 Settings::Instance().ResetNetPlayServer();
341
342 #ifdef USE_RETRO_ACHIEVEMENTS
343 Config::RemoveConfigChangedCallback(m_config_changed_callback_id);
344 AchievementManager::GetInstance().Shutdown();
345 #endif // USE_RETRO_ACHIEVEMENTS
346
347 delete m_render_widget;
348 delete m_netplay_dialog;
349
350 for (int i = 0; i < 4; i++)
351 {
352 delete m_gc_tas_input_windows[i];
353 delete m_gba_tas_input_windows[i];
354 delete m_wii_tas_input_windows[i];
355 }
356
357 ShutdownControllers();
358
359 QSettings& settings = Settings::GetQSettings();
360
361 if (!Settings::Instance().IsBatchModeEnabled())
362 {
363 settings.setValue(QStringLiteral("mainwindow/state"), saveState());
364 settings.setValue(QStringLiteral("mainwindow/geometry"), saveGeometry());
365 }
366
367 settings.setValue(QStringLiteral("renderwidget/geometry"), m_render_widget_geometry);
368
369 Config::Save();
370 }
371
372 WindowSystemInfo MainWindow::GetWindowSystemInfo() const
373 {
374 return ::GetWindowSystemInfo(m_render_widget->windowHandle());
375 }
376
377 void MainWindow::InitControllers()
378 {
379 if (g_controller_interface.IsInit())
380 return;
381
382 UICommon::InitControllers(::GetWindowSystemInfo(windowHandle()));
383
384 m_hotkey_scheduler = new HotkeyScheduler();
385 m_hotkey_scheduler->Start();
386
387 // Defaults won't work reliably without loading and saving the config first
388
389 Wiimote::LoadConfig();
390 Wiimote::GetConfig()->SaveConfig();
391
392 Pad::LoadConfig();
393 Pad::GetConfig()->SaveConfig();
394
395 Pad::LoadGBAConfig();
396 Pad::GetGBAConfig()->SaveConfig();
397
398 Keyboard::LoadConfig();
399 Keyboard::GetConfig()->SaveConfig();
400
401 FreeLook::LoadInputConfig();
402 FreeLook::GetInputConfig()->SaveConfig();
403 }
404
405 void MainWindow::ShutdownControllers()
406 {
407 m_hotkey_scheduler->Stop();
408
409 Settings::Instance().UnregisterDevicesChangedCallback();
410
411 UICommon::ShutdownControllers();
412
413 m_hotkey_scheduler->deleteLater();
414 }
415
416 void MainWindow::InitCoreCallbacks()
417 {
418 connect(&Settings::Instance(), &Settings::EmulationStateChanged, this, [this](Core::State state) {
419 if (state == Core::State::Uninitialized)
420 OnStopComplete();
421
422 if (state == Core::State::Running && m_fullscreen_requested)
423 {
424 FullScreen();
425 m_fullscreen_requested = false;
426 }
427 });
428 installEventFilter(this);
429 m_render_widget->installEventFilter(this);
430
431 // Handle file open events
432 auto* filter = new FileOpenEventFilter(QGuiApplication::instance());
433 connect(filter, &FileOpenEventFilter::fileOpened, this, [this](const QString& file_name) {
434 StartGame(BootParameters::GenerateFromFile(file_name.toStdString()));
435 });
436 }
437
438 static void InstallHotkeyFilter(QWidget* dialog)
439 {
440 auto* filter = new WindowActivationEventFilter(dialog);
441 dialog->installEventFilter(filter);
442
443 filter->connect(filter, &WindowActivationEventFilter::windowDeactivated,
444 [] { HotkeyManagerEmu::Enable(true); });
445 filter->connect(filter, &WindowActivationEventFilter::windowActivated,
446 [] { HotkeyManagerEmu::Enable(false); });
447 }
448
449 void MainWindow::CreateComponents()
450 {
451 m_menu_bar = new MenuBar(this);
452 m_tool_bar = new ToolBar(this);
453 m_search_bar = new SearchBar(this);
454 m_game_count = new GameCount(this);
455 m_game_list = new GameList(this);
456 m_render_widget = new RenderWidget;
457 m_stack = new QStackedWidget(this);
458
459 for (int i = 0; i < 4; i++)
460 {
461 m_gc_tas_input_windows[i] = new GCTASInputWindow(nullptr, i);
462 m_gba_tas_input_windows[i] = new GBATASInputWindow(nullptr, i);
463 m_wii_tas_input_windows[i] = new WiiTASInputWindow(nullptr, i);
464 }
465
466 m_jit_widget = new JITWidget(m_system, this);
467 m_log_widget = new LogWidget(this);
468 m_log_config_widget = new LogConfigWidget(this);
469 m_memory_widget = new MemoryWidget(m_system, this);
470 m_network_widget = new NetworkWidget(this);
471 m_register_widget = new RegisterWidget(this);
472 m_thread_widget = new ThreadWidget(this);
473 m_watch_widget = new WatchWidget(this);
474 m_breakpoint_widget = new BreakpointWidget(this);
475 m_code_widget = new CodeWidget(this);
476 m_assembler_widget = new AssemblerWidget(this);
477
478 const auto request_watch = [this](const QString& name, u32 addr) {
479 m_watch_widget->AddWatch(name, addr);
480 };
481 const auto request_breakpoint = [this](u32 addr) { m_breakpoint_widget->AddBP(addr); };
482 const auto request_memory_breakpoint = [this](u32 addr) {
483 m_breakpoint_widget->AddAddressMBP(addr);
484 };
485 const auto request_view_in_memory = [this](u32 addr) { m_memory_widget->SetAddress(addr); };
486 const auto request_view_in_code = [this](u32 addr) {
487 m_code_widget->SetAddress(addr, CodeViewWidget::SetAddressUpdate::WithDetailedUpdate);
488 };
489
490 connect(m_jit_widget, &JITWidget::SetCodeAddress, m_code_widget, &CodeWidget::OnSetCodeAddress);
491 connect(m_watch_widget, &WatchWidget::RequestMemoryBreakpoint, request_memory_breakpoint);
492 connect(m_watch_widget, &WatchWidget::ShowMemory, m_memory_widget, &MemoryWidget::SetAddress);
493 connect(m_register_widget, &RegisterWidget::RequestMemoryBreakpoint, request_memory_breakpoint);
494 connect(m_register_widget, &RegisterWidget::RequestWatch, request_watch);
495 connect(m_register_widget, &RegisterWidget::RequestViewInMemory, request_view_in_memory);
496 connect(m_register_widget, &RegisterWidget::RequestViewInCode, request_view_in_code);
497 connect(m_thread_widget, &ThreadWidget::RequestBreakpoint, request_breakpoint);
498 connect(m_thread_widget, &ThreadWidget::RequestMemoryBreakpoint, request_memory_breakpoint);
499 connect(m_thread_widget, &ThreadWidget::RequestWatch, request_watch);
500 connect(m_thread_widget, &ThreadWidget::RequestViewInMemory, request_view_in_memory);
501 connect(m_thread_widget, &ThreadWidget::RequestViewInCode, request_view_in_code);
502
503 connect(m_code_widget, &CodeWidget::RequestPPCComparison, m_jit_widget,
504 &JITWidget::OnRequestPPCComparison);
505 connect(m_code_widget, &CodeWidget::ShowMemory, m_memory_widget, &MemoryWidget::SetAddress);
506 connect(m_memory_widget, &MemoryWidget::ShowCode, m_code_widget, [this](u32 address) {
507 m_code_widget->SetAddress(address, CodeViewWidget::SetAddressUpdate::WithDetailedUpdate);
508 });
509 connect(m_memory_widget, &MemoryWidget::RequestWatch, request_watch);
510
511 connect(m_breakpoint_widget, &BreakpointWidget::ShowCode, [this](u32 address) {
512 if (Core::GetState(m_system) == Core::State::Paused)
513 m_code_widget->SetAddress(address, CodeViewWidget::SetAddressUpdate::WithDetailedUpdate);
514 });
515 connect(m_breakpoint_widget, &BreakpointWidget::ShowMemory, m_memory_widget,
516 &MemoryWidget::SetAddress);
517 }
518
519 void MainWindow::ConnectMenuBar()
520 {
521 setMenuBar(m_menu_bar);
522 // File
523 connect(m_menu_bar, &MenuBar::Open, this, &MainWindow::Open);
524 connect(m_menu_bar, &MenuBar::Exit, this, &MainWindow::close);
525 connect(m_menu_bar, &MenuBar::EjectDisc, this, &MainWindow::EjectDisc);
526 connect(m_menu_bar, &MenuBar::ChangeDisc, this, &MainWindow::ChangeDisc);
527 connect(m_menu_bar, &MenuBar::OpenUserFolder, this, &MainWindow::OpenUserFolder);
528 connect(m_menu_bar, &MenuBar::OpenConfigFolder, this, &MainWindow::OpenConfigFolder);
529 connect(m_menu_bar, &MenuBar::OpenCacheFolder, this, &MainWindow::OpenCacheFolder);
530
531 // Emulation
532 connect(m_menu_bar, &MenuBar::Pause, this, &MainWindow::Pause);
533 connect(m_menu_bar, &MenuBar::Play, this, [this] { Play(); });
534 connect(m_menu_bar, &MenuBar::Stop, this, &MainWindow::RequestStop);
535 connect(m_menu_bar, &MenuBar::Reset, this, &MainWindow::Reset);
536 connect(m_menu_bar, &MenuBar::Fullscreen, this, &MainWindow::FullScreen);
537 connect(m_menu_bar, &MenuBar::FrameAdvance, this, &MainWindow::FrameAdvance);
538 connect(m_menu_bar, &MenuBar::Screenshot, this, &MainWindow::ScreenShot);
539 connect(m_menu_bar, &MenuBar::StateLoad, this, &MainWindow::StateLoad);
540 connect(m_menu_bar, &MenuBar::StateSave, this, &MainWindow::StateSave);
541 connect(m_menu_bar, &MenuBar::StateLoadSlot, this, &MainWindow::StateLoadSlot);
542 connect(m_menu_bar, &MenuBar::StateSaveSlot, this, &MainWindow::StateSaveSlot);
543 connect(m_menu_bar, &MenuBar::StateLoadSlotAt, this, &MainWindow::StateLoadSlotAt);
544 connect(m_menu_bar, &MenuBar::StateSaveSlotAt, this, &MainWindow::StateSaveSlotAt);
545 connect(m_menu_bar, &MenuBar::StateLoadUndo, this, &MainWindow::StateLoadUndo);
546 connect(m_menu_bar, &MenuBar::StateSaveUndo, this, &MainWindow::StateSaveUndo);
547 connect(m_menu_bar, &MenuBar::StateSaveOldest, this, &MainWindow::StateSaveOldest);
548 connect(m_menu_bar, &MenuBar::SetStateSlot, this, &MainWindow::SetStateSlot);
549
550 // Options
551 connect(m_menu_bar, &MenuBar::Configure, this, &MainWindow::ShowSettingsWindow);
552 connect(m_menu_bar, &MenuBar::ConfigureGraphics, this, &MainWindow::ShowGraphicsWindow);
553 connect(m_menu_bar, &MenuBar::ConfigureAudio, this, &MainWindow::ShowAudioWindow);
554 connect(m_menu_bar, &MenuBar::ConfigureControllers, this, &MainWindow::ShowControllersWindow);
555 connect(m_menu_bar, &MenuBar::ConfigureHotkeys, this, &MainWindow::ShowHotkeyDialog);
556 connect(m_menu_bar, &MenuBar::ConfigureFreelook, this, &MainWindow::ShowFreeLookWindow);
557
558 // Tools
559 connect(m_menu_bar, &MenuBar::ShowMemcardManager, this, &MainWindow::ShowMemcardManager);
560 connect(m_menu_bar, &MenuBar::ShowResourcePackManager, this,
561 &MainWindow::ShowResourcePackManager);
562 connect(m_menu_bar, &MenuBar::ShowCheatsManager, this, &MainWindow::ShowCheatsManager);
563 connect(m_menu_bar, &MenuBar::BootGameCubeIPL, this, &MainWindow::OnBootGameCubeIPL);
564 connect(m_menu_bar, &MenuBar::ImportNANDBackup, this, &MainWindow::OnImportNANDBackup);
565 connect(m_menu_bar, &MenuBar::PerformOnlineUpdate, this, &MainWindow::PerformOnlineUpdate);
566 connect(m_menu_bar, &MenuBar::BootWiiSystemMenu, this, &MainWindow::BootWiiSystemMenu);
567 connect(m_menu_bar, &MenuBar::StartNetPlay, this, &MainWindow::ShowNetPlaySetupDialog);
568 connect(m_menu_bar, &MenuBar::BrowseNetPlay, this, &MainWindow::ShowNetPlayBrowser);
569 connect(m_menu_bar, &MenuBar::ShowFIFOPlayer, this, &MainWindow::ShowFIFOPlayer);
570 connect(m_menu_bar, &MenuBar::ShowSkylanderPortal, this, &MainWindow::ShowSkylanderPortal);
571 connect(m_menu_bar, &MenuBar::ShowInfinityBase, this, &MainWindow::ShowInfinityBase);
572 connect(m_menu_bar, &MenuBar::ShowWiiSpeakWindow, this, &MainWindow::ShowWiiSpeakWindow);
573 connect(m_menu_bar, &MenuBar::ShowLogitechMicWindow, this, &MainWindow::ShowLogitechMicWindow);
574 connect(m_menu_bar, &MenuBar::ConnectWiiRemote, this, &MainWindow::OnConnectWiiRemote);
575
576 #ifdef USE_RETRO_ACHIEVEMENTS
577 connect(m_menu_bar, &MenuBar::ShowAchievementsWindow, this, &MainWindow::ShowAchievementsWindow);
578 #endif // USE_RETRO_ACHIEVEMENTS
579
580 // Movie
581 connect(m_menu_bar, &MenuBar::PlayRecording, this, &MainWindow::OnPlayRecording);
582 connect(m_menu_bar, &MenuBar::StartRecording, this, &MainWindow::OnStartRecording);
583 connect(m_menu_bar, &MenuBar::StopRecording, this, &MainWindow::OnStopRecording);
584 connect(m_menu_bar, &MenuBar::ExportRecording, this, &MainWindow::OnExportRecording);
585 connect(m_menu_bar, &MenuBar::ShowTASInput, this, &MainWindow::ShowTASInput);
586 connect(m_menu_bar, &MenuBar::ConfigureOSD, this, &MainWindow::ShowOSDWindow);
587
588 // View
589 connect(m_menu_bar, &MenuBar::ShowList, m_game_list, &GameList::SetListView);
590 connect(m_menu_bar, &MenuBar::ShowGrid, m_game_list, &GameList::SetGridView);
591 connect(m_menu_bar, &MenuBar::PurgeGameListCache, m_game_list, &GameList::PurgeCache);
592 connect(m_menu_bar, &MenuBar::ShowSearch, m_search_bar, &SearchBar::Show);
593
594 connect(m_menu_bar, &MenuBar::ColumnVisibilityToggled, m_game_list,
595 &GameList::OnColumnVisibilityToggled);
596
597 connect(m_menu_bar, &MenuBar::GameListPlatformVisibilityToggled, m_game_list,
598 &GameList::OnGameListVisibilityChanged);
599 connect(m_menu_bar, &MenuBar::GameListRegionVisibilityToggled, m_game_list,
600 &GameList::OnGameListVisibilityChanged);
601
602 connect(m_menu_bar, &MenuBar::ShowAboutDialog, this, &MainWindow::ShowAboutDialog);
603
604 connect(m_game_list, &GameList::SelectionChanged, m_menu_bar, &MenuBar::SelectionChanged);
605 connect(this, &MainWindow::ReadOnlyModeChanged, m_menu_bar, &MenuBar::ReadOnlyModeChanged);
606 connect(this, &MainWindow::RecordingStatusChanged, m_menu_bar, &MenuBar::RecordingStatusChanged);
607 }
608
609 void MainWindow::ConnectHotkeys()
610 {
611 connect(m_hotkey_scheduler, &HotkeyScheduler::Open, this, &MainWindow::Open);
612 connect(m_hotkey_scheduler, &HotkeyScheduler::ChangeDisc, this, &MainWindow::ChangeDisc);
613 connect(m_hotkey_scheduler, &HotkeyScheduler::EjectDisc, this, &MainWindow::EjectDisc);
614 connect(m_hotkey_scheduler, &HotkeyScheduler::ExitHotkey, this, &MainWindow::close);
615 connect(m_hotkey_scheduler, &HotkeyScheduler::UnlockCursor, this, &MainWindow::UnlockCursor);
616 connect(m_hotkey_scheduler, &HotkeyScheduler::TogglePauseHotkey, this, &MainWindow::TogglePause);
617 connect(m_hotkey_scheduler, &HotkeyScheduler::ActivateChat, this, &MainWindow::OnActivateChat);
618 connect(m_hotkey_scheduler, &HotkeyScheduler::RequestGolfControl, this,
619 &MainWindow::OnRequestGolfControl);
620 connect(m_hotkey_scheduler, &HotkeyScheduler::RefreshGameListHotkey, this,
621 &MainWindow::RefreshGameList);
622 connect(m_hotkey_scheduler, &HotkeyScheduler::StopHotkey, this, &MainWindow::RequestStop);
623 connect(m_hotkey_scheduler, &HotkeyScheduler::ResetHotkey, this, &MainWindow::Reset);
624 connect(m_hotkey_scheduler, &HotkeyScheduler::ScreenShotHotkey, this, &MainWindow::ScreenShot);
625 connect(m_hotkey_scheduler, &HotkeyScheduler::FullScreenHotkey, this, &MainWindow::FullScreen);
626
627 connect(m_hotkey_scheduler, &HotkeyScheduler::StateLoadSlot, this, &MainWindow::StateLoadSlotAt);
628 connect(m_hotkey_scheduler, &HotkeyScheduler::StateSaveSlot, this, &MainWindow::StateSaveSlotAt);
629 connect(m_hotkey_scheduler, &HotkeyScheduler::StateLoadLastSaved, this,
630 &MainWindow::StateLoadLastSavedAt);
631 connect(m_hotkey_scheduler, &HotkeyScheduler::StateLoadUndo, this, &MainWindow::StateLoadUndo);
632 connect(m_hotkey_scheduler, &HotkeyScheduler::StateSaveUndo, this, &MainWindow::StateSaveUndo);
633 connect(m_hotkey_scheduler, &HotkeyScheduler::StateSaveOldest, this,
634 &MainWindow::StateSaveOldest);
635 connect(m_hotkey_scheduler, &HotkeyScheduler::StateSaveFile, this, &MainWindow::StateSave);
636 connect(m_hotkey_scheduler, &HotkeyScheduler::StateLoadFile, this, &MainWindow::StateLoad);
637
638 connect(m_hotkey_scheduler, &HotkeyScheduler::StateLoadSlotHotkey, this,
639 &MainWindow::StateLoadSlot);
640 connect(m_hotkey_scheduler, &HotkeyScheduler::StateSaveSlotHotkey, this,
641 &MainWindow::StateSaveSlot);
642 connect(m_hotkey_scheduler, &HotkeyScheduler::SetStateSlotHotkey, this,
643 &MainWindow::SetStateSlot);
644 connect(m_hotkey_scheduler, &HotkeyScheduler::IncrementSelectedStateSlotHotkey, this,
645 &MainWindow::IncrementSelectedStateSlot);
646 connect(m_hotkey_scheduler, &HotkeyScheduler::DecrementSelectedStateSlotHotkey, this,
647 &MainWindow::DecrementSelectedStateSlot);
648 connect(m_hotkey_scheduler, &HotkeyScheduler::StartRecording, this,
649 &MainWindow::OnStartRecording);
650 connect(m_hotkey_scheduler, &HotkeyScheduler::PlayRecording, this, &MainWindow::OnPlayRecording);
651 connect(m_hotkey_scheduler, &HotkeyScheduler::ExportRecording, this,
652 &MainWindow::OnExportRecording);
653 connect(m_hotkey_scheduler, &HotkeyScheduler::ConnectWiiRemote, this,
654 &MainWindow::OnConnectWiiRemote);
655 connect(m_hotkey_scheduler, &HotkeyScheduler::ToggleReadOnlyMode, [this] {
656 auto& movie = m_system.GetMovie();
657 bool read_only = !movie.IsReadOnly();
658 movie.SetReadOnly(read_only);
659 emit ReadOnlyModeChanged(read_only);
660 });
661 #ifdef USE_RETRO_ACHIEVEMENTS
662 connect(m_hotkey_scheduler, &HotkeyScheduler::OpenAchievements, this,
663 &MainWindow::ShowAchievementsWindow, Qt::QueuedConnection);
664 #endif // USE_RETRO_ACHIEVEMENTS
665
666 connect(m_hotkey_scheduler, &HotkeyScheduler::Step, m_code_widget, &CodeWidget::Step);
667 connect(m_hotkey_scheduler, &HotkeyScheduler::StepOver, m_code_widget, &CodeWidget::StepOver);
668 connect(m_hotkey_scheduler, &HotkeyScheduler::StepOut, m_code_widget, &CodeWidget::StepOut);
669 connect(m_hotkey_scheduler, &HotkeyScheduler::Skip, m_code_widget, &CodeWidget::Skip);
670
671 connect(m_hotkey_scheduler, &HotkeyScheduler::ShowPC, m_code_widget, &CodeWidget::ShowPC);
672 connect(m_hotkey_scheduler, &HotkeyScheduler::SetPC, m_code_widget, &CodeWidget::SetPC);
673
674 connect(m_hotkey_scheduler, &HotkeyScheduler::ToggleBreakpoint, m_code_widget,
675 &CodeWidget::ToggleBreakpoint);
676 connect(m_hotkey_scheduler, &HotkeyScheduler::AddBreakpoint, m_code_widget,
677 &CodeWidget::AddBreakpoint);
678
679 connect(m_hotkey_scheduler, &HotkeyScheduler::SkylandersPortalHotkey, this,
680 &MainWindow::ShowSkylanderPortal);
681 connect(m_hotkey_scheduler, &HotkeyScheduler::InfinityBaseHotkey, this,
682 &MainWindow::ShowInfinityBase);
683 }
684
685 void MainWindow::ConnectToolBar()
686 {
687 addToolBar(m_tool_bar);
688
689 connect(m_tool_bar, &ToolBar::OpenPressed, this, &MainWindow::Open);
690 connect(m_tool_bar, &ToolBar::RefreshPressed, this, &MainWindow::RefreshGameList);
691
692 connect(m_tool_bar, &ToolBar::PlayPressed, this, [this] { Play(); });
693 connect(m_tool_bar, &ToolBar::PausePressed, this, &MainWindow::Pause);
694 connect(m_tool_bar, &ToolBar::StopPressed, this, &MainWindow::RequestStop);
695 connect(m_tool_bar, &ToolBar::FullScreenPressed, this, &MainWindow::FullScreen);
696 connect(m_tool_bar, &ToolBar::ScreenShotPressed, this, &MainWindow::ScreenShot);
697 connect(m_tool_bar, &ToolBar::SettingsPressed, this, &MainWindow::ShowSettingsWindow);
698 connect(m_tool_bar, &ToolBar::ControllersPressed, this, &MainWindow::ShowControllersWindow);
699 connect(m_tool_bar, &ToolBar::GraphicsPressed, this, &MainWindow::ShowGraphicsWindow);
700
701 connect(m_tool_bar, &ToolBar::StepPressed, m_code_widget, &CodeWidget::Step);
702 connect(m_tool_bar, &ToolBar::StepOverPressed, m_code_widget, &CodeWidget::StepOver);
703 connect(m_tool_bar, &ToolBar::StepOutPressed, m_code_widget, &CodeWidget::StepOut);
704 connect(m_tool_bar, &ToolBar::SkipPressed, m_code_widget, &CodeWidget::Skip);
705 connect(m_tool_bar, &ToolBar::ShowPCPressed, m_code_widget, &CodeWidget::ShowPC);
706 connect(m_tool_bar, &ToolBar::SetPCPressed, m_code_widget, &CodeWidget::SetPC);
707 }
708
709 void MainWindow::ConnectGameList()
710 {
711 connect(m_game_list, &GameList::GameSelected, this, [this] { Play(); });
712 connect(m_game_list, &GameList::NetPlayHost, this, &MainWindow::NetPlayHost);
713 connect(m_game_list, &GameList::OnStartWithRiivolution, this,
714 &MainWindow::ShowRiivolutionBootWidget);
715
716 connect(m_game_list, &GameList::OpenGeneralSettings, this, &MainWindow::ShowGeneralWindow);
717 connect(m_game_list, &GameList::OpenGraphicsSettings, this, &MainWindow::ShowGraphicsWindow);
718 }
719
720 void MainWindow::ConnectRenderWidget()
721 {
722 m_rendering_to_main = false;
723 m_render_widget->hide();
724 connect(m_render_widget, &RenderWidget::Closed, this, &MainWindow::ForceStop);
725 connect(m_render_widget, &RenderWidget::FocusChanged, this, [this](bool focus) {
726 if (m_render_widget->isFullScreen())
727 SetFullScreenResolution(focus);
728 });
729 }
730
731 void MainWindow::ConnectHost()
732 {
733 connect(Host::GetInstance(), &Host::RequestStop, this, &MainWindow::RequestStop);
734 }
735
736 void MainWindow::ConnectStack()
737 {
738 auto* widget = new QWidget;
739 auto* layout = new QVBoxLayout;
740 widget->setLayout(layout);
741
742 layout->addWidget(m_game_list);
743 layout->addWidget(m_search_bar);
744 layout->addWidget(m_game_count);
745 layout->setSpacing(0);
746 layout->setContentsMargins(0, 0, 0, 0);
747
748 connect(m_search_bar, &SearchBar::Search, m_game_list, &GameList::SetSearchTerm);
749 connect(m_game_list, &GameList::GameCountUpdated, m_game_count, &GameCount::OnGameCountUpdated);
750
751 m_game_list->UpdateGameCount();
752
753 const auto update_spacing = [this](const bool game_count_is_visible) {
754 // The bottom margin of the search bar and the top margin of the game count are both suitable
755 // when the other widget is hidden, but when both are visible the gap created by the combination
756 // is too large. To fix this we set the bottom margin of the search bar to 0 when the game count
757 // is visible and set it to the top margin when the game count is hidden.
758 m_game_count->setVisible(game_count_is_visible);
759 auto* const search_layout = m_search_bar->layout();
760 QMargins search_margins = search_layout->contentsMargins();
761 const int new_bottom_margin = game_count_is_visible ? 0 : search_margins.top();
762 search_margins.setBottom(new_bottom_margin);
763 search_layout->setContentsMargins(search_margins);
764 };
765 update_spacing(Settings::Instance().IsGameCountVisible());
766
767 connect(&Settings::Instance(), &Settings::GameCountVisibilityChanged, update_spacing);
768
769 m_stack->addWidget(widget);
770
771 setCentralWidget(m_stack);
772
773 setDockOptions(DockOption::AllowNestedDocks | DockOption::AllowTabbedDocks);
774 setTabPosition(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea, QTabWidget::North);
775 addDockWidget(Qt::LeftDockWidgetArea, m_log_widget);
776 addDockWidget(Qt::LeftDockWidgetArea, m_log_config_widget);
777 addDockWidget(Qt::LeftDockWidgetArea, m_code_widget);
778 addDockWidget(Qt::LeftDockWidgetArea, m_register_widget);
779 addDockWidget(Qt::LeftDockWidgetArea, m_thread_widget);
780 addDockWidget(Qt::LeftDockWidgetArea, m_watch_widget);
781 addDockWidget(Qt::LeftDockWidgetArea, m_breakpoint_widget);
782 addDockWidget(Qt::LeftDockWidgetArea, m_memory_widget);
783 addDockWidget(Qt::LeftDockWidgetArea, m_network_widget);
784 addDockWidget(Qt::LeftDockWidgetArea, m_jit_widget);
785 addDockWidget(Qt::LeftDockWidgetArea, m_assembler_widget);
786
787 tabifyDockWidget(m_log_widget, m_log_config_widget);
788 tabifyDockWidget(m_log_widget, m_code_widget);
789 tabifyDockWidget(m_log_widget, m_register_widget);
790 tabifyDockWidget(m_log_widget, m_thread_widget);
791 tabifyDockWidget(m_log_widget, m_watch_widget);
792 tabifyDockWidget(m_log_widget, m_breakpoint_widget);
793 tabifyDockWidget(m_log_widget, m_memory_widget);
794 tabifyDockWidget(m_log_widget, m_network_widget);
795 tabifyDockWidget(m_log_widget, m_jit_widget);
796 tabifyDockWidget(m_log_widget, m_assembler_widget);
797 }
798
799 void MainWindow::RefreshGameList()
800 {
801 Settings::Instance().ReloadTitleDB();
802 Settings::Instance().RefreshGameList();
803 }
804
805 QStringList MainWindow::PromptFileNames()
806 {
807 auto& settings = Settings::Instance().GetQSettings();
808 QStringList paths = DolphinFileDialog::getOpenFileNames(
809 this, tr("Select a File"),
810 settings.value(QStringLiteral("mainwindow/lastdir"), QString{}).toString(),
811 QStringLiteral("%1 (*.elf *.dol *.gcm *.bin *.iso *.tgc *.wbfs *.ciso *.gcz *.wia *.rvz "
812 "hif_000000.nfs *.wad *.dff *.m3u *.json);;%2 (*)")
813 .arg(tr("All GC/Wii files"))
814 .arg(tr("All Files")));
815
816 if (!paths.isEmpty())
817 {
818 settings.setValue(QStringLiteral("mainwindow/lastdir"),
819 QFileInfo(paths.front()).absoluteDir().absolutePath());
820 }
821
822 return paths;
823 }
824
825 void MainWindow::ChangeDisc()
826 {
827 std::vector<std::string> paths = StringListToStdVector(PromptFileNames());
828
829 if (paths.empty())
830 return;
831
832 m_system.GetDVDInterface().ChangeDisc(Core::CPUThreadGuard{m_system}, paths);
833 }
834
835 void MainWindow::EjectDisc()
836 {
837 m_system.GetDVDInterface().EjectDisc(Core::CPUThreadGuard{m_system}, DVD::EjectCause::User);
838 }
839
840 void MainWindow::OpenUserFolder()
841 {
842 std::string path = File::GetUserPath(D_USER_IDX);
843
844 QUrl url = QUrl::fromLocalFile(QString::fromStdString(path));
845 QDesktopServices::openUrl(url);
846 }
847
848 void MainWindow::OpenConfigFolder()
849 {
850 std::string path = File::GetUserPath(D_CONFIG_IDX);
851
852 QUrl url = QUrl::fromLocalFile(QString::fromStdString(path));
853 QDesktopServices::openUrl(url);
854 }
855
856 void MainWindow::OpenCacheFolder()
857 {
858 std::string path = File::GetUserPath(D_CACHE_IDX);
859
860 QUrl url = QUrl::fromLocalFile(QString::fromStdString(path));
861 QDesktopServices::openUrl(url);
862 }
863
864 void MainWindow::Open()
865 {
866 QStringList files = PromptFileNames();
867 if (!files.isEmpty())
868 StartGame(StringListToStdVector(files));
869 }
870
871 void MainWindow::Play(const std::optional<std::string>& savestate_path)
872 {
873 // If we're in a paused game, start it up again.
874 // Otherwise, play the selected game, if there is one.
875 // Otherwise, play the default game.
876 // Otherwise, play the last played game, if there is one.
877 // Otherwise, prompt for a new game.
878 if (Core::GetState(m_system) == Core::State::Paused)
879 {
880 Core::SetState(m_system, Core::State::Running);
881 }
882 else
883 {
884 std::shared_ptr<const UICommon::GameFile> selection = m_game_list->GetSelectedGame();
885 if (selection)
886 {
887 StartGame(selection->GetFilePath(), ScanForSecondDisc::Yes,
888 std::make_unique<BootSessionData>(savestate_path, DeleteSavestateAfterBoot::No));
889 }
890 else
891 {
892 const QString default_path = QString::fromStdString(Config::Get(Config::MAIN_DEFAULT_ISO));
893 if (!default_path.isEmpty() && QFile::exists(default_path))
894 {
895 StartGame(default_path, ScanForSecondDisc::Yes,
896 std::make_unique<BootSessionData>(savestate_path, DeleteSavestateAfterBoot::No));
897 }
898 else
899 {
900 Open();
901 }
902 }
903 }
904 }
905
906 void MainWindow::Pause()
907 {
908 Core::SetState(m_system, Core::State::Paused);
909 }
910
911 void MainWindow::TogglePause()
912 {
913 if (Core::GetState(m_system) == Core::State::Paused)
914 {
915 Play();
916 }
917 else
918 {
919 Pause();
920 }
921 }
922
923 void MainWindow::OnStopComplete()
924 {
925 m_stop_requested = false;
926 HideRenderWidget(!m_exit_requested, m_exit_requested);
927 #ifdef USE_DISCORD_PRESENCE
928 if (!m_netplay_dialog->isVisible())
929 Discord::UpdateDiscordPresence();
930 #endif
931
932 SetFullScreenResolution(false);
933
934 if (m_exit_requested || Settings::Instance().IsBatchModeEnabled())
935 {
936 if (m_assembler_widget->ApplicationCloseRequest())
937 {
938 QGuiApplication::exit(0);
939 }
940 else
941 {
942 m_exit_requested = false;
943 }
944 }
945
946 // If the current emulation prevented the booting of another, do that now
947 if (m_pending_boot != nullptr)
948 {
949 StartGame(std::move(m_pending_boot));
950 m_pending_boot.reset();
951 }
952 }
953
954 bool MainWindow::RequestStop()
955 {
956 if (Core::IsUninitialized(m_system))
957 {
958 Core::QueueHostJob([this](Core::System&) { OnStopComplete(); }, true);
959 return true;
960 }
961
962 const bool rendered_widget_was_active =
963 Settings::Instance().IsKeepWindowOnTopEnabled() ||
964 (m_render_widget->isActiveWindow() && !m_render_widget->isFullScreen());
965 QWidget* confirm_parent = (!m_rendering_to_main && rendered_widget_was_active) ?
966 m_render_widget :
967 static_cast<QWidget*>(this);
968 const bool was_cursor_locked = m_render_widget->IsCursorLocked();
969
970 if (!m_render_widget->isFullScreen())
971 m_render_widget_geometry = m_render_widget->saveGeometry();
972 else
973 FullScreen();
974
975 bool confirm_on_stop = Config::Get(Config::MAIN_CONFIRM_ON_STOP);
976 #ifdef RC_CLIENT_SUPPORTS_RAINTEGRATION
977 confirm_on_stop = confirm_on_stop || AchievementManager::GetInstance().CheckForModifications();
978 #endif // RC_CLIENT_SUPPORTS_RAINTEGRATION
979 if (confirm_on_stop)
980 {
981 if (std::exchange(m_stop_confirm_showing, true))
982 return true;
983
984 Common::ScopeGuard confirm_lock([this] { m_stop_confirm_showing = false; });
985
986 const Core::State state = Core::GetState(m_system);
987
988 // Only pause the game, if NetPlay is not running
989 bool pause = !Settings::Instance().GetNetPlayClient();
990
991 if (pause)
992 Core::SetState(m_system, Core::State::Paused);
993
994 if (rendered_widget_was_active)
995 {
996 // We have to do this before creating the message box, otherwise we might receive the window
997 // activation event before we know we need to lock the cursor again.
998 m_render_widget->SetCursorLockedOnNextActivation(was_cursor_locked);
999 }
1000
1001 // This is to avoid any "race conditions" between the "Window Activate" message and the
1002 // message box returning, which could break cursor locking depending on the order
1003 m_render_widget->SetWaitingForMessageBox(true);
1004 QString message;
1005 if (m_stop_requested)
1006 {
1007 message = tr("A shutdown is already in progress. Unsaved data "
1008 "may be lost if you stop the current emulation "
1009 "before it completes. Force stop?");
1010 }
1011 #ifdef RC_CLIENT_SUPPORTS_RAINTEGRATION
1012 else if (AchievementManager::GetInstance().CheckForModifications())
1013 {
1014 message = tr(
1015 "Do you want to stop the current emulation? Unsaved achievement modifications detected.");
1016 }
1017 #endif // RC_CLIENT_SUPPORTS_RAINTEGRATION
1018 else
1019 {
1020 message = tr("Do you want to stop the current emulation?");
1021 }
1022 auto confirm = ModalMessageBox::question(confirm_parent, tr("Confirm"), message,
1023 QMessageBox::Yes | QMessageBox::No,
1024 QMessageBox::NoButton, Qt::ApplicationModal);
1025
1026 // If a user confirmed stopping the emulation, we do not capture the cursor again,
1027 // even if the render widget will stay alive for a while.
1028 // If a used rejected stopping the emulation, we instead capture the cursor again,
1029 // and let them continue playing as if nothing had happened
1030 // (assuming cursor locking is on).
1031 if (confirm != QMessageBox::Yes)
1032 {
1033 m_render_widget->SetWaitingForMessageBox(false);
1034
1035 if (pause)
1036 Core::SetState(m_system, state);
1037
1038 return false;
1039 }
1040 else
1041 {
1042 m_render_widget->SetCursorLockedOnNextActivation(false);
1043 // This needs to be after SetCursorLockedOnNextActivation(false) as it depends on it
1044 m_render_widget->SetWaitingForMessageBox(false);
1045 }
1046 }
1047
1048 OnStopRecording();
1049 // TODO: Add Debugger shutdown
1050
1051 if (!m_stop_requested && UICommon::TriggerSTMPowerEvent())
1052 {
1053 m_stop_requested = true;
1054
1055 // Unpause because gracefully shutting down needs the game to actually request a shutdown.
1056 // TODO: Do not unpause in debug mode to allow debugging until the complete shutdown.
1057 if (Core::GetState(m_system) == Core::State::Paused)
1058 Core::SetState(m_system, Core::State::Running);
1059
1060 // Tell NetPlay about the power event
1061 if (NetPlay::IsNetPlayRunning())
1062 NetPlay::SendPowerButtonEvent();
1063
1064 return true;
1065 }
1066
1067 ForceStop();
1068 #ifdef Q_OS_WIN
1069 // Allow windows to idle or turn off display again
1070 SetThreadExecutionState(ES_CONTINUOUS);
1071 #endif
1072 return true;
1073 }
1074
1075 void MainWindow::ForceStop()
1076 {
1077 Core::Stop(m_system);
1078 }
1079
1080 void MainWindow::Reset()
1081 {
1082 auto& movie = m_system.GetMovie();
1083 if (movie.IsRecordingInput())
1084 movie.SetReset(true);
1085 m_system.GetProcessorInterface().ResetButton_Tap();
1086 }
1087
1088 void MainWindow::FrameAdvance()
1089 {
1090 Core::DoFrameStep(m_system);
1091 }
1092
1093 void MainWindow::FullScreen()
1094 {
1095 // If the render widget is fullscreen we want to reset it to whatever is in
1096 // settings. If it's set to be fullscreen then it just remakes the window,
1097 // which probably isn't ideal.
1098 bool was_fullscreen = m_render_widget->isFullScreen();
1099
1100 if (!was_fullscreen)
1101 m_render_widget_geometry = m_render_widget->saveGeometry();
1102
1103 HideRenderWidget(false);
1104 SetFullScreenResolution(!was_fullscreen);
1105
1106 if (was_fullscreen)
1107 {
1108 ShowRenderWidget();
1109 }
1110 else
1111 {
1112 m_render_widget->showFullScreen();
1113 }
1114 }
1115
1116 void MainWindow::UnlockCursor()
1117 {
1118 if (!m_render_widget->isFullScreen())
1119 m_render_widget->SetCursorLocked(false);
1120 }
1121
1122 void MainWindow::ScreenShot()
1123 {
1124 Core::SaveScreenShot();
1125 }
1126
1127 void MainWindow::ScanForSecondDiscAndStartGame(const UICommon::GameFile& game,
1128 std::unique_ptr<BootSessionData> boot_session_data)
1129 {
1130 auto second_game = m_game_list->FindSecondDisc(game);
1131
1132 std::vector<std::string> paths = {game.GetFilePath()};
1133 if (second_game != nullptr)
1134 paths.push_back(second_game->GetFilePath());
1135
1136 StartGame(paths, std::move(boot_session_data));
1137 }
1138
1139 void MainWindow::StartGame(const QString& path, ScanForSecondDisc scan,
1140 std::unique_ptr<BootSessionData> boot_session_data)
1141 {
1142 StartGame(path.toStdString(), scan, std::move(boot_session_data));
1143 }
1144
1145 void MainWindow::StartGame(const std::string& path, ScanForSecondDisc scan,
1146 std::unique_ptr<BootSessionData> boot_session_data)
1147 {
1148 if (scan == ScanForSecondDisc::Yes)
1149 {
1150 std::shared_ptr<const UICommon::GameFile> game = m_game_list->FindGame(path);
1151 if (game != nullptr)
1152 {
1153 ScanForSecondDiscAndStartGame(*game, std::move(boot_session_data));
1154 return;
1155 }
1156 }
1157
1158 StartGame(BootParameters::GenerateFromFile(
1159 path, boot_session_data ? std::move(*boot_session_data) : BootSessionData()));
1160 }
1161
1162 void MainWindow::StartGame(const std::vector<std::string>& paths,
1163 std::unique_ptr<BootSessionData> boot_session_data)
1164 {
1165 StartGame(BootParameters::GenerateFromFile(
1166 paths, boot_session_data ? std::move(*boot_session_data) : BootSessionData()));
1167 }
1168
1169 void MainWindow::StartGame(std::unique_ptr<BootParameters>&& parameters)
1170 {
1171 if (parameters && std::holds_alternative<BootParameters::Disc>(parameters->parameters))
1172 {
1173 if (std::get<BootParameters::Disc>(parameters->parameters).volume->IsNKit())
1174 {
1175 if (!NKitWarningDialog::ShowUnlessDisabled())
1176 return;
1177 }
1178
1179 const auto volume_type =
1180 std::get<BootParameters::Disc>(parameters->parameters).volume->GetVolumeType();
1181 if (volume_type != DiscIO::Platform::Triforce)
1182 {
1183 const bool triforce_hardware_sp1 =
1184 Config::Get(Config::MAIN_SERIAL_PORT_1) == ExpansionInterface::EXIDeviceType::Baseboard;
1185 const bool triforce_hardware_port_1 = Config::Get(Config::GetInfoForSIDevice(0)) ==
1186 SerialInterface::SIDevices::SIDEVICE_AM_BASEBOARD;
1187
1188 // Some Triforce tools don't include a boot.id file, but they can still be launched.
1189 if (triforce_hardware_sp1)
1190 {
1191 ModalMessageBox::warning(this, tr("Warning"),
1192 tr("Non-Triforce games cannot be booted with Triforce hardware "
1193 "attached.\nPlease remove the Triforce Baseboard from SP1."),
1194 QMessageBox::Ok);
1195 }
1196 if (triforce_hardware_port_1)
1197 {
1198 ModalMessageBox::warning(this, tr("Warning"),
1199 tr("Non-Triforce games cannot be booted with Triforce hardware "
1200 "attached.\nPlease remove the Triforce Baseboard from Port 1."),
1201 QMessageBox::Ok);
1202 }
1203 }
1204 }
1205
1206 // If we're running, only start a new game once we've stopped the last.
1207 if (!Core::IsUninitialized(m_system))
1208 {
1209 if (!RequestStop())
1210 return;
1211
1212 // As long as the shutdown isn't complete, we can't boot, so let's boot later
1213 m_pending_boot = std::move(parameters);
1214 return;
1215 }
1216
1217 // We need the render widget before booting.
1218 ShowRenderWidget();
1219
1220 // Boot up, show an error if it fails to load the game.
1221 if (!BootManager::BootCore(m_system, std::move(parameters),
1222 ::GetWindowSystemInfo(m_render_widget->windowHandle())))
1223 {
1224 ModalMessageBox::critical(this, tr("Error"), tr("Failed to init core"), QMessageBox::Ok);
1225 HideRenderWidget();
1226 return;
1227 }
1228
1229 #ifdef USE_DISCORD_PRESENCE
1230 if (!NetPlay::IsNetPlayRunning())
1231 Discord::UpdateDiscordPresence();
1232 #endif
1233
1234 if (Config::Get(Config::MAIN_FULLSCREEN))
1235 m_fullscreen_requested = true;
1236 }
1237
1238 void MainWindow::SetFullScreenResolution(bool fullscreen)
1239 {
1240 if (Config::Get(Config::MAIN_FULLSCREEN_DISPLAY_RES) == "Auto")
1241 return;
1242 #ifdef _WIN32
1243
1244 if (!fullscreen)
1245 {
1246 ChangeDisplaySettings(nullptr, CDS_FULLSCREEN);
1247 return;
1248 }
1249
1250 DEVMODE screen_settings;
1251 memset(&screen_settings, 0, sizeof(screen_settings));
1252 screen_settings.dmSize = sizeof(screen_settings);
1253 sscanf(Config::Get(Config::MAIN_FULLSCREEN_DISPLAY_RES).c_str(), "%lux%lu",
1254 &screen_settings.dmPelsWidth, &screen_settings.dmPelsHeight);
1255 screen_settings.dmBitsPerPel = 32;
1256 screen_settings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
1257
1258 // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
1259 ChangeDisplaySettings(&screen_settings, CDS_FULLSCREEN);
1260 #elif defined(HAVE_XRANDR) && HAVE_XRANDR
1261 if (m_xrr_config)
1262 m_xrr_config->ToggleDisplayMode(fullscreen);
1263 #endif
1264 }
1265
1266 void MainWindow::ShowRenderWidget()
1267 {
1268 SetFullScreenResolution(false);
1269 Host::GetInstance()->SetRenderFullscreen(false);
1270
1271 if (Config::Get(Config::MAIN_RENDER_TO_MAIN))
1272 {
1273 // If we're rendering to main, add it to the stack and update our title when necessary.
1274 m_rendering_to_main = true;
1275
1276 m_stack->setCurrentIndex(m_stack->addWidget(m_render_widget));
1277 connect(Host::GetInstance(), &Host::RequestTitle, this, &MainWindow::setWindowTitle);
1278 m_stack->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
1279 m_stack->repaint();
1280
1281 Host::GetInstance()->SetRenderFocus(isActiveWindow());
1282 }
1283 else
1284 {
1285 // Otherwise, just show it.
1286 m_rendering_to_main = false;
1287
1288 m_render_widget->showNormal();
1289 m_render_widget->restoreGeometry(m_render_widget_geometry);
1290 }
1291 }
1292
1293 void MainWindow::HideRenderWidget(bool reinit, bool is_exit)
1294 {
1295 if (m_rendering_to_main)
1296 {
1297 // Remove the widget from the stack and reparent it to nullptr, so that it can draw
1298 // itself in a new window if it wants. Disconnect the title updates.
1299 m_stack->removeWidget(m_render_widget);
1300 m_render_widget->setParent(nullptr);
1301 m_rendering_to_main = false;
1302 m_stack->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
1303 disconnect(Host::GetInstance(), &Host::RequestTitle, this, &MainWindow::setWindowTitle);
1304 setWindowTitle(QString::fromStdString(Common::GetScmRevStr()));
1305 }
1306
1307 // The following code works around a driver bug that would lead to Dolphin crashing when changing
1308 // graphics backends (e.g. OpenGL to Vulkan). To avoid this the render widget is (safely)
1309 // recreated
1310 if (reinit)
1311 {
1312 m_render_widget->hide();
1313 disconnect(m_render_widget, &RenderWidget::Closed, this, &MainWindow::ForceStop);
1314
1315 m_render_widget->removeEventFilter(this);
1316 m_render_widget->deleteLater();
1317
1318 m_render_widget = new RenderWidget;
1319
1320 m_render_widget->installEventFilter(this);
1321 connect(m_render_widget, &RenderWidget::Closed, this, &MainWindow::ForceStop);
1322 connect(m_render_widget, &RenderWidget::FocusChanged, this, [this](bool focus) {
1323 if (m_render_widget->isFullScreen())
1324 SetFullScreenResolution(focus);
1325 });
1326
1327 // The controller interface will still be registered to the old render widget, if the core
1328 // has booted. Therefore, we should re-bind it to the main window for now. When the core
1329 // is next started, it will be swapped back to the new render widget.
1330 g_controller_interface.ChangeWindow(::GetWindowSystemInfo(windowHandle()).render_window,
1331 is_exit ? ControllerInterface::WindowChangeReason::Exit :
1332 ControllerInterface::WindowChangeReason::Other);
1333 }
1334 }
1335
1336 void MainWindow::ShowControllersWindow()
1337 {
1338 ShowSettingsWindow();
1339 m_settings_window->SelectPane(SettingsWindowPaneIndex::Controllers);
1340 }
1341
1342 void MainWindow::ShowTriforceWindow()
1343 {
1344 ShowSettingsWindow();
1345 m_settings_window->SelectPane(SettingsWindowPaneIndex::Triforce);
1346 }
1347
1348 void MainWindow::ShowFreeLookWindow()
1349 {
1350 if (!m_freelook_window)
1351 {
1352 m_freelook_window = new FreeLookWindow(this);
1353 InstallHotkeyFilter(m_freelook_window);
1354
1355 #ifdef USE_RETRO_ACHIEVEMENTS
1356 connect(m_freelook_window, &FreeLookWindow::OpenAchievementSettings, this,
1357 &MainWindow::ShowAchievementSettings);
1358 #endif // USE_RETRO_ACHIEVEMENTS
1359 }
1360
1361 m_freelook_window->show();
1362 m_freelook_window->raise();
1363 m_freelook_window->activateWindow();
1364 }
1365
1366 void MainWindow::ShowSettingsWindow()
1367 {
1368 if (!m_settings_window)
1369 {
1370 #ifdef HAVE_XRANDR
1371 if (GetWindowSystemType() == WindowSystemType::X11)
1372 {
1373 m_xrr_config = std::make_unique<X11Utils::XRRConfiguration>(
1374 static_cast<Display*>(QGuiApplication::platformNativeInterface()->nativeResourceForWindow(
1375 "display", windowHandle())),
1376 winId());
1377 }
1378 #endif
1379 m_settings_window = new SettingsWindow(this);
1380 InstallHotkeyFilter(m_settings_window);
1381 }
1382
1383 m_settings_window->show();
1384 m_settings_window->raise();
1385 m_settings_window->activateWindow();
1386 }
1387
1388 void MainWindow::ShowAudioWindow()
1389 {
1390 ShowSettingsWindow();
1391 m_settings_window->SelectPane(SettingsWindowPaneIndex::Audio);
1392 }
1393
1394 void MainWindow::ShowGeneralWindow()
1395 {
1396 ShowSettingsWindow();
1397 m_settings_window->SelectPane(SettingsWindowPaneIndex::General);
1398 }
1399
1400 void MainWindow::ShowOSDWindow()
1401 {
1402 ShowSettingsWindow();
1403 m_settings_window->SelectPane(SettingsWindowPaneIndex::OnScreenDisplay);
1404 }
1405
1406 void MainWindow::ShowAboutDialog()
1407 {
1408 AboutDialog about{this};
1409 about.exec();
1410 }
1411
1412 void MainWindow::ShowHotkeyDialog()
1413 {
1414 if (!m_hotkey_window)
1415 {
1416 m_hotkey_window = new MappingWindow(this, MappingWindow::Type::MAPPING_HOTKEYS, 0);
1417 InstallHotkeyFilter(m_hotkey_window);
1418 }
1419
1420 m_hotkey_window->show();
1421 m_hotkey_window->raise();
1422 m_hotkey_window->activateWindow();
1423 }
1424
1425 void MainWindow::ShowGraphicsWindow()
1426 {
1427 ShowSettingsWindow();
1428 m_settings_window->SelectPane(SettingsWindowPaneIndex::Graphics);
1429 }
1430
1431 void MainWindow::ShowNetPlaySetupDialog()
1432 {
1433 m_netplay_setup_dialog->show();
1434 m_netplay_setup_dialog->raise();
1435 m_netplay_setup_dialog->activateWindow();
1436 }
1437
1438 void MainWindow::ShowNetPlayBrowser()
1439 {
1440 auto* browser = new NetPlayBrowser(this);
1441 browser->setAttribute(Qt::WA_DeleteOnClose, true);
1442 connect(browser, &NetPlayBrowser::Join, this, &MainWindow::NetPlayJoin);
1443 browser->exec();
1444 }
1445
1446 void MainWindow::ShowFIFOPlayer()
1447 {
1448 if (!m_fifo_window)
1449 {
1450 m_fifo_window.reset(new FIFOPlayerWindow(m_system.GetFifoPlayer(), m_system.GetFifoRecorder()));
1451 connect(m_fifo_window.get(), &FIFOPlayerWindow::LoadFIFORequested, this,
1452 [this](const QString& path) { StartGame(path, ScanForSecondDisc::No); });
1453 }
1454
1455 m_fifo_window->show();
1456 m_fifo_window->raise();
1457 m_fifo_window->activateWindow();
1458 }
1459
1460 void MainWindow::ShowSkylanderPortal()
1461 {
1462 if (!m_skylander_window)
1463 {
1464 m_skylander_window = new SkylanderPortalWindow();
1465 }
1466
1467 m_skylander_window->show();
1468 m_skylander_window->raise();
1469 m_skylander_window->activateWindow();
1470 }
1471
1472 void MainWindow::ShowInfinityBase()
1473 {
1474 if (!m_infinity_window)
1475 {
1476 m_infinity_window = new InfinityBaseWindow();
1477 }
1478
1479 m_infinity_window->show();
1480 m_infinity_window->raise();
1481 m_infinity_window->activateWindow();
1482 }
1483
1484 void MainWindow::ShowWiiSpeakWindow()
1485 {
1486 if (!m_wii_speak_window)
1487 {
1488 m_wii_speak_window = new WiiSpeakWindow();
1489 }
1490
1491 m_wii_speak_window->show();
1492 m_wii_speak_window->raise();
1493 m_wii_speak_window->activateWindow();
1494 }
1495
1496 void MainWindow::ShowLogitechMicWindow()
1497 {
1498 if (!m_logitech_mic_window)
1499 {
1500 m_logitech_mic_window = new LogitechMicWindow();
1501 }
1502
1503 m_logitech_mic_window->show();
1504 m_logitech_mic_window->raise();
1505 m_logitech_mic_window->activateWindow();
1506 }
1507
1508 void MainWindow::StateLoad()
1509 {
1510 QString dialog_path = (Config::Get(Config::MAIN_CURRENT_STATE_PATH).empty()) ?
1511 QDir::currentPath() :
1512 QString::fromStdString(Config::Get(Config::MAIN_CURRENT_STATE_PATH));
1513 QString path = DolphinFileDialog::getOpenFileName(
1514 this, tr("Select a File"), dialog_path, tr("All Save States (*.sav *.s??);; All Files (*)"));
1515 Config::SetBase(Config::MAIN_CURRENT_STATE_PATH, QFileInfo(path).dir().path().toStdString());
1516 if (!path.isEmpty())
1517 State::LoadAs(m_system, path.toStdString());
1518 }
1519
1520 void MainWindow::StateSave()
1521 {
1522 QString dialog_path = (Config::Get(Config::MAIN_CURRENT_STATE_PATH).empty()) ?
1523 QDir::currentPath() :
1524 QString::fromStdString(Config::Get(Config::MAIN_CURRENT_STATE_PATH));
1525 QString path = DolphinFileDialog::getSaveFileName(
1526 this, tr("Select a File"), dialog_path, tr("All Save States (*.sav *.s??);; All Files (*)"));
1527 Config::SetBase(Config::MAIN_CURRENT_STATE_PATH, QFileInfo(path).dir().path().toStdString());
1528 if (!path.isEmpty())
1529 State::SaveAs(m_system, path.toStdString());
1530 }
1531
1532 void MainWindow::StateLoadSlot()
1533 {
1534 State::Load(m_system, m_state_slot);
1535 }
1536
1537 void MainWindow::StateSaveSlot()
1538 {
1539 State::Save(m_system, m_state_slot);
1540 }
1541
1542 void MainWindow::StateLoadSlotAt(int slot)
1543 {
1544 State::Load(m_system, slot);
1545 }
1546
1547 void MainWindow::StateLoadLastSavedAt(int slot)
1548 {
1549 State::LoadLastSaved(m_system, slot);
1550 }
1551
1552 void MainWindow::StateSaveSlotAt(int slot)
1553 {
1554 State::Save(m_system, slot);
1555 }
1556
1557 void MainWindow::StateLoadUndo()
1558 {
1559 State::UndoLoadState(m_system);
1560 }
1561
1562 void MainWindow::StateSaveUndo()
1563 {
1564 State::UndoSaveState(m_system);
1565 }
1566
1567 void MainWindow::StateSaveOldest()
1568 {
1569 State::SaveFirstSaved(m_system);
1570 }
1571
1572 void MainWindow::SetStateSlot(int slot)
1573 {
1574 Settings::Instance().SetStateSlot(slot);
1575 m_state_slot = slot;
1576
1577 Core::DisplayMessage(fmt::format("Selected slot {} - {}", m_state_slot,
1578 State::GetInfoStringOfSlot(m_state_slot, false)),
1579 2500);
1580 }
1581
1582 void MainWindow::IncrementSelectedStateSlot()
1583 {
1584 u32 state_slot = m_state_slot + 1;
1585 if (state_slot > State::NUM_STATES)
1586 state_slot = 1;
1587 m_menu_bar->SetStateSlot(state_slot);
1588 }
1589
1590 void MainWindow::DecrementSelectedStateSlot()
1591 {
1592 u32 state_slot = m_state_slot - 1;
1593 if (state_slot < 1)
1594 state_slot = State::NUM_STATES;
1595 m_menu_bar->SetStateSlot(state_slot);
1596 }
1597
1598 void MainWindow::PerformOnlineUpdate(const std::string& region)
1599 {
1600 WiiUpdate::PerformOnlineUpdate(region, this);
1601 // Since the update may have installed a newer system menu, trigger a refresh.
1602 Settings::Instance().NANDRefresh();
1603 }
1604
1605 void MainWindow::BootWiiSystemMenu()
1606 {
1607 StartGame(std::make_unique<BootParameters>(BootParameters::NANDTitle{Titles::SYSTEM_MENU}));
1608 }
1609
1610 void MainWindow::NetPlayInit()
1611 {
1612 const auto& game_list_model = m_game_list->GetGameListModel();
1613 m_netplay_setup_dialog = new NetPlaySetupDialog(game_list_model, this);
1614 m_netplay_dialog = new NetPlayDialog(
1615 game_list_model,
1616 [this](const std::string& path, std::unique_ptr<BootSessionData> boot_session_data) {
1617 StartGame(path, ScanForSecondDisc::Yes, std::move(boot_session_data));
1618 });
1619 #ifdef USE_DISCORD_PRESENCE
1620 m_netplay_discord = new DiscordHandler(this);
1621 #endif
1622
1623 connect(m_netplay_dialog, &NetPlayDialog::Stop, this, &MainWindow::ForceStop);
1624 connect(m_netplay_dialog, &NetPlayDialog::rejected, this, &MainWindow::NetPlayQuit);
1625 connect(m_netplay_setup_dialog, &NetPlaySetupDialog::Join, this, &MainWindow::NetPlayJoin);
1626 connect(m_netplay_setup_dialog, &NetPlaySetupDialog::Host, this, &MainWindow::NetPlayHost);
1627 #ifdef USE_DISCORD_PRESENCE
1628 connect(m_netplay_discord, &DiscordHandler::Join, this, &MainWindow::NetPlayJoin);
1629
1630 Discord::InitNetPlayFunctionality(*m_netplay_discord);
1631 m_netplay_discord->Start();
1632 #endif
1633 connect(&Settings::Instance(), &Settings::ConfigChanged, this,
1634 &MainWindow::UpdateScreenSaverInhibition);
1635 connect(&Settings::Instance(), &Settings::EmulationStateChanged, this,
1636 &MainWindow::UpdateScreenSaverInhibition);
1637 }
1638
1639 bool MainWindow::NetPlayJoin()
1640 {
1641 if (!Core::IsUninitialized(m_system))
1642 {
1643 ModalMessageBox::critical(nullptr, tr("Error"),
1644 tr("Can't start a NetPlay Session while a game is still running!"));
1645 return false;
1646 }
1647
1648 if (m_netplay_dialog->isVisible())
1649 {
1650 ModalMessageBox::critical(nullptr, tr("Error"),
1651 tr("A NetPlay Session is already in progress!"));
1652 return false;
1653 }
1654
1655 auto server = Settings::Instance().GetNetPlayServer();
1656
1657 // Settings
1658 const std::string traversal_choice = Config::Get(Config::NETPLAY_TRAVERSAL_CHOICE);
1659 const bool is_traversal = traversal_choice == "traversal";
1660
1661 std::string host_ip;
1662 u16 host_port;
1663 if (server)
1664 {
1665 host_ip = "127.0.0.1";
1666 host_port = server->GetPort();
1667 }
1668 else
1669 {
1670 host_ip = is_traversal ? Config::Get(Config::NETPLAY_HOST_CODE) :
1671 Config::Get(Config::NETPLAY_ADDRESS);
1672 host_port = Config::Get(Config::NETPLAY_CONNECT_PORT);
1673 }
1674
1675 const std::string traversal_host = Config::Get(Config::NETPLAY_TRAVERSAL_SERVER);
1676 const u16 traversal_port = Config::Get(Config::NETPLAY_TRAVERSAL_PORT);
1677 const std::string nickname = Config::Get(Config::NETPLAY_NICKNAME);
1678 const std::string network_mode = Config::Get(Config::NETPLAY_NETWORK_MODE);
1679 const bool host_input_authority = network_mode == "hostinputauthority" || network_mode == "golf";
1680
1681 if (server)
1682 {
1683 server->SetHostInputAuthority(host_input_authority);
1684 server->AdjustPadBufferSize(Config::Get(Config::NETPLAY_BUFFER_SIZE));
1685 }
1686
1687 // Create Client
1688 const bool is_hosting_netplay = server != nullptr;
1689 Settings::Instance().ResetNetPlayClient(new NetPlay::NetPlayClient(
1690 host_ip, host_port, m_netplay_dialog, nickname,
1691 NetPlay::NetTraversalConfig{is_hosting_netplay ? false : is_traversal, traversal_host,
1692 traversal_port}));
1693
1694 if (!Settings::Instance().GetNetPlayClient()->IsConnected())
1695 {
1696 NetPlayQuit();
1697 return false;
1698 }
1699
1700 m_netplay_setup_dialog->close();
1701 m_netplay_dialog->show(nickname, is_traversal);
1702
1703 return true;
1704 }
1705
1706 bool MainWindow::NetPlayHost(const UICommon::GameFile& game)
1707 {
1708 if (!Core::IsUninitialized(m_system))
1709 {
1710 ModalMessageBox::critical(nullptr, tr("Error"),
1711 tr("Can't start a NetPlay Session while a game is still running!"));
1712 return false;
1713 }
1714
1715 if (m_netplay_dialog->isVisible())
1716 {
1717 ModalMessageBox::critical(nullptr, tr("Error"),
1718 tr("A NetPlay Session is already in progress!"));
1719 return false;
1720 }
1721
1722 // Settings
1723 u16 host_port = Config::Get(Config::NETPLAY_HOST_PORT);
1724 const std::string traversal_choice = Config::Get(Config::NETPLAY_TRAVERSAL_CHOICE);
1725 const bool is_traversal = traversal_choice == "traversal";
1726 const bool use_upnp = Config::Get(Config::NETPLAY_USE_UPNP);
1727
1728 const std::string traversal_host = Config::Get(Config::NETPLAY_TRAVERSAL_SERVER);
1729 const u16 traversal_port = Config::Get(Config::NETPLAY_TRAVERSAL_PORT);
1730 const u16 traversal_port_alt = Config::Get(Config::NETPLAY_TRAVERSAL_PORT_ALT);
1731
1732 if (is_traversal)
1733 host_port = Config::Get(Config::NETPLAY_LISTEN_PORT);
1734
1735 // Create Server
1736 Settings::Instance().ResetNetPlayServer(
1737 new NetPlay::NetPlayServer(host_port, use_upnp, m_netplay_dialog,
1738 NetPlay::NetTraversalConfig{is_traversal, traversal_host,
1739 traversal_port, traversal_port_alt}));
1740
1741 if (!Settings::Instance().GetNetPlayServer()->is_connected)
1742 {
1743 ModalMessageBox::critical(
1744 nullptr, tr("Failed to open server"),
1745 tr("Failed to listen on port %1. Is another instance of the NetPlay server running?")
1746 .arg(host_port));
1747 NetPlayQuit();
1748 return false;
1749 }
1750
1751 Settings::Instance().GetNetPlayServer()->ChangeGame(game.GetSyncIdentifier(),
1752 m_game_list->GetNetPlayName(game));
1753
1754 // Join our local server
1755 return NetPlayJoin();
1756 }
1757
1758 void MainWindow::NetPlayQuit()
1759 {
1760 Settings::Instance().ResetNetPlayClient();
1761 Settings::Instance().ResetNetPlayServer();
1762 #ifdef USE_DISCORD_PRESENCE
1763 Discord::UpdateDiscordPresence();
1764 #endif
1765 }
1766
1767 void MainWindow::UpdateScreenSaverInhibition()
1768 {
1769 const bool inhibit = Config::Get(Config::MAIN_DISABLE_SCREENSAVER) &&
1770 (Core::GetState(m_system) == Core::State::Running);
1771
1772 if (inhibit == m_is_screensaver_inhibited)
1773 return;
1774
1775 m_is_screensaver_inhibited = inhibit;
1776
1777 UICommon::InhibitScreenSaver(inhibit);
1778 }
1779
1780 bool MainWindow::eventFilter(QObject* object, QEvent* event)
1781 {
1782 if (event->type() == QEvent::Close)
1783 {
1784 if (RequestStop() && object == this)
1785 m_exit_requested = true;
1786
1787 static_cast<QCloseEvent*>(event)->ignore();
1788 return true;
1789 }
1790
1791 return false;
1792 }
1793
1794 QMenu* MainWindow::createPopupMenu()
1795 {
1796 // Disable the default popup menu as it exposes the debugger UI even when the debugger UI is
1797 // disabled, which can lead to user confusion (see e.g. https://bugs.dolphin-emu.org/issues/13306)
1798 return nullptr;
1799 }
1800
1801 void MainWindow::dragEnterEvent(QDragEnterEvent* event)
1802 {
1803 if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1)
1804 event->acceptProposedAction();
1805 }
1806
1807 void MainWindow::dropEvent(QDropEvent* event)
1808 {
1809 const QList<QUrl>& urls = event->mimeData()->urls();
1810 if (urls.empty())
1811 return;
1812
1813 QStringList files;
1814 QStringList folders;
1815
1816 for (const QUrl& url : urls)
1817 {
1818 QFileInfo file_info(url.toLocalFile());
1819 QString path = file_info.filePath();
1820
1821 if (!file_info.exists() || !file_info.isReadable())
1822 {
1823 ModalMessageBox::critical(this, tr("Error"), tr("Failed to open '%1'").arg(path));
1824 return;
1825 }
1826
1827 (file_info.isFile() ? files : folders).append(path);
1828 }
1829
1830 if (!files.isEmpty())
1831 {
1832 StartGame(StringListToStdVector(files));
1833 }
1834 else
1835 {
1836 Settings& settings = Settings::Instance();
1837 const bool show_confirm = !settings.GetPaths().empty();
1838
1839 for (const QString& folder : folders)
1840 {
1841 if (show_confirm)
1842 {
1843 if (ModalMessageBox::question(
1844 this, tr("Confirm"),
1845 tr("Do you want to add \"%1\" to the list of Game Paths?").arg(folder)) !=
1846 QMessageBox::Yes)
1847 return;
1848 }
1849 settings.AddPath(folder);
1850 }
1851 }
1852 }
1853
1854 QSize MainWindow::sizeHint() const
1855 {
1856 return QSize(800, 600);
1857 }
1858
1859 void MainWindow::OnBootGameCubeIPL(DiscIO::Region region)
1860 {
1861 StartGame(std::make_unique<BootParameters>(BootParameters::IPL{region}));
1862 }
1863
1864 void MainWindow::OnImportNANDBackup()
1865 {
1866 auto response = ModalMessageBox::question(
1867 this, tr("Question"),
1868 tr("Merging a new NAND over your currently selected NAND will overwrite any channels "
1869 "and savegames that already exist. This process is not reversible, so it is "
1870 "recommended that you keep backups of both NANDs. Are you sure you want to "
1871 "continue?"));
1872
1873 if (response == QMessageBox::No)
1874 return;
1875
1876 QString file =
1877 DolphinFileDialog::getOpenFileName(this, tr("Select NAND Backup"), QDir::currentPath(),
1878 tr("BootMii NAND backup file (*.bin);;"
1879 "All Files (*)"));
1880
1881 if (file.isEmpty())
1882 return;
1883
1884 ParallelProgressDialog dialog(this);
1885 dialog.GetRaw()->setWindowTitle(tr("Importing NAND backup"));
1886
1887 std::future<void> result = std::async(std::launch::async, [&] {
1888 DiscIO::NANDImporter().ImportNANDBin(
1889 file.toStdString(),
1890 [&dialog](DiscIO::NANDImporter::Step step, u32 cur, u32 max) {
1891 switch (step)
1892 {
1893 case DiscIO::NANDImporter::Step::Loading:
1894 dialog.SetLabelText(tr("Loading NAND..."));
1895 break;
1896 case DiscIO::NANDImporter::Step::Extracting:
1897 dialog.SetLabelText(tr("Extracting NAND..."));
1898 break;
1899 }
1900 dialog.SetValue(cur);
1901 dialog.SetMaximum(max);
1902 return dialog.WasCanceled();
1903 },
1904 [this] {
1905 std::optional<std::string> keys_file = RunOnObject(this, [this] {
1906 return DolphinFileDialog::getOpenFileName(
1907 this, tr("Select Keys File (OTP/SEEPROM Dump)"), QDir::currentPath(),
1908 tr("BootMii keys file (*.bin);;"
1909 "All Files (*)"))
1910 .toStdString();
1911 });
1912 if (keys_file)
1913 return *keys_file;
1914 return std::string("");
1915 });
1916 dialog.Reset();
1917 });
1918
1919 dialog.GetRaw()->exec();
1920
1921 result.wait();
1922
1923 m_menu_bar->UpdateToolsMenu(Core::State::Uninitialized);
1924 }
1925
1926 void MainWindow::OnPlayRecording()
1927 {
1928 if (AchievementManager::GetInstance().IsHardcoreModeActive())
1929 {
1930 ModalMessageBox::critical(
1931 this, tr("Error"),
1932 tr("Playback of input recordings is disabled in RetroAchievements hardcore mode."));
1933 return;
1934 }
1935
1936 QString dtm_file = DolphinFileDialog::getOpenFileName(
1937 this, tr("Select the Recording File to Play"), QString(), tr("Dolphin TAS Movies (*.dtm)"));
1938
1939 if (dtm_file.isEmpty())
1940 return;
1941
1942 auto& movie = m_system.GetMovie();
1943 if (!movie.IsReadOnly())
1944 {
1945 // let's make the read-only flag consistent at the start of a movie.
1946 movie.SetReadOnly(true);
1947 emit ReadOnlyModeChanged(true);
1948 }
1949
1950 std::optional<std::string> savestate_path;
1951 if (movie.PlayInput(dtm_file.toStdString(), &savestate_path))
1952 {
1953 emit RecordingStatusChanged(true);
1954
1955 Play(savestate_path);
1956 }
1957 }
1958
1959 void MainWindow::OnStartRecording()
1960 {
1961 auto& movie = m_system.GetMovie();
1962 if (Core::GetState(m_system) == Core::State::Starting ||
1963 Core::GetState(m_system) == Core::State::Stopping || movie.IsRecordingInput() ||
1964 movie.IsPlayingInput())
1965 {
1966 return;
1967 }
1968
1969 if (movie.IsReadOnly())
1970 {
1971 // The user just chose to record a movie, so that should take precedence
1972 movie.SetReadOnly(false);
1973 emit ReadOnlyModeChanged(true);
1974 }
1975
1976 Movie::ControllerTypeArray controllers{};
1977 Movie::WiimoteEnabledArray wiimotes{};
1978
1979 for (int i = 0; i < 4; i++)
1980 {
1981 const SerialInterface::SIDevices si_device = Config::Get(Config::GetInfoForSIDevice(i));
1982 if (si_device == SerialInterface::SIDEVICE_GC_GBA_EMULATED)
1983 controllers[i] = Movie::ControllerType::GBA;
1984 else if (SerialInterface::SIDevice_IsGCController(si_device))
1985 controllers[i] = Movie::ControllerType::GC;
1986 else
1987 controllers[i] = Movie::ControllerType::None;
1988 wiimotes[i] = Config::Get(Config::GetInfoForWiimoteSource(i)) != WiimoteSource::None;
1989 }
1990
1991 if (movie.BeginRecordingInput(controllers, wiimotes))
1992 {
1993 emit RecordingStatusChanged(true);
1994
1995 if (Core::IsUninitialized(m_system))
1996 Play();
1997 }
1998 }
1999
2000 void MainWindow::OnStopRecording()
2001 {
2002 auto& movie = m_system.GetMovie();
2003 if (movie.IsRecordingInput())
2004 OnExportRecording();
2005 if (movie.IsMovieActive())
2006 movie.EndPlayInput(false);
2007 emit RecordingStatusChanged(false);
2008 }
2009
2010 void MainWindow::OnExportRecording()
2011 {
2012 const Core::CPUThreadGuard guard(m_system);
2013
2014 QString dtm_file = DolphinFileDialog::getSaveFileName(
2015 this, tr("Save Recording File As"), QString(), tr("Dolphin TAS Movies (*.dtm)"));
2016 if (!dtm_file.isEmpty())
2017 m_system.GetMovie().SaveRecording(dtm_file.toStdString());
2018 }
2019
2020 void MainWindow::OnActivateChat()
2021 {
2022 if (g_netplay_chat_ui)
2023 g_netplay_chat_ui->Activate();
2024 }
2025
2026 void MainWindow::OnRequestGolfControl()
2027 {
2028 auto client = Settings::Instance().GetNetPlayClient();
2029 if (client)
2030 client->RequestGolfControl();
2031 }
2032
2033 void MainWindow::ShowTASInput()
2034 {
2035 for (int i = 0; i < num_gc_controllers; i++)
2036 {
2037 const auto si_device = Config::Get(Config::GetInfoForSIDevice(i));
2038 if (si_device == SerialInterface::SIDEVICE_GC_GBA_EMULATED)
2039 {
2040 m_gba_tas_input_windows[i]->show();
2041 m_gba_tas_input_windows[i]->raise();
2042 m_gba_tas_input_windows[i]->activateWindow();
2043 }
2044 else if (si_device != SerialInterface::SIDEVICE_NONE &&
2045 si_device != SerialInterface::SIDEVICE_GC_GBA)
2046 {
2047 m_gc_tas_input_windows[i]->show();
2048 m_gc_tas_input_windows[i]->raise();
2049 m_gc_tas_input_windows[i]->activateWindow();
2050 }
2051 }
2052
2053 for (int i = 0; i < num_wii_controllers; i++)
2054 {
2055 if (Config::Get(Config::GetInfoForWiimoteSource(i)) == WiimoteSource::Emulated &&
2056 (!Core::IsRunning(m_system) || m_system.IsWii()))
2057 {
2058 m_wii_tas_input_windows[i]->show();
2059 m_wii_tas_input_windows[i]->raise();
2060 m_wii_tas_input_windows[i]->activateWindow();
2061 }
2062 }
2063 }
2064
2065 void MainWindow::OnConnectWiiRemote(int id)
2066 {
2067 const Core::CPUThreadGuard guard(m_system);
2068 if (const auto bt = WiiUtils::GetBluetoothEmuDevice())
2069 {
2070 const auto wm = bt->AccessWiimoteByIndex(id);
2071 wm->Activate(!wm->IsConnected());
2072 }
2073 }
2074
2075 #ifdef USE_RETRO_ACHIEVEMENTS
2076 void MainWindow::ShowAchievementsWindow()
2077 {
2078 if (!m_achievements_window)
2079 {
2080 m_achievements_window = new AchievementsWindow(this);
2081 }
2082
2083 m_achievements_window->show();
2084 m_achievements_window->raise();
2085 m_achievements_window->activateWindow();
2086 m_achievements_window->UpdateData(AchievementManager::UpdatedItems{.all = true});
2087 }
2088
2089 void MainWindow::ShowAchievementSettings()
2090 {
2091 ShowAchievementsWindow();
2092 m_achievements_window->ForceSettingsTab();
2093 }
2094
2095 void MainWindow::OnHardcoreChanged()
2096 {
2097 bool hardcore_active = AchievementManager::GetInstance().IsHardcoreModeActive();
2098 if (hardcore_active)
2099 Settings::Instance().SetDebugModeEnabled(false);
2100 // EmulationStateChanged causes several dialogs to redraw, including anything affected by hardcore
2101 // mode. Every dialog that depends on hardcore mode is redrawn by EmulationStateChanged.
2102 if (hardcore_active != m_former_hardcore_setting)
2103 emit Settings::Instance().EmulationStateChanged(Core::GetState(Core::System::GetInstance()));
2104 m_former_hardcore_setting = hardcore_active;
2105 }
2106 #endif // USE_RETRO_ACHIEVEMENTS
2107
2108 void MainWindow::ShowMemcardManager()
2109 {
2110 GCMemcardManager manager(this);
2111
2112 manager.exec();
2113 }
2114
2115 void MainWindow::ShowResourcePackManager()
2116 {
2117 ResourcePackManager manager(this);
2118
2119 manager.exec();
2120 }
2121
2122 void MainWindow::ShowCheatsManager()
2123 {
2124 if (!m_cheats_manager)
2125 {
2126 m_cheats_manager = new CheatsManager(m_system, this);
2127
2128 connect(m_cheats_manager, &CheatsManager::ShowMemory, m_memory_widget,
2129 &MemoryWidget::SetAddress);
2130 connect(m_cheats_manager, &CheatsManager::RequestWatch, m_watch_widget, &WatchWidget::AddWatch);
2131 connect(m_cheats_manager, &CheatsManager::OpenGeneralSettings, this,
2132 &MainWindow::ShowGeneralWindow);
2133
2134 #ifdef USE_RETRO_ACHIEVEMENTS
2135 connect(m_cheats_manager, &CheatsManager::OpenAchievementSettings, this,
2136 &MainWindow::ShowAchievementSettings);
2137 #endif // USE_RETRO_ACHIEVEMENTS
2138 }
2139
2140 m_cheats_manager->show();
2141 }
2142
2143 void MainWindow::ShowRiivolutionBootWidget(const UICommon::GameFile& game)
2144 {
2145 auto second_game = m_game_list->FindSecondDisc(game);
2146 std::vector<std::string> paths = {game.GetFilePath()};
2147 if (second_game != nullptr)
2148 paths.push_back(second_game->GetFilePath());
2149 std::unique_ptr<BootParameters> boot_params = BootParameters::GenerateFromFile(paths);
2150 if (!boot_params)
2151 return;
2152 if (!std::holds_alternative<BootParameters::Disc>(boot_params->parameters))
2153 return;
2154
2155 auto& disc = std::get<BootParameters::Disc>(boot_params->parameters);
2156 RiivolutionBootWidget w(disc.volume->GetGameID(), disc.volume->GetRevision(),
2157 disc.volume->GetDiscNumber(), game.GetFilePath(), this);
2158
2159 #ifdef USE_RETRO_ACHIEVEMENTS
2160 connect(&w, &RiivolutionBootWidget::OpenAchievementSettings, this,
2161 &MainWindow::ShowAchievementSettings);
2162 #endif // USE_RETRO_ACHIEVEMENTS
2163
2164 w.exec();
2165 if (!w.ShouldBoot())
2166 return;
2167
2168 AddRiivolutionPatches(boot_params.get(), std::move(w.GetPatches()));
2169 StartGame(std::move(boot_params));
2170 }