main.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  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. title_name = FileUtil::GetFilename(filename.toStdString());
  512. setWindowTitle(QString("yuzu %1| %4 | %2-%3")
  513. .arg(Common::g_build_name, Common::g_scm_branch, Common::g_scm_desc,
  514. QString::fromStdString(title_name)));
  515. render_window->show();
  516. render_window->setFocus();
  517. emulation_running = true;
  518. if (ui.action_Fullscreen->isChecked()) {
  519. ShowFullscreen();
  520. }
  521. OnStartGame();
  522. }
  523. void GMainWindow::ShutdownGame() {
  524. emu_thread->RequestStop();
  525. emit EmulationStopping();
  526. // Wait for emulation thread to complete and delete it
  527. emu_thread->wait();
  528. emu_thread = nullptr;
  529. // The emulation is stopped, so closing the window or not does not matter anymore
  530. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  531. // Update the GUI
  532. ui.action_Start->setEnabled(false);
  533. ui.action_Start->setText(tr("Start"));
  534. ui.action_Pause->setEnabled(false);
  535. ui.action_Stop->setEnabled(false);
  536. ui.action_Restart->setEnabled(false);
  537. render_window->hide();
  538. game_list->show();
  539. game_list->setFilterFocus();
  540. setWindowTitle(QString("yuzu %1| %2-%3")
  541. .arg(Common::g_build_name, Common::g_scm_branch, Common::g_scm_desc));
  542. // Disable status bar updates
  543. status_bar_update_timer.stop();
  544. message_label->setVisible(false);
  545. emu_speed_label->setVisible(false);
  546. game_fps_label->setVisible(false);
  547. emu_frametime_label->setVisible(false);
  548. emulation_running = false;
  549. game_path.clear();
  550. }
  551. void GMainWindow::StoreRecentFile(const QString& filename) {
  552. UISettings::values.recent_files.prepend(filename);
  553. UISettings::values.recent_files.removeDuplicates();
  554. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  555. UISettings::values.recent_files.removeLast();
  556. }
  557. UpdateRecentFiles();
  558. }
  559. void GMainWindow::UpdateRecentFiles() {
  560. const int num_recent_files =
  561. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  562. for (int i = 0; i < num_recent_files; i++) {
  563. const QString text = QString("&%1. %2").arg(i + 1).arg(
  564. QFileInfo(UISettings::values.recent_files[i]).fileName());
  565. actions_recent_files[i]->setText(text);
  566. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  567. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  568. actions_recent_files[i]->setVisible(true);
  569. }
  570. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  571. actions_recent_files[j]->setVisible(false);
  572. }
  573. // Enable the recent files menu if the list isn't empty
  574. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  575. }
  576. void GMainWindow::OnGameListLoadFile(QString game_path) {
  577. BootGame(game_path);
  578. }
  579. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target) {
  580. std::string path;
  581. std::string open_target;
  582. switch (target) {
  583. case GameListOpenTarget::SaveData: {
  584. open_target = "Save Data";
  585. const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
  586. ASSERT(program_id != 0);
  587. // TODO(tech4me): Update this to work with arbitrary user profile
  588. // Refer to core/hle/service/acc/profile_manager.cpp ProfileManager constructor
  589. constexpr u128 user_id = {1, 0};
  590. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser,
  591. FileSys::SaveDataType::SaveData,
  592. program_id, user_id, 0);
  593. break;
  594. }
  595. default:
  596. UNIMPLEMENTED();
  597. }
  598. const QString qpath = QString::fromStdString(path);
  599. const QDir dir(qpath);
  600. if (!dir.exists()) {
  601. QMessageBox::warning(this,
  602. tr("Error Opening %1 Folder").arg(QString::fromStdString(open_target)),
  603. tr("Folder does not exist!"));
  604. return;
  605. }
  606. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target, program_id);
  607. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  608. }
  609. void GMainWindow::OnGameListNavigateToGamedbEntry(
  610. u64 program_id,
  611. std::unordered_map<std::string, std::pair<QString, QString>>& compatibility_list) {
  612. auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  613. QString directory;
  614. if (it != compatibility_list.end())
  615. directory = it->second.second;
  616. QDesktopServices::openUrl(QUrl("https://yuzu-emu.org/game/" + directory));
  617. }
  618. void GMainWindow::OnMenuLoadFile() {
  619. QString extensions;
  620. for (const auto& piece : game_list->supported_file_extensions)
  621. extensions += "*." + piece + " ";
  622. extensions += "main ";
  623. QString file_filter = tr("Switch Executable") + " (" + extensions + ")";
  624. file_filter += ";;" + tr("All Files (*.*)");
  625. QString filename = QFileDialog::getOpenFileName(this, tr("Load File"),
  626. UISettings::values.roms_path, file_filter);
  627. if (!filename.isEmpty()) {
  628. UISettings::values.roms_path = QFileInfo(filename).path();
  629. BootGame(filename);
  630. }
  631. }
  632. void GMainWindow::OnMenuLoadFolder() {
  633. const QString dir_path =
  634. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  635. if (dir_path.isNull()) {
  636. return;
  637. }
  638. const QDir dir{dir_path};
  639. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  640. if (matching_main.size() == 1) {
  641. BootGame(dir.path() + DIR_SEP + matching_main[0]);
  642. } else {
  643. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  644. tr("The directory you have selected does not contain a 'main' file."));
  645. }
  646. }
  647. void GMainWindow::OnMenuInstallToNAND() {
  648. const QString file_filter =
  649. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  650. "(*.nca);;Nintendo Submissions Package (*.nsp);;NX Cartridge "
  651. "Image (*.xci)");
  652. QString filename = QFileDialog::getOpenFileName(this, tr("Install File"),
  653. UISettings::values.roms_path, file_filter);
  654. if (filename.isEmpty()) {
  655. return;
  656. }
  657. const auto qt_raw_copy = [this](FileSys::VirtualFile src, FileSys::VirtualFile dest) {
  658. if (src == nullptr || dest == nullptr)
  659. return false;
  660. if (!dest->Resize(src->GetSize()))
  661. return false;
  662. std::array<u8, 0x1000> buffer{};
  663. const int progress_maximum = static_cast<int>(src->GetSize() / buffer.size());
  664. QProgressDialog progress(
  665. tr("Installing file \"%1\"...").arg(QString::fromStdString(src->GetName())),
  666. tr("Cancel"), 0, progress_maximum, this);
  667. progress.setWindowModality(Qt::WindowModal);
  668. for (size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  669. if (progress.wasCanceled()) {
  670. dest->Resize(0);
  671. return false;
  672. }
  673. const int progress_value = static_cast<int>(i / buffer.size());
  674. progress.setValue(progress_value);
  675. const auto read = src->Read(buffer.data(), buffer.size(), i);
  676. dest->Write(buffer.data(), read, i);
  677. }
  678. return true;
  679. };
  680. const auto success = [this]() {
  681. QMessageBox::information(this, tr("Successfully Installed"),
  682. tr("The file was successfully installed."));
  683. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  684. };
  685. const auto failed = [this]() {
  686. QMessageBox::warning(
  687. this, tr("Failed to Install"),
  688. tr("There was an error while attempting to install the provided file. It "
  689. "could have an incorrect format or be missing metadata. Please "
  690. "double-check your file and try again."));
  691. };
  692. const auto overwrite = [this]() {
  693. return QMessageBox::question(this, tr("Failed to Install"),
  694. tr("The file you are attempting to install already exists "
  695. "in the cache. Would you like to overwrite it?")) ==
  696. QMessageBox::Yes;
  697. };
  698. if (filename.endsWith("xci", Qt::CaseInsensitive) ||
  699. filename.endsWith("nsp", Qt::CaseInsensitive)) {
  700. std::shared_ptr<FileSys::NSP> nsp;
  701. if (filename.endsWith("nsp", Qt::CaseInsensitive)) {
  702. nsp = std::make_shared<FileSys::NSP>(
  703. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  704. if (nsp->IsExtractedType())
  705. failed();
  706. } else {
  707. const auto xci = std::make_shared<FileSys::XCI>(
  708. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  709. nsp = xci->GetSecurePartitionNSP();
  710. }
  711. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  712. failed();
  713. return;
  714. }
  715. const auto res =
  716. Service::FileSystem::GetUserNANDContents()->InstallEntry(nsp, false, qt_raw_copy);
  717. if (res == FileSys::InstallResult::Success) {
  718. success();
  719. } else {
  720. if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  721. if (overwrite()) {
  722. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  723. nsp, true, qt_raw_copy);
  724. if (res2 == FileSys::InstallResult::Success) {
  725. success();
  726. } else {
  727. failed();
  728. }
  729. }
  730. } else {
  731. failed();
  732. }
  733. }
  734. } else {
  735. const auto nca = std::make_shared<FileSys::NCA>(
  736. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  737. if (nca->GetStatus() != Loader::ResultStatus::Success) {
  738. failed();
  739. return;
  740. }
  741. const QStringList tt_options{tr("System Application"),
  742. tr("System Archive"),
  743. tr("System Application Update"),
  744. tr("Firmware Package (Type A)"),
  745. tr("Firmware Package (Type B)"),
  746. tr("Game"),
  747. tr("Game Update"),
  748. tr("Game DLC"),
  749. tr("Delta Title")};
  750. bool ok;
  751. const auto item = QInputDialog::getItem(
  752. this, tr("Select NCA Install Type..."),
  753. tr("Please select the type of title you would like to install this NCA as:\n(In "
  754. "most instances, the default 'Game' is fine.)"),
  755. tt_options, 5, false, &ok);
  756. auto index = tt_options.indexOf(item);
  757. if (!ok || index == -1) {
  758. QMessageBox::warning(this, tr("Failed to Install"),
  759. tr("The title type you selected for the NCA is invalid."));
  760. return;
  761. }
  762. if (index >= 5)
  763. index += 0x7B;
  764. const auto res = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  765. nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  766. if (res == FileSys::InstallResult::Success) {
  767. success();
  768. } else if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  769. if (overwrite()) {
  770. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  771. nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  772. if (res2 == FileSys::InstallResult::Success) {
  773. success();
  774. } else {
  775. failed();
  776. }
  777. }
  778. } else {
  779. failed();
  780. }
  781. }
  782. }
  783. void GMainWindow::OnMenuSelectGameListRoot() {
  784. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  785. if (!dir_path.isEmpty()) {
  786. UISettings::values.gamedir = dir_path;
  787. game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan);
  788. }
  789. }
  790. void GMainWindow::OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget target) {
  791. const auto res = QMessageBox::information(
  792. this, tr("Changing Emulated Directory"),
  793. tr("You are about to change the emulated %1 directory of the system. Please note "
  794. "that this does not also move the contents of the previous directory to the "
  795. "new one and you will have to do that yourself.")
  796. .arg(target == EmulatedDirectoryTarget::SDMC ? tr("SD card") : tr("NAND")),
  797. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  798. if (res == QMessageBox::Cancel)
  799. return;
  800. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  801. if (!dir_path.isEmpty()) {
  802. FileUtil::GetUserPath(target == EmulatedDirectoryTarget::SDMC ? FileUtil::UserPath::SDMCDir
  803. : FileUtil::UserPath::NANDDir,
  804. dir_path.toStdString());
  805. Service::FileSystem::CreateFactories(vfs);
  806. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  807. }
  808. }
  809. void GMainWindow::OnMenuRecentFile() {
  810. QAction* action = qobject_cast<QAction*>(sender());
  811. assert(action);
  812. const QString filename = action->data().toString();
  813. if (QFileInfo::exists(filename)) {
  814. BootGame(filename);
  815. } else {
  816. // Display an error message and remove the file from the list.
  817. QMessageBox::information(this, tr("File not found"),
  818. tr("File \"%1\" not found").arg(filename));
  819. UISettings::values.recent_files.removeOne(filename);
  820. UpdateRecentFiles();
  821. }
  822. }
  823. void GMainWindow::OnStartGame() {
  824. emu_thread->SetRunning(true);
  825. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  826. qRegisterMetaType<std::string>("std::string");
  827. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  828. ui.action_Start->setEnabled(false);
  829. ui.action_Start->setText(tr("Continue"));
  830. ui.action_Pause->setEnabled(true);
  831. ui.action_Stop->setEnabled(true);
  832. ui.action_Restart->setEnabled(true);
  833. }
  834. void GMainWindow::OnPauseGame() {
  835. emu_thread->SetRunning(false);
  836. ui.action_Start->setEnabled(true);
  837. ui.action_Pause->setEnabled(false);
  838. ui.action_Stop->setEnabled(true);
  839. }
  840. void GMainWindow::OnStopGame() {
  841. ShutdownGame();
  842. }
  843. void GMainWindow::ToggleFullscreen() {
  844. if (!emulation_running) {
  845. return;
  846. }
  847. if (ui.action_Fullscreen->isChecked()) {
  848. ShowFullscreen();
  849. } else {
  850. HideFullscreen();
  851. }
  852. }
  853. void GMainWindow::ShowFullscreen() {
  854. if (ui.action_Single_Window_Mode->isChecked()) {
  855. UISettings::values.geometry = saveGeometry();
  856. ui.menubar->hide();
  857. statusBar()->hide();
  858. showFullScreen();
  859. } else {
  860. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  861. render_window->showFullScreen();
  862. }
  863. }
  864. void GMainWindow::HideFullscreen() {
  865. if (ui.action_Single_Window_Mode->isChecked()) {
  866. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  867. ui.menubar->show();
  868. showNormal();
  869. restoreGeometry(UISettings::values.geometry);
  870. } else {
  871. render_window->showNormal();
  872. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  873. }
  874. }
  875. void GMainWindow::ToggleWindowMode() {
  876. if (ui.action_Single_Window_Mode->isChecked()) {
  877. // Render in the main window...
  878. render_window->BackupGeometry();
  879. ui.horizontalLayout->addWidget(render_window);
  880. render_window->setFocusPolicy(Qt::ClickFocus);
  881. if (emulation_running) {
  882. render_window->setVisible(true);
  883. render_window->setFocus();
  884. game_list->hide();
  885. }
  886. } else {
  887. // Render in a separate window...
  888. ui.horizontalLayout->removeWidget(render_window);
  889. render_window->setParent(nullptr);
  890. render_window->setFocusPolicy(Qt::NoFocus);
  891. if (emulation_running) {
  892. render_window->setVisible(true);
  893. render_window->RestoreGeometry();
  894. game_list->show();
  895. }
  896. }
  897. }
  898. void GMainWindow::OnConfigure() {
  899. ConfigureDialog configureDialog(this, hotkey_registry);
  900. auto old_theme = UISettings::values.theme;
  901. auto result = configureDialog.exec();
  902. if (result == QDialog::Accepted) {
  903. configureDialog.applyConfiguration();
  904. if (UISettings::values.theme != old_theme)
  905. UpdateUITheme();
  906. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  907. config->Save();
  908. }
  909. }
  910. void GMainWindow::OnAbout() {
  911. AboutDialog aboutDialog(this);
  912. aboutDialog.exec();
  913. }
  914. void GMainWindow::OnToggleFilterBar() {
  915. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  916. if (ui.action_Show_Filter_Bar->isChecked()) {
  917. game_list->setFilterFocus();
  918. } else {
  919. game_list->clearFilter();
  920. }
  921. }
  922. void GMainWindow::UpdateStatusBar() {
  923. if (emu_thread == nullptr) {
  924. status_bar_update_timer.stop();
  925. return;
  926. }
  927. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  928. if (Settings::values.use_frame_limit) {
  929. emu_speed_label->setText(tr("Speed: %1% / %2%")
  930. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  931. .arg(Settings::values.frame_limit));
  932. } else {
  933. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  934. }
  935. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  936. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  937. emu_speed_label->setVisible(true);
  938. game_fps_label->setVisible(true);
  939. emu_frametime_label->setVisible(true);
  940. }
  941. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  942. QMessageBox::StandardButton answer;
  943. QString status_message;
  944. const QString common_message = tr(
  945. "The game you are trying to load requires additional files from your Switch to be dumped "
  946. "before playing.<br/><br/>For more information on dumping these files, please see the "
  947. "following wiki page: <a "
  948. "href='https://yuzu-emu.org/wiki/"
  949. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  950. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to quit "
  951. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  952. "data, or other bugs.");
  953. switch (result) {
  954. case Core::System::ResultStatus::ErrorSystemFiles: {
  955. QString message = "yuzu was unable to locate a Switch system archive";
  956. if (!details.empty()) {
  957. message.append(tr(": %1. ").arg(details.c_str()));
  958. } else {
  959. message.append(". ");
  960. }
  961. message.append(common_message);
  962. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  963. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  964. status_message = "System Archive Missing";
  965. break;
  966. }
  967. case Core::System::ResultStatus::ErrorSharedFont: {
  968. QString message = tr("yuzu was unable to locate the Switch shared fonts. ");
  969. message.append(common_message);
  970. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  971. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  972. status_message = "Shared Font Missing";
  973. break;
  974. }
  975. default:
  976. answer = QMessageBox::question(
  977. this, tr("Fatal Error"),
  978. tr("yuzu has encountered a fatal error, please see the log for more details. "
  979. "For more information on accessing the log, please see the following page: "
  980. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How to "
  981. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game list? "
  982. "Continuing emulation may result in crashes, corrupted save data, or other bugs."),
  983. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  984. status_message = "Fatal Error encountered";
  985. break;
  986. }
  987. if (answer == QMessageBox::Yes) {
  988. if (emu_thread) {
  989. ShutdownGame();
  990. }
  991. } else {
  992. // Only show the message if the game is still running.
  993. if (emu_thread) {
  994. emu_thread->SetRunning(true);
  995. message_label->setText(status_message);
  996. message_label->setVisible(true);
  997. }
  998. }
  999. }
  1000. bool GMainWindow::ConfirmClose() {
  1001. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  1002. return true;
  1003. QMessageBox::StandardButton answer =
  1004. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  1005. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1006. return answer != QMessageBox::No;
  1007. }
  1008. void GMainWindow::closeEvent(QCloseEvent* event) {
  1009. if (!ConfirmClose()) {
  1010. event->ignore();
  1011. return;
  1012. }
  1013. if (ui.action_Fullscreen->isChecked()) {
  1014. UISettings::values.geometry = saveGeometry();
  1015. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1016. }
  1017. UISettings::values.state = saveState();
  1018. #if MICROPROFILE_ENABLED
  1019. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  1020. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  1021. #endif
  1022. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  1023. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  1024. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  1025. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  1026. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  1027. UISettings::values.first_start = false;
  1028. game_list->SaveInterfaceLayout();
  1029. hotkey_registry.SaveHotkeys();
  1030. // Shutdown session if the emu thread is active...
  1031. if (emu_thread != nullptr)
  1032. ShutdownGame();
  1033. render_window->close();
  1034. QWidget::closeEvent(event);
  1035. }
  1036. static bool IsSingleFileDropEvent(QDropEvent* event) {
  1037. const QMimeData* mimeData = event->mimeData();
  1038. return mimeData->hasUrls() && mimeData->urls().length() == 1;
  1039. }
  1040. void GMainWindow::dropEvent(QDropEvent* event) {
  1041. if (IsSingleFileDropEvent(event) && ConfirmChangeGame()) {
  1042. const QMimeData* mimeData = event->mimeData();
  1043. QString filename = mimeData->urls().at(0).toLocalFile();
  1044. BootGame(filename);
  1045. }
  1046. }
  1047. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  1048. if (IsSingleFileDropEvent(event)) {
  1049. event->acceptProposedAction();
  1050. }
  1051. }
  1052. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  1053. event->acceptProposedAction();
  1054. }
  1055. bool GMainWindow::ConfirmChangeGame() {
  1056. if (emu_thread == nullptr)
  1057. return true;
  1058. auto answer = QMessageBox::question(
  1059. this, tr("yuzu"),
  1060. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  1061. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1062. return answer != QMessageBox::No;
  1063. }
  1064. void GMainWindow::filterBarSetChecked(bool state) {
  1065. ui.action_Show_Filter_Bar->setChecked(state);
  1066. emit(OnToggleFilterBar());
  1067. }
  1068. void GMainWindow::UpdateUITheme() {
  1069. QStringList theme_paths(default_theme_paths);
  1070. if (UISettings::values.theme != UISettings::themes[0].second &&
  1071. !UISettings::values.theme.isEmpty()) {
  1072. const QString theme_uri(":" + UISettings::values.theme + "/style.qss");
  1073. QFile f(theme_uri);
  1074. if (f.open(QFile::ReadOnly | QFile::Text)) {
  1075. QTextStream ts(&f);
  1076. qApp->setStyleSheet(ts.readAll());
  1077. GMainWindow::setStyleSheet(ts.readAll());
  1078. } else {
  1079. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  1080. }
  1081. theme_paths.append(QStringList{":/icons/default", ":/icons/" + UISettings::values.theme});
  1082. QIcon::setThemeName(":/icons/" + UISettings::values.theme);
  1083. } else {
  1084. qApp->setStyleSheet("");
  1085. GMainWindow::setStyleSheet("");
  1086. theme_paths.append(QStringList{":/icons/default"});
  1087. QIcon::setThemeName(":/icons/default");
  1088. }
  1089. QIcon::setThemeSearchPaths(theme_paths);
  1090. emit UpdateThemedIcons();
  1091. }
  1092. #ifdef main
  1093. #undef main
  1094. #endif
  1095. int main(int argc, char* argv[]) {
  1096. MicroProfileOnThreadCreate("Frontend");
  1097. SCOPE_EXIT({ MicroProfileShutdown(); });
  1098. // Init settings params
  1099. QCoreApplication::setOrganizationName("yuzu team");
  1100. QCoreApplication::setApplicationName("yuzu");
  1101. QApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  1102. QApplication app(argc, argv);
  1103. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  1104. // generating shaders
  1105. setlocale(LC_ALL, "C");
  1106. GMainWindow main_window;
  1107. // After settings have been loaded by GMainWindow, apply the filter
  1108. main_window.show();
  1109. return app.exec();
  1110. }