main.cpp 33 KB

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