main.cpp 56 KB

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