main.cpp 34 KB

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