1 // Copyright 2014 Citra Emulator Project
2 // Licensed under GPLv2 or any later version
3 // Refer to the license.txt file included.
4 
5 #include <clocale>
6 #include <fstream>
7 #include <memory>
8 #include <thread>
9 #include <QDesktopWidget>
10 #include <QFileDialog>
11 #include <QFutureWatcher>
12 #include <QLabel>
13 #include <QMessageBox>
14 #include <QOpenGLFunctions_3_3_Core>
15 #include <QSysInfo>
16 #include <QtConcurrent/QtConcurrentRun>
17 #include <QtGui>
18 #include <QtWidgets>
19 #include <fmt/format.h>
20 #ifdef __APPLE__
21 #include <unistd.h> // for chdir
22 #endif
23 #ifdef _WIN32
24 #include <windows.h>
25 #endif
26 #include "citra_qt/aboutdialog.h"
27 #include "citra_qt/applets/mii_selector.h"
28 #include "citra_qt/applets/swkbd.h"
29 #include "citra_qt/bootmanager.h"
30 #include "citra_qt/camera/qt_multimedia_camera.h"
31 #include "citra_qt/camera/still_image_camera.h"
32 #include "citra_qt/cheats.h"
33 #include "citra_qt/compatdb.h"
34 #include "citra_qt/compatibility_list.h"
35 #include "citra_qt/configuration/config.h"
36 #include "citra_qt/configuration/configure_dialog.h"
37 #include "citra_qt/debugger/console.h"
38 #include "citra_qt/debugger/graphics/graphics.h"
39 #include "citra_qt/debugger/graphics/graphics_breakpoints.h"
40 #include "citra_qt/debugger/graphics/graphics_cmdlists.h"
41 #include "citra_qt/debugger/graphics/graphics_surface.h"
42 #include "citra_qt/debugger/graphics/graphics_tracing.h"
43 #include "citra_qt/debugger/graphics/graphics_vertex_shader.h"
44 #include "citra_qt/debugger/ipc/recorder.h"
45 #include "citra_qt/debugger/lle_service_modules.h"
46 #include "citra_qt/debugger/profiler.h"
47 #include "citra_qt/debugger/registers.h"
48 #include "citra_qt/debugger/wait_tree.h"
49 #include "citra_qt/discord.h"
50 #include "citra_qt/game_list.h"
51 #include "citra_qt/hotkeys.h"
52 #include "citra_qt/loading_screen.h"
53 #include "citra_qt/main.h"
54 #include "citra_qt/movie/movie_play_dialog.h"
55 #include "citra_qt/movie/movie_record_dialog.h"
56 #include "citra_qt/multiplayer/state.h"
57 #include "citra_qt/qt_image_interface.h"
58 #include "citra_qt/uisettings.h"
59 #include "citra_qt/updater/updater.h"
60 #include "citra_qt/util/clickable_label.h"
61 #include "common/common_paths.h"
62 #include "common/detached_tasks.h"
63 #include "common/file_util.h"
64 #include "common/logging/backend.h"
65 #include "common/logging/filter.h"
66 #include "common/logging/log.h"
67 #include "common/logging/text_formatter.h"
68 #include "common/microprofile.h"
69 #include "common/scm_rev.h"
70 #include "common/scope_exit.h"
71 #ifdef ARCHITECTURE_x86_64
72 #include "common/x64/cpu_detect.h"
73 #endif
74 #include "core/core.h"
75 #include "core/dumping/backend.h"
76 #include "core/file_sys/archive_extsavedata.h"
77 #include "core/file_sys/archive_source_sd_savedata.h"
78 #include "core/frontend/applets/default_applets.h"
79 #include "core/frontend/scope_acquire_context.h"
80 #include "core/gdbstub/gdbstub.h"
81 #include "core/hle/service/fs/archive.h"
82 #include "core/hle/service/nfc/nfc.h"
83 #include "core/loader/loader.h"
84 #include "core/movie.h"
85 #include "core/savestate.h"
86 #include "core/settings.h"
87 #include "game_list_p.h"
88 #include "ui_main.h"
89 #include "video_core/renderer_base.h"
90 #include "video_core/video_core.h"
91 
92 #ifdef USE_DISCORD_PRESENCE
93 #include "citra_qt/discord_impl.h"
94 #endif
95 
96 #ifdef ENABLE_FFMPEG_VIDEO_DUMPER
97 #include "citra_qt/dumping/dumping_dialog.h"
98 #endif
99 
100 #ifdef QT_STATICPLUGIN
101 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
102 #endif
103 
104 #ifdef _WIN32
105 extern "C" {
106 // tells Nvidia drivers to use the dedicated GPU by default on laptops with switchable graphics
107 __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
108 }
109 #endif
110 
111 constexpr int default_mouse_timeout = 2500;
112 
113 /**
114  * "Callouts" are one-time instructional messages shown to the user. In the config settings, there
115  * is a bitfield "callout_flags" options, used to track if a message has already been shown to the
116  * user. This is 32-bits - if we have more than 32 callouts, we should retire and recycle old ones.
117  */
118 enum class CalloutFlag : uint32_t {
119     Telemetry = 0x1,
120 };
121 
ShowTelemetryCallout()122 void GMainWindow::ShowTelemetryCallout() {
123     if (UISettings::values.callout_flags & static_cast<uint32_t>(CalloutFlag::Telemetry)) {
124         return;
125     }
126 
127     UISettings::values.callout_flags |= static_cast<uint32_t>(CalloutFlag::Telemetry);
128     const QString telemetry_message =
129         tr("<a href='https://citra-emu.org/entry/telemetry-and-why-thats-a-good-thing/'>Anonymous "
130            "data is collected</a> to help improve Citra. "
131            "<br/><br/>Would you like to share your usage data with us?");
132     if (QMessageBox::question(this, tr("Telemetry"), telemetry_message) != QMessageBox::Yes) {
133         Settings::values.enable_telemetry = false;
134         Settings::Apply();
135     }
136 }
137 
138 const int GMainWindow::max_recent_files_item;
139 
InitializeLogging()140 static void InitializeLogging() {
141     Log::Filter log_filter;
142     log_filter.ParseFilterString(Settings::values.log_filter);
143     Log::SetGlobalFilter(log_filter);
144 
145     const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
146     FileUtil::CreateFullPath(log_dir);
147     Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
148 #ifdef _WIN32
149     Log::AddBackend(std::make_unique<Log::DebuggerBackend>());
150 #endif
151 }
152 
GMainWindow()153 GMainWindow::GMainWindow()
154     : config(std::make_unique<Config>()), emu_thread(nullptr),
155       ui(std::make_unique<Ui::MainWindow>()) {
156     InitializeLogging();
157     Debugger::ToggleConsole();
158     Settings::LogSettings();
159 
160     // register types to use in slots and signals
161     qRegisterMetaType<std::size_t>("std::size_t");
162     qRegisterMetaType<Service::AM::InstallStatus>("Service::AM::InstallStatus");
163 
164     LoadTranslation();
165 
166     Pica::g_debug_context = Pica::DebugContext::Construct();
167     setAcceptDrops(true);
168     ui->setupUi(this);
169     statusBar()->hide();
170 
171     default_theme_paths = QIcon::themeSearchPaths();
172     UpdateUITheme();
173 
174     SetDiscordEnabled(UISettings::values.enable_discord_presence);
175     discord_rpc->Update();
176 
177     Network::Init();
178 
179     Core::Movie::GetInstance().SetPlaybackCompletionCallback([this] {
180         QMetaObject::invokeMethod(this, "OnMoviePlaybackCompleted", Qt::BlockingQueuedConnection);
181     });
182 
183     InitializeWidgets();
184     InitializeDebugWidgets();
185     InitializeRecentFileMenuActions();
186     InitializeSaveStateMenuActions();
187     InitializeHotkeys();
188     ShowUpdaterWidgets();
189 
190     SetDefaultUIGeometry();
191     RestoreUIState();
192 
193     ConnectMenuEvents();
194     ConnectWidgetEvents();
195 
196     LOG_INFO(Frontend, "Citra Version: {} | {}-{}", Common::g_build_fullname, Common::g_scm_branch,
197              Common::g_scm_desc);
198 #ifdef ARCHITECTURE_x86_64
199     const auto& caps = Common::GetCPUCaps();
200     std::string cpu_string = caps.cpu_string;
201     if (caps.avx || caps.avx2 || caps.avx512) {
202         cpu_string += " | AVX";
203         if (caps.avx512) {
204             cpu_string += "512";
205         } else if (caps.avx2) {
206             cpu_string += '2';
207         }
208         if (caps.fma || caps.fma4) {
209             cpu_string += " | FMA";
210         }
211     }
212     LOG_INFO(Frontend, "Host CPU: {}", cpu_string);
213 #endif
214     LOG_INFO(Frontend, "Host OS: {}", QSysInfo::prettyProductName().toStdString());
215     UpdateWindowTitle();
216 
217     show();
218 
219     game_list->LoadCompatibilityList();
220     game_list->PopulateAsync(UISettings::values.game_dirs);
221 
222     // Show one-time "callout" messages to the user
223     ShowTelemetryCallout();
224 
225     mouse_hide_timer.setInterval(default_mouse_timeout);
226     connect(&mouse_hide_timer, &QTimer::timeout, this, &GMainWindow::HideMouseCursor);
227     connect(ui->menubar, &QMenuBar::hovered, this, &GMainWindow::OnMouseActivity);
228 
229     if (UISettings::values.check_for_update_on_start) {
230         CheckForUpdates();
231     }
232 
233     QStringList args = QApplication::arguments();
234     if (args.length() >= 2) {
235         BootGame(args[1]);
236     }
237 }
238 
~GMainWindow()239 GMainWindow::~GMainWindow() {
240     // will get automatically deleted otherwise
241     if (render_window->parent() == nullptr)
242         delete render_window;
243 
244     Pica::g_debug_context.reset();
245     Network::Shutdown();
246 }
247 
InitializeWidgets()248 void GMainWindow::InitializeWidgets() {
249 #ifdef CITRA_ENABLE_COMPATIBILITY_REPORTING
250     ui->action_Report_Compatibility->setVisible(true);
251 #endif
252     render_window = new GRenderWindow(this, emu_thread.get());
253     render_window->hide();
254 
255     game_list = new GameList(this);
256     ui->horizontalLayout->addWidget(game_list);
257 
258     game_list_placeholder = new GameListPlaceholder(this);
259     ui->horizontalLayout->addWidget(game_list_placeholder);
260     game_list_placeholder->setVisible(false);
261 
262     loading_screen = new LoadingScreen(this);
263     loading_screen->hide();
264     ui->horizontalLayout->addWidget(loading_screen);
265     connect(loading_screen, &LoadingScreen::Hidden, [&] {
266         loading_screen->Clear();
267         if (emulation_running) {
268             render_window->show();
269             render_window->setFocus();
270         }
271     });
272 
273     multiplayer_state = new MultiplayerState(this, game_list->GetModel(), ui->action_Leave_Room,
274                                              ui->action_Show_Room);
275     multiplayer_state->setVisible(false);
276 
277     // Setup updater
278     updater = new Updater(this);
279     UISettings::values.updater_found = updater->HasUpdater();
280 
281     // Create status bar
282     message_label = new QLabel();
283     // Configured separately for left alignment
284     message_label->setVisible(false);
285     message_label->setFrameStyle(QFrame::NoFrame);
286     message_label->setContentsMargins(4, 0, 4, 0);
287     message_label->setAlignment(Qt::AlignLeft);
288     statusBar()->addPermanentWidget(message_label, 1);
289 
290     progress_bar = new QProgressBar();
291     progress_bar->hide();
292     statusBar()->addPermanentWidget(progress_bar);
293 
294     emu_speed_label = new QLabel();
295     emu_speed_label->setToolTip(tr("Current emulation speed. Values higher or lower than 100% "
296                                    "indicate emulation is running faster or slower than a 3DS."));
297     game_fps_label = new QLabel();
298     game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
299                                   "This will vary from game to game and scene to scene."));
300     emu_frametime_label = new QLabel();
301     emu_frametime_label->setToolTip(
302         tr("Time taken to emulate a 3DS frame, not counting framelimiting or v-sync. For "
303            "full-speed emulation this should be at most 16.67 ms."));
304 
305     for (auto& label : {emu_speed_label, game_fps_label, emu_frametime_label}) {
306         label->setVisible(false);
307         label->setFrameStyle(QFrame::NoFrame);
308         label->setContentsMargins(4, 0, 4, 0);
309         statusBar()->addPermanentWidget(label, 0);
310     }
311     statusBar()->addPermanentWidget(multiplayer_state->GetStatusText(), 0);
312     statusBar()->addPermanentWidget(multiplayer_state->GetStatusIcon(), 0);
313     statusBar()->setVisible(true);
314 
315     // Removes an ugly inner border from the status bar widgets under Linux
316     setStyleSheet(QStringLiteral("QStatusBar::item{border: none;}"));
317 
318     QActionGroup* actionGroup_ScreenLayouts = new QActionGroup(this);
319     actionGroup_ScreenLayouts->addAction(ui->action_Screen_Layout_Default);
320     actionGroup_ScreenLayouts->addAction(ui->action_Screen_Layout_Single_Screen);
321     actionGroup_ScreenLayouts->addAction(ui->action_Screen_Layout_Large_Screen);
322     actionGroup_ScreenLayouts->addAction(ui->action_Screen_Layout_Side_by_Side);
323 }
324 
InitializeDebugWidgets()325 void GMainWindow::InitializeDebugWidgets() {
326     connect(ui->action_Create_Pica_Surface_Viewer, &QAction::triggered, this,
327             &GMainWindow::OnCreateGraphicsSurfaceViewer);
328 
329     QMenu* debug_menu = ui->menu_View_Debugging;
330 
331 #if MICROPROFILE_ENABLED
332     microProfileDialog = new MicroProfileDialog(this);
333     microProfileDialog->hide();
334     debug_menu->addAction(microProfileDialog->toggleViewAction());
335 #endif
336 
337     registersWidget = new RegistersWidget(this);
338     addDockWidget(Qt::RightDockWidgetArea, registersWidget);
339     registersWidget->hide();
340     debug_menu->addAction(registersWidget->toggleViewAction());
341     connect(this, &GMainWindow::EmulationStarting, registersWidget,
342             &RegistersWidget::OnEmulationStarting);
343     connect(this, &GMainWindow::EmulationStopping, registersWidget,
344             &RegistersWidget::OnEmulationStopping);
345 
346     graphicsWidget = new GPUCommandStreamWidget(this);
347     addDockWidget(Qt::RightDockWidgetArea, graphicsWidget);
348     graphicsWidget->hide();
349     debug_menu->addAction(graphicsWidget->toggleViewAction());
350 
351     graphicsCommandsWidget = new GPUCommandListWidget(this);
352     addDockWidget(Qt::RightDockWidgetArea, graphicsCommandsWidget);
353     graphicsCommandsWidget->hide();
354     debug_menu->addAction(graphicsCommandsWidget->toggleViewAction());
355 
356     graphicsBreakpointsWidget = new GraphicsBreakPointsWidget(Pica::g_debug_context, this);
357     addDockWidget(Qt::RightDockWidgetArea, graphicsBreakpointsWidget);
358     graphicsBreakpointsWidget->hide();
359     debug_menu->addAction(graphicsBreakpointsWidget->toggleViewAction());
360 
361     graphicsVertexShaderWidget = new GraphicsVertexShaderWidget(Pica::g_debug_context, this);
362     addDockWidget(Qt::RightDockWidgetArea, graphicsVertexShaderWidget);
363     graphicsVertexShaderWidget->hide();
364     debug_menu->addAction(graphicsVertexShaderWidget->toggleViewAction());
365 
366     graphicsTracingWidget = new GraphicsTracingWidget(Pica::g_debug_context, this);
367     addDockWidget(Qt::RightDockWidgetArea, graphicsTracingWidget);
368     graphicsTracingWidget->hide();
369     debug_menu->addAction(graphicsTracingWidget->toggleViewAction());
370     connect(this, &GMainWindow::EmulationStarting, graphicsTracingWidget,
371             &GraphicsTracingWidget::OnEmulationStarting);
372     connect(this, &GMainWindow::EmulationStopping, graphicsTracingWidget,
373             &GraphicsTracingWidget::OnEmulationStopping);
374 
375     waitTreeWidget = new WaitTreeWidget(this);
376     addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
377     waitTreeWidget->hide();
378     debug_menu->addAction(waitTreeWidget->toggleViewAction());
379     connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
380             &WaitTreeWidget::OnEmulationStarting);
381     connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
382             &WaitTreeWidget::OnEmulationStopping);
383 
384     lleServiceModulesWidget = new LLEServiceModulesWidget(this);
385     addDockWidget(Qt::RightDockWidgetArea, lleServiceModulesWidget);
386     lleServiceModulesWidget->hide();
387     debug_menu->addAction(lleServiceModulesWidget->toggleViewAction());
388     connect(this, &GMainWindow::EmulationStarting,
389             [this] { lleServiceModulesWidget->setDisabled(true); });
390     connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
391             [this] { lleServiceModulesWidget->setDisabled(false); });
392 
393     ipcRecorderWidget = new IPCRecorderWidget(this);
394     addDockWidget(Qt::RightDockWidgetArea, ipcRecorderWidget);
395     ipcRecorderWidget->hide();
396     debug_menu->addAction(ipcRecorderWidget->toggleViewAction());
397     connect(this, &GMainWindow::EmulationStarting, ipcRecorderWidget,
398             &IPCRecorderWidget::OnEmulationStarting);
399 }
400 
InitializeRecentFileMenuActions()401 void GMainWindow::InitializeRecentFileMenuActions() {
402     for (int i = 0; i < max_recent_files_item; ++i) {
403         actions_recent_files[i] = new QAction(this);
404         actions_recent_files[i]->setVisible(false);
405         connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile);
406 
407         ui->menu_recent_files->addAction(actions_recent_files[i]);
408     }
409     ui->menu_recent_files->addSeparator();
410     QAction* action_clear_recent_files = new QAction(this);
411     action_clear_recent_files->setText(tr("Clear Recent Files"));
412     connect(action_clear_recent_files, &QAction::triggered, this, [this] {
413         UISettings::values.recent_files.clear();
414         UpdateRecentFiles();
415     });
416     ui->menu_recent_files->addAction(action_clear_recent_files);
417 
418     UpdateRecentFiles();
419 }
420 
InitializeSaveStateMenuActions()421 void GMainWindow::InitializeSaveStateMenuActions() {
422     for (u32 i = 0; i < Core::SaveStateSlotCount; ++i) {
423         actions_load_state[i] = new QAction(this);
424         actions_load_state[i]->setData(i + 1);
425         connect(actions_load_state[i], &QAction::triggered, this, &GMainWindow::OnLoadState);
426         ui->menu_Load_State->addAction(actions_load_state[i]);
427 
428         actions_save_state[i] = new QAction(this);
429         actions_save_state[i]->setData(i + 1);
430         connect(actions_save_state[i], &QAction::triggered, this, &GMainWindow::OnSaveState);
431         ui->menu_Save_State->addAction(actions_save_state[i]);
432     }
433 
434     connect(ui->action_Load_from_Newest_Slot, &QAction::triggered, [this] {
435         UpdateSaveStates();
436         if (newest_slot != 0) {
437             actions_load_state[newest_slot - 1]->trigger();
438         }
439     });
440     connect(ui->action_Save_to_Oldest_Slot, &QAction::triggered, [this] {
441         UpdateSaveStates();
442         actions_save_state[oldest_slot - 1]->trigger();
443     });
444 
445     connect(ui->menu_Load_State->menuAction(), &QAction::hovered, this,
446             &GMainWindow::UpdateSaveStates);
447     connect(ui->menu_Save_State->menuAction(), &QAction::hovered, this,
448             &GMainWindow::UpdateSaveStates);
449 
450     UpdateSaveStates();
451 }
452 
InitializeHotkeys()453 void GMainWindow::InitializeHotkeys() {
454     hotkey_registry.LoadHotkeys();
455 
456     const QString main_window = QStringLiteral("Main Window");
457     const QString load_file = QStringLiteral("Load File");
458     const QString exit_citra = QStringLiteral("Exit Citra");
459     const QString stop_emulation = QStringLiteral("Stop Emulation");
460     const QString toggle_filter_bar = QStringLiteral("Toggle Filter Bar");
461     const QString toggle_status_bar = QStringLiteral("Toggle Status Bar");
462     const QString fullscreen = QStringLiteral("Fullscreen");
463 
464     ui->action_Show_Filter_Bar->setShortcut(
465         hotkey_registry.GetKeySequence(main_window, toggle_filter_bar));
466     ui->action_Show_Filter_Bar->setShortcutContext(
467         hotkey_registry.GetShortcutContext(main_window, toggle_filter_bar));
468 
469     ui->action_Show_Status_Bar->setShortcut(
470         hotkey_registry.GetKeySequence(main_window, toggle_status_bar));
471     ui->action_Show_Status_Bar->setShortcutContext(
472         hotkey_registry.GetShortcutContext(main_window, toggle_status_bar));
473 
474     connect(hotkey_registry.GetHotkey(main_window, load_file, this), &QShortcut::activated,
475             ui->action_Load_File, &QAction::trigger);
476 
477     connect(hotkey_registry.GetHotkey(main_window, stop_emulation, this), &QShortcut::activated,
478             ui->action_Stop, &QAction::trigger);
479 
480     connect(hotkey_registry.GetHotkey(main_window, exit_citra, this), &QShortcut::activated,
481             ui->action_Exit, &QAction::trigger);
482 
483     connect(
484         hotkey_registry.GetHotkey(main_window, QStringLiteral("Continue/Pause Emulation"), this),
485         &QShortcut::activated, this, [&] {
486             if (emulation_running) {
487                 if (emu_thread->IsRunning()) {
488                     OnPauseGame();
489                 } else {
490                     OnStartGame();
491                 }
492             }
493         });
494     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Restart Emulation"), this),
495             &QShortcut::activated, this, [this] {
496                 if (!Core::System::GetInstance().IsPoweredOn())
497                     return;
498                 BootGame(QString(game_path));
499             });
500     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Swap Screens"), render_window),
501             &QShortcut::activated, ui->action_Screen_Layout_Swap_Screens, &QAction::trigger);
502     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Rotate Screens Upright"),
503                                       render_window),
504             &QShortcut::activated, ui->action_Screen_Layout_Upright_Screens, &QAction::trigger);
505     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Toggle Screen Layout"),
506                                       render_window),
507             &QShortcut::activated, this, &GMainWindow::ToggleScreenLayout);
508     connect(hotkey_registry.GetHotkey(main_window, fullscreen, render_window),
509             &QShortcut::activated, ui->action_Fullscreen, &QAction::trigger);
510     connect(hotkey_registry.GetHotkey(main_window, fullscreen, render_window),
511             &QShortcut::activatedAmbiguously, ui->action_Fullscreen, &QAction::trigger);
512     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Exit Fullscreen"), this),
513             &QShortcut::activated, this, [&] {
514                 if (emulation_running) {
515                     ui->action_Fullscreen->setChecked(false);
516                     ToggleFullscreen();
517                 }
518             });
519     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Toggle Alternate Speed"), this),
520             &QShortcut::activated, this, [&] {
521                 Settings::values.use_frame_limit_alternate =
522                     !Settings::values.use_frame_limit_alternate;
523                 UpdateStatusBar();
524             });
525     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Toggle Texture Dumping"), this),
526             &QShortcut::activated, this,
527             [&] { Settings::values.dump_textures = !Settings::values.dump_textures; });
528     // We use "static" here in order to avoid capturing by lambda due to a MSVC bug, which makes
529     // the variable hold a garbage value after this function exits
530     static constexpr u16 SPEED_LIMIT_STEP = 5;
531     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Increase Speed Limit"), this),
532             &QShortcut::activated, this, [&] {
533                 if (Settings::values.use_frame_limit_alternate) {
534                     if (Settings::values.frame_limit_alternate == 0) {
535                         return;
536                     }
537                     if (Settings::values.frame_limit_alternate < 995 - SPEED_LIMIT_STEP) {
538                         Settings::values.frame_limit_alternate += SPEED_LIMIT_STEP;
539                     } else {
540                         Settings::values.frame_limit_alternate = 0;
541                     }
542                 } else {
543                     if (Settings::values.frame_limit == 0) {
544                         return;
545                     }
546                     if (Settings::values.frame_limit < 995 - SPEED_LIMIT_STEP) {
547                         Settings::values.frame_limit += SPEED_LIMIT_STEP;
548                     } else {
549                         Settings::values.frame_limit = 0;
550                     }
551                 }
552                 UpdateStatusBar();
553             });
554     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Decrease Speed Limit"), this),
555             &QShortcut::activated, this, [&] {
556                 if (Settings::values.use_frame_limit_alternate) {
557                     if (Settings::values.frame_limit_alternate == 0) {
558                         Settings::values.frame_limit_alternate = 995;
559                     } else if (Settings::values.frame_limit_alternate > SPEED_LIMIT_STEP) {
560                         Settings::values.frame_limit_alternate -= SPEED_LIMIT_STEP;
561                     }
562                 } else {
563                     if (Settings::values.frame_limit == 0) {
564                         Settings::values.frame_limit = 995;
565                     } else if (Settings::values.frame_limit > SPEED_LIMIT_STEP) {
566                         Settings::values.frame_limit -= SPEED_LIMIT_STEP;
567                         UpdateStatusBar();
568                     }
569                 }
570                 UpdateStatusBar();
571             });
572     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Toggle Frame Advancing"), this),
573             &QShortcut::activated, ui->action_Enable_Frame_Advancing, &QAction::trigger);
574     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Advance Frame"), this),
575             &QShortcut::activated, ui->action_Advance_Frame, &QAction::trigger);
576     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Load Amiibo"), this),
577             &QShortcut::activated, this, [&] {
578                 if (ui->action_Load_Amiibo->isEnabled()) {
579                     OnLoadAmiibo();
580                 }
581             });
582     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Remove Amiibo"), this),
583             &QShortcut::activated, this, [&] {
584                 if (ui->action_Remove_Amiibo->isEnabled()) {
585                     OnRemoveAmiibo();
586                 }
587             });
588     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Capture Screenshot"), this),
589             &QShortcut::activated, this, [&] {
590                 if (emu_thread->IsRunning()) {
591                     OnCaptureScreenshot();
592                 }
593             });
594     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Load from Newest Slot"), this),
595             &QShortcut::activated, ui->action_Load_from_Newest_Slot, &QAction::trigger);
596     connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Save to Oldest Slot"), this),
597             &QShortcut::activated, ui->action_Save_to_Oldest_Slot, &QAction::trigger);
598 }
599 
ShowUpdaterWidgets()600 void GMainWindow::ShowUpdaterWidgets() {
601     ui->action_Check_For_Updates->setVisible(UISettings::values.updater_found);
602     ui->action_Open_Maintenance_Tool->setVisible(UISettings::values.updater_found);
603 
604     connect(updater, &Updater::CheckUpdatesDone, this, &GMainWindow::OnUpdateFound);
605 }
606 
SetDefaultUIGeometry()607 void GMainWindow::SetDefaultUIGeometry() {
608     // geometry: 55% of the window contents are in the upper screen half, 45% in the lower half
609     const QRect screenRect = QApplication::desktop()->screenGeometry(this);
610 
611     const int w = screenRect.width() * 2 / 3;
612     const int h = screenRect.height() / 2;
613     const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
614     const int y = (screenRect.y() + screenRect.height()) / 2 - h * 55 / 100;
615 
616     setGeometry(x, y, w, h);
617 }
618 
RestoreUIState()619 void GMainWindow::RestoreUIState() {
620     restoreGeometry(UISettings::values.geometry);
621     restoreState(UISettings::values.state);
622     render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
623 #if MICROPROFILE_ENABLED
624     microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
625     microProfileDialog->setVisible(UISettings::values.microprofile_visible);
626 #endif
627     ui->action_Cheats->setEnabled(false);
628 
629     game_list->LoadInterfaceLayout();
630 
631     ui->action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode);
632     ToggleWindowMode();
633 
634     ui->action_Fullscreen->setChecked(UISettings::values.fullscreen);
635     SyncMenuUISettings();
636 
637     ui->action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);
638     OnDisplayTitleBars(ui->action_Display_Dock_Widget_Headers->isChecked());
639 
640     ui->action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar);
641     game_list->SetFilterVisible(ui->action_Show_Filter_Bar->isChecked());
642 
643     ui->action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);
644     statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
645 }
646 
OnAppFocusStateChanged(Qt::ApplicationState state)647 void GMainWindow::OnAppFocusStateChanged(Qt::ApplicationState state) {
648     if (!UISettings::values.pause_when_in_background) {
649         return;
650     }
651     if (state != Qt::ApplicationHidden && state != Qt::ApplicationInactive &&
652         state != Qt::ApplicationActive) {
653         LOG_DEBUG(Frontend, "ApplicationState unusual flag: {} ", state);
654     }
655     if (ui->action_Pause->isEnabled() &&
656         (state & (Qt::ApplicationHidden | Qt::ApplicationInactive))) {
657         auto_paused = true;
658         OnPauseGame();
659     } else if (ui->action_Start->isEnabled() && auto_paused && state == Qt::ApplicationActive) {
660         auto_paused = false;
661         OnStartGame();
662     }
663 }
664 
ConnectWidgetEvents()665 void GMainWindow::ConnectWidgetEvents() {
666     connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
667     connect(game_list, &GameList::OpenDirectory, this, &GMainWindow::OnGameListOpenDirectory);
668     connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
669     connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
670             &GMainWindow::OnGameListNavigateToGamedbEntry);
671     connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS);
672     connect(game_list, &GameList::AddDirectory, this, &GMainWindow::OnGameListAddDirectory);
673     connect(game_list_placeholder, &GameListPlaceholder::AddDirectory, this,
674             &GMainWindow::OnGameListAddDirectory);
675     connect(game_list, &GameList::ShowList, this, &GMainWindow::OnGameListShowList);
676     connect(game_list, &GameList::PopulatingCompleted,
677             [this] { multiplayer_state->UpdateGameList(game_list->GetModel()); });
678 
679     connect(this, &GMainWindow::EmulationStarting, render_window,
680             &GRenderWindow::OnEmulationStarting);
681     connect(this, &GMainWindow::EmulationStopping, render_window,
682             &GRenderWindow::OnEmulationStopping);
683 
684     connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
685 
686     connect(this, &GMainWindow::UpdateProgress, this, &GMainWindow::OnUpdateProgress);
687     connect(this, &GMainWindow::CIAInstallReport, this, &GMainWindow::OnCIAInstallReport);
688     connect(this, &GMainWindow::CIAInstallFinished, this, &GMainWindow::OnCIAInstallFinished);
689     connect(this, &GMainWindow::UpdateThemedIcons, multiplayer_state,
690             &MultiplayerState::UpdateThemedIcons);
691 }
692 
ConnectMenuEvents()693 void GMainWindow::ConnectMenuEvents() {
694     // File
695     connect(ui->action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
696     connect(ui->action_Install_CIA, &QAction::triggered, this, &GMainWindow::OnMenuInstallCIA);
697     connect(ui->action_Exit, &QAction::triggered, this, &QMainWindow::close);
698     connect(ui->action_Load_Amiibo, &QAction::triggered, this, &GMainWindow::OnLoadAmiibo);
699     connect(ui->action_Remove_Amiibo, &QAction::triggered, this, &GMainWindow::OnRemoveAmiibo);
700 
701     // Emulation
702     connect(ui->action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
703     connect(ui->action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
704     connect(ui->action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
705     connect(ui->action_Restart, &QAction::triggered, this,
706             [this] { BootGame(QString(game_path)); });
707     connect(ui->action_Report_Compatibility, &QAction::triggered, this,
708             &GMainWindow::OnMenuReportCompatibility);
709     connect(ui->action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
710     connect(ui->action_Cheats, &QAction::triggered, this, &GMainWindow::OnCheats);
711 
712     // View
713     connect(ui->action_Single_Window_Mode, &QAction::triggered, this,
714             &GMainWindow::ToggleWindowMode);
715     connect(ui->action_Display_Dock_Widget_Headers, &QAction::triggered, this,
716             &GMainWindow::OnDisplayTitleBars);
717     connect(ui->action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
718     connect(ui->action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
719 
720     // Multiplayer
721     connect(ui->action_View_Lobby, &QAction::triggered, multiplayer_state,
722             &MultiplayerState::OnViewLobby);
723     connect(ui->action_Start_Room, &QAction::triggered, multiplayer_state,
724             &MultiplayerState::OnCreateRoom);
725     connect(ui->action_Leave_Room, &QAction::triggered, multiplayer_state,
726             &MultiplayerState::OnCloseRoom);
727     connect(ui->action_Connect_To_Room, &QAction::triggered, multiplayer_state,
728             &MultiplayerState::OnDirectConnectToRoom);
729     connect(ui->action_Show_Room, &QAction::triggered, multiplayer_state,
730             &MultiplayerState::OnOpenNetworkRoom);
731 
732     ui->action_Fullscreen->setShortcut(
733         hotkey_registry
734             .GetHotkey(QStringLiteral("Main Window"), QStringLiteral("Fullscreen"), this)
735             ->key());
736     ui->action_Screen_Layout_Swap_Screens->setShortcut(
737         hotkey_registry
738             .GetHotkey(QStringLiteral("Main Window"), QStringLiteral("Swap Screens"), this)
739             ->key());
740     ui->action_Screen_Layout_Swap_Screens->setShortcutContext(Qt::WidgetWithChildrenShortcut);
741     ui->action_Screen_Layout_Upright_Screens->setShortcut(
742         hotkey_registry
743             .GetHotkey(QStringLiteral("Main Window"), QStringLiteral("Rotate Screens Upright"),
744                        this)
745             ->key());
746     ui->action_Screen_Layout_Upright_Screens->setShortcutContext(Qt::WidgetWithChildrenShortcut);
747     connect(ui->action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
748     connect(ui->action_Screen_Layout_Default, &QAction::triggered, this,
749             &GMainWindow::ChangeScreenLayout);
750     connect(ui->action_Screen_Layout_Single_Screen, &QAction::triggered, this,
751             &GMainWindow::ChangeScreenLayout);
752     connect(ui->action_Screen_Layout_Large_Screen, &QAction::triggered, this,
753             &GMainWindow::ChangeScreenLayout);
754     connect(ui->action_Screen_Layout_Side_by_Side, &QAction::triggered, this,
755             &GMainWindow::ChangeScreenLayout);
756     connect(ui->action_Screen_Layout_Swap_Screens, &QAction::triggered, this,
757             &GMainWindow::OnSwapScreens);
758     connect(ui->action_Screen_Layout_Upright_Screens, &QAction::triggered, this,
759             &GMainWindow::OnRotateScreens);
760 
761     // Movie
762     connect(ui->action_Record_Movie, &QAction::triggered, this, &GMainWindow::OnRecordMovie);
763     connect(ui->action_Play_Movie, &QAction::triggered, this, &GMainWindow::OnPlayMovie);
764     connect(ui->action_Close_Movie, &QAction::triggered, this, &GMainWindow::OnCloseMovie);
765     connect(ui->action_Save_Movie, &QAction::triggered, this, &GMainWindow::OnSaveMovie);
766     connect(ui->action_Movie_Read_Only_Mode, &QAction::toggled, this,
767             [this](bool checked) { Core::Movie::GetInstance().SetReadOnly(checked); });
768     connect(ui->action_Enable_Frame_Advancing, &QAction::triggered, this, [this] {
769         if (emulation_running) {
770             Core::System::GetInstance().frame_limiter.SetFrameAdvancing(
771                 ui->action_Enable_Frame_Advancing->isChecked());
772             ui->action_Advance_Frame->setEnabled(ui->action_Enable_Frame_Advancing->isChecked());
773         }
774     });
775     connect(ui->action_Advance_Frame, &QAction::triggered, this, [this] {
776         if (emulation_running) {
777             ui->action_Enable_Frame_Advancing->setChecked(true);
778             ui->action_Advance_Frame->setEnabled(true);
779             Core::System::GetInstance().frame_limiter.SetFrameAdvancing(true);
780             Core::System::GetInstance().frame_limiter.AdvanceFrame();
781         }
782     });
783     connect(ui->action_Capture_Screenshot, &QAction::triggered, this,
784             &GMainWindow::OnCaptureScreenshot);
785 
786 #ifdef ENABLE_FFMPEG_VIDEO_DUMPER
787     connect(ui->action_Dump_Video, &QAction::triggered, [this] {
788         if (ui->action_Dump_Video->isChecked()) {
789             OnStartVideoDumping();
790         } else {
791             OnStopVideoDumping();
792         }
793     });
794 #else
795     ui->action_Dump_Video->setEnabled(false);
796 #endif
797 
798     // Help
799     connect(ui->action_Open_Citra_Folder, &QAction::triggered, this,
800             &GMainWindow::OnOpenCitraFolder);
801     connect(ui->action_FAQ, &QAction::triggered, []() {
802         QDesktopServices::openUrl(QUrl(QStringLiteral("https://citra-emu.org/wiki/faq/")));
803     });
804     connect(ui->action_About, &QAction::triggered, this, &GMainWindow::OnMenuAboutCitra);
805     connect(ui->action_Check_For_Updates, &QAction::triggered, this,
806             &GMainWindow::OnCheckForUpdates);
807     connect(ui->action_Open_Maintenance_Tool, &QAction::triggered, this,
808             &GMainWindow::OnOpenUpdater);
809 }
810 
OnDisplayTitleBars(bool show)811 void GMainWindow::OnDisplayTitleBars(bool show) {
812     QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
813 
814     if (show) {
815         for (QDockWidget* widget : widgets) {
816             QWidget* old = widget->titleBarWidget();
817             widget->setTitleBarWidget(nullptr);
818             if (old != nullptr)
819                 delete old;
820         }
821     } else {
822         for (QDockWidget* widget : widgets) {
823             QWidget* old = widget->titleBarWidget();
824             widget->setTitleBarWidget(new QWidget());
825             if (old != nullptr)
826                 delete old;
827         }
828     }
829 }
830 
OnCheckForUpdates()831 void GMainWindow::OnCheckForUpdates() {
832     explicit_update_check = true;
833     CheckForUpdates();
834 }
835 
CheckForUpdates()836 void GMainWindow::CheckForUpdates() {
837     if (updater->CheckForUpdates()) {
838         LOG_INFO(Frontend, "Update check started");
839     } else {
840         LOG_WARNING(Frontend, "Unable to start check for updates");
841     }
842 }
843 
OnUpdateFound(bool found,bool error)844 void GMainWindow::OnUpdateFound(bool found, bool error) {
845     if (error) {
846         LOG_WARNING(Frontend, "Update check failed");
847         return;
848     }
849 
850     if (!found) {
851         LOG_INFO(Frontend, "No updates found");
852 
853         // If the user explicitly clicked the "Check for Updates" button, we are
854         //  going to want to show them a prompt anyway.
855         if (explicit_update_check) {
856             explicit_update_check = false;
857             ShowNoUpdatePrompt();
858         }
859         return;
860     }
861 
862     if (emulation_running && !explicit_update_check) {
863         LOG_INFO(Frontend, "Update found, deferring as game is running");
864         defer_update_prompt = true;
865         return;
866     }
867 
868     LOG_INFO(Frontend, "Update found!");
869     explicit_update_check = false;
870 
871     ShowUpdatePrompt();
872 }
873 
ShowUpdatePrompt()874 void GMainWindow::ShowUpdatePrompt() {
875     defer_update_prompt = false;
876 
877     auto result =
878         QMessageBox::question(this, tr("Update Available"),
879                               tr("An update is available. Would you like to install it now?"),
880                               QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
881 
882     if (result == QMessageBox::Yes) {
883         updater->LaunchUIOnExit();
884         close();
885     }
886 }
887 
ShowNoUpdatePrompt()888 void GMainWindow::ShowNoUpdatePrompt() {
889     QMessageBox::information(this, tr("No Update Found"), tr("No update is found."),
890                              QMessageBox::Ok, QMessageBox::Ok);
891 }
892 
OnOpenUpdater()893 void GMainWindow::OnOpenUpdater() {
894     updater->LaunchUI();
895 }
896 
PreventOSSleep()897 void GMainWindow::PreventOSSleep() {
898 #ifdef _WIN32
899     SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
900 #endif
901 }
902 
AllowOSSleep()903 void GMainWindow::AllowOSSleep() {
904 #ifdef _WIN32
905     SetThreadExecutionState(ES_CONTINUOUS);
906 #endif
907 }
908 
LoadROM(const QString & filename)909 bool GMainWindow::LoadROM(const QString& filename) {
910     // Shutdown previous session if the emu thread is still active...
911     if (emu_thread != nullptr)
912         ShutdownGame();
913 
914     render_window->InitRenderTarget();
915 
916     Frontend::ScopeAcquireContext scope(*render_window);
917 
918     const QString below_gl33_title = tr("OpenGL 3.3 Unsupported");
919     const QString below_gl33_message = tr("Your GPU may not support OpenGL 3.3, or you do not "
920                                           "have the latest graphics driver.");
921 
922     if (!QOpenGLContext::globalShareContext()->versionFunctions<QOpenGLFunctions_3_3_Core>()) {
923         QMessageBox::critical(this, below_gl33_title, below_gl33_message);
924         return false;
925     }
926 
927     Core::System& system{Core::System::GetInstance()};
928 
929     const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
930 
931     if (result != Core::System::ResultStatus::Success) {
932         switch (result) {
933         case Core::System::ResultStatus::ErrorGetLoader:
934             LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
935             QMessageBox::critical(
936                 this, tr("Invalid ROM Format"),
937                 tr("Your ROM format is not supported.<br/>Please follow the guides to redump your "
938                    "<a href='https://citra-emu.org/wiki/dumping-game-cartridges/'>game "
939                    "cartridges</a> or "
940                    "<a href='https://citra-emu.org/wiki/dumping-installed-titles/'>installed "
941                    "titles</a>."));
942             break;
943 
944         case Core::System::ResultStatus::ErrorSystemMode:
945             LOG_CRITICAL(Frontend, "Failed to load ROM!");
946             QMessageBox::critical(
947                 this, tr("ROM Corrupted"),
948                 tr("Your ROM is corrupted. <br/>Please follow the guides to redump your "
949                    "<a href='https://citra-emu.org/wiki/dumping-game-cartridges/'>game "
950                    "cartridges</a> or "
951                    "<a href='https://citra-emu.org/wiki/dumping-installed-titles/'>installed "
952                    "titles</a>."));
953             break;
954 
955         case Core::System::ResultStatus::ErrorLoader_ErrorEncrypted: {
956             QMessageBox::critical(
957                 this, tr("ROM Encrypted"),
958                 tr("Your ROM is encrypted. <br/>Please follow the guides to redump your "
959                    "<a href='https://citra-emu.org/wiki/dumping-game-cartridges/'>game "
960                    "cartridges</a> or "
961                    "<a href='https://citra-emu.org/wiki/dumping-installed-titles/'>installed "
962                    "titles</a>."));
963             break;
964         }
965         case Core::System::ResultStatus::ErrorLoader_ErrorInvalidFormat:
966             QMessageBox::critical(
967                 this, tr("Invalid ROM Format"),
968                 tr("Your ROM format is not supported.<br/>Please follow the guides to redump your "
969                    "<a href='https://citra-emu.org/wiki/dumping-game-cartridges/'>game "
970                    "cartridges</a> or "
971                    "<a href='https://citra-emu.org/wiki/dumping-installed-titles/'>installed "
972                    "titles</a>."));
973             break;
974 
975         case Core::System::ResultStatus::ErrorVideoCore:
976             QMessageBox::critical(
977                 this, tr("Video Core Error"),
978                 tr("An error has occurred. Please <a "
979                    "href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>see "
980                    "the "
981                    "log</a> for more details. "
982                    "Ensure that you have the latest graphics drivers for your GPU."));
983             break;
984 
985         case Core::System::ResultStatus::ErrorVideoCore_ErrorGenericDrivers:
986             QMessageBox::critical(
987                 this, tr("Video Core Error"),
988                 tr("You are running default Windows drivers "
989                    "for your GPU. You need to install the "
990                    "proper drivers for your graphics card from the manufacturer's website."));
991             break;
992 
993         case Core::System::ResultStatus::ErrorVideoCore_ErrorBelowGL33:
994             QMessageBox::critical(this, below_gl33_title, below_gl33_message);
995             break;
996 
997         default:
998             QMessageBox::critical(
999                 this, tr("Error while loading ROM!"),
1000                 tr("An unknown error occurred. Please see the log for more details."));
1001             break;
1002         }
1003         return false;
1004     }
1005 
1006     std::string title;
1007     system.GetAppLoader().ReadTitle(title);
1008     game_title = QString::fromStdString(title);
1009     UpdateWindowTitle();
1010 
1011     game_path = filename;
1012 
1013     system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "Qt");
1014     return true;
1015 }
1016 
BootGame(const QString & filename)1017 void GMainWindow::BootGame(const QString& filename) {
1018     if (filename.endsWith(QStringLiteral(".cia"))) {
1019         const auto answer = QMessageBox::question(
1020             this, tr("CIA must be installed before usage"),
1021             tr("Before using this CIA, you must install it. Do you want to install it now?"),
1022             QMessageBox::Yes | QMessageBox::No);
1023 
1024         if (answer == QMessageBox::Yes)
1025             InstallCIA(QStringList(filename));
1026 
1027         return;
1028     }
1029 
1030     LOG_INFO(Frontend, "Citra starting...");
1031     StoreRecentFile(filename); // Put the filename on top of the list
1032 
1033     if (movie_record_on_start) {
1034         Core::Movie::GetInstance().PrepareForRecording();
1035     }
1036     if (movie_playback_on_start) {
1037         Core::Movie::GetInstance().PrepareForPlayback(movie_playback_path.toStdString());
1038     }
1039 
1040     // Save configurations
1041     UpdateUISettings();
1042     game_list->SaveInterfaceLayout();
1043     config->Save();
1044 
1045     if (!LoadROM(filename))
1046         return;
1047 
1048     // Set everything up
1049     if (movie_record_on_start) {
1050         Core::Movie::GetInstance().StartRecording(movie_record_path.toStdString(),
1051                                                   movie_record_author.toStdString());
1052         movie_record_on_start = false;
1053         movie_record_path.clear();
1054         movie_record_author.clear();
1055     }
1056     if (movie_playback_on_start) {
1057         Core::Movie::GetInstance().StartPlayback(movie_playback_path.toStdString());
1058         movie_playback_on_start = false;
1059         movie_playback_path.clear();
1060     }
1061 
1062     if (ui->action_Enable_Frame_Advancing->isChecked()) {
1063         ui->action_Advance_Frame->setEnabled(true);
1064         Core::System::GetInstance().frame_limiter.SetFrameAdvancing(true);
1065     } else {
1066         ui->action_Advance_Frame->setEnabled(false);
1067     }
1068 
1069     if (video_dumping_on_start) {
1070         Layout::FramebufferLayout layout{
1071             Layout::FrameLayoutFromResolutionScale(VideoCore::GetResolutionScaleFactor())};
1072         if (!Core::System::GetInstance().VideoDumper().StartDumping(
1073                 video_dumping_path.toStdString(), layout)) {
1074 
1075             QMessageBox::critical(
1076                 this, tr("Citra"),
1077                 tr("Could not start video dumping.<br>Refer to the log for details."));
1078             ui->action_Dump_Video->setChecked(false);
1079         }
1080         video_dumping_on_start = false;
1081         video_dumping_path.clear();
1082     }
1083 
1084     // Create and start the emulation thread
1085     emu_thread = std::make_unique<EmuThread>(*render_window);
1086     emit EmulationStarting(emu_thread.get());
1087     emu_thread->start();
1088 
1089     connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
1090     connect(render_window, &GRenderWindow::MouseActivity, this, &GMainWindow::OnMouseActivity);
1091 
1092     // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
1093     // before the CPU continues
1094     connect(emu_thread.get(), &EmuThread::DebugModeEntered, registersWidget,
1095             &RegistersWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
1096     connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
1097             &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
1098     connect(emu_thread.get(), &EmuThread::DebugModeLeft, registersWidget,
1099             &RegistersWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
1100     connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
1101             &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
1102 
1103     connect(emu_thread.get(), &EmuThread::LoadProgress, loading_screen,
1104             &LoadingScreen::OnLoadProgress, Qt::QueuedConnection);
1105     connect(emu_thread.get(), &EmuThread::HideLoadingScreen, loading_screen,
1106             &LoadingScreen::OnLoadComplete);
1107 
1108     // Update the GUI
1109     registersWidget->OnDebugModeEntered();
1110     if (ui->action_Single_Window_Mode->isChecked()) {
1111         game_list->hide();
1112         game_list_placeholder->hide();
1113     }
1114     status_bar_update_timer.start(1000);
1115 
1116     if (UISettings::values.hide_mouse) {
1117         mouse_hide_timer.start();
1118         setMouseTracking(true);
1119     }
1120 
1121     // show and hide the render_window to create the context
1122     render_window->show();
1123     render_window->hide();
1124 
1125     loading_screen->Prepare(Core::System::GetInstance().GetAppLoader());
1126     loading_screen->show();
1127 
1128     emulation_running = true;
1129     if (ui->action_Fullscreen->isChecked()) {
1130         ShowFullscreen();
1131     }
1132 
1133     OnStartGame();
1134 }
1135 
ShutdownGame()1136 void GMainWindow::ShutdownGame() {
1137     if (!emulation_running) {
1138         return;
1139     }
1140 
1141     if (ui->action_Fullscreen->isChecked()) {
1142         HideFullscreen();
1143     }
1144 
1145 #ifdef ENABLE_FFMPEG_VIDEO_DUMPER
1146     if (Core::System::GetInstance().VideoDumper().IsDumping()) {
1147         game_shutdown_delayed = true;
1148         OnStopVideoDumping();
1149         return;
1150     }
1151 #endif
1152 
1153     AllowOSSleep();
1154 
1155     discord_rpc->Pause();
1156     emu_thread->RequestStop();
1157 
1158     // Release emu threads from any breakpoints
1159     // This belongs after RequestStop() and before wait() because if emulation stops on a GPU
1160     // breakpoint after (or before) RequestStop() is called, the emulation would never be able
1161     // to continue out to the main loop and terminate. Thus wait() would hang forever.
1162     // TODO(bunnei): This function is not thread safe, but it's being used as if it were
1163     Pica::g_debug_context->ClearBreakpoints();
1164 
1165     // Frame advancing must be cancelled in order to release the emu thread from waiting
1166     Core::System::GetInstance().frame_limiter.SetFrameAdvancing(false);
1167 
1168     emit EmulationStopping();
1169 
1170     // Wait for emulation thread to complete and delete it
1171     emu_thread->wait();
1172     emu_thread = nullptr;
1173 
1174     OnCloseMovie();
1175 
1176     discord_rpc->Update();
1177 
1178     Camera::QtMultimediaCameraHandler::ReleaseHandlers();
1179 
1180     // The emulation is stopped, so closing the window or not does not matter anymore
1181     disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
1182 
1183     // Update the GUI
1184     ui->action_Start->setEnabled(false);
1185     ui->action_Start->setText(tr("Start"));
1186     ui->action_Pause->setEnabled(false);
1187     ui->action_Stop->setEnabled(false);
1188     ui->action_Restart->setEnabled(false);
1189     ui->action_Cheats->setEnabled(false);
1190     ui->action_Load_Amiibo->setEnabled(false);
1191     ui->action_Remove_Amiibo->setEnabled(false);
1192     ui->action_Report_Compatibility->setEnabled(false);
1193     ui->action_Advance_Frame->setEnabled(false);
1194     ui->action_Capture_Screenshot->setEnabled(false);
1195     render_window->hide();
1196     loading_screen->hide();
1197     loading_screen->Clear();
1198     if (game_list->IsEmpty())
1199         game_list_placeholder->show();
1200     else
1201         game_list->show();
1202     game_list->SetFilterFocus();
1203 
1204     setMouseTracking(false);
1205 
1206     // Disable status bar updates
1207     status_bar_update_timer.stop();
1208     message_label->setVisible(false);
1209     message_label_used_for_movie = false;
1210     emu_speed_label->setVisible(false);
1211     game_fps_label->setVisible(false);
1212     emu_frametime_label->setVisible(false);
1213 
1214     UpdateSaveStates();
1215 
1216     emulation_running = false;
1217 
1218     if (defer_update_prompt) {
1219         ShowUpdatePrompt();
1220     }
1221 
1222     game_title.clear();
1223     UpdateWindowTitle();
1224 
1225     game_path.clear();
1226 
1227     // When closing the game, destroy the GLWindow to clear the context after the game is closed
1228     render_window->ReleaseRenderTarget();
1229 }
1230 
StoreRecentFile(const QString & filename)1231 void GMainWindow::StoreRecentFile(const QString& filename) {
1232     UISettings::values.recent_files.prepend(filename);
1233     UISettings::values.recent_files.removeDuplicates();
1234     while (UISettings::values.recent_files.size() > max_recent_files_item) {
1235         UISettings::values.recent_files.removeLast();
1236     }
1237 
1238     UpdateRecentFiles();
1239 }
1240 
UpdateRecentFiles()1241 void GMainWindow::UpdateRecentFiles() {
1242     const int num_recent_files =
1243         std::min(UISettings::values.recent_files.size(), max_recent_files_item);
1244 
1245     for (int i = 0; i < num_recent_files; i++) {
1246         const QString text = QStringLiteral("&%1. %2").arg(i + 1).arg(
1247             QFileInfo(UISettings::values.recent_files[i]).fileName());
1248         actions_recent_files[i]->setText(text);
1249         actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
1250         actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
1251         actions_recent_files[i]->setVisible(true);
1252     }
1253 
1254     for (int j = num_recent_files; j < max_recent_files_item; ++j) {
1255         actions_recent_files[j]->setVisible(false);
1256     }
1257 
1258     // Enable the recent files menu if the list isn't empty
1259     ui->menu_recent_files->setEnabled(num_recent_files != 0);
1260 }
1261 
UpdateSaveStates()1262 void GMainWindow::UpdateSaveStates() {
1263     if (!Core::System::GetInstance().IsPoweredOn()) {
1264         ui->menu_Load_State->setEnabled(false);
1265         ui->menu_Save_State->setEnabled(false);
1266         return;
1267     }
1268 
1269     ui->menu_Load_State->setEnabled(true);
1270     ui->menu_Save_State->setEnabled(true);
1271     ui->action_Load_from_Newest_Slot->setEnabled(false);
1272 
1273     oldest_slot = newest_slot = 0;
1274     oldest_slot_time = std::numeric_limits<u64>::max();
1275     newest_slot_time = 0;
1276 
1277     u64 title_id;
1278     if (Core::System::GetInstance().GetAppLoader().ReadProgramId(title_id) !=
1279         Loader::ResultStatus::Success) {
1280         return;
1281     }
1282     auto savestates = Core::ListSaveStates(title_id);
1283     for (u32 i = 0; i < Core::SaveStateSlotCount; ++i) {
1284         actions_load_state[i]->setEnabled(false);
1285         actions_load_state[i]->setText(tr("Slot %1").arg(i + 1));
1286         actions_save_state[i]->setText(tr("Slot %1").arg(i + 1));
1287     }
1288     for (const auto& savestate : savestates) {
1289         const auto text = tr("Slot %1 - %2")
1290                               .arg(savestate.slot)
1291                               .arg(QDateTime::fromSecsSinceEpoch(savestate.time)
1292                                        .toString(QStringLiteral("yyyy-MM-dd hh:mm:ss")));
1293         actions_load_state[savestate.slot - 1]->setEnabled(true);
1294         actions_load_state[savestate.slot - 1]->setText(text);
1295         actions_save_state[savestate.slot - 1]->setText(text);
1296 
1297         ui->action_Load_from_Newest_Slot->setEnabled(true);
1298 
1299         if (savestate.time > newest_slot_time) {
1300             newest_slot = savestate.slot;
1301             newest_slot_time = savestate.time;
1302         }
1303         if (savestate.time < oldest_slot_time) {
1304             oldest_slot = savestate.slot;
1305             oldest_slot_time = savestate.time;
1306         }
1307     }
1308     for (u32 i = 0; i < Core::SaveStateSlotCount; ++i) {
1309         if (!actions_load_state[i]->isEnabled()) {
1310             // Prefer empty slot
1311             oldest_slot = i + 1;
1312             oldest_slot_time = 0;
1313             break;
1314         }
1315     }
1316 }
1317 
OnGameListLoadFile(QString game_path)1318 void GMainWindow::OnGameListLoadFile(QString game_path) {
1319     BootGame(game_path);
1320 }
1321 
OnGameListOpenFolder(u64 data_id,GameListOpenTarget target)1322 void GMainWindow::OnGameListOpenFolder(u64 data_id, GameListOpenTarget target) {
1323     std::string path;
1324     std::string open_target;
1325 
1326     switch (target) {
1327     case GameListOpenTarget::SAVE_DATA: {
1328         open_target = "Save Data";
1329         std::string sdmc_dir = FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir);
1330         path = FileSys::ArchiveSource_SDSaveData::GetSaveDataPathFor(sdmc_dir, data_id);
1331         break;
1332     }
1333     case GameListOpenTarget::EXT_DATA: {
1334         open_target = "Extra Data";
1335         std::string sdmc_dir = FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir);
1336         path = FileSys::GetExtDataPathFromId(sdmc_dir, data_id);
1337         break;
1338     }
1339     case GameListOpenTarget::APPLICATION: {
1340         open_target = "Application";
1341         auto media_type = Service::AM::GetTitleMediaType(data_id);
1342         path = Service::AM::GetTitlePath(media_type, data_id) + "content/";
1343         break;
1344     }
1345     case GameListOpenTarget::UPDATE_DATA:
1346         open_target = "Update Data";
1347         path = Service::AM::GetTitlePath(Service::FS::MediaType::SDMC, data_id + 0xe00000000) +
1348                "content/";
1349         break;
1350     case GameListOpenTarget::TEXTURE_DUMP:
1351         open_target = "Dumped Textures";
1352         path = fmt::format("{}textures/{:016X}/",
1353                            FileUtil::GetUserPath(FileUtil::UserPath::DumpDir), data_id);
1354         break;
1355     case GameListOpenTarget::TEXTURE_LOAD:
1356         open_target = "Custom Textures";
1357         path = fmt::format("{}textures/{:016X}/",
1358                            FileUtil::GetUserPath(FileUtil::UserPath::LoadDir), data_id);
1359         break;
1360     case GameListOpenTarget::MODS:
1361         open_target = "Mods";
1362         path = fmt::format("{}mods/{:016X}/", FileUtil::GetUserPath(FileUtil::UserPath::LoadDir),
1363                            data_id);
1364         break;
1365     default:
1366         LOG_ERROR(Frontend, "Unexpected target {}", static_cast<int>(target));
1367         return;
1368     }
1369 
1370     QString qpath = QString::fromStdString(path);
1371 
1372     QDir dir(qpath);
1373     if (!dir.exists()) {
1374         QMessageBox::critical(
1375             this, tr("Error Opening %1 Folder").arg(QString::fromStdString(open_target)),
1376             tr("Folder does not exist!"));
1377         return;
1378     }
1379 
1380     LOG_INFO(Frontend, "Opening {} path for data_id={:016x}", open_target, data_id);
1381 
1382     QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
1383 }
1384 
OnGameListNavigateToGamedbEntry(u64 program_id,const CompatibilityList & compatibility_list)1385 void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
1386                                                   const CompatibilityList& compatibility_list) {
1387     auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
1388 
1389     QString directory;
1390     if (it != compatibility_list.end())
1391         directory = it->second.second;
1392 
1393     QDesktopServices::openUrl(QUrl(QStringLiteral("https://citra-emu.org/game/") + directory));
1394 }
1395 
OnGameListDumpRomFS(QString game_path,u64 program_id)1396 void GMainWindow::OnGameListDumpRomFS(QString game_path, u64 program_id) {
1397     auto* dialog = new QProgressDialog(tr("Dumping..."), tr("Cancel"), 0, 0, this);
1398     dialog->setWindowModality(Qt::WindowModal);
1399     dialog->setWindowFlags(dialog->windowFlags() &
1400                            ~(Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint));
1401     dialog->setCancelButton(nullptr);
1402     dialog->setMinimumDuration(0);
1403     dialog->setValue(0);
1404 
1405     const auto base_path = fmt::format(
1406         "{}romfs/{:016X}", FileUtil::GetUserPath(FileUtil::UserPath::DumpDir), program_id);
1407     const auto update_path =
1408         fmt::format("{}romfs/{:016X}", FileUtil::GetUserPath(FileUtil::UserPath::DumpDir),
1409                     program_id | 0x0004000e00000000);
1410     using FutureWatcher = QFutureWatcher<std::pair<Loader::ResultStatus, Loader::ResultStatus>>;
1411     auto* future_watcher = new FutureWatcher(this);
1412     connect(future_watcher, &FutureWatcher::finished,
1413             [this, dialog, base_path, update_path, future_watcher] {
1414                 dialog->hide();
1415                 const auto& [base, update] = future_watcher->result();
1416                 if (base != Loader::ResultStatus::Success) {
1417                     QMessageBox::critical(
1418                         this, tr("Citra"),
1419                         tr("Could not dump base RomFS.\nRefer to the log for details."));
1420                     return;
1421                 }
1422                 QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(base_path)));
1423                 if (update == Loader::ResultStatus::Success) {
1424                     QDesktopServices::openUrl(
1425                         QUrl::fromLocalFile(QString::fromStdString(update_path)));
1426                 }
1427             });
1428 
1429     auto future = QtConcurrent::run([game_path, base_path, update_path] {
1430         std::unique_ptr<Loader::AppLoader> loader = Loader::GetLoader(game_path.toStdString());
1431         return std::make_pair(loader->DumpRomFS(base_path), loader->DumpUpdateRomFS(update_path));
1432     });
1433     future_watcher->setFuture(future);
1434 }
1435 
OnGameListOpenDirectory(const QString & directory)1436 void GMainWindow::OnGameListOpenDirectory(const QString& directory) {
1437     QString path;
1438     if (directory == QStringLiteral("INSTALLED")) {
1439         path = QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir) +
1440                                       "Nintendo "
1441                                       "3DS/00000000000000000000000000000000/"
1442                                       "00000000000000000000000000000000/title/00040000");
1443     } else if (directory == QStringLiteral("SYSTEM")) {
1444         path = QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
1445                                       "00000000000000000000000000000000/title/00040010");
1446     } else {
1447         path = directory;
1448     }
1449     if (!QFileInfo::exists(path)) {
1450         QMessageBox::critical(this, tr("Error Opening %1").arg(path), tr("Folder does not exist!"));
1451         return;
1452     }
1453     QDesktopServices::openUrl(QUrl::fromLocalFile(path));
1454 }
1455 
OnGameListAddDirectory()1456 void GMainWindow::OnGameListAddDirectory() {
1457     const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
1458     if (dir_path.isEmpty())
1459         return;
1460     UISettings::GameDir game_dir{dir_path, false, true};
1461     if (!UISettings::values.game_dirs.contains(game_dir)) {
1462         UISettings::values.game_dirs.append(game_dir);
1463         game_list->PopulateAsync(UISettings::values.game_dirs);
1464     } else {
1465         LOG_WARNING(Frontend, "Selected directory is already in the game list");
1466     }
1467 }
1468 
OnGameListShowList(bool show)1469 void GMainWindow::OnGameListShowList(bool show) {
1470     if (emulation_running && ui->action_Single_Window_Mode->isChecked())
1471         return;
1472     game_list->setVisible(show);
1473     game_list_placeholder->setVisible(!show);
1474 };
1475 
OnMenuLoadFile()1476 void GMainWindow::OnMenuLoadFile() {
1477     const QString extensions = QStringLiteral("*.").append(
1478         GameList::supported_file_extensions.join(QStringLiteral(" *.")));
1479     const QString file_filter = tr("3DS Executable (%1);;All Files (*.*)",
1480                                    "%1 is an identifier for the 3DS executable file extensions.")
1481                                     .arg(extensions);
1482     const QString filename = QFileDialog::getOpenFileName(
1483         this, tr("Load File"), UISettings::values.roms_path, file_filter);
1484 
1485     if (filename.isEmpty()) {
1486         return;
1487     }
1488 
1489     UISettings::values.roms_path = QFileInfo(filename).path();
1490     BootGame(filename);
1491 }
1492 
OnMenuInstallCIA()1493 void GMainWindow::OnMenuInstallCIA() {
1494     QStringList filepaths = QFileDialog::getOpenFileNames(
1495         this, tr("Load Files"), UISettings::values.roms_path,
1496         tr("3DS Installation File (*.CIA*)") + QStringLiteral(";;") + tr("All Files (*.*)"));
1497     if (filepaths.isEmpty())
1498         return;
1499 
1500     InstallCIA(filepaths);
1501 }
1502 
InstallCIA(QStringList filepaths)1503 void GMainWindow::InstallCIA(QStringList filepaths) {
1504     ui->action_Install_CIA->setEnabled(false);
1505     game_list->SetDirectoryWatcherEnabled(false);
1506     progress_bar->show();
1507     progress_bar->setMaximum(INT_MAX);
1508 
1509     QtConcurrent::run([&, filepaths] {
1510         Service::AM::InstallStatus status;
1511         const auto cia_progress = [&](std::size_t written, std::size_t total) {
1512             emit UpdateProgress(written, total);
1513         };
1514         for (const auto current_path : filepaths) {
1515             status = Service::AM::InstallCIA(current_path.toStdString(), cia_progress);
1516             emit CIAInstallReport(status, current_path);
1517         }
1518         emit CIAInstallFinished();
1519     });
1520 }
1521 
OnUpdateProgress(std::size_t written,std::size_t total)1522 void GMainWindow::OnUpdateProgress(std::size_t written, std::size_t total) {
1523     progress_bar->setValue(
1524         static_cast<int>(INT_MAX * (static_cast<double>(written) / static_cast<double>(total))));
1525 }
1526 
OnCIAInstallReport(Service::AM::InstallStatus status,QString filepath)1527 void GMainWindow::OnCIAInstallReport(Service::AM::InstallStatus status, QString filepath) {
1528     QString filename = QFileInfo(filepath).fileName();
1529     switch (status) {
1530     case Service::AM::InstallStatus::Success:
1531         this->statusBar()->showMessage(tr("%1 has been installed successfully.").arg(filename));
1532         break;
1533     case Service::AM::InstallStatus::ErrorFailedToOpenFile:
1534         QMessageBox::critical(this, tr("Unable to open File"),
1535                               tr("Could not open %1").arg(filename));
1536         break;
1537     case Service::AM::InstallStatus::ErrorAborted:
1538         QMessageBox::critical(
1539             this, tr("Installation aborted"),
1540             tr("The installation of %1 was aborted. Please see the log for more details")
1541                 .arg(filename));
1542         break;
1543     case Service::AM::InstallStatus::ErrorInvalid:
1544         QMessageBox::critical(this, tr("Invalid File"), tr("%1 is not a valid CIA").arg(filename));
1545         break;
1546     case Service::AM::InstallStatus::ErrorEncrypted:
1547         QMessageBox::critical(this, tr("Encrypted File"),
1548                               tr("%1 must be decrypted "
1549                                  "before being used with Citra. A real 3DS is required.")
1550                                   .arg(filename));
1551         break;
1552     }
1553 }
1554 
OnCIAInstallFinished()1555 void GMainWindow::OnCIAInstallFinished() {
1556     progress_bar->hide();
1557     progress_bar->setValue(0);
1558     game_list->SetDirectoryWatcherEnabled(true);
1559     ui->action_Install_CIA->setEnabled(true);
1560     game_list->PopulateAsync(UISettings::values.game_dirs);
1561 }
1562 
OnMenuRecentFile()1563 void GMainWindow::OnMenuRecentFile() {
1564     QAction* action = qobject_cast<QAction*>(sender());
1565     ASSERT(action);
1566 
1567     const QString filename = action->data().toString();
1568     if (QFileInfo::exists(filename)) {
1569         BootGame(filename);
1570     } else {
1571         // Display an error message and remove the file from the list.
1572         QMessageBox::information(this, tr("File not found"),
1573                                  tr("File \"%1\" not found").arg(filename));
1574 
1575         UISettings::values.recent_files.removeOne(filename);
1576         UpdateRecentFiles();
1577     }
1578 }
1579 
OnStartGame()1580 void GMainWindow::OnStartGame() {
1581     Camera::QtMultimediaCameraHandler::ResumeCameras();
1582 
1583     PreventOSSleep();
1584 
1585     emu_thread->SetRunning(true);
1586     qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
1587     qRegisterMetaType<std::string>("std::string");
1588     connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
1589 
1590     ui->action_Start->setEnabled(false);
1591     ui->action_Start->setText(tr("Continue"));
1592 
1593     ui->action_Pause->setEnabled(true);
1594     ui->action_Stop->setEnabled(true);
1595     ui->action_Restart->setEnabled(true);
1596     ui->action_Cheats->setEnabled(true);
1597     ui->action_Load_Amiibo->setEnabled(true);
1598     ui->action_Report_Compatibility->setEnabled(true);
1599     ui->action_Capture_Screenshot->setEnabled(true);
1600 
1601     discord_rpc->Update();
1602 
1603     UpdateSaveStates();
1604 }
1605 
OnPauseGame()1606 void GMainWindow::OnPauseGame() {
1607     emu_thread->SetRunning(false);
1608     Camera::QtMultimediaCameraHandler::StopCameras();
1609     ui->action_Start->setEnabled(true);
1610     ui->action_Pause->setEnabled(false);
1611     ui->action_Stop->setEnabled(true);
1612     ui->action_Capture_Screenshot->setEnabled(false);
1613 
1614     AllowOSSleep();
1615 }
1616 
OnStopGame()1617 void GMainWindow::OnStopGame() {
1618     ShutdownGame();
1619 }
1620 
OnLoadComplete()1621 void GMainWindow::OnLoadComplete() {
1622     loading_screen->OnLoadComplete();
1623 }
1624 
OnMenuReportCompatibility()1625 void GMainWindow::OnMenuReportCompatibility() {
1626     if (!Settings::values.citra_token.empty() && !Settings::values.citra_username.empty()) {
1627         CompatDB compatdb{this};
1628         compatdb.exec();
1629     } else {
1630         QMessageBox::critical(this, tr("Missing Citra Account"),
1631                               tr("You must link your Citra account to submit test cases."
1632                                  "<br/>Go to Emulation &gt; Configure... &gt; Web to do so."));
1633     }
1634 }
1635 
ToggleFullscreen()1636 void GMainWindow::ToggleFullscreen() {
1637     if (!emulation_running) {
1638         return;
1639     }
1640     if (ui->action_Fullscreen->isChecked()) {
1641         ShowFullscreen();
1642     } else {
1643         HideFullscreen();
1644     }
1645 }
1646 
ShowFullscreen()1647 void GMainWindow::ShowFullscreen() {
1648     if (ui->action_Single_Window_Mode->isChecked()) {
1649         UISettings::values.geometry = saveGeometry();
1650         ui->menubar->hide();
1651         statusBar()->hide();
1652         showFullScreen();
1653     } else {
1654         UISettings::values.renderwindow_geometry = render_window->saveGeometry();
1655         render_window->showFullScreen();
1656     }
1657 }
1658 
HideFullscreen()1659 void GMainWindow::HideFullscreen() {
1660     if (ui->action_Single_Window_Mode->isChecked()) {
1661         statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
1662         ui->menubar->show();
1663         showNormal();
1664         restoreGeometry(UISettings::values.geometry);
1665     } else {
1666         render_window->showNormal();
1667         render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
1668     }
1669 }
1670 
ToggleWindowMode()1671 void GMainWindow::ToggleWindowMode() {
1672     if (ui->action_Single_Window_Mode->isChecked()) {
1673         // Render in the main window...
1674         render_window->BackupGeometry();
1675         ui->horizontalLayout->addWidget(render_window);
1676         render_window->setFocusPolicy(Qt::StrongFocus);
1677         if (emulation_running) {
1678             render_window->setVisible(true);
1679             render_window->setFocus();
1680             game_list->hide();
1681         }
1682 
1683     } else {
1684         // Render in a separate window...
1685         ui->horizontalLayout->removeWidget(render_window);
1686         render_window->setParent(nullptr);
1687         render_window->setFocusPolicy(Qt::NoFocus);
1688         if (emulation_running) {
1689             render_window->setVisible(true);
1690             render_window->RestoreGeometry();
1691             game_list->show();
1692         }
1693     }
1694 }
1695 
ChangeScreenLayout()1696 void GMainWindow::ChangeScreenLayout() {
1697     Settings::LayoutOption new_layout = Settings::LayoutOption::Default;
1698 
1699     if (ui->action_Screen_Layout_Default->isChecked()) {
1700         new_layout = Settings::LayoutOption::Default;
1701     } else if (ui->action_Screen_Layout_Single_Screen->isChecked()) {
1702         new_layout = Settings::LayoutOption::SingleScreen;
1703     } else if (ui->action_Screen_Layout_Large_Screen->isChecked()) {
1704         new_layout = Settings::LayoutOption::LargeScreen;
1705     } else if (ui->action_Screen_Layout_Side_by_Side->isChecked()) {
1706         new_layout = Settings::LayoutOption::SideScreen;
1707     }
1708 
1709     Settings::values.layout_option = new_layout;
1710     Settings::Apply();
1711 }
1712 
ToggleScreenLayout()1713 void GMainWindow::ToggleScreenLayout() {
1714     Settings::LayoutOption new_layout = Settings::LayoutOption::Default;
1715 
1716     switch (Settings::values.layout_option) {
1717     case Settings::LayoutOption::Default:
1718         new_layout = Settings::LayoutOption::SingleScreen;
1719         break;
1720     case Settings::LayoutOption::SingleScreen:
1721         new_layout = Settings::LayoutOption::LargeScreen;
1722         break;
1723     case Settings::LayoutOption::LargeScreen:
1724         new_layout = Settings::LayoutOption::SideScreen;
1725         break;
1726     case Settings::LayoutOption::SideScreen:
1727         new_layout = Settings::LayoutOption::Default;
1728         break;
1729     }
1730 
1731     Settings::values.layout_option = new_layout;
1732     SyncMenuUISettings();
1733     Settings::Apply();
1734 }
1735 
OnSwapScreens()1736 void GMainWindow::OnSwapScreens() {
1737     Settings::values.swap_screen = ui->action_Screen_Layout_Swap_Screens->isChecked();
1738     Settings::Apply();
1739 }
1740 
OnRotateScreens()1741 void GMainWindow::OnRotateScreens() {
1742     Settings::values.upright_screen = ui->action_Screen_Layout_Upright_Screens->isChecked();
1743     Settings::Apply();
1744 }
1745 
OnCheats()1746 void GMainWindow::OnCheats() {
1747     CheatDialog cheat_dialog(this);
1748     cheat_dialog.exec();
1749 }
1750 
OnSaveState()1751 void GMainWindow::OnSaveState() {
1752     QAction* action = qobject_cast<QAction*>(sender());
1753     assert(action);
1754 
1755     Core::System::GetInstance().SendSignal(Core::System::Signal::Save, action->data().toUInt());
1756     Core::System::GetInstance().frame_limiter.AdvanceFrame();
1757     newest_slot = action->data().toUInt();
1758 }
1759 
OnLoadState()1760 void GMainWindow::OnLoadState() {
1761     QAction* action = qobject_cast<QAction*>(sender());
1762     assert(action);
1763 
1764     Core::System::GetInstance().SendSignal(Core::System::Signal::Load, action->data().toUInt());
1765     Core::System::GetInstance().frame_limiter.AdvanceFrame();
1766 }
1767 
OnConfigure()1768 void GMainWindow::OnConfigure() {
1769     ConfigureDialog configureDialog(this, hotkey_registry,
1770                                     !multiplayer_state->IsHostingPublicRoom());
1771     connect(&configureDialog, &ConfigureDialog::LanguageChanged, this,
1772             &GMainWindow::OnLanguageChanged);
1773     auto old_theme = UISettings::values.theme;
1774     const int old_input_profile_index = Settings::values.current_input_profile_index;
1775     const auto old_input_profiles = Settings::values.input_profiles;
1776     const auto old_touch_from_button_maps = Settings::values.touch_from_button_maps;
1777     const bool old_discord_presence = UISettings::values.enable_discord_presence;
1778     auto result = configureDialog.exec();
1779     if (result == QDialog::Accepted) {
1780         configureDialog.ApplyConfiguration();
1781         InitializeHotkeys();
1782         if (UISettings::values.theme != old_theme)
1783             UpdateUITheme();
1784         if (UISettings::values.enable_discord_presence != old_discord_presence)
1785             SetDiscordEnabled(UISettings::values.enable_discord_presence);
1786         if (!multiplayer_state->IsHostingPublicRoom())
1787             multiplayer_state->UpdateCredentials();
1788         emit UpdateThemedIcons();
1789         SyncMenuUISettings();
1790         game_list->RefreshGameDirectory();
1791         config->Save();
1792         if (UISettings::values.hide_mouse && emulation_running) {
1793             setMouseTracking(true);
1794             mouse_hide_timer.start();
1795         } else {
1796             setMouseTracking(false);
1797         }
1798     } else {
1799         Settings::values.input_profiles = old_input_profiles;
1800         Settings::values.touch_from_button_maps = old_touch_from_button_maps;
1801         Settings::LoadProfile(old_input_profile_index);
1802     }
1803 }
1804 
OnLoadAmiibo()1805 void GMainWindow::OnLoadAmiibo() {
1806     const QString extensions{QStringLiteral("*.bin")};
1807     const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
1808     const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter);
1809 
1810     if (filename.isEmpty()) {
1811         return;
1812     }
1813 
1814     LoadAmiibo(filename);
1815 }
1816 
LoadAmiibo(const QString & filename)1817 void GMainWindow::LoadAmiibo(const QString& filename) {
1818     Core::System& system{Core::System::GetInstance()};
1819     Service::SM::ServiceManager& sm = system.ServiceManager();
1820     auto nfc = sm.GetService<Service::NFC::Module::Interface>("nfc:u");
1821     if (nfc == nullptr) {
1822         return;
1823     }
1824 
1825     QFile nfc_file{filename};
1826     if (!nfc_file.open(QIODevice::ReadOnly)) {
1827         QMessageBox::warning(this, tr("Error opening Amiibo data file"),
1828                              tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
1829         return;
1830     }
1831 
1832     Service::NFC::AmiiboData amiibo_data{};
1833     const u64 read_size =
1834         nfc_file.read(reinterpret_cast<char*>(&amiibo_data), sizeof(Service::NFC::AmiiboData));
1835     if (read_size != sizeof(Service::NFC::AmiiboData)) {
1836         QMessageBox::warning(this, tr("Error reading Amiibo data file"),
1837                              tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
1838                                 "was only able to read %2 bytes.")
1839                                  .arg(sizeof(Service::NFC::AmiiboData))
1840                                  .arg(read_size));
1841         return;
1842     }
1843 
1844     nfc->LoadAmiibo(amiibo_data);
1845     ui->action_Remove_Amiibo->setEnabled(true);
1846 }
1847 
OnRemoveAmiibo()1848 void GMainWindow::OnRemoveAmiibo() {
1849     Core::System& system{Core::System::GetInstance()};
1850     Service::SM::ServiceManager& sm = system.ServiceManager();
1851     auto nfc = sm.GetService<Service::NFC::Module::Interface>("nfc:u");
1852     if (nfc == nullptr) {
1853         return;
1854     }
1855 
1856     nfc->RemoveAmiibo();
1857     ui->action_Remove_Amiibo->setEnabled(false);
1858 }
1859 
OnOpenCitraFolder()1860 void GMainWindow::OnOpenCitraFolder() {
1861     QDesktopServices::openUrl(QUrl::fromLocalFile(
1862         QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::UserDir))));
1863 }
1864 
OnToggleFilterBar()1865 void GMainWindow::OnToggleFilterBar() {
1866     game_list->SetFilterVisible(ui->action_Show_Filter_Bar->isChecked());
1867     if (ui->action_Show_Filter_Bar->isChecked()) {
1868         game_list->SetFilterFocus();
1869     } else {
1870         game_list->ClearFilter();
1871     }
1872 }
1873 
OnCreateGraphicsSurfaceViewer()1874 void GMainWindow::OnCreateGraphicsSurfaceViewer() {
1875     auto graphicsSurfaceViewerWidget = new GraphicsSurfaceWidget(Pica::g_debug_context, this);
1876     addDockWidget(Qt::RightDockWidgetArea, graphicsSurfaceViewerWidget);
1877     // TODO: Maybe graphicsSurfaceViewerWidget->setFloating(true);
1878     graphicsSurfaceViewerWidget->show();
1879 }
1880 
OnRecordMovie()1881 void GMainWindow::OnRecordMovie() {
1882     MovieRecordDialog dialog(this);
1883     if (dialog.exec() != QDialog::Accepted) {
1884         return;
1885     }
1886 
1887     movie_record_on_start = true;
1888     movie_record_path = dialog.GetPath();
1889     movie_record_author = dialog.GetAuthor();
1890 
1891     if (emulation_running) { // Restart game
1892         BootGame(QString(game_path));
1893     }
1894     ui->action_Close_Movie->setEnabled(true);
1895     ui->action_Save_Movie->setEnabled(true);
1896 }
1897 
OnPlayMovie()1898 void GMainWindow::OnPlayMovie() {
1899     MoviePlayDialog dialog(this, game_list);
1900     if (dialog.exec() != QDialog::Accepted) {
1901         return;
1902     }
1903 
1904     movie_playback_on_start = true;
1905     movie_playback_path = dialog.GetMoviePath();
1906     BootGame(dialog.GetGamePath());
1907 
1908     ui->action_Close_Movie->setEnabled(true);
1909     ui->action_Save_Movie->setEnabled(false);
1910 }
1911 
OnCloseMovie()1912 void GMainWindow::OnCloseMovie() {
1913     if (movie_record_on_start) {
1914         QMessageBox::information(this, tr("Record Movie"), tr("Movie recording cancelled."));
1915         movie_record_on_start = false;
1916         movie_record_path.clear();
1917         movie_record_author.clear();
1918     } else {
1919         const bool was_running = emu_thread && emu_thread->IsRunning();
1920         if (was_running) {
1921             OnPauseGame();
1922         }
1923 
1924         const bool was_recording =
1925             Core::Movie::GetInstance().GetPlayMode() == Core::Movie::PlayMode::Recording;
1926         Core::Movie::GetInstance().Shutdown();
1927         if (was_recording) {
1928             QMessageBox::information(this, tr("Movie Saved"),
1929                                      tr("The movie is successfully saved."));
1930         }
1931 
1932         if (was_running) {
1933             OnStartGame();
1934         }
1935     }
1936 
1937     ui->action_Close_Movie->setEnabled(false);
1938     ui->action_Save_Movie->setEnabled(false);
1939 }
1940 
OnSaveMovie()1941 void GMainWindow::OnSaveMovie() {
1942     const bool was_running = emu_thread && emu_thread->IsRunning();
1943     if (was_running) {
1944         OnPauseGame();
1945     }
1946 
1947     if (Core::Movie::GetInstance().GetPlayMode() == Core::Movie::PlayMode::Recording) {
1948         Core::Movie::GetInstance().SaveMovie();
1949         QMessageBox::information(this, tr("Movie Saved"), tr("The movie is successfully saved."));
1950     } else {
1951         LOG_ERROR(Frontend, "Tried to save movie while movie is not being recorded");
1952     }
1953 
1954     if (was_running) {
1955         OnStartGame();
1956     }
1957 }
1958 
OnCaptureScreenshot()1959 void GMainWindow::OnCaptureScreenshot() {
1960     OnPauseGame();
1961     QFileDialog png_dialog(this, tr("Capture Screenshot"), UISettings::values.screenshot_path,
1962                            tr("PNG Image (*.png)"));
1963     png_dialog.setAcceptMode(QFileDialog::AcceptSave);
1964     png_dialog.setDefaultSuffix(QStringLiteral("png"));
1965     if (png_dialog.exec()) {
1966         const QString path = png_dialog.selectedFiles().first();
1967         if (!path.isEmpty()) {
1968             UISettings::values.screenshot_path = QFileInfo(path).path();
1969             render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor, path);
1970         }
1971     }
1972     OnStartGame();
1973 }
1974 
1975 #ifdef ENABLE_FFMPEG_VIDEO_DUMPER
OnStartVideoDumping()1976 void GMainWindow::OnStartVideoDumping() {
1977     DumpingDialog dialog(this);
1978     if (dialog.exec() != QDialog::DialogCode::Accepted) {
1979         ui->action_Dump_Video->setChecked(false);
1980         return;
1981     }
1982     const auto path = dialog.GetFilePath();
1983     if (emulation_running) {
1984         Layout::FramebufferLayout layout{
1985             Layout::FrameLayoutFromResolutionScale(VideoCore::GetResolutionScaleFactor())};
1986         if (!Core::System::GetInstance().VideoDumper().StartDumping(path.toStdString(), layout)) {
1987             QMessageBox::critical(
1988                 this, tr("Citra"),
1989                 tr("Could not start video dumping.<br>Refer to the log for details."));
1990             ui->action_Dump_Video->setChecked(false);
1991         }
1992     } else {
1993         video_dumping_on_start = true;
1994         video_dumping_path = path;
1995     }
1996 }
1997 
OnStopVideoDumping()1998 void GMainWindow::OnStopVideoDumping() {
1999     ui->action_Dump_Video->setChecked(false);
2000 
2001     if (video_dumping_on_start) {
2002         video_dumping_on_start = false;
2003         video_dumping_path.clear();
2004     } else {
2005         const bool was_dumping = Core::System::GetInstance().VideoDumper().IsDumping();
2006         if (!was_dumping)
2007             return;
2008 
2009         game_paused_for_dumping = emu_thread->IsRunning();
2010         OnPauseGame();
2011 
2012         auto future =
2013             QtConcurrent::run([] { Core::System::GetInstance().VideoDumper().StopDumping(); });
2014         auto* future_watcher = new QFutureWatcher<void>(this);
2015         connect(future_watcher, &QFutureWatcher<void>::finished, this, [this] {
2016             if (game_shutdown_delayed) {
2017                 game_shutdown_delayed = false;
2018                 ShutdownGame();
2019             } else if (game_paused_for_dumping) {
2020                 game_paused_for_dumping = false;
2021                 OnStartGame();
2022             }
2023         });
2024         future_watcher->setFuture(future);
2025     }
2026 }
2027 #endif
2028 
UpdateStatusBar()2029 void GMainWindow::UpdateStatusBar() {
2030     if (emu_thread == nullptr) {
2031         status_bar_update_timer.stop();
2032         return;
2033     }
2034 
2035     // Update movie status
2036     const u64 current = Core::Movie::GetInstance().GetCurrentInputIndex();
2037     const u64 total = Core::Movie::GetInstance().GetTotalInputCount();
2038     const auto play_mode = Core::Movie::GetInstance().GetPlayMode();
2039     if (play_mode == Core::Movie::PlayMode::Recording) {
2040         message_label->setText(tr("Recording %1").arg(current));
2041         message_label->setVisible(true);
2042         message_label_used_for_movie = true;
2043         ui->action_Save_Movie->setEnabled(true);
2044     } else if (play_mode == Core::Movie::PlayMode::Playing) {
2045         message_label->setText(tr("Playing %1 / %2").arg(current).arg(total));
2046         message_label->setVisible(true);
2047         message_label_used_for_movie = true;
2048         ui->action_Save_Movie->setEnabled(false);
2049     } else if (play_mode == Core::Movie::PlayMode::MovieFinished) {
2050         message_label->setText(tr("Movie Finished"));
2051         message_label->setVisible(true);
2052         message_label_used_for_movie = true;
2053         ui->action_Save_Movie->setEnabled(false);
2054     } else if (message_label_used_for_movie) { // Clear the label if movie was just closed
2055         message_label->setText(QString{});
2056         message_label->setVisible(false);
2057         message_label_used_for_movie = false;
2058         ui->action_Save_Movie->setEnabled(false);
2059     }
2060 
2061     auto results = Core::System::GetInstance().GetAndResetPerfStats();
2062 
2063     if (Settings::values.use_frame_limit_alternate) {
2064         if (Settings::values.frame_limit_alternate == 0) {
2065             emu_speed_label->setText(
2066                 tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
2067 
2068         } else {
2069             emu_speed_label->setText(tr("Speed: %1% / %2%")
2070                                          .arg(results.emulation_speed * 100.0, 0, 'f', 0)
2071                                          .arg(Settings::values.frame_limit_alternate));
2072         }
2073     } else if (Settings::values.frame_limit == 0) {
2074         emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
2075     } else {
2076         emu_speed_label->setText(tr("Speed: %1% / %2%")
2077                                      .arg(results.emulation_speed * 100.0, 0, 'f', 0)
2078                                      .arg(Settings::values.frame_limit));
2079     }
2080     game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
2081     emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
2082 
2083     emu_speed_label->setVisible(true);
2084     game_fps_label->setVisible(true);
2085     emu_frametime_label->setVisible(true);
2086 }
2087 
HideMouseCursor()2088 void GMainWindow::HideMouseCursor() {
2089     if (emu_thread == nullptr || UISettings::values.hide_mouse == false) {
2090         mouse_hide_timer.stop();
2091         ShowMouseCursor();
2092         return;
2093     }
2094     render_window->setCursor(QCursor(Qt::BlankCursor));
2095 }
2096 
ShowMouseCursor()2097 void GMainWindow::ShowMouseCursor() {
2098     render_window->unsetCursor();
2099     if (emu_thread != nullptr && UISettings::values.hide_mouse) {
2100         mouse_hide_timer.start();
2101     }
2102 }
2103 
OnMouseActivity()2104 void GMainWindow::OnMouseActivity() {
2105     ShowMouseCursor();
2106 }
2107 
mouseMoveEvent(QMouseEvent * event)2108 void GMainWindow::mouseMoveEvent([[maybe_unused]] QMouseEvent* event) {
2109     OnMouseActivity();
2110 }
2111 
mousePressEvent(QMouseEvent * event)2112 void GMainWindow::mousePressEvent([[maybe_unused]] QMouseEvent* event) {
2113     OnMouseActivity();
2114 }
2115 
mouseReleaseEvent(QMouseEvent * event)2116 void GMainWindow::mouseReleaseEvent([[maybe_unused]] QMouseEvent* event) {
2117     OnMouseActivity();
2118 }
2119 
OnCoreError(Core::System::ResultStatus result,std::string details)2120 void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
2121     QString status_message;
2122 
2123     QString title, message;
2124     if (result == Core::System::ResultStatus::ErrorSystemFiles) {
2125         const QString common_message =
2126             tr("%1 is missing. Please <a "
2127                "href='https://citra-emu.org/wiki/"
2128                "dumping-system-archives-and-the-shared-fonts-from-a-3ds-console/'>dump your "
2129                "system archives</a>.<br/>Continuing emulation may result in crashes and bugs.");
2130 
2131         if (!details.empty()) {
2132             message = common_message.arg(QString::fromStdString(details));
2133         } else {
2134             message = common_message.arg(tr("A system archive"));
2135         }
2136 
2137         title = tr("System Archive Not Found");
2138         status_message = tr("System Archive Missing");
2139     } else if (result == Core::System::ResultStatus::ErrorSavestate) {
2140         title = tr("Save/load Error");
2141         message = QString::fromStdString(details);
2142     } else {
2143         title = tr("Fatal Error");
2144         message =
2145             tr("A fatal error occurred. "
2146                "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>Check "
2147                "the log</a> for details."
2148                "<br/>Continuing emulation may result in crashes and bugs.");
2149         status_message = tr("Fatal Error encountered");
2150     }
2151 
2152     QMessageBox message_box;
2153     message_box.setWindowTitle(title);
2154     message_box.setText(message);
2155     message_box.setIcon(QMessageBox::Icon::Critical);
2156     message_box.addButton(tr("Continue"), QMessageBox::RejectRole);
2157     QPushButton* abort_button = message_box.addButton(tr("Abort"), QMessageBox::AcceptRole);
2158     if (result != Core::System::ResultStatus::ShutdownRequested)
2159         message_box.exec();
2160 
2161     if (result == Core::System::ResultStatus::ShutdownRequested ||
2162         message_box.clickedButton() == abort_button) {
2163         if (emu_thread) {
2164             ShutdownGame();
2165         }
2166     } else {
2167         // Only show the message if the game is still running.
2168         if (emu_thread) {
2169             emu_thread->SetRunning(true);
2170             message_label->setText(status_message);
2171             message_label->setVisible(true);
2172             message_label_used_for_movie = false;
2173         }
2174     }
2175 }
2176 
OnMenuAboutCitra()2177 void GMainWindow::OnMenuAboutCitra() {
2178     AboutDialog about{this};
2179     about.exec();
2180 }
2181 
ConfirmClose()2182 bool GMainWindow::ConfirmClose() {
2183     if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
2184         return true;
2185 
2186     QMessageBox::StandardButton answer =
2187         QMessageBox::question(this, tr("Citra"), tr("Would you like to exit now?"),
2188                               QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
2189     return answer != QMessageBox::No;
2190 }
2191 
closeEvent(QCloseEvent * event)2192 void GMainWindow::closeEvent(QCloseEvent* event) {
2193     if (!ConfirmClose()) {
2194         event->ignore();
2195         return;
2196     }
2197 
2198     UpdateUISettings();
2199     game_list->SaveInterfaceLayout();
2200     hotkey_registry.SaveHotkeys();
2201 
2202     // Shutdown session if the emu thread is active...
2203     if (emu_thread != nullptr)
2204         ShutdownGame();
2205 
2206     render_window->close();
2207     multiplayer_state->Close();
2208     QWidget::closeEvent(event);
2209 }
2210 
IsSingleFileDropEvent(const QMimeData * mime)2211 static bool IsSingleFileDropEvent(const QMimeData* mime) {
2212     return mime->hasUrls() && mime->urls().length() == 1;
2213 }
2214 
2215 static const std::array<std::string, 8> AcceptedExtensions = {"cci",  "3ds", "cxi", "bin",
2216                                                               "3dsx", "app", "elf", "axf"};
2217 
IsCorrectFileExtension(const QMimeData * mime)2218 static bool IsCorrectFileExtension(const QMimeData* mime) {
2219     const QString& filename = mime->urls().at(0).toLocalFile();
2220     return std::find(AcceptedExtensions.begin(), AcceptedExtensions.end(),
2221                      QFileInfo(filename).suffix().toStdString()) != AcceptedExtensions.end();
2222 }
2223 
IsAcceptableDropEvent(QDropEvent * event)2224 static bool IsAcceptableDropEvent(QDropEvent* event) {
2225     return IsSingleFileDropEvent(event->mimeData()) && IsCorrectFileExtension(event->mimeData());
2226 }
2227 
AcceptDropEvent(QDropEvent * event)2228 void GMainWindow::AcceptDropEvent(QDropEvent* event) {
2229     if (IsAcceptableDropEvent(event)) {
2230         event->setDropAction(Qt::DropAction::LinkAction);
2231         event->accept();
2232     }
2233 }
2234 
DropAction(QDropEvent * event)2235 bool GMainWindow::DropAction(QDropEvent* event) {
2236     if (!IsAcceptableDropEvent(event)) {
2237         return false;
2238     }
2239 
2240     const QMimeData* mime_data = event->mimeData();
2241     const QString& filename = mime_data->urls().at(0).toLocalFile();
2242 
2243     if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
2244         // Amiibo
2245         LoadAmiibo(filename);
2246     } else {
2247         // Game
2248         if (ConfirmChangeGame()) {
2249             BootGame(filename);
2250         }
2251     }
2252     return true;
2253 }
2254 
dropEvent(QDropEvent * event)2255 void GMainWindow::dropEvent(QDropEvent* event) {
2256     DropAction(event);
2257 }
2258 
dragEnterEvent(QDragEnterEvent * event)2259 void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
2260     AcceptDropEvent(event);
2261 }
2262 
dragMoveEvent(QDragMoveEvent * event)2263 void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
2264     AcceptDropEvent(event);
2265 }
2266 
ConfirmChangeGame()2267 bool GMainWindow::ConfirmChangeGame() {
2268     if (emu_thread == nullptr)
2269         return true;
2270 
2271     auto answer = QMessageBox::question(
2272         this, tr("Citra"), tr("The game is still running. Would you like to stop emulation?"),
2273         QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
2274     return answer != QMessageBox::No;
2275 }
2276 
filterBarSetChecked(bool state)2277 void GMainWindow::filterBarSetChecked(bool state) {
2278     ui->action_Show_Filter_Bar->setChecked(state);
2279     emit(OnToggleFilterBar());
2280 }
2281 
UpdateUITheme()2282 void GMainWindow::UpdateUITheme() {
2283     const QString default_icons = QStringLiteral(":/icons/default");
2284     const QString& current_theme = UISettings::values.theme;
2285     const bool is_default_theme = current_theme == QString::fromUtf8(UISettings::themes[0].second);
2286     QStringList theme_paths(default_theme_paths);
2287 
2288     if (is_default_theme || current_theme.isEmpty()) {
2289         qApp->setStyleSheet({});
2290         setStyleSheet({});
2291         theme_paths.append(default_icons);
2292         QIcon::setThemeName(default_icons);
2293     } else {
2294         const QString theme_uri(QLatin1Char{':'} + current_theme + QStringLiteral("/style.qss"));
2295         QFile f(theme_uri);
2296         if (f.open(QFile::ReadOnly | QFile::Text)) {
2297             QTextStream ts(&f);
2298             qApp->setStyleSheet(ts.readAll());
2299             setStyleSheet(ts.readAll());
2300         } else {
2301             LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
2302         }
2303 
2304         const QString theme_name = QStringLiteral(":/icons/") + current_theme;
2305         theme_paths.append({default_icons, theme_name});
2306         QIcon::setThemeName(theme_name);
2307     }
2308 
2309     QIcon::setThemeSearchPaths(theme_paths);
2310 }
2311 
LoadTranslation()2312 void GMainWindow::LoadTranslation() {
2313     // If the selected language is English, no need to install any translation
2314     if (UISettings::values.language == QStringLiteral("en")) {
2315         return;
2316     }
2317 
2318     bool loaded;
2319 
2320     if (UISettings::values.language.isEmpty()) {
2321         // If the selected language is empty, use system locale
2322         loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/"));
2323     } else {
2324         // Otherwise load from the specified file
2325         loaded = translator.load(UISettings::values.language, QStringLiteral(":/languages/"));
2326     }
2327 
2328     if (loaded) {
2329         qApp->installTranslator(&translator);
2330     } else {
2331         UISettings::values.language = QStringLiteral("en");
2332     }
2333 }
2334 
OnLanguageChanged(const QString & locale)2335 void GMainWindow::OnLanguageChanged(const QString& locale) {
2336     if (UISettings::values.language != QStringLiteral("en")) {
2337         qApp->removeTranslator(&translator);
2338     }
2339 
2340     UISettings::values.language = locale;
2341     LoadTranslation();
2342     ui->retranslateUi(this);
2343     RetranslateStatusBar();
2344     UpdateWindowTitle();
2345 
2346     if (emulation_running)
2347         ui->action_Start->setText(tr("Continue"));
2348 }
2349 
OnMoviePlaybackCompleted()2350 void GMainWindow::OnMoviePlaybackCompleted() {
2351     OnPauseGame();
2352     QMessageBox::information(this, tr("Playback Completed"), tr("Movie playback completed."));
2353 }
2354 
UpdateWindowTitle()2355 void GMainWindow::UpdateWindowTitle() {
2356     const QString full_name = QString::fromUtf8(Common::g_build_fullname);
2357 
2358     if (game_title.isEmpty()) {
2359         setWindowTitle(tr("Citra %1").arg(full_name));
2360     } else {
2361         setWindowTitle(tr("Citra %1| %2").arg(full_name, game_title));
2362     }
2363 }
2364 
UpdateUISettings()2365 void GMainWindow::UpdateUISettings() {
2366     if (!ui->action_Fullscreen->isChecked()) {
2367         UISettings::values.geometry = saveGeometry();
2368         UISettings::values.renderwindow_geometry = render_window->saveGeometry();
2369     }
2370     UISettings::values.state = saveState();
2371 #if MICROPROFILE_ENABLED
2372     UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
2373     UISettings::values.microprofile_visible = microProfileDialog->isVisible();
2374 #endif
2375     UISettings::values.single_window_mode = ui->action_Single_Window_Mode->isChecked();
2376     UISettings::values.fullscreen = ui->action_Fullscreen->isChecked();
2377     UISettings::values.display_titlebar = ui->action_Display_Dock_Widget_Headers->isChecked();
2378     UISettings::values.show_filter_bar = ui->action_Show_Filter_Bar->isChecked();
2379     UISettings::values.show_status_bar = ui->action_Show_Status_Bar->isChecked();
2380     UISettings::values.first_start = false;
2381 }
2382 
SyncMenuUISettings()2383 void GMainWindow::SyncMenuUISettings() {
2384     ui->action_Screen_Layout_Default->setChecked(Settings::values.layout_option ==
2385                                                  Settings::LayoutOption::Default);
2386     ui->action_Screen_Layout_Single_Screen->setChecked(Settings::values.layout_option ==
2387                                                        Settings::LayoutOption::SingleScreen);
2388     ui->action_Screen_Layout_Large_Screen->setChecked(Settings::values.layout_option ==
2389                                                       Settings::LayoutOption::LargeScreen);
2390     ui->action_Screen_Layout_Side_by_Side->setChecked(Settings::values.layout_option ==
2391                                                       Settings::LayoutOption::SideScreen);
2392     ui->action_Screen_Layout_Swap_Screens->setChecked(Settings::values.swap_screen);
2393     ui->action_Screen_Layout_Upright_Screens->setChecked(Settings::values.upright_screen);
2394 }
2395 
RetranslateStatusBar()2396 void GMainWindow::RetranslateStatusBar() {
2397     if (emu_thread)
2398         UpdateStatusBar();
2399 
2400     emu_speed_label->setToolTip(tr("Current emulation speed. Values higher or lower than 100% "
2401                                    "indicate emulation is running faster or slower than a 3DS."));
2402     game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
2403                                   "This will vary from game to game and scene to scene."));
2404     emu_frametime_label->setToolTip(
2405         tr("Time taken to emulate a 3DS frame, not counting framelimiting or v-sync. For "
2406            "full-speed emulation this should be at most 16.67 ms."));
2407 
2408     multiplayer_state->retranslateUi();
2409 }
2410 
SetDiscordEnabled(bool state)2411 void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
2412 #ifdef USE_DISCORD_PRESENCE
2413     if (state) {
2414         discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
2415     } else {
2416         discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
2417     }
2418 #else
2419     discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
2420 #endif
2421     discord_rpc->Update();
2422 }
2423 
2424 #ifdef main
2425 #undef main
2426 #endif
2427 
main(int argc,char * argv[])2428 int main(int argc, char* argv[]) {
2429     Common::DetachedTasks detached_tasks;
2430     MicroProfileOnThreadCreate("Frontend");
2431     SCOPE_EXIT({ MicroProfileShutdown(); });
2432 
2433     // Init settings params
2434     QCoreApplication::setOrganizationName(QStringLiteral("Citra team"));
2435     QCoreApplication::setApplicationName(QStringLiteral("Citra"));
2436 
2437     QSurfaceFormat format;
2438     format.setVersion(3, 3);
2439     format.setProfile(QSurfaceFormat::CoreProfile);
2440     format.setSwapInterval(0);
2441     // TODO: expose a setting for buffer value (ie default/single/double/triple)
2442     format.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior);
2443     QSurfaceFormat::setDefaultFormat(format);
2444 
2445 #ifdef __APPLE__
2446     std::string bin_path = FileUtil::GetBundleDirectory() + DIR_SEP + "..";
2447     chdir(bin_path.c_str());
2448 #endif
2449     QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
2450     QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
2451     QApplication app(argc, argv);
2452 
2453     // Qt changes the locale and causes issues in float conversion using std::to_string() when
2454     // generating shaders
2455     setlocale(LC_ALL, "C");
2456 
2457     GMainWindow main_window;
2458 
2459     // Register CameraFactory
2460     Camera::RegisterFactory("image", std::make_unique<Camera::StillImageCameraFactory>());
2461     Camera::RegisterFactory("qt", std::make_unique<Camera::QtMultimediaCameraFactory>());
2462     Camera::QtMultimediaCameraHandler::Init();
2463 
2464     // Register frontend applets
2465     Frontend::RegisterDefaultApplets();
2466     Core::System::GetInstance().RegisterMiiSelector(std::make_shared<QtMiiSelector>(main_window));
2467     Core::System::GetInstance().RegisterSoftwareKeyboard(std::make_shared<QtKeyboard>(main_window));
2468 
2469     // Register Qt image interface
2470     Core::System::GetInstance().RegisterImageInterface(std::make_shared<QtImageInterface>());
2471 
2472     main_window.show();
2473 
2474     QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
2475                      &GMainWindow::OnAppFocusStateChanged);
2476 
2477     int result = app.exec();
2478     detached_tasks.WaitForAllTasks();
2479     return result;
2480 }
2481