main.cpp 34 KB

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