main.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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 <glad/glad.h>
  9. #define QT_NO_OPENGL
  10. #include <QDesktopWidget>
  11. #include <QFileDialog>
  12. #include <QMessageBox>
  13. #include <QtGui>
  14. #include <QtWidgets>
  15. #include "common/common_paths.h"
  16. #include "common/logging/backend.h"
  17. #include "common/logging/filter.h"
  18. #include "common/logging/log.h"
  19. #include "common/logging/text_formatter.h"
  20. #include "common/microprofile.h"
  21. #include "common/scm_rev.h"
  22. #include "common/scope_exit.h"
  23. #include "common/string_util.h"
  24. #include "core/core.h"
  25. #include "core/crypto/key_manager.h"
  26. #include "core/file_sys/vfs_real.h"
  27. #include "core/gdbstub/gdbstub.h"
  28. #include "core/loader/loader.h"
  29. #include "core/settings.h"
  30. #include "video_core/debug_utils/debug_utils.h"
  31. #include "yuzu/about_dialog.h"
  32. #include "yuzu/bootmanager.h"
  33. #include "yuzu/configuration/config.h"
  34. #include "yuzu/configuration/configure_dialog.h"
  35. #include "yuzu/debugger/console.h"
  36. #include "yuzu/debugger/graphics/graphics_breakpoints.h"
  37. #include "yuzu/debugger/graphics/graphics_surface.h"
  38. #include "yuzu/debugger/profiler.h"
  39. #include "yuzu/debugger/wait_tree.h"
  40. #include "yuzu/game_list.h"
  41. #include "yuzu/hotkeys.h"
  42. #include "yuzu/main.h"
  43. #include "yuzu/ui_settings.h"
  44. #ifdef QT_STATICPLUGIN
  45. Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
  46. #endif
  47. #ifdef _WIN32
  48. extern "C" {
  49. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  50. // graphics
  51. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  52. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  53. }
  54. #endif
  55. /**
  56. * "Callouts" are one-time instructional messages shown to the user. In the config settings, there
  57. * is a bitfield "callout_flags" options, used to track if a message has already been shown to the
  58. * user. This is 32-bits - if we have more than 32 callouts, we should retire and recyle old ones.
  59. */
  60. enum class CalloutFlag : uint32_t {
  61. Telemetry = 0x1,
  62. };
  63. static void ShowCalloutMessage(const QString& message, CalloutFlag flag) {
  64. if (UISettings::values.callout_flags & static_cast<uint32_t>(flag)) {
  65. return;
  66. }
  67. UISettings::values.callout_flags |= static_cast<uint32_t>(flag);
  68. QMessageBox msg;
  69. msg.setText(message);
  70. msg.setStandardButtons(QMessageBox::Ok);
  71. msg.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  72. msg.setStyleSheet("QLabel{min-width: 900px;}");
  73. msg.exec();
  74. }
  75. void GMainWindow::ShowCallouts() {}
  76. GMainWindow::GMainWindow()
  77. : config(new Config()), emu_thread(nullptr),
  78. vfs(std::make_shared<FileSys::RealVfsFilesystem>()) {
  79. debug_context = Tegra::DebugContext::Construct();
  80. setAcceptDrops(true);
  81. ui.setupUi(this);
  82. statusBar()->hide();
  83. default_theme_paths = QIcon::themeSearchPaths();
  84. UpdateUITheme();
  85. InitializeWidgets();
  86. InitializeDebugWidgets();
  87. InitializeRecentFileMenuActions();
  88. InitializeHotkeys();
  89. SetDefaultUIGeometry();
  90. RestoreUIState();
  91. ConnectMenuEvents();
  92. ConnectWidgetEvents();
  93. LOG_INFO(Frontend, "yuzu Version: {} | {}-{}", Common::g_build_name, Common::g_scm_branch,
  94. Common::g_scm_desc);
  95. setWindowTitle(QString("yuzu %1| %2-%3")
  96. .arg(Common::g_build_name, Common::g_scm_branch, Common::g_scm_desc));
  97. show();
  98. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  99. // Show one-time "callout" messages to the user
  100. ShowCallouts();
  101. QStringList args = QApplication::arguments();
  102. if (args.length() >= 2) {
  103. BootGame(args[1]);
  104. }
  105. }
  106. GMainWindow::~GMainWindow() {
  107. // will get automatically deleted otherwise
  108. if (render_window->parent() == nullptr)
  109. delete render_window;
  110. }
  111. void GMainWindow::InitializeWidgets() {
  112. render_window = new GRenderWindow(this, emu_thread.get());
  113. render_window->hide();
  114. game_list = new GameList(vfs, this);
  115. ui.horizontalLayout->addWidget(game_list);
  116. // Create status bar
  117. message_label = new QLabel();
  118. // Configured separately for left alignment
  119. message_label->setVisible(false);
  120. message_label->setFrameStyle(QFrame::NoFrame);
  121. message_label->setContentsMargins(4, 0, 4, 0);
  122. message_label->setAlignment(Qt::AlignLeft);
  123. statusBar()->addPermanentWidget(message_label, 1);
  124. emu_speed_label = new QLabel();
  125. emu_speed_label->setToolTip(
  126. tr("Current emulation speed. Values higher or lower than 100% "
  127. "indicate emulation is running faster or slower than a Switch."));
  128. game_fps_label = new QLabel();
  129. game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
  130. "This will vary from game to game and scene to scene."));
  131. emu_frametime_label = new QLabel();
  132. emu_frametime_label->setToolTip(
  133. tr("Time taken to emulate a Switch frame, not counting framelimiting or v-sync. For "
  134. "full-speed emulation this should be at most 16.67 ms."));
  135. for (auto& label : {emu_speed_label, game_fps_label, emu_frametime_label}) {
  136. label->setVisible(false);
  137. label->setFrameStyle(QFrame::NoFrame);
  138. label->setContentsMargins(4, 0, 4, 0);
  139. statusBar()->addPermanentWidget(label, 0);
  140. }
  141. statusBar()->setVisible(true);
  142. setStyleSheet("QStatusBar::item{border: none;}");
  143. }
  144. void GMainWindow::InitializeDebugWidgets() {
  145. QMenu* debug_menu = ui.menu_View_Debugging;
  146. #if MICROPROFILE_ENABLED
  147. microProfileDialog = new MicroProfileDialog(this);
  148. microProfileDialog->hide();
  149. debug_menu->addAction(microProfileDialog->toggleViewAction());
  150. #endif
  151. graphicsBreakpointsWidget = new GraphicsBreakPointsWidget(debug_context, this);
  152. addDockWidget(Qt::RightDockWidgetArea, graphicsBreakpointsWidget);
  153. graphicsBreakpointsWidget->hide();
  154. debug_menu->addAction(graphicsBreakpointsWidget->toggleViewAction());
  155. graphicsSurfaceWidget = new GraphicsSurfaceWidget(debug_context, this);
  156. addDockWidget(Qt::RightDockWidgetArea, graphicsSurfaceWidget);
  157. graphicsSurfaceWidget->hide();
  158. debug_menu->addAction(graphicsSurfaceWidget->toggleViewAction());
  159. waitTreeWidget = new WaitTreeWidget(this);
  160. addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
  161. waitTreeWidget->hide();
  162. debug_menu->addAction(waitTreeWidget->toggleViewAction());
  163. connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
  164. &WaitTreeWidget::OnEmulationStarting);
  165. connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
  166. &WaitTreeWidget::OnEmulationStopping);
  167. }
  168. void GMainWindow::InitializeRecentFileMenuActions() {
  169. for (int i = 0; i < max_recent_files_item; ++i) {
  170. actions_recent_files[i] = new QAction(this);
  171. actions_recent_files[i]->setVisible(false);
  172. connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile);
  173. ui.menu_recent_files->addAction(actions_recent_files[i]);
  174. }
  175. UpdateRecentFiles();
  176. }
  177. void GMainWindow::InitializeHotkeys() {
  178. hotkey_registry.RegisterHotkey("Main Window", "Load File", QKeySequence::Open);
  179. hotkey_registry.RegisterHotkey("Main Window", "Start Emulation");
  180. hotkey_registry.RegisterHotkey("Main Window", "Continue/Pause", QKeySequence(Qt::Key_F4));
  181. hotkey_registry.RegisterHotkey("Main Window", "Fullscreen", QKeySequence::FullScreen);
  182. hotkey_registry.RegisterHotkey("Main Window", "Exit Fullscreen", QKeySequence(Qt::Key_Escape),
  183. Qt::ApplicationShortcut);
  184. hotkey_registry.RegisterHotkey("Main Window", "Toggle Speed Limit", QKeySequence("CTRL+Z"),
  185. Qt::ApplicationShortcut);
  186. hotkey_registry.LoadHotkeys();
  187. connect(hotkey_registry.GetHotkey("Main Window", "Load File", this), &QShortcut::activated,
  188. this, &GMainWindow::OnMenuLoadFile);
  189. connect(hotkey_registry.GetHotkey("Main Window", "Start Emulation", this),
  190. &QShortcut::activated, this, &GMainWindow::OnStartGame);
  191. connect(hotkey_registry.GetHotkey("Main Window", "Continue/Pause", this), &QShortcut::activated,
  192. this, [&] {
  193. if (emulation_running) {
  194. if (emu_thread->IsRunning()) {
  195. OnPauseGame();
  196. } else {
  197. OnStartGame();
  198. }
  199. }
  200. });
  201. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  202. &QShortcut::activated, ui.action_Fullscreen, &QAction::trigger);
  203. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  204. &QShortcut::activatedAmbiguously, ui.action_Fullscreen, &QAction::trigger);
  205. connect(hotkey_registry.GetHotkey("Main Window", "Exit Fullscreen", this),
  206. &QShortcut::activated, this, [&] {
  207. if (emulation_running) {
  208. ui.action_Fullscreen->setChecked(false);
  209. ToggleFullscreen();
  210. }
  211. });
  212. connect(hotkey_registry.GetHotkey("Main Window", "Toggle Speed Limit", this),
  213. &QShortcut::activated, this, [&] {
  214. Settings::values.toggle_framelimit = !Settings::values.toggle_framelimit;
  215. UpdateStatusBar();
  216. });
  217. }
  218. void GMainWindow::SetDefaultUIGeometry() {
  219. // geometry: 55% of the window contents are in the upper screen half, 45% in the lower half
  220. const QRect screenRect = QApplication::desktop()->screenGeometry(this);
  221. const int w = screenRect.width() * 2 / 3;
  222. const int h = screenRect.height() / 2;
  223. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  224. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 55 / 100;
  225. setGeometry(x, y, w, h);
  226. }
  227. void GMainWindow::RestoreUIState() {
  228. restoreGeometry(UISettings::values.geometry);
  229. restoreState(UISettings::values.state);
  230. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  231. #if MICROPROFILE_ENABLED
  232. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  233. microProfileDialog->setVisible(UISettings::values.microprofile_visible);
  234. #endif
  235. game_list->LoadInterfaceLayout();
  236. ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode);
  237. ToggleWindowMode();
  238. ui.action_Fullscreen->setChecked(UISettings::values.fullscreen);
  239. ui.action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);
  240. OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked());
  241. ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar);
  242. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  243. ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);
  244. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  245. Debugger::ToggleConsole();
  246. }
  247. void GMainWindow::ConnectWidgetEvents() {
  248. connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
  249. connect(game_list, &GameList::OpenSaveFolderRequested, this,
  250. &GMainWindow::OnGameListOpenSaveFolder);
  251. connect(this, &GMainWindow::EmulationStarting, render_window,
  252. &GRenderWindow::OnEmulationStarting);
  253. connect(this, &GMainWindow::EmulationStopping, render_window,
  254. &GRenderWindow::OnEmulationStopping);
  255. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  256. }
  257. void GMainWindow::ConnectMenuEvents() {
  258. // File
  259. connect(ui.action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
  260. connect(ui.action_Load_Folder, &QAction::triggered, this, &GMainWindow::OnMenuLoadFolder);
  261. connect(ui.action_Select_Game_List_Root, &QAction::triggered, this,
  262. &GMainWindow::OnMenuSelectGameListRoot);
  263. connect(ui.action_Exit, &QAction::triggered, this, &QMainWindow::close);
  264. // Emulation
  265. connect(ui.action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
  266. connect(ui.action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
  267. connect(ui.action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
  268. connect(ui.action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
  269. // View
  270. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  271. &GMainWindow::ToggleWindowMode);
  272. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  273. &GMainWindow::OnDisplayTitleBars);
  274. ui.action_Show_Filter_Bar->setShortcut(tr("CTRL+F"));
  275. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  276. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  277. // Fullscreen
  278. ui.action_Fullscreen->setShortcut(
  279. hotkey_registry.GetHotkey("Main Window", "Fullscreen", this)->key());
  280. connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
  281. // Help
  282. connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
  283. }
  284. void GMainWindow::OnDisplayTitleBars(bool show) {
  285. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  286. if (show) {
  287. for (QDockWidget* widget : widgets) {
  288. QWidget* old = widget->titleBarWidget();
  289. widget->setTitleBarWidget(nullptr);
  290. if (old != nullptr)
  291. delete old;
  292. }
  293. } else {
  294. for (QDockWidget* widget : widgets) {
  295. QWidget* old = widget->titleBarWidget();
  296. widget->setTitleBarWidget(new QWidget());
  297. if (old != nullptr)
  298. delete old;
  299. }
  300. }
  301. }
  302. bool GMainWindow::SupportsRequiredGLExtensions() {
  303. QStringList unsupported_ext;
  304. if (!GLAD_GL_ARB_program_interface_query)
  305. unsupported_ext.append("ARB_program_interface_query");
  306. if (!GLAD_GL_ARB_separate_shader_objects)
  307. unsupported_ext.append("ARB_separate_shader_objects");
  308. if (!GLAD_GL_ARB_vertex_attrib_binding)
  309. unsupported_ext.append("ARB_vertex_attrib_binding");
  310. if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
  311. unsupported_ext.append("ARB_vertex_type_10f_11f_11f_rev");
  312. // Extensions required to support some texture formats.
  313. if (!GLAD_GL_EXT_texture_compression_s3tc)
  314. unsupported_ext.append("EXT_texture_compression_s3tc");
  315. if (!GLAD_GL_ARB_texture_compression_rgtc)
  316. unsupported_ext.append("ARB_texture_compression_rgtc");
  317. if (!GLAD_GL_ARB_texture_compression_bptc)
  318. unsupported_ext.append("ARB_texture_compression_bptc");
  319. if (!GLAD_GL_ARB_depth_buffer_float)
  320. unsupported_ext.append("ARB_depth_buffer_float");
  321. for (const QString& ext : unsupported_ext)
  322. LOG_CRITICAL(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  323. return unsupported_ext.empty();
  324. }
  325. bool GMainWindow::LoadROM(const QString& filename) {
  326. // Shutdown previous session if the emu thread is still active...
  327. if (emu_thread != nullptr)
  328. ShutdownGame();
  329. render_window->InitRenderTarget();
  330. render_window->MakeCurrent();
  331. if (!gladLoadGL()) {
  332. QMessageBox::critical(this, tr("Error while initializing OpenGL 3.3 Core!"),
  333. tr("Your GPU may not support OpenGL 3.3, or you do not "
  334. "have the latest graphics driver."));
  335. return false;
  336. }
  337. if (!SupportsRequiredGLExtensions()) {
  338. QMessageBox::critical(
  339. this, tr("Error while initializing OpenGL Core!"),
  340. tr("Your GPU may not support one or more required OpenGL extensions. Please "
  341. "ensure you have the latest graphics driver. See the log for more details."));
  342. return false;
  343. }
  344. Core::System& system{Core::System::GetInstance()};
  345. system.SetFilesystem(vfs);
  346. system.SetGPUDebugContext(debug_context);
  347. const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
  348. render_window->DoneCurrent();
  349. if (result != Core::System::ResultStatus::Success) {
  350. switch (result) {
  351. case Core::System::ResultStatus::ErrorGetLoader:
  352. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  353. QMessageBox::critical(this, tr("Error while loading ROM!"),
  354. tr("The ROM format is not supported."));
  355. break;
  356. case Core::System::ResultStatus::ErrorUnsupportedArch:
  357. LOG_CRITICAL(Frontend, "Unsupported architecture detected!", filename.toStdString());
  358. QMessageBox::critical(this, tr("Error while loading ROM!"),
  359. tr("The ROM uses currently unusable 32-bit architecture"));
  360. break;
  361. case Core::System::ResultStatus::ErrorSystemMode:
  362. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  363. QMessageBox::critical(this, tr("Error while loading ROM!"),
  364. tr("Could not determine the system mode."));
  365. break;
  366. case Core::System::ResultStatus::ErrorLoader_ErrorMissingKeys: {
  367. const auto reg_found = Core::Crypto::KeyManager::KeyFileExists(false);
  368. const auto title_found = Core::Crypto::KeyManager::KeyFileExists(true);
  369. std::string file_text;
  370. if (!reg_found && !title_found) {
  371. file_text = "A proper key file (prod.keys, dev.keys, or title.keys) could not be "
  372. "found. You will need to dump your keys from your switch to continue.";
  373. } else if (reg_found && title_found) {
  374. file_text =
  375. "Both key files were found in your config directory, but the correct key could"
  376. "not be found. You may be missing a titlekey or general key, depending on "
  377. "the game.";
  378. } else if (reg_found) {
  379. file_text =
  380. "The regular keys file (prod.keys/dev.keys) was found in your config, but the "
  381. "titlekeys file (title.keys) was not. You are either missing the correct "
  382. "titlekey or missing a general key required to decrypt the game.";
  383. } else {
  384. file_text = "The title keys file (title.keys) was found in your config, but "
  385. "the regular keys file (prod.keys/dev.keys) was not. Unfortunately, "
  386. "having the titlekey is not enough, you need additional general keys "
  387. "to properly decrypt the game. You should double-check to make sure "
  388. "your keys are correct.";
  389. }
  390. QMessageBox::critical(
  391. this, tr("Error while loading ROM!"),
  392. tr(("The game you are trying to load is encrypted and the required keys to load "
  393. "the game could not be found in your configuration. " +
  394. file_text + " Please refer to the yuzu wiki for help.")
  395. .c_str()));
  396. break;
  397. }
  398. case Core::System::ResultStatus::ErrorLoader_ErrorDecrypting: {
  399. QMessageBox::critical(
  400. this, tr("Error while loading ROM!"),
  401. tr("There was a general error while decrypting the game. This means that the keys "
  402. "necessary were found, but were either incorrect, the game itself was not a "
  403. "valid game or the game uses an unhandled cryptographic scheme. Please double "
  404. "check that you have the correct "
  405. "keys."));
  406. break;
  407. }
  408. case Core::System::ResultStatus::ErrorLoader_ErrorInvalidFormat:
  409. QMessageBox::critical(this, tr("Error while loading ROM!"),
  410. tr("The ROM format is not supported."));
  411. break;
  412. case Core::System::ResultStatus::ErrorVideoCore:
  413. QMessageBox::critical(
  414. this, tr("An error occurred initializing the video core."),
  415. tr("yuzu has encountered an error while running the video core, please see the "
  416. "log for more details."
  417. "For more information on accessing the log, please see the following page: "
  418. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  419. "to "
  420. "Upload the Log File</a>."
  421. "Ensure that you have the latest graphics drivers for your GPU."));
  422. break;
  423. default:
  424. QMessageBox::critical(
  425. this, tr("Error while loading ROM!"),
  426. tr("An unknown error occurred. Please see the log for more details."));
  427. break;
  428. }
  429. return false;
  430. }
  431. Core::Telemetry().AddField(Telemetry::FieldType::App, "Frontend", "Qt");
  432. return true;
  433. }
  434. void GMainWindow::BootGame(const QString& filename) {
  435. LOG_INFO(Frontend, "yuzu starting...");
  436. StoreRecentFile(filename); // Put the filename on top of the list
  437. if (!LoadROM(filename))
  438. return;
  439. // Create and start the emulation thread
  440. emu_thread = std::make_unique<EmuThread>(render_window);
  441. emit EmulationStarting(emu_thread.get());
  442. render_window->moveContext();
  443. emu_thread->start();
  444. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  445. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  446. // before the CPU continues
  447. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  448. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  449. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  450. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  451. // Update the GUI
  452. if (ui.action_Single_Window_Mode->isChecked()) {
  453. game_list->hide();
  454. }
  455. status_bar_update_timer.start(2000);
  456. render_window->show();
  457. render_window->setFocus();
  458. emulation_running = true;
  459. if (ui.action_Fullscreen->isChecked()) {
  460. ShowFullscreen();
  461. }
  462. OnStartGame();
  463. }
  464. void GMainWindow::ShutdownGame() {
  465. emu_thread->RequestStop();
  466. emit EmulationStopping();
  467. // Wait for emulation thread to complete and delete it
  468. emu_thread->wait();
  469. emu_thread = nullptr;
  470. // The emulation is stopped, so closing the window or not does not matter anymore
  471. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  472. // Update the GUI
  473. ui.action_Start->setEnabled(false);
  474. ui.action_Start->setText(tr("Start"));
  475. ui.action_Pause->setEnabled(false);
  476. ui.action_Stop->setEnabled(false);
  477. render_window->hide();
  478. game_list->show();
  479. game_list->setFilterFocus();
  480. // Disable status bar updates
  481. status_bar_update_timer.stop();
  482. message_label->setVisible(false);
  483. emu_speed_label->setVisible(false);
  484. game_fps_label->setVisible(false);
  485. emu_frametime_label->setVisible(false);
  486. emulation_running = false;
  487. }
  488. void GMainWindow::StoreRecentFile(const QString& filename) {
  489. UISettings::values.recent_files.prepend(filename);
  490. UISettings::values.recent_files.removeDuplicates();
  491. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  492. UISettings::values.recent_files.removeLast();
  493. }
  494. UpdateRecentFiles();
  495. }
  496. void GMainWindow::UpdateRecentFiles() {
  497. const int num_recent_files =
  498. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  499. for (int i = 0; i < num_recent_files; i++) {
  500. const QString text = QString("&%1. %2").arg(i + 1).arg(
  501. QFileInfo(UISettings::values.recent_files[i]).fileName());
  502. actions_recent_files[i]->setText(text);
  503. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  504. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  505. actions_recent_files[i]->setVisible(true);
  506. }
  507. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  508. actions_recent_files[j]->setVisible(false);
  509. }
  510. // Enable the recent files menu if the list isn't empty
  511. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  512. }
  513. void GMainWindow::OnGameListLoadFile(QString game_path) {
  514. BootGame(game_path);
  515. }
  516. void GMainWindow::OnGameListOpenSaveFolder(u64 program_id) {
  517. UNIMPLEMENTED();
  518. }
  519. void GMainWindow::OnMenuLoadFile() {
  520. QString extensions;
  521. for (const auto& piece : game_list->supported_file_extensions)
  522. extensions += "*." + piece + " ";
  523. extensions += "main ";
  524. QString file_filter = tr("Switch Executable") + " (" + extensions + ")";
  525. file_filter += ";;" + tr("All Files (*.*)");
  526. QString filename = QFileDialog::getOpenFileName(this, tr("Load File"),
  527. UISettings::values.roms_path, file_filter);
  528. if (!filename.isEmpty()) {
  529. UISettings::values.roms_path = QFileInfo(filename).path();
  530. BootGame(filename);
  531. }
  532. }
  533. void GMainWindow::OnMenuLoadFolder() {
  534. const QString dir_path =
  535. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  536. if (dir_path.isNull()) {
  537. return;
  538. }
  539. const QDir dir{dir_path};
  540. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  541. if (matching_main.size() == 1) {
  542. BootGame(dir.path() + DIR_SEP + matching_main[0]);
  543. } else {
  544. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  545. tr("The directory you have selected does not contain a 'main' file."));
  546. }
  547. }
  548. void GMainWindow::OnMenuSelectGameListRoot() {
  549. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  550. if (!dir_path.isEmpty()) {
  551. UISettings::values.gamedir = dir_path;
  552. game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan);
  553. }
  554. }
  555. void GMainWindow::OnMenuRecentFile() {
  556. QAction* action = qobject_cast<QAction*>(sender());
  557. assert(action);
  558. const QString filename = action->data().toString();
  559. if (QFileInfo::exists(filename)) {
  560. BootGame(filename);
  561. } else {
  562. // Display an error message and remove the file from the list.
  563. QMessageBox::information(this, tr("File not found"),
  564. tr("File \"%1\" not found").arg(filename));
  565. UISettings::values.recent_files.removeOne(filename);
  566. UpdateRecentFiles();
  567. }
  568. }
  569. void GMainWindow::OnStartGame() {
  570. emu_thread->SetRunning(true);
  571. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  572. qRegisterMetaType<std::string>("std::string");
  573. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  574. ui.action_Start->setEnabled(false);
  575. ui.action_Start->setText(tr("Continue"));
  576. ui.action_Pause->setEnabled(true);
  577. ui.action_Stop->setEnabled(true);
  578. }
  579. void GMainWindow::OnPauseGame() {
  580. emu_thread->SetRunning(false);
  581. ui.action_Start->setEnabled(true);
  582. ui.action_Pause->setEnabled(false);
  583. ui.action_Stop->setEnabled(true);
  584. }
  585. void GMainWindow::OnStopGame() {
  586. ShutdownGame();
  587. }
  588. void GMainWindow::ToggleFullscreen() {
  589. if (!emulation_running) {
  590. return;
  591. }
  592. if (ui.action_Fullscreen->isChecked()) {
  593. ShowFullscreen();
  594. } else {
  595. HideFullscreen();
  596. }
  597. }
  598. void GMainWindow::ShowFullscreen() {
  599. if (ui.action_Single_Window_Mode->isChecked()) {
  600. UISettings::values.geometry = saveGeometry();
  601. ui.menubar->hide();
  602. statusBar()->hide();
  603. showFullScreen();
  604. } else {
  605. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  606. render_window->showFullScreen();
  607. }
  608. }
  609. void GMainWindow::HideFullscreen() {
  610. if (ui.action_Single_Window_Mode->isChecked()) {
  611. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  612. ui.menubar->show();
  613. showNormal();
  614. restoreGeometry(UISettings::values.geometry);
  615. } else {
  616. render_window->showNormal();
  617. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  618. }
  619. }
  620. void GMainWindow::ToggleWindowMode() {
  621. if (ui.action_Single_Window_Mode->isChecked()) {
  622. // Render in the main window...
  623. render_window->BackupGeometry();
  624. ui.horizontalLayout->addWidget(render_window);
  625. render_window->setFocusPolicy(Qt::ClickFocus);
  626. if (emulation_running) {
  627. render_window->setVisible(true);
  628. render_window->setFocus();
  629. game_list->hide();
  630. }
  631. } else {
  632. // Render in a separate window...
  633. ui.horizontalLayout->removeWidget(render_window);
  634. render_window->setParent(nullptr);
  635. render_window->setFocusPolicy(Qt::NoFocus);
  636. if (emulation_running) {
  637. render_window->setVisible(true);
  638. render_window->RestoreGeometry();
  639. game_list->show();
  640. }
  641. }
  642. }
  643. void GMainWindow::OnConfigure() {
  644. ConfigureDialog configureDialog(this, hotkey_registry);
  645. auto old_theme = UISettings::values.theme;
  646. auto result = configureDialog.exec();
  647. if (result == QDialog::Accepted) {
  648. configureDialog.applyConfiguration();
  649. if (UISettings::values.theme != old_theme)
  650. UpdateUITheme();
  651. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  652. config->Save();
  653. }
  654. }
  655. void GMainWindow::OnAbout() {
  656. AboutDialog aboutDialog(this);
  657. aboutDialog.exec();
  658. }
  659. void GMainWindow::OnToggleFilterBar() {
  660. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  661. if (ui.action_Show_Filter_Bar->isChecked()) {
  662. game_list->setFilterFocus();
  663. } else {
  664. game_list->clearFilter();
  665. }
  666. }
  667. void GMainWindow::UpdateStatusBar() {
  668. if (emu_thread == nullptr) {
  669. status_bar_update_timer.stop();
  670. return;
  671. }
  672. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  673. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  674. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  675. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  676. emu_speed_label->setVisible(true);
  677. game_fps_label->setVisible(true);
  678. emu_frametime_label->setVisible(true);
  679. }
  680. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  681. QMessageBox::StandardButton answer;
  682. QString status_message;
  683. const QString common_message = tr(
  684. "The game you are trying to load requires additional files from your Switch to be dumped "
  685. "before playing.<br/><br/>For more information on dumping these files, please see the "
  686. "following wiki page: <a "
  687. "href='https://yuzu-emu.org/wiki/"
  688. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  689. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to quit "
  690. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  691. "data, or other bugs.");
  692. switch (result) {
  693. case Core::System::ResultStatus::ErrorSystemFiles: {
  694. QString message = "yuzu was unable to locate a Switch system archive";
  695. if (!details.empty()) {
  696. message.append(tr(": %1. ").arg(details.c_str()));
  697. } else {
  698. message.append(". ");
  699. }
  700. message.append(common_message);
  701. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  702. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  703. status_message = "System Archive Missing";
  704. break;
  705. }
  706. case Core::System::ResultStatus::ErrorSharedFont: {
  707. QString message = tr("yuzu was unable to locate the Switch shared fonts. ");
  708. message.append(common_message);
  709. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  710. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  711. status_message = "Shared Font Missing";
  712. break;
  713. }
  714. default:
  715. answer = QMessageBox::question(
  716. this, tr("Fatal Error"),
  717. tr("yuzu has encountered a fatal error, please see the log for more details. "
  718. "For more information on accessing the log, please see the following page: "
  719. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How to "
  720. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game list? "
  721. "Continuing emulation may result in crashes, corrupted save data, or other bugs."),
  722. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  723. status_message = "Fatal Error encountered";
  724. break;
  725. }
  726. if (answer == QMessageBox::Yes) {
  727. if (emu_thread) {
  728. ShutdownGame();
  729. }
  730. } else {
  731. // Only show the message if the game is still running.
  732. if (emu_thread) {
  733. emu_thread->SetRunning(true);
  734. message_label->setText(status_message);
  735. message_label->setVisible(true);
  736. }
  737. }
  738. }
  739. bool GMainWindow::ConfirmClose() {
  740. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  741. return true;
  742. QMessageBox::StandardButton answer =
  743. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  744. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  745. return answer != QMessageBox::No;
  746. }
  747. void GMainWindow::closeEvent(QCloseEvent* event) {
  748. if (!ConfirmClose()) {
  749. event->ignore();
  750. return;
  751. }
  752. if (ui.action_Fullscreen->isChecked()) {
  753. UISettings::values.geometry = saveGeometry();
  754. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  755. }
  756. UISettings::values.state = saveState();
  757. #if MICROPROFILE_ENABLED
  758. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  759. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  760. #endif
  761. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  762. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  763. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  764. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  765. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  766. UISettings::values.first_start = false;
  767. game_list->SaveInterfaceLayout();
  768. hotkey_registry.SaveHotkeys();
  769. // Shutdown session if the emu thread is active...
  770. if (emu_thread != nullptr)
  771. ShutdownGame();
  772. render_window->close();
  773. QWidget::closeEvent(event);
  774. }
  775. static bool IsSingleFileDropEvent(QDropEvent* event) {
  776. const QMimeData* mimeData = event->mimeData();
  777. return mimeData->hasUrls() && mimeData->urls().length() == 1;
  778. }
  779. void GMainWindow::dropEvent(QDropEvent* event) {
  780. if (IsSingleFileDropEvent(event) && ConfirmChangeGame()) {
  781. const QMimeData* mimeData = event->mimeData();
  782. QString filename = mimeData->urls().at(0).toLocalFile();
  783. BootGame(filename);
  784. }
  785. }
  786. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  787. if (IsSingleFileDropEvent(event)) {
  788. event->acceptProposedAction();
  789. }
  790. }
  791. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  792. event->acceptProposedAction();
  793. }
  794. bool GMainWindow::ConfirmChangeGame() {
  795. if (emu_thread == nullptr)
  796. return true;
  797. auto answer = QMessageBox::question(
  798. this, tr("yuzu"),
  799. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  800. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  801. return answer != QMessageBox::No;
  802. }
  803. void GMainWindow::filterBarSetChecked(bool state) {
  804. ui.action_Show_Filter_Bar->setChecked(state);
  805. emit(OnToggleFilterBar());
  806. }
  807. void GMainWindow::UpdateUITheme() {
  808. QStringList theme_paths(default_theme_paths);
  809. if (UISettings::values.theme != UISettings::themes[0].second &&
  810. !UISettings::values.theme.isEmpty()) {
  811. const QString theme_uri(":" + UISettings::values.theme + "/style.qss");
  812. QFile f(theme_uri);
  813. if (f.open(QFile::ReadOnly | QFile::Text)) {
  814. QTextStream ts(&f);
  815. qApp->setStyleSheet(ts.readAll());
  816. GMainWindow::setStyleSheet(ts.readAll());
  817. } else {
  818. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  819. }
  820. theme_paths.append(QStringList{":/icons/default", ":/icons/" + UISettings::values.theme});
  821. QIcon::setThemeName(":/icons/" + UISettings::values.theme);
  822. } else {
  823. qApp->setStyleSheet("");
  824. GMainWindow::setStyleSheet("");
  825. theme_paths.append(QStringList{":/icons/default"});
  826. QIcon::setThemeName(":/icons/default");
  827. }
  828. QIcon::setThemeSearchPaths(theme_paths);
  829. emit UpdateThemedIcons();
  830. }
  831. #ifdef main
  832. #undef main
  833. #endif
  834. static void InitializeLogging() {
  835. Log::Filter log_filter;
  836. log_filter.ParseFilterString(Settings::values.log_filter);
  837. Log::SetGlobalFilter(log_filter);
  838. const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
  839. FileUtil::CreateFullPath(log_dir);
  840. Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
  841. }
  842. int main(int argc, char* argv[]) {
  843. MicroProfileOnThreadCreate("Frontend");
  844. SCOPE_EXIT({ MicroProfileShutdown(); });
  845. // Init settings params
  846. QCoreApplication::setOrganizationName("yuzu team");
  847. QCoreApplication::setApplicationName("yuzu");
  848. QApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  849. QApplication app(argc, argv);
  850. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  851. // generating shaders
  852. setlocale(LC_ALL, "C");
  853. GMainWindow main_window;
  854. // After settings have been loaded by GMainWindow, apply the filter
  855. InitializeLogging();
  856. main_window.show();
  857. return app.exec();
  858. }