main.cpp 35 KB

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