main.cpp 36 KB

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