main.cpp 50 KB

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