main.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cinttypes>
  5. #include <clocale>
  6. #include <memory>
  7. #include <thread>
  8. // VFS includes must be before glad as they will conflict with Windows file api, which uses defines.
  9. #include "core/file_sys/vfs.h"
  10. #include "core/file_sys/vfs_real.h"
  11. // These are wrappers to avoid the calls to CreateDirectory and CreateFile becuase of the Windows
  12. // defines.
  13. static FileSys::VirtualDir VfsFilesystemCreateDirectoryWrapper(
  14. const FileSys::VirtualFilesystem& vfs, const std::string& path, FileSys::Mode mode) {
  15. return vfs->CreateDirectory(path, mode);
  16. }
  17. static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::VirtualDir& dir,
  18. const std::string& path) {
  19. return dir->CreateFile(path);
  20. }
  21. #include <fmt/ostream.h>
  22. #include <glad/glad.h>
  23. #define QT_NO_OPENGL
  24. #include <QDesktopWidget>
  25. #include <QDialogButtonBox>
  26. #include <QFileDialog>
  27. #include <QMessageBox>
  28. #include <QtConcurrent/QtConcurrent>
  29. #include <QtGui>
  30. #include <QtWidgets>
  31. #include <fmt/format.h>
  32. #include "common/common_paths.h"
  33. #include "common/detached_tasks.h"
  34. #include "common/file_util.h"
  35. #include "common/logging/backend.h"
  36. #include "common/logging/filter.h"
  37. #include "common/logging/log.h"
  38. #include "common/microprofile.h"
  39. #include "common/scm_rev.h"
  40. #include "common/scope_exit.h"
  41. #include "common/string_util.h"
  42. #include "common/telemetry.h"
  43. #include "core/core.h"
  44. #include "core/crypto/key_manager.h"
  45. #include "core/file_sys/bis_factory.h"
  46. #include "core/file_sys/card_image.h"
  47. #include "core/file_sys/content_archive.h"
  48. #include "core/file_sys/control_metadata.h"
  49. #include "core/file_sys/patch_manager.h"
  50. #include "core/file_sys/registered_cache.h"
  51. #include "core/file_sys/romfs.h"
  52. #include "core/file_sys/savedata_factory.h"
  53. #include "core/file_sys/submission_package.h"
  54. #include "core/hle/kernel/process.h"
  55. #include "core/hle/service/filesystem/filesystem.h"
  56. #include "core/hle/service/filesystem/fsp_ldr.h"
  57. #include "core/hle/service/nfp/nfp.h"
  58. #include "core/hle/service/sm/sm.h"
  59. #include "core/loader/loader.h"
  60. #include "core/perf_stats.h"
  61. #include "core/settings.h"
  62. #include "core/telemetry_session.h"
  63. #include "video_core/debug_utils/debug_utils.h"
  64. #include "yuzu/about_dialog.h"
  65. #include "yuzu/bootmanager.h"
  66. #include "yuzu/compatdb.h"
  67. #include "yuzu/compatibility_list.h"
  68. #include "yuzu/configuration/config.h"
  69. #include "yuzu/configuration/configure_dialog.h"
  70. #include "yuzu/debugger/console.h"
  71. #include "yuzu/debugger/graphics/graphics_breakpoints.h"
  72. #include "yuzu/debugger/graphics/graphics_surface.h"
  73. #include "yuzu/debugger/profiler.h"
  74. #include "yuzu/debugger/wait_tree.h"
  75. #include "yuzu/discord.h"
  76. #include "yuzu/game_list.h"
  77. #include "yuzu/game_list_p.h"
  78. #include "yuzu/hotkeys.h"
  79. #include "yuzu/main.h"
  80. #include "yuzu/ui_settings.h"
  81. #ifdef USE_DISCORD_PRESENCE
  82. #include "yuzu/discord_impl.h"
  83. #endif
  84. #ifdef QT_STATICPLUGIN
  85. Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
  86. #endif
  87. #ifdef _WIN32
  88. extern "C" {
  89. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  90. // graphics
  91. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  92. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  93. }
  94. #endif
  95. constexpr u64 DLC_BASE_TITLE_ID_MASK = 0xFFFFFFFFFFFFE000;
  96. /**
  97. * "Callouts" are one-time instructional messages shown to the user. In the config settings, there
  98. * is a bitfield "callout_flags" options, used to track if a message has already been shown to the
  99. * user. This is 32-bits - if we have more than 32 callouts, we should retire and recyle old ones.
  100. */
  101. enum class CalloutFlag : uint32_t {
  102. Telemetry = 0x1,
  103. DRDDeprecation = 0x2,
  104. };
  105. void GMainWindow::ShowTelemetryCallout() {
  106. if (UISettings::values.callout_flags & static_cast<uint32_t>(CalloutFlag::Telemetry)) {
  107. return;
  108. }
  109. UISettings::values.callout_flags |= static_cast<uint32_t>(CalloutFlag::Telemetry);
  110. const QString telemetry_message =
  111. tr("<a href='https://yuzu-emu.org/help/feature/telemetry/'>Anonymous "
  112. "data is collected</a> to help improve yuzu. "
  113. "<br/><br/>Would you like to share your usage data with us?");
  114. if (QMessageBox::question(this, tr("Telemetry"), telemetry_message) != QMessageBox::Yes) {
  115. Settings::values.enable_telemetry = false;
  116. Settings::Apply();
  117. }
  118. }
  119. const int GMainWindow::max_recent_files_item;
  120. static void InitializeLogging() {
  121. Log::Filter log_filter;
  122. log_filter.ParseFilterString(Settings::values.log_filter);
  123. Log::SetGlobalFilter(log_filter);
  124. const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
  125. FileUtil::CreateFullPath(log_dir);
  126. Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
  127. }
  128. GMainWindow::GMainWindow()
  129. : config(new Config()), emu_thread(nullptr),
  130. vfs(std::make_shared<FileSys::RealVfsFilesystem>()) {
  131. InitializeLogging();
  132. debug_context = Tegra::DebugContext::Construct();
  133. setAcceptDrops(true);
  134. ui.setupUi(this);
  135. statusBar()->hide();
  136. default_theme_paths = QIcon::themeSearchPaths();
  137. UpdateUITheme();
  138. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  139. discord_rpc->Update();
  140. InitializeWidgets();
  141. InitializeDebugWidgets();
  142. InitializeRecentFileMenuActions();
  143. InitializeHotkeys();
  144. SetDefaultUIGeometry();
  145. RestoreUIState();
  146. ConnectMenuEvents();
  147. ConnectWidgetEvents();
  148. LOG_INFO(Frontend, "yuzu Version: {} | {}-{}", Common::g_build_fullname, Common::g_scm_branch,
  149. Common::g_scm_desc);
  150. setWindowTitle(QString("yuzu %1| %2-%3")
  151. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc));
  152. show();
  153. // Gen keys if necessary
  154. OnReinitializeKeys(ReinitializeKeyBehavior::NoWarning);
  155. // Necessary to load titles from nand in gamelist.
  156. Service::FileSystem::CreateFactories(*vfs);
  157. game_list->LoadCompatibilityList();
  158. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  159. // Show one-time "callout" messages to the user
  160. ShowTelemetryCallout();
  161. QStringList args = QApplication::arguments();
  162. if (args.length() >= 2) {
  163. BootGame(args[1]);
  164. }
  165. }
  166. GMainWindow::~GMainWindow() {
  167. // will get automatically deleted otherwise
  168. if (render_window->parent() == nullptr)
  169. delete render_window;
  170. }
  171. void GMainWindow::InitializeWidgets() {
  172. #ifdef YUZU_ENABLE_COMPATIBILITY_REPORTING
  173. ui.action_Report_Compatibility->setVisible(true);
  174. #endif
  175. render_window = new GRenderWindow(this, emu_thread.get());
  176. render_window->hide();
  177. game_list = new GameList(vfs, this);
  178. ui.horizontalLayout->addWidget(game_list);
  179. // Create status bar
  180. message_label = new QLabel();
  181. // Configured separately for left alignment
  182. message_label->setVisible(false);
  183. message_label->setFrameStyle(QFrame::NoFrame);
  184. message_label->setContentsMargins(4, 0, 4, 0);
  185. message_label->setAlignment(Qt::AlignLeft);
  186. statusBar()->addPermanentWidget(message_label, 1);
  187. emu_speed_label = new QLabel();
  188. emu_speed_label->setToolTip(
  189. tr("Current emulation speed. Values higher or lower than 100% "
  190. "indicate emulation is running faster or slower than a Switch."));
  191. game_fps_label = new QLabel();
  192. game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
  193. "This will vary from game to game and scene to scene."));
  194. emu_frametime_label = new QLabel();
  195. emu_frametime_label->setToolTip(
  196. tr("Time taken to emulate a Switch frame, not counting framelimiting or v-sync. For "
  197. "full-speed emulation this should be at most 16.67 ms."));
  198. for (auto& label : {emu_speed_label, game_fps_label, emu_frametime_label}) {
  199. label->setVisible(false);
  200. label->setFrameStyle(QFrame::NoFrame);
  201. label->setContentsMargins(4, 0, 4, 0);
  202. statusBar()->addPermanentWidget(label, 0);
  203. }
  204. statusBar()->setVisible(true);
  205. setStyleSheet("QStatusBar::item{border: none;}");
  206. }
  207. void GMainWindow::InitializeDebugWidgets() {
  208. QMenu* debug_menu = ui.menu_View_Debugging;
  209. #if MICROPROFILE_ENABLED
  210. microProfileDialog = new MicroProfileDialog(this);
  211. microProfileDialog->hide();
  212. debug_menu->addAction(microProfileDialog->toggleViewAction());
  213. #endif
  214. graphicsBreakpointsWidget = new GraphicsBreakPointsWidget(debug_context, this);
  215. addDockWidget(Qt::RightDockWidgetArea, graphicsBreakpointsWidget);
  216. graphicsBreakpointsWidget->hide();
  217. debug_menu->addAction(graphicsBreakpointsWidget->toggleViewAction());
  218. graphicsSurfaceWidget = new GraphicsSurfaceWidget(debug_context, this);
  219. addDockWidget(Qt::RightDockWidgetArea, graphicsSurfaceWidget);
  220. graphicsSurfaceWidget->hide();
  221. debug_menu->addAction(graphicsSurfaceWidget->toggleViewAction());
  222. waitTreeWidget = new WaitTreeWidget(this);
  223. addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
  224. waitTreeWidget->hide();
  225. debug_menu->addAction(waitTreeWidget->toggleViewAction());
  226. connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
  227. &WaitTreeWidget::OnEmulationStarting);
  228. connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
  229. &WaitTreeWidget::OnEmulationStopping);
  230. }
  231. void GMainWindow::InitializeRecentFileMenuActions() {
  232. for (int i = 0; i < max_recent_files_item; ++i) {
  233. actions_recent_files[i] = new QAction(this);
  234. actions_recent_files[i]->setVisible(false);
  235. connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile);
  236. ui.menu_recent_files->addAction(actions_recent_files[i]);
  237. }
  238. ui.menu_recent_files->addSeparator();
  239. QAction* action_clear_recent_files = new QAction(this);
  240. action_clear_recent_files->setText(tr("Clear Recent Files"));
  241. connect(action_clear_recent_files, &QAction::triggered, this, [this] {
  242. UISettings::values.recent_files.clear();
  243. UpdateRecentFiles();
  244. });
  245. ui.menu_recent_files->addAction(action_clear_recent_files);
  246. UpdateRecentFiles();
  247. }
  248. void GMainWindow::InitializeHotkeys() {
  249. hotkey_registry.RegisterHotkey("Main Window", "Load File", QKeySequence::Open);
  250. hotkey_registry.RegisterHotkey("Main Window", "Start Emulation");
  251. hotkey_registry.RegisterHotkey("Main Window", "Continue/Pause", QKeySequence(Qt::Key_F4));
  252. hotkey_registry.RegisterHotkey("Main Window", "Restart", QKeySequence(Qt::Key_F5));
  253. hotkey_registry.RegisterHotkey("Main Window", "Fullscreen", QKeySequence::FullScreen);
  254. hotkey_registry.RegisterHotkey("Main Window", "Exit Fullscreen", QKeySequence(Qt::Key_Escape),
  255. Qt::ApplicationShortcut);
  256. hotkey_registry.RegisterHotkey("Main Window", "Toggle Speed Limit", QKeySequence("CTRL+Z"),
  257. Qt::ApplicationShortcut);
  258. hotkey_registry.RegisterHotkey("Main Window", "Increase Speed Limit", QKeySequence("+"),
  259. Qt::ApplicationShortcut);
  260. hotkey_registry.RegisterHotkey("Main Window", "Decrease Speed Limit", QKeySequence("-"),
  261. Qt::ApplicationShortcut);
  262. hotkey_registry.LoadHotkeys();
  263. connect(hotkey_registry.GetHotkey("Main Window", "Load File", this), &QShortcut::activated,
  264. this, &GMainWindow::OnMenuLoadFile);
  265. connect(hotkey_registry.GetHotkey("Main Window", "Start Emulation", this),
  266. &QShortcut::activated, this, &GMainWindow::OnStartGame);
  267. connect(hotkey_registry.GetHotkey("Main Window", "Continue/Pause", this), &QShortcut::activated,
  268. this, [&] {
  269. if (emulation_running) {
  270. if (emu_thread->IsRunning()) {
  271. OnPauseGame();
  272. } else {
  273. OnStartGame();
  274. }
  275. }
  276. });
  277. connect(hotkey_registry.GetHotkey("Main Window", "Restart", this), &QShortcut::activated, this,
  278. [this] {
  279. if (!Core::System::GetInstance().IsPoweredOn())
  280. return;
  281. BootGame(QString(game_path));
  282. });
  283. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  284. &QShortcut::activated, ui.action_Fullscreen, &QAction::trigger);
  285. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  286. &QShortcut::activatedAmbiguously, ui.action_Fullscreen, &QAction::trigger);
  287. connect(hotkey_registry.GetHotkey("Main Window", "Exit Fullscreen", this),
  288. &QShortcut::activated, this, [&] {
  289. if (emulation_running) {
  290. ui.action_Fullscreen->setChecked(false);
  291. ToggleFullscreen();
  292. }
  293. });
  294. connect(hotkey_registry.GetHotkey("Main Window", "Toggle Speed Limit", this),
  295. &QShortcut::activated, this, [&] {
  296. Settings::values.use_frame_limit = !Settings::values.use_frame_limit;
  297. UpdateStatusBar();
  298. });
  299. constexpr u16 SPEED_LIMIT_STEP = 5;
  300. connect(hotkey_registry.GetHotkey("Main Window", "Increase Speed Limit", this),
  301. &QShortcut::activated, this, [&] {
  302. if (Settings::values.frame_limit < 9999 - SPEED_LIMIT_STEP) {
  303. Settings::values.frame_limit += SPEED_LIMIT_STEP;
  304. UpdateStatusBar();
  305. }
  306. });
  307. connect(hotkey_registry.GetHotkey("Main Window", "Decrease Speed Limit", this),
  308. &QShortcut::activated, this, [&] {
  309. if (Settings::values.frame_limit > SPEED_LIMIT_STEP) {
  310. Settings::values.frame_limit -= SPEED_LIMIT_STEP;
  311. UpdateStatusBar();
  312. }
  313. });
  314. }
  315. void GMainWindow::SetDefaultUIGeometry() {
  316. // geometry: 55% of the window contents are in the upper screen half, 45% in the lower half
  317. const QRect screenRect = QApplication::desktop()->screenGeometry(this);
  318. const int w = screenRect.width() * 2 / 3;
  319. const int h = screenRect.height() / 2;
  320. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  321. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 55 / 100;
  322. setGeometry(x, y, w, h);
  323. }
  324. void GMainWindow::RestoreUIState() {
  325. restoreGeometry(UISettings::values.geometry);
  326. restoreState(UISettings::values.state);
  327. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  328. #if MICROPROFILE_ENABLED
  329. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  330. microProfileDialog->setVisible(UISettings::values.microprofile_visible);
  331. #endif
  332. game_list->LoadInterfaceLayout();
  333. ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode);
  334. ToggleWindowMode();
  335. ui.action_Fullscreen->setChecked(UISettings::values.fullscreen);
  336. ui.action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);
  337. OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked());
  338. ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar);
  339. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  340. ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);
  341. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  342. Debugger::ToggleConsole();
  343. }
  344. void GMainWindow::ConnectWidgetEvents() {
  345. connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
  346. connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
  347. connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS);
  348. connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID);
  349. connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
  350. &GMainWindow::OnGameListNavigateToGamedbEntry);
  351. connect(this, &GMainWindow::EmulationStarting, render_window,
  352. &GRenderWindow::OnEmulationStarting);
  353. connect(this, &GMainWindow::EmulationStopping, render_window,
  354. &GRenderWindow::OnEmulationStopping);
  355. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  356. }
  357. void GMainWindow::ConnectMenuEvents() {
  358. // File
  359. connect(ui.action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
  360. connect(ui.action_Load_Folder, &QAction::triggered, this, &GMainWindow::OnMenuLoadFolder);
  361. connect(ui.action_Install_File_NAND, &QAction::triggered, this,
  362. &GMainWindow::OnMenuInstallToNAND);
  363. connect(ui.action_Select_Game_List_Root, &QAction::triggered, this,
  364. &GMainWindow::OnMenuSelectGameListRoot);
  365. connect(ui.action_Select_NAND_Directory, &QAction::triggered, this,
  366. [this] { OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget::NAND); });
  367. connect(ui.action_Select_SDMC_Directory, &QAction::triggered, this,
  368. [this] { OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget::SDMC); });
  369. connect(ui.action_Exit, &QAction::triggered, this, &QMainWindow::close);
  370. connect(ui.action_Load_Amiibo, &QAction::triggered, this, &GMainWindow::OnLoadAmiibo);
  371. // Emulation
  372. connect(ui.action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
  373. connect(ui.action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
  374. connect(ui.action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
  375. connect(ui.action_Report_Compatibility, &QAction::triggered, this,
  376. &GMainWindow::OnMenuReportCompatibility);
  377. connect(ui.action_Restart, &QAction::triggered, this, [this] { BootGame(QString(game_path)); });
  378. connect(ui.action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
  379. // View
  380. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  381. &GMainWindow::ToggleWindowMode);
  382. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  383. &GMainWindow::OnDisplayTitleBars);
  384. ui.action_Show_Filter_Bar->setShortcut(tr("CTRL+F"));
  385. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  386. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  387. // Fullscreen
  388. ui.action_Fullscreen->setShortcut(
  389. hotkey_registry.GetHotkey("Main Window", "Fullscreen", this)->key());
  390. connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
  391. // Help
  392. connect(ui.action_Rederive, &QAction::triggered, this,
  393. std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning));
  394. connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
  395. }
  396. void GMainWindow::OnDisplayTitleBars(bool show) {
  397. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  398. if (show) {
  399. for (QDockWidget* widget : widgets) {
  400. QWidget* old = widget->titleBarWidget();
  401. widget->setTitleBarWidget(nullptr);
  402. if (old != nullptr)
  403. delete old;
  404. }
  405. } else {
  406. for (QDockWidget* widget : widgets) {
  407. QWidget* old = widget->titleBarWidget();
  408. widget->setTitleBarWidget(new QWidget());
  409. if (old != nullptr)
  410. delete old;
  411. }
  412. }
  413. }
  414. QStringList GMainWindow::GetUnsupportedGLExtensions() {
  415. QStringList unsupported_ext;
  416. if (!GLAD_GL_ARB_program_interface_query)
  417. unsupported_ext.append("ARB_program_interface_query");
  418. if (!GLAD_GL_ARB_separate_shader_objects)
  419. unsupported_ext.append("ARB_separate_shader_objects");
  420. if (!GLAD_GL_ARB_vertex_attrib_binding)
  421. unsupported_ext.append("ARB_vertex_attrib_binding");
  422. if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
  423. unsupported_ext.append("ARB_vertex_type_10f_11f_11f_rev");
  424. if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
  425. unsupported_ext.append("ARB_texture_mirror_clamp_to_edge");
  426. if (!GLAD_GL_ARB_base_instance)
  427. unsupported_ext.append("ARB_base_instance");
  428. if (!GLAD_GL_ARB_texture_storage)
  429. unsupported_ext.append("ARB_texture_storage");
  430. if (!GLAD_GL_ARB_multi_bind)
  431. unsupported_ext.append("ARB_multi_bind");
  432. if (!GLAD_GL_ARB_copy_image)
  433. unsupported_ext.append("ARB_copy_image");
  434. // Extensions required to support some texture formats.
  435. if (!GLAD_GL_EXT_texture_compression_s3tc)
  436. unsupported_ext.append("EXT_texture_compression_s3tc");
  437. if (!GLAD_GL_ARB_texture_compression_rgtc)
  438. unsupported_ext.append("ARB_texture_compression_rgtc");
  439. if (!GLAD_GL_ARB_texture_compression_bptc)
  440. unsupported_ext.append("ARB_texture_compression_bptc");
  441. if (!GLAD_GL_ARB_depth_buffer_float)
  442. unsupported_ext.append("ARB_depth_buffer_float");
  443. for (const QString& ext : unsupported_ext)
  444. LOG_CRITICAL(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  445. return unsupported_ext;
  446. }
  447. bool GMainWindow::LoadROM(const QString& filename) {
  448. // Shutdown previous session if the emu thread is still active...
  449. if (emu_thread != nullptr)
  450. ShutdownGame();
  451. render_window->InitRenderTarget();
  452. render_window->MakeCurrent();
  453. if (!gladLoadGL()) {
  454. QMessageBox::critical(this, tr("Error while initializing OpenGL 3.3 Core!"),
  455. tr("Your GPU may not support OpenGL 3.3, or you do not "
  456. "have the latest graphics driver."));
  457. return false;
  458. }
  459. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  460. if (!unsupported_gl_extensions.empty()) {
  461. QMessageBox::critical(this, tr("Error while initializing OpenGL Core!"),
  462. tr("Your GPU may not support one or more required OpenGL"
  463. "extensions. Please ensure you have the latest graphics "
  464. "driver.<br><br>Unsupported extensions:<br>") +
  465. unsupported_gl_extensions.join("<br>"));
  466. return false;
  467. }
  468. Core::System& system{Core::System::GetInstance()};
  469. system.SetFilesystem(vfs);
  470. system.SetGPUDebugContext(debug_context);
  471. const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
  472. const auto drd_callout =
  473. (UISettings::values.callout_flags & static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  474. if (result == Core::System::ResultStatus::Success &&
  475. system.GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  476. drd_callout) {
  477. UISettings::values.callout_flags |= static_cast<u32>(CalloutFlag::DRDDeprecation);
  478. QMessageBox::warning(
  479. this, tr("Warning Outdated Game Format"),
  480. tr("You are using the deconstructed ROM directory format for this game, which is an "
  481. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  482. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  483. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  484. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  485. "wiki</a>. This message will not be shown again."));
  486. }
  487. render_window->DoneCurrent();
  488. if (result != Core::System::ResultStatus::Success) {
  489. switch (result) {
  490. case Core::System::ResultStatus::ErrorGetLoader:
  491. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  492. QMessageBox::critical(this, tr("Error while loading ROM!"),
  493. tr("The ROM format is not supported."));
  494. break;
  495. case Core::System::ResultStatus::ErrorSystemMode:
  496. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  497. QMessageBox::critical(this, tr("Error while loading ROM!"),
  498. tr("Could not determine the system mode."));
  499. break;
  500. case Core::System::ResultStatus::ErrorVideoCore:
  501. QMessageBox::critical(
  502. this, tr("An error occurred initializing the video core."),
  503. tr("yuzu has encountered an error while running the video core, please see the "
  504. "log for more details."
  505. "For more information on accessing the log, please see the following page: "
  506. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  507. "to "
  508. "Upload the Log File</a>."
  509. "Ensure that you have the latest graphics drivers for your GPU."));
  510. break;
  511. default:
  512. if (static_cast<u32>(result) >
  513. static_cast<u32>(Core::System::ResultStatus::ErrorLoader)) {
  514. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  515. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  516. const u16 error_id = static_cast<u16>(result) - loader_id;
  517. QMessageBox::critical(
  518. this, tr("Error while loading ROM!"),
  519. QString::fromStdString(fmt::format(
  520. "While attempting to load the ROM requested, an error occured. Please "
  521. "refer to the yuzu wiki for more information or the yuzu discord for "
  522. "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
  523. loader_id, error_id, static_cast<Loader::ResultStatus>(error_id))));
  524. } else {
  525. QMessageBox::critical(
  526. this, tr("Error while loading ROM!"),
  527. tr("An unknown error occurred. Please see the log for more details."));
  528. }
  529. break;
  530. }
  531. return false;
  532. }
  533. game_path = filename;
  534. Core::Telemetry().AddField(Telemetry::FieldType::App, "Frontend", "Qt");
  535. return true;
  536. }
  537. void GMainWindow::BootGame(const QString& filename) {
  538. LOG_INFO(Frontend, "yuzu starting...");
  539. StoreRecentFile(filename); // Put the filename on top of the list
  540. if (!LoadROM(filename))
  541. return;
  542. // Create and start the emulation thread
  543. emu_thread = std::make_unique<EmuThread>(render_window);
  544. emit EmulationStarting(emu_thread.get());
  545. render_window->moveContext();
  546. emu_thread->start();
  547. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  548. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  549. // before the CPU continues
  550. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  551. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  552. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  553. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  554. // Update the GUI
  555. if (ui.action_Single_Window_Mode->isChecked()) {
  556. game_list->hide();
  557. }
  558. status_bar_update_timer.start(2000);
  559. std::string title_name;
  560. const auto res = Core::System::GetInstance().GetGameName(title_name);
  561. if (res != Loader::ResultStatus::Success) {
  562. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  563. const auto [nacp, icon_file] = FileSys::PatchManager(title_id).GetControlMetadata();
  564. if (nacp != nullptr)
  565. title_name = nacp->GetApplicationName();
  566. if (title_name.empty())
  567. title_name = FileUtil::GetFilename(filename.toStdString());
  568. }
  569. setWindowTitle(QString("yuzu %1| %4 | %2-%3")
  570. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc,
  571. QString::fromStdString(title_name)));
  572. render_window->show();
  573. render_window->setFocus();
  574. emulation_running = true;
  575. if (ui.action_Fullscreen->isChecked()) {
  576. ShowFullscreen();
  577. }
  578. OnStartGame();
  579. }
  580. void GMainWindow::ShutdownGame() {
  581. discord_rpc->Pause();
  582. emu_thread->RequestStop();
  583. emit EmulationStopping();
  584. // Wait for emulation thread to complete and delete it
  585. emu_thread->wait();
  586. emu_thread = nullptr;
  587. discord_rpc->Update();
  588. // The emulation is stopped, so closing the window or not does not matter anymore
  589. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  590. // Update the GUI
  591. ui.action_Start->setEnabled(false);
  592. ui.action_Start->setText(tr("Start"));
  593. ui.action_Pause->setEnabled(false);
  594. ui.action_Stop->setEnabled(false);
  595. ui.action_Restart->setEnabled(false);
  596. ui.action_Report_Compatibility->setEnabled(false);
  597. ui.action_Load_Amiibo->setEnabled(false);
  598. render_window->hide();
  599. game_list->show();
  600. game_list->setFilterFocus();
  601. setWindowTitle(QString("yuzu %1| %2-%3")
  602. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc));
  603. // Disable status bar updates
  604. status_bar_update_timer.stop();
  605. message_label->setVisible(false);
  606. emu_speed_label->setVisible(false);
  607. game_fps_label->setVisible(false);
  608. emu_frametime_label->setVisible(false);
  609. emulation_running = false;
  610. game_path.clear();
  611. }
  612. void GMainWindow::StoreRecentFile(const QString& filename) {
  613. UISettings::values.recent_files.prepend(filename);
  614. UISettings::values.recent_files.removeDuplicates();
  615. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  616. UISettings::values.recent_files.removeLast();
  617. }
  618. UpdateRecentFiles();
  619. }
  620. void GMainWindow::UpdateRecentFiles() {
  621. const int num_recent_files =
  622. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  623. for (int i = 0; i < num_recent_files; i++) {
  624. const QString text = QString("&%1. %2").arg(i + 1).arg(
  625. QFileInfo(UISettings::values.recent_files[i]).fileName());
  626. actions_recent_files[i]->setText(text);
  627. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  628. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  629. actions_recent_files[i]->setVisible(true);
  630. }
  631. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  632. actions_recent_files[j]->setVisible(false);
  633. }
  634. // Enable the recent files menu if the list isn't empty
  635. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  636. }
  637. void GMainWindow::OnGameListLoadFile(QString game_path) {
  638. BootGame(game_path);
  639. }
  640. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target) {
  641. std::string path;
  642. std::string open_target;
  643. switch (target) {
  644. case GameListOpenTarget::SaveData: {
  645. open_target = "Save Data";
  646. const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
  647. ASSERT(program_id != 0);
  648. // TODO(tech4me): Update this to work with arbitrary user profile
  649. // Refer to core/hle/service/acc/profile_manager.cpp ProfileManager constructor
  650. constexpr u128 user_id = {1, 0};
  651. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser,
  652. FileSys::SaveDataType::SaveData,
  653. program_id, user_id, 0);
  654. break;
  655. }
  656. case GameListOpenTarget::ModData: {
  657. open_target = "Mod Data";
  658. const auto load_dir = FileUtil::GetUserPath(FileUtil::UserPath::LoadDir);
  659. path = fmt::format("{}{:016X}", load_dir, program_id);
  660. break;
  661. }
  662. default:
  663. UNIMPLEMENTED();
  664. }
  665. const QString qpath = QString::fromStdString(path);
  666. const QDir dir(qpath);
  667. if (!dir.exists()) {
  668. QMessageBox::warning(this,
  669. tr("Error Opening %1 Folder").arg(QString::fromStdString(open_target)),
  670. tr("Folder does not exist!"));
  671. return;
  672. }
  673. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target, program_id);
  674. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  675. }
  676. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  677. std::size_t out = 0;
  678. for (const auto& subdir : dir->GetSubdirectories()) {
  679. out += 1 + CalculateRomFSEntrySize(subdir, full);
  680. }
  681. return out + (full ? dir->GetFiles().size() : 0);
  682. }
  683. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  684. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  685. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  686. return false;
  687. if (dialog.wasCanceled())
  688. return false;
  689. if (full) {
  690. for (const auto& file : src->GetFiles()) {
  691. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  692. if (!FileSys::VfsRawCopy(file, out, block_size))
  693. return false;
  694. dialog.setValue(dialog.value() + 1);
  695. if (dialog.wasCanceled())
  696. return false;
  697. }
  698. }
  699. for (const auto& dir : src->GetSubdirectories()) {
  700. const auto out = dest->CreateSubdirectory(dir->GetName());
  701. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  702. return false;
  703. dialog.setValue(dialog.value() + 1);
  704. if (dialog.wasCanceled())
  705. return false;
  706. }
  707. return true;
  708. }
  709. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path) {
  710. const auto failed = [this] {
  711. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  712. tr("There was an error copying the RomFS files or the user "
  713. "cancelled the operation."));
  714. };
  715. const auto loader = Loader::GetLoader(vfs->OpenFile(game_path, FileSys::Mode::Read));
  716. if (loader == nullptr) {
  717. failed();
  718. return;
  719. }
  720. FileSys::VirtualFile file;
  721. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  722. failed();
  723. return;
  724. }
  725. const auto installed = Service::FileSystem::GetUnionContents();
  726. auto romfs_title_id = SelectRomFSDumpTarget(*installed, program_id);
  727. if (!romfs_title_id) {
  728. failed();
  729. return;
  730. }
  731. const auto path = fmt::format(
  732. "{}{:016X}/romfs", FileUtil::GetUserPath(FileUtil::UserPath::DumpDir), *romfs_title_id);
  733. FileSys::VirtualFile romfs;
  734. if (*romfs_title_id == program_id) {
  735. romfs = file;
  736. } else {
  737. romfs = installed->GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  738. }
  739. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  740. if (extracted == nullptr) {
  741. failed();
  742. return;
  743. }
  744. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  745. if (out == nullptr) {
  746. failed();
  747. vfs->DeleteDirectory(path);
  748. return;
  749. }
  750. bool ok;
  751. const auto res = QInputDialog::getItem(
  752. this, tr("Select RomFS Dump Mode"),
  753. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  754. "files into the new directory while <br>skeleton will only create the directory "
  755. "structure."),
  756. {"Full", "Skeleton"}, 0, false, &ok);
  757. if (!ok) {
  758. failed();
  759. vfs->DeleteDirectory(path);
  760. return;
  761. }
  762. const auto full = res == "Full";
  763. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  764. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0, entry_size, this);
  765. progress.setWindowModality(Qt::WindowModal);
  766. progress.setMinimumDuration(100);
  767. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  768. progress.close();
  769. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  770. tr("The operation completed successfully."));
  771. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  772. } else {
  773. progress.close();
  774. failed();
  775. vfs->DeleteDirectory(path);
  776. }
  777. }
  778. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  779. QClipboard* clipboard = QGuiApplication::clipboard();
  780. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  781. }
  782. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  783. const CompatibilityList& compatibility_list) {
  784. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  785. QString directory;
  786. if (it != compatibility_list.end())
  787. directory = it->second.second;
  788. QDesktopServices::openUrl(QUrl("https://yuzu-emu.org/game/" + directory));
  789. }
  790. void GMainWindow::OnMenuLoadFile() {
  791. const QString extensions =
  792. QString("*.").append(GameList::supported_file_extensions.join(" *.")).append(" main");
  793. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  794. "%1 is an identifier for the Switch executable file extensions.")
  795. .arg(extensions);
  796. const QString filename = QFileDialog::getOpenFileName(
  797. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  798. if (filename.isEmpty()) {
  799. return;
  800. }
  801. UISettings::values.roms_path = QFileInfo(filename).path();
  802. BootGame(filename);
  803. }
  804. void GMainWindow::OnMenuLoadFolder() {
  805. const QString dir_path =
  806. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  807. if (dir_path.isNull()) {
  808. return;
  809. }
  810. const QDir dir{dir_path};
  811. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  812. if (matching_main.size() == 1) {
  813. BootGame(dir.path() + DIR_SEP + matching_main[0]);
  814. } else {
  815. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  816. tr("The directory you have selected does not contain a 'main' file."));
  817. }
  818. }
  819. void GMainWindow::OnMenuInstallToNAND() {
  820. const QString file_filter =
  821. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  822. "(*.nca);;Nintendo Submissions Package (*.nsp);;NX Cartridge "
  823. "Image (*.xci)");
  824. QString filename = QFileDialog::getOpenFileName(this, tr("Install File"),
  825. UISettings::values.roms_path, file_filter);
  826. if (filename.isEmpty()) {
  827. return;
  828. }
  829. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  830. const FileSys::VirtualFile& dest, std::size_t block_size) {
  831. if (src == nullptr || dest == nullptr)
  832. return false;
  833. if (!dest->Resize(src->GetSize()))
  834. return false;
  835. std::array<u8, 0x1000> buffer{};
  836. const int progress_maximum = static_cast<int>(src->GetSize() / buffer.size());
  837. QProgressDialog progress(
  838. tr("Installing file \"%1\"...").arg(QString::fromStdString(src->GetName())),
  839. tr("Cancel"), 0, progress_maximum, this);
  840. progress.setWindowModality(Qt::WindowModal);
  841. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  842. if (progress.wasCanceled()) {
  843. dest->Resize(0);
  844. return false;
  845. }
  846. const int progress_value = static_cast<int>(i / buffer.size());
  847. progress.setValue(progress_value);
  848. const auto read = src->Read(buffer.data(), buffer.size(), i);
  849. dest->Write(buffer.data(), read, i);
  850. }
  851. return true;
  852. };
  853. const auto success = [this]() {
  854. QMessageBox::information(this, tr("Successfully Installed"),
  855. tr("The file was successfully installed."));
  856. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  857. };
  858. const auto failed = [this]() {
  859. QMessageBox::warning(
  860. this, tr("Failed to Install"),
  861. tr("There was an error while attempting to install the provided file. It "
  862. "could have an incorrect format or be missing metadata. Please "
  863. "double-check your file and try again."));
  864. };
  865. const auto overwrite = [this]() {
  866. return QMessageBox::question(this, tr("Failed to Install"),
  867. tr("The file you are attempting to install already exists "
  868. "in the cache. Would you like to overwrite it?")) ==
  869. QMessageBox::Yes;
  870. };
  871. if (filename.endsWith("xci", Qt::CaseInsensitive) ||
  872. filename.endsWith("nsp", Qt::CaseInsensitive)) {
  873. std::shared_ptr<FileSys::NSP> nsp;
  874. if (filename.endsWith("nsp", Qt::CaseInsensitive)) {
  875. nsp = std::make_shared<FileSys::NSP>(
  876. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  877. if (nsp->IsExtractedType())
  878. failed();
  879. } else {
  880. const auto xci = std::make_shared<FileSys::XCI>(
  881. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  882. nsp = xci->GetSecurePartitionNSP();
  883. }
  884. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  885. failed();
  886. return;
  887. }
  888. const auto res =
  889. Service::FileSystem::GetUserNANDContents()->InstallEntry(nsp, false, qt_raw_copy);
  890. if (res == FileSys::InstallResult::Success) {
  891. success();
  892. } else {
  893. if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  894. if (overwrite()) {
  895. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  896. nsp, true, qt_raw_copy);
  897. if (res2 == FileSys::InstallResult::Success) {
  898. success();
  899. } else {
  900. failed();
  901. }
  902. }
  903. } else {
  904. failed();
  905. }
  906. }
  907. } else {
  908. const auto nca = std::make_shared<FileSys::NCA>(
  909. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  910. const auto id = nca->GetStatus();
  911. // Game updates necessary are missing base RomFS
  912. if (id != Loader::ResultStatus::Success &&
  913. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  914. failed();
  915. return;
  916. }
  917. const QStringList tt_options{tr("System Application"),
  918. tr("System Archive"),
  919. tr("System Application Update"),
  920. tr("Firmware Package (Type A)"),
  921. tr("Firmware Package (Type B)"),
  922. tr("Game"),
  923. tr("Game Update"),
  924. tr("Game DLC"),
  925. tr("Delta Title")};
  926. bool ok;
  927. const auto item = QInputDialog::getItem(
  928. this, tr("Select NCA Install Type..."),
  929. tr("Please select the type of title you would like to install this NCA as:\n(In "
  930. "most instances, the default 'Game' is fine.)"),
  931. tt_options, 5, false, &ok);
  932. auto index = tt_options.indexOf(item);
  933. if (!ok || index == -1) {
  934. QMessageBox::warning(this, tr("Failed to Install"),
  935. tr("The title type you selected for the NCA is invalid."));
  936. return;
  937. }
  938. // If index is equal to or past Game, add the jump in TitleType.
  939. if (index >= 5) {
  940. index += static_cast<size_t>(FileSys::TitleType::Application) -
  941. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  942. }
  943. FileSys::InstallResult res;
  944. if (index >= static_cast<size_t>(FileSys::TitleType::Application)) {
  945. res = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  946. nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  947. } else {
  948. res = Service::FileSystem::GetSystemNANDContents()->InstallEntry(
  949. nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  950. }
  951. if (res == FileSys::InstallResult::Success) {
  952. success();
  953. } else if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  954. if (overwrite()) {
  955. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  956. nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  957. if (res2 == FileSys::InstallResult::Success) {
  958. success();
  959. } else {
  960. failed();
  961. }
  962. }
  963. } else {
  964. failed();
  965. }
  966. }
  967. }
  968. void GMainWindow::OnMenuSelectGameListRoot() {
  969. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  970. if (!dir_path.isEmpty()) {
  971. UISettings::values.gamedir = dir_path;
  972. game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan);
  973. }
  974. }
  975. void GMainWindow::OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget target) {
  976. const auto res = QMessageBox::information(
  977. this, tr("Changing Emulated Directory"),
  978. tr("You are about to change the emulated %1 directory of the system. Please note "
  979. "that this does not also move the contents of the previous directory to the "
  980. "new one and you will have to do that yourself.")
  981. .arg(target == EmulatedDirectoryTarget::SDMC ? tr("SD card") : tr("NAND")),
  982. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  983. if (res == QMessageBox::Cancel)
  984. return;
  985. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  986. if (!dir_path.isEmpty()) {
  987. FileUtil::GetUserPath(target == EmulatedDirectoryTarget::SDMC ? FileUtil::UserPath::SDMCDir
  988. : FileUtil::UserPath::NANDDir,
  989. dir_path.toStdString());
  990. Service::FileSystem::CreateFactories(*vfs);
  991. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  992. }
  993. }
  994. void GMainWindow::OnMenuRecentFile() {
  995. QAction* action = qobject_cast<QAction*>(sender());
  996. assert(action);
  997. const QString filename = action->data().toString();
  998. if (QFileInfo::exists(filename)) {
  999. BootGame(filename);
  1000. } else {
  1001. // Display an error message and remove the file from the list.
  1002. QMessageBox::information(this, tr("File not found"),
  1003. tr("File \"%1\" not found").arg(filename));
  1004. UISettings::values.recent_files.removeOne(filename);
  1005. UpdateRecentFiles();
  1006. }
  1007. }
  1008. void GMainWindow::OnStartGame() {
  1009. emu_thread->SetRunning(true);
  1010. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  1011. qRegisterMetaType<std::string>("std::string");
  1012. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  1013. ui.action_Start->setEnabled(false);
  1014. ui.action_Start->setText(tr("Continue"));
  1015. ui.action_Pause->setEnabled(true);
  1016. ui.action_Stop->setEnabled(true);
  1017. ui.action_Restart->setEnabled(true);
  1018. ui.action_Report_Compatibility->setEnabled(true);
  1019. discord_rpc->Update();
  1020. ui.action_Load_Amiibo->setEnabled(true);
  1021. }
  1022. void GMainWindow::OnPauseGame() {
  1023. emu_thread->SetRunning(false);
  1024. ui.action_Start->setEnabled(true);
  1025. ui.action_Pause->setEnabled(false);
  1026. ui.action_Stop->setEnabled(true);
  1027. }
  1028. void GMainWindow::OnStopGame() {
  1029. ShutdownGame();
  1030. }
  1031. void GMainWindow::OnMenuReportCompatibility() {
  1032. if (!Settings::values.yuzu_token.empty() && !Settings::values.yuzu_username.empty()) {
  1033. CompatDB compatdb{this};
  1034. compatdb.exec();
  1035. } else {
  1036. QMessageBox::critical(
  1037. this, tr("Missing yuzu Account"),
  1038. tr("In order to submit a game compatibility test case, you must link your yuzu "
  1039. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  1040. "&gt; "
  1041. "Web."));
  1042. }
  1043. }
  1044. void GMainWindow::ToggleFullscreen() {
  1045. if (!emulation_running) {
  1046. return;
  1047. }
  1048. if (ui.action_Fullscreen->isChecked()) {
  1049. ShowFullscreen();
  1050. } else {
  1051. HideFullscreen();
  1052. }
  1053. }
  1054. void GMainWindow::ShowFullscreen() {
  1055. if (ui.action_Single_Window_Mode->isChecked()) {
  1056. UISettings::values.geometry = saveGeometry();
  1057. ui.menubar->hide();
  1058. statusBar()->hide();
  1059. showFullScreen();
  1060. } else {
  1061. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1062. render_window->showFullScreen();
  1063. }
  1064. }
  1065. void GMainWindow::HideFullscreen() {
  1066. if (ui.action_Single_Window_Mode->isChecked()) {
  1067. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  1068. ui.menubar->show();
  1069. showNormal();
  1070. restoreGeometry(UISettings::values.geometry);
  1071. } else {
  1072. render_window->showNormal();
  1073. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  1074. }
  1075. }
  1076. void GMainWindow::ToggleWindowMode() {
  1077. if (ui.action_Single_Window_Mode->isChecked()) {
  1078. // Render in the main window...
  1079. render_window->BackupGeometry();
  1080. ui.horizontalLayout->addWidget(render_window);
  1081. render_window->setFocusPolicy(Qt::ClickFocus);
  1082. if (emulation_running) {
  1083. render_window->setVisible(true);
  1084. render_window->setFocus();
  1085. game_list->hide();
  1086. }
  1087. } else {
  1088. // Render in a separate window...
  1089. ui.horizontalLayout->removeWidget(render_window);
  1090. render_window->setParent(nullptr);
  1091. render_window->setFocusPolicy(Qt::NoFocus);
  1092. if (emulation_running) {
  1093. render_window->setVisible(true);
  1094. render_window->RestoreGeometry();
  1095. game_list->show();
  1096. }
  1097. }
  1098. }
  1099. void GMainWindow::OnConfigure() {
  1100. ConfigureDialog configureDialog(this, hotkey_registry);
  1101. auto old_theme = UISettings::values.theme;
  1102. const bool old_discord_presence = UISettings::values.enable_discord_presence;
  1103. auto result = configureDialog.exec();
  1104. if (result == QDialog::Accepted) {
  1105. configureDialog.applyConfiguration();
  1106. if (UISettings::values.theme != old_theme)
  1107. UpdateUITheme();
  1108. if (UISettings::values.enable_discord_presence != old_discord_presence)
  1109. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  1110. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1111. config->Save();
  1112. }
  1113. }
  1114. void GMainWindow::OnLoadAmiibo() {
  1115. const QString extensions{"*.bin"};
  1116. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  1117. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), "", file_filter);
  1118. if (!filename.isEmpty()) {
  1119. Core::System& system{Core::System::GetInstance()};
  1120. Service::SM::ServiceManager& sm = system.ServiceManager();
  1121. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  1122. if (nfc != nullptr) {
  1123. auto nfc_file = FileUtil::IOFile(filename.toStdString(), "rb");
  1124. if (!nfc_file.IsOpen()) {
  1125. return;
  1126. }
  1127. std::vector<u8> amiibo_buffer(nfc_file.GetSize());
  1128. nfc_file.ReadBytes(amiibo_buffer.data(), amiibo_buffer.size());
  1129. nfc_file.Close();
  1130. nfc->LoadAmiibo(amiibo_buffer);
  1131. }
  1132. }
  1133. }
  1134. void GMainWindow::OnAbout() {
  1135. AboutDialog aboutDialog(this);
  1136. aboutDialog.exec();
  1137. }
  1138. void GMainWindow::OnToggleFilterBar() {
  1139. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  1140. if (ui.action_Show_Filter_Bar->isChecked()) {
  1141. game_list->setFilterFocus();
  1142. } else {
  1143. game_list->clearFilter();
  1144. }
  1145. }
  1146. void GMainWindow::UpdateStatusBar() {
  1147. if (emu_thread == nullptr) {
  1148. status_bar_update_timer.stop();
  1149. return;
  1150. }
  1151. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  1152. if (Settings::values.use_frame_limit) {
  1153. emu_speed_label->setText(tr("Speed: %1% / %2%")
  1154. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  1155. .arg(Settings::values.frame_limit));
  1156. } else {
  1157. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  1158. }
  1159. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  1160. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  1161. emu_speed_label->setVisible(true);
  1162. game_fps_label->setVisible(true);
  1163. emu_frametime_label->setVisible(true);
  1164. }
  1165. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  1166. QMessageBox::StandardButton answer;
  1167. QString status_message;
  1168. const QString common_message =
  1169. tr("The game you are trying to load requires additional files from your Switch to be "
  1170. "dumped "
  1171. "before playing.<br/><br/>For more information on dumping these files, please see the "
  1172. "following wiki page: <a "
  1173. "href='https://yuzu-emu.org/wiki/"
  1174. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  1175. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  1176. "quit "
  1177. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  1178. "data, or other bugs.");
  1179. switch (result) {
  1180. case Core::System::ResultStatus::ErrorSystemFiles: {
  1181. QString message = "yuzu was unable to locate a Switch system archive";
  1182. if (!details.empty()) {
  1183. message.append(tr(": %1. ").arg(details.c_str()));
  1184. } else {
  1185. message.append(". ");
  1186. }
  1187. message.append(common_message);
  1188. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  1189. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1190. status_message = "System Archive Missing";
  1191. break;
  1192. }
  1193. case Core::System::ResultStatus::ErrorSharedFont: {
  1194. QString message = tr("yuzu was unable to locate the Switch shared fonts. ");
  1195. message.append(common_message);
  1196. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  1197. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1198. status_message = "Shared Font Missing";
  1199. break;
  1200. }
  1201. default:
  1202. answer = QMessageBox::question(
  1203. this, tr("Fatal Error"),
  1204. tr("yuzu has encountered a fatal error, please see the log for more details. "
  1205. "For more information on accessing the log, please see the following page: "
  1206. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  1207. "to "
  1208. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  1209. "list? "
  1210. "Continuing emulation may result in crashes, corrupted save data, or other "
  1211. "bugs."),
  1212. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1213. status_message = "Fatal Error encountered";
  1214. break;
  1215. }
  1216. if (answer == QMessageBox::Yes) {
  1217. if (emu_thread) {
  1218. ShutdownGame();
  1219. }
  1220. } else {
  1221. // Only show the message if the game is still running.
  1222. if (emu_thread) {
  1223. emu_thread->SetRunning(true);
  1224. message_label->setText(status_message);
  1225. message_label->setVisible(true);
  1226. }
  1227. }
  1228. }
  1229. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  1230. if (behavior == ReinitializeKeyBehavior::Warning) {
  1231. const auto res = QMessageBox::information(
  1232. this, tr("Confirm Key Rederivation"),
  1233. tr("You are about to force rederive all of your keys. \nIf you do not know what this "
  1234. "means or what you are doing, \nthis is a potentially destructive action. \nPlease "
  1235. "make "
  1236. "sure this is what you want \nand optionally make backups.\n\nThis will delete your "
  1237. "autogenerated key files and re-run the key derivation module."),
  1238. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1239. if (res == QMessageBox::Cancel)
  1240. return;
  1241. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1242. "prod.keys_autogenerated");
  1243. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1244. "console.keys_autogenerated");
  1245. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1246. "title.keys_autogenerated");
  1247. }
  1248. Core::Crypto::KeyManager keys{};
  1249. if (keys.BaseDeriveNecessary()) {
  1250. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory(
  1251. FileUtil::GetUserPath(FileUtil::UserPath::SysDataDir), FileSys::Mode::Read)};
  1252. const auto function = [this, &keys, &pdm] {
  1253. keys.PopulateFromPartitionData(pdm);
  1254. Service::FileSystem::CreateFactories(*vfs);
  1255. keys.DeriveETicket(pdm);
  1256. };
  1257. QString errors;
  1258. if (!pdm.HasFuses())
  1259. errors += tr("- Missing fuses - Cannot derive SBK\n");
  1260. if (!pdm.HasBoot0())
  1261. errors += tr("- Missing BOOT0 - Cannot derive master keys\n");
  1262. if (!pdm.HasPackage2())
  1263. errors += tr("- Missing BCPKG2-1-Normal-Main - Cannot derive general keys\n");
  1264. if (!pdm.HasProdInfo())
  1265. errors += tr("- Missing PRODINFO - Cannot derive title keys\n");
  1266. if (!errors.isEmpty()) {
  1267. QMessageBox::warning(
  1268. this, tr("Warning Missing Derivation Components"),
  1269. tr("The following are missing from your configuration that may hinder key "
  1270. "derivation. It will be attempted but may not complete.<br><br>") +
  1271. errors +
  1272. tr("<br><br>You can get all of these and dump all of your games easily by "
  1273. "following <a href='https://yuzu-emu.org/help/quickstart/quickstart/'>the "
  1274. "quickstart guide</a>. Alternatively, you can use another method of dumping "
  1275. "to obtain all of your keys."));
  1276. }
  1277. QProgressDialog prog;
  1278. prog.setRange(0, 0);
  1279. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  1280. "system's performance."));
  1281. prog.setWindowTitle(tr("Deriving Keys"));
  1282. prog.show();
  1283. auto future = QtConcurrent::run(function);
  1284. while (!future.isFinished()) {
  1285. QCoreApplication::processEvents();
  1286. }
  1287. prog.close();
  1288. }
  1289. Service::FileSystem::CreateFactories(*vfs);
  1290. if (behavior == ReinitializeKeyBehavior::Warning) {
  1291. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1292. }
  1293. }
  1294. boost::optional<u64> GMainWindow::SelectRomFSDumpTarget(
  1295. const FileSys::RegisteredCacheUnion& installed, u64 program_id) {
  1296. const auto dlc_entries =
  1297. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1298. std::vector<FileSys::RegisteredCacheEntry> dlc_match;
  1299. dlc_match.reserve(dlc_entries.size());
  1300. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  1301. [&program_id, &installed](const FileSys::RegisteredCacheEntry& entry) {
  1302. return (entry.title_id & DLC_BASE_TITLE_ID_MASK) == program_id &&
  1303. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  1304. });
  1305. std::vector<u64> romfs_tids;
  1306. romfs_tids.push_back(program_id);
  1307. for (const auto& entry : dlc_match)
  1308. romfs_tids.push_back(entry.title_id);
  1309. if (romfs_tids.size() > 1) {
  1310. QStringList list{"Base"};
  1311. for (std::size_t i = 1; i < romfs_tids.size(); ++i)
  1312. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  1313. bool ok;
  1314. const auto res = QInputDialog::getItem(
  1315. this, tr("Select RomFS Dump Target"),
  1316. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  1317. if (!ok) {
  1318. return boost::none;
  1319. }
  1320. return romfs_tids[list.indexOf(res)];
  1321. }
  1322. return program_id;
  1323. }
  1324. bool GMainWindow::ConfirmClose() {
  1325. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  1326. return true;
  1327. QMessageBox::StandardButton answer =
  1328. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  1329. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1330. return answer != QMessageBox::No;
  1331. }
  1332. void GMainWindow::closeEvent(QCloseEvent* event) {
  1333. if (!ConfirmClose()) {
  1334. event->ignore();
  1335. return;
  1336. }
  1337. if (ui.action_Fullscreen->isChecked()) {
  1338. UISettings::values.geometry = saveGeometry();
  1339. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1340. }
  1341. UISettings::values.state = saveState();
  1342. #if MICROPROFILE_ENABLED
  1343. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  1344. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  1345. #endif
  1346. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  1347. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  1348. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  1349. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  1350. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  1351. UISettings::values.first_start = false;
  1352. game_list->SaveInterfaceLayout();
  1353. hotkey_registry.SaveHotkeys();
  1354. // Shutdown session if the emu thread is active...
  1355. if (emu_thread != nullptr)
  1356. ShutdownGame();
  1357. render_window->close();
  1358. QWidget::closeEvent(event);
  1359. }
  1360. static bool IsSingleFileDropEvent(QDropEvent* event) {
  1361. const QMimeData* mimeData = event->mimeData();
  1362. return mimeData->hasUrls() && mimeData->urls().length() == 1;
  1363. }
  1364. void GMainWindow::dropEvent(QDropEvent* event) {
  1365. if (IsSingleFileDropEvent(event) && ConfirmChangeGame()) {
  1366. const QMimeData* mimeData = event->mimeData();
  1367. QString filename = mimeData->urls().at(0).toLocalFile();
  1368. BootGame(filename);
  1369. }
  1370. }
  1371. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  1372. if (IsSingleFileDropEvent(event)) {
  1373. event->acceptProposedAction();
  1374. }
  1375. }
  1376. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  1377. event->acceptProposedAction();
  1378. }
  1379. bool GMainWindow::ConfirmChangeGame() {
  1380. if (emu_thread == nullptr)
  1381. return true;
  1382. auto answer = QMessageBox::question(
  1383. this, tr("yuzu"),
  1384. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  1385. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1386. return answer != QMessageBox::No;
  1387. }
  1388. void GMainWindow::filterBarSetChecked(bool state) {
  1389. ui.action_Show_Filter_Bar->setChecked(state);
  1390. emit(OnToggleFilterBar());
  1391. }
  1392. void GMainWindow::UpdateUITheme() {
  1393. QStringList theme_paths(default_theme_paths);
  1394. if (UISettings::values.theme != UISettings::themes[0].second &&
  1395. !UISettings::values.theme.isEmpty()) {
  1396. const QString theme_uri(":" + UISettings::values.theme + "/style.qss");
  1397. QFile f(theme_uri);
  1398. if (f.open(QFile::ReadOnly | QFile::Text)) {
  1399. QTextStream ts(&f);
  1400. qApp->setStyleSheet(ts.readAll());
  1401. GMainWindow::setStyleSheet(ts.readAll());
  1402. } else {
  1403. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  1404. }
  1405. theme_paths.append(QStringList{":/icons/default", ":/icons/" + UISettings::values.theme});
  1406. QIcon::setThemeName(":/icons/" + UISettings::values.theme);
  1407. } else {
  1408. qApp->setStyleSheet("");
  1409. GMainWindow::setStyleSheet("");
  1410. theme_paths.append(QStringList{":/icons/default"});
  1411. QIcon::setThemeName(":/icons/default");
  1412. }
  1413. QIcon::setThemeSearchPaths(theme_paths);
  1414. emit UpdateThemedIcons();
  1415. }
  1416. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  1417. #ifdef USE_DISCORD_PRESENCE
  1418. if (state) {
  1419. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  1420. } else {
  1421. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1422. }
  1423. #else
  1424. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1425. #endif
  1426. discord_rpc->Update();
  1427. }
  1428. #ifdef main
  1429. #undef main
  1430. #endif
  1431. int main(int argc, char* argv[]) {
  1432. Common::DetachedTasks detached_tasks;
  1433. MicroProfileOnThreadCreate("Frontend");
  1434. SCOPE_EXIT({ MicroProfileShutdown(); });
  1435. // Init settings params
  1436. QCoreApplication::setOrganizationName("yuzu team");
  1437. QCoreApplication::setApplicationName("yuzu");
  1438. QApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  1439. QApplication app(argc, argv);
  1440. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  1441. // generating shaders
  1442. setlocale(LC_ALL, "C");
  1443. GMainWindow main_window;
  1444. // After settings have been loaded by GMainWindow, apply the filter
  1445. main_window.show();
  1446. int result = app.exec();
  1447. detached_tasks.WaitForAllTasks();
  1448. return result;
  1449. }