main.cpp 58 KB

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