main.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  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 <fmt/ostream.h>
  9. #include <glad/glad.h>
  10. #define QT_NO_OPENGL
  11. #include <QDesktopWidget>
  12. #include <QFileDialog>
  13. #include <QMessageBox>
  14. #include <QtGui>
  15. #include <QtWidgets>
  16. #include "common/common_paths.h"
  17. #include "common/logging/backend.h"
  18. #include "common/logging/filter.h"
  19. #include "common/logging/log.h"
  20. #include "common/logging/text_formatter.h"
  21. #include "common/microprofile.h"
  22. #include "common/scm_rev.h"
  23. #include "common/scope_exit.h"
  24. #include "common/string_util.h"
  25. #include "core/core.h"
  26. #include "core/crypto/key_manager.h"
  27. #include "core/file_sys/bis_factory.h"
  28. #include "core/file_sys/card_image.h"
  29. #include "core/file_sys/registered_cache.h"
  30. #include "core/file_sys/savedata_factory.h"
  31. #include "core/file_sys/vfs_real.h"
  32. #include "core/gdbstub/gdbstub.h"
  33. #include "core/loader/loader.h"
  34. #include "core/settings.h"
  35. #include "video_core/debug_utils/debug_utils.h"
  36. #include "yuzu/about_dialog.h"
  37. #include "yuzu/bootmanager.h"
  38. #include "yuzu/configuration/config.h"
  39. #include "yuzu/configuration/configure_dialog.h"
  40. #include "yuzu/debugger/console.h"
  41. #include "yuzu/debugger/graphics/graphics_breakpoints.h"
  42. #include "yuzu/debugger/graphics/graphics_surface.h"
  43. #include "yuzu/debugger/profiler.h"
  44. #include "yuzu/debugger/wait_tree.h"
  45. #include "yuzu/game_list.h"
  46. #include "yuzu/hotkeys.h"
  47. #include "yuzu/main.h"
  48. #include "yuzu/ui_settings.h"
  49. #ifdef QT_STATICPLUGIN
  50. Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
  51. #endif
  52. #ifdef _WIN32
  53. extern "C" {
  54. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  55. // graphics
  56. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  57. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  58. }
  59. #endif
  60. /**
  61. * "Callouts" are one-time instructional messages shown to the user. In the config settings, there
  62. * is a bitfield "callout_flags" options, used to track if a message has already been shown to the
  63. * user. This is 32-bits - if we have more than 32 callouts, we should retire and recyle old ones.
  64. */
  65. enum class CalloutFlag : uint32_t {
  66. Telemetry = 0x1,
  67. };
  68. static void ShowCalloutMessage(const QString& message, CalloutFlag flag) {
  69. if (UISettings::values.callout_flags & static_cast<uint32_t>(flag)) {
  70. return;
  71. }
  72. UISettings::values.callout_flags |= static_cast<uint32_t>(flag);
  73. QMessageBox msg;
  74. msg.setText(message);
  75. msg.setStandardButtons(QMessageBox::Ok);
  76. msg.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  77. msg.setStyleSheet("QLabel{min-width: 900px;}");
  78. msg.exec();
  79. }
  80. void GMainWindow::ShowCallouts() {}
  81. const int GMainWindow::max_recent_files_item;
  82. GMainWindow::GMainWindow()
  83. : config(new Config()), emu_thread(nullptr),
  84. vfs(std::make_shared<FileSys::RealVfsFilesystem>()) {
  85. debug_context = Tegra::DebugContext::Construct();
  86. setAcceptDrops(true);
  87. ui.setupUi(this);
  88. statusBar()->hide();
  89. default_theme_paths = QIcon::themeSearchPaths();
  90. UpdateUITheme();
  91. InitializeWidgets();
  92. InitializeDebugWidgets();
  93. InitializeRecentFileMenuActions();
  94. InitializeHotkeys();
  95. SetDefaultUIGeometry();
  96. RestoreUIState();
  97. ConnectMenuEvents();
  98. ConnectWidgetEvents();
  99. LOG_INFO(Frontend, "yuzu Version: {} | {}-{}", Common::g_build_name, Common::g_scm_branch,
  100. Common::g_scm_desc);
  101. setWindowTitle(QString("yuzu %1| %2-%3")
  102. .arg(Common::g_build_name, Common::g_scm_branch, Common::g_scm_desc));
  103. show();
  104. // Necessary to load titles from nand in gamelist.
  105. Service::FileSystem::CreateFactories(vfs);
  106. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  107. // Show one-time "callout" messages to the user
  108. ShowCallouts();
  109. QStringList args = QApplication::arguments();
  110. if (args.length() >= 2) {
  111. BootGame(args[1]);
  112. }
  113. }
  114. GMainWindow::~GMainWindow() {
  115. // will get automatically deleted otherwise
  116. if (render_window->parent() == nullptr)
  117. delete render_window;
  118. }
  119. void GMainWindow::InitializeWidgets() {
  120. render_window = new GRenderWindow(this, emu_thread.get());
  121. render_window->hide();
  122. game_list = new GameList(vfs, this);
  123. ui.horizontalLayout->addWidget(game_list);
  124. // Create status bar
  125. message_label = new QLabel();
  126. // Configured separately for left alignment
  127. message_label->setVisible(false);
  128. message_label->setFrameStyle(QFrame::NoFrame);
  129. message_label->setContentsMargins(4, 0, 4, 0);
  130. message_label->setAlignment(Qt::AlignLeft);
  131. statusBar()->addPermanentWidget(message_label, 1);
  132. emu_speed_label = new QLabel();
  133. emu_speed_label->setToolTip(
  134. tr("Current emulation speed. Values higher or lower than 100% "
  135. "indicate emulation is running faster or slower than a Switch."));
  136. game_fps_label = new QLabel();
  137. game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
  138. "This will vary from game to game and scene to scene."));
  139. emu_frametime_label = new QLabel();
  140. emu_frametime_label->setToolTip(
  141. tr("Time taken to emulate a Switch frame, not counting framelimiting or v-sync. For "
  142. "full-speed emulation this should be at most 16.67 ms."));
  143. for (auto& label : {emu_speed_label, game_fps_label, emu_frametime_label}) {
  144. label->setVisible(false);
  145. label->setFrameStyle(QFrame::NoFrame);
  146. label->setContentsMargins(4, 0, 4, 0);
  147. statusBar()->addPermanentWidget(label, 0);
  148. }
  149. statusBar()->setVisible(true);
  150. setStyleSheet("QStatusBar::item{border: none;}");
  151. }
  152. void GMainWindow::InitializeDebugWidgets() {
  153. QMenu* debug_menu = ui.menu_View_Debugging;
  154. #if MICROPROFILE_ENABLED
  155. microProfileDialog = new MicroProfileDialog(this);
  156. microProfileDialog->hide();
  157. debug_menu->addAction(microProfileDialog->toggleViewAction());
  158. #endif
  159. graphicsBreakpointsWidget = new GraphicsBreakPointsWidget(debug_context, this);
  160. addDockWidget(Qt::RightDockWidgetArea, graphicsBreakpointsWidget);
  161. graphicsBreakpointsWidget->hide();
  162. debug_menu->addAction(graphicsBreakpointsWidget->toggleViewAction());
  163. graphicsSurfaceWidget = new GraphicsSurfaceWidget(debug_context, this);
  164. addDockWidget(Qt::RightDockWidgetArea, graphicsSurfaceWidget);
  165. graphicsSurfaceWidget->hide();
  166. debug_menu->addAction(graphicsSurfaceWidget->toggleViewAction());
  167. waitTreeWidget = new WaitTreeWidget(this);
  168. addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
  169. waitTreeWidget->hide();
  170. debug_menu->addAction(waitTreeWidget->toggleViewAction());
  171. connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
  172. &WaitTreeWidget::OnEmulationStarting);
  173. connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
  174. &WaitTreeWidget::OnEmulationStopping);
  175. }
  176. void GMainWindow::InitializeRecentFileMenuActions() {
  177. for (int i = 0; i < max_recent_files_item; ++i) {
  178. actions_recent_files[i] = new QAction(this);
  179. actions_recent_files[i]->setVisible(false);
  180. connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile);
  181. ui.menu_recent_files->addAction(actions_recent_files[i]);
  182. }
  183. ui.menu_recent_files->addSeparator();
  184. QAction* action_clear_recent_files = new QAction(this);
  185. action_clear_recent_files->setText(tr("Clear Recent Files"));
  186. connect(action_clear_recent_files, &QAction::triggered, this, [this] {
  187. UISettings::values.recent_files.clear();
  188. UpdateRecentFiles();
  189. });
  190. ui.menu_recent_files->addAction(action_clear_recent_files);
  191. UpdateRecentFiles();
  192. }
  193. void GMainWindow::InitializeHotkeys() {
  194. hotkey_registry.RegisterHotkey("Main Window", "Load File", QKeySequence::Open);
  195. hotkey_registry.RegisterHotkey("Main Window", "Start Emulation");
  196. hotkey_registry.RegisterHotkey("Main Window", "Continue/Pause", QKeySequence(Qt::Key_F4));
  197. hotkey_registry.RegisterHotkey("Main Window", "Restart", QKeySequence(Qt::Key_F5));
  198. hotkey_registry.RegisterHotkey("Main Window", "Fullscreen", QKeySequence::FullScreen);
  199. hotkey_registry.RegisterHotkey("Main Window", "Exit Fullscreen", QKeySequence(Qt::Key_Escape),
  200. Qt::ApplicationShortcut);
  201. hotkey_registry.RegisterHotkey("Main Window", "Toggle Speed Limit", QKeySequence("CTRL+Z"),
  202. Qt::ApplicationShortcut);
  203. hotkey_registry.RegisterHotkey("Main Window", "Increase Speed Limit", QKeySequence("+"),
  204. Qt::ApplicationShortcut);
  205. hotkey_registry.RegisterHotkey("Main Window", "Decrease Speed Limit", QKeySequence("-"),
  206. Qt::ApplicationShortcut);
  207. hotkey_registry.LoadHotkeys();
  208. connect(hotkey_registry.GetHotkey("Main Window", "Load File", this), &QShortcut::activated,
  209. this, &GMainWindow::OnMenuLoadFile);
  210. connect(hotkey_registry.GetHotkey("Main Window", "Start Emulation", this),
  211. &QShortcut::activated, this, &GMainWindow::OnStartGame);
  212. connect(hotkey_registry.GetHotkey("Main Window", "Continue/Pause", this), &QShortcut::activated,
  213. this, [&] {
  214. if (emulation_running) {
  215. if (emu_thread->IsRunning()) {
  216. OnPauseGame();
  217. } else {
  218. OnStartGame();
  219. }
  220. }
  221. });
  222. connect(hotkey_registry.GetHotkey("Main Window", "Restart", this), &QShortcut::activated, this,
  223. [this] {
  224. if (!Core::System::GetInstance().IsPoweredOn())
  225. return;
  226. BootGame(QString(game_path));
  227. });
  228. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  229. &QShortcut::activated, ui.action_Fullscreen, &QAction::trigger);
  230. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  231. &QShortcut::activatedAmbiguously, ui.action_Fullscreen, &QAction::trigger);
  232. connect(hotkey_registry.GetHotkey("Main Window", "Exit Fullscreen", this),
  233. &QShortcut::activated, this, [&] {
  234. if (emulation_running) {
  235. ui.action_Fullscreen->setChecked(false);
  236. ToggleFullscreen();
  237. }
  238. });
  239. connect(hotkey_registry.GetHotkey("Main Window", "Toggle Speed Limit", this),
  240. &QShortcut::activated, this, [&] {
  241. Settings::values.use_frame_limit = !Settings::values.use_frame_limit;
  242. UpdateStatusBar();
  243. });
  244. constexpr u16 SPEED_LIMIT_STEP = 5;
  245. connect(hotkey_registry.GetHotkey("Main Window", "Increase Speed Limit", this),
  246. &QShortcut::activated, this, [&] {
  247. if (Settings::values.frame_limit < 9999 - SPEED_LIMIT_STEP) {
  248. Settings::values.frame_limit += SPEED_LIMIT_STEP;
  249. UpdateStatusBar();
  250. }
  251. });
  252. connect(hotkey_registry.GetHotkey("Main Window", "Decrease Speed Limit", this),
  253. &QShortcut::activated, this, [&] {
  254. if (Settings::values.frame_limit > SPEED_LIMIT_STEP) {
  255. Settings::values.frame_limit -= SPEED_LIMIT_STEP;
  256. UpdateStatusBar();
  257. }
  258. });
  259. }
  260. void GMainWindow::SetDefaultUIGeometry() {
  261. // geometry: 55% of the window contents are in the upper screen half, 45% in the lower half
  262. const QRect screenRect = QApplication::desktop()->screenGeometry(this);
  263. const int w = screenRect.width() * 2 / 3;
  264. const int h = screenRect.height() / 2;
  265. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  266. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 55 / 100;
  267. setGeometry(x, y, w, h);
  268. }
  269. void GMainWindow::RestoreUIState() {
  270. restoreGeometry(UISettings::values.geometry);
  271. restoreState(UISettings::values.state);
  272. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  273. #if MICROPROFILE_ENABLED
  274. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  275. microProfileDialog->setVisible(UISettings::values.microprofile_visible);
  276. #endif
  277. game_list->LoadInterfaceLayout();
  278. ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode);
  279. ToggleWindowMode();
  280. ui.action_Fullscreen->setChecked(UISettings::values.fullscreen);
  281. ui.action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);
  282. OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked());
  283. ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar);
  284. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  285. ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);
  286. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  287. Debugger::ToggleConsole();
  288. }
  289. void GMainWindow::ConnectWidgetEvents() {
  290. connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
  291. connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
  292. connect(this, &GMainWindow::EmulationStarting, render_window,
  293. &GRenderWindow::OnEmulationStarting);
  294. connect(this, &GMainWindow::EmulationStopping, render_window,
  295. &GRenderWindow::OnEmulationStopping);
  296. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  297. }
  298. void GMainWindow::ConnectMenuEvents() {
  299. // File
  300. connect(ui.action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
  301. connect(ui.action_Load_Folder, &QAction::triggered, this, &GMainWindow::OnMenuLoadFolder);
  302. connect(ui.action_Install_File_NAND, &QAction::triggered, this,
  303. &GMainWindow::OnMenuInstallToNAND);
  304. connect(ui.action_Select_Game_List_Root, &QAction::triggered, this,
  305. &GMainWindow::OnMenuSelectGameListRoot);
  306. connect(ui.action_Exit, &QAction::triggered, this, &QMainWindow::close);
  307. // Emulation
  308. connect(ui.action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
  309. connect(ui.action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
  310. connect(ui.action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
  311. connect(ui.action_Restart, &QAction::triggered, this, [this] { BootGame(QString(game_path)); });
  312. connect(ui.action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
  313. // View
  314. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  315. &GMainWindow::ToggleWindowMode);
  316. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  317. &GMainWindow::OnDisplayTitleBars);
  318. ui.action_Show_Filter_Bar->setShortcut(tr("CTRL+F"));
  319. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  320. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  321. // Fullscreen
  322. ui.action_Fullscreen->setShortcut(
  323. hotkey_registry.GetHotkey("Main Window", "Fullscreen", this)->key());
  324. connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
  325. // Help
  326. connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
  327. }
  328. void GMainWindow::OnDisplayTitleBars(bool show) {
  329. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  330. if (show) {
  331. for (QDockWidget* widget : widgets) {
  332. QWidget* old = widget->titleBarWidget();
  333. widget->setTitleBarWidget(nullptr);
  334. if (old != nullptr)
  335. delete old;
  336. }
  337. } else {
  338. for (QDockWidget* widget : widgets) {
  339. QWidget* old = widget->titleBarWidget();
  340. widget->setTitleBarWidget(new QWidget());
  341. if (old != nullptr)
  342. delete old;
  343. }
  344. }
  345. }
  346. bool GMainWindow::SupportsRequiredGLExtensions() {
  347. QStringList unsupported_ext;
  348. if (!GLAD_GL_ARB_program_interface_query)
  349. unsupported_ext.append("ARB_program_interface_query");
  350. if (!GLAD_GL_ARB_separate_shader_objects)
  351. unsupported_ext.append("ARB_separate_shader_objects");
  352. if (!GLAD_GL_ARB_vertex_attrib_binding)
  353. unsupported_ext.append("ARB_vertex_attrib_binding");
  354. if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
  355. unsupported_ext.append("ARB_vertex_type_10f_11f_11f_rev");
  356. if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
  357. unsupported_ext.append("ARB_texture_mirror_clamp_to_edge");
  358. // Extensions required to support some texture formats.
  359. if (!GLAD_GL_EXT_texture_compression_s3tc)
  360. unsupported_ext.append("EXT_texture_compression_s3tc");
  361. if (!GLAD_GL_ARB_texture_compression_rgtc)
  362. unsupported_ext.append("ARB_texture_compression_rgtc");
  363. if (!GLAD_GL_ARB_texture_compression_bptc)
  364. unsupported_ext.append("ARB_texture_compression_bptc");
  365. if (!GLAD_GL_ARB_depth_buffer_float)
  366. unsupported_ext.append("ARB_depth_buffer_float");
  367. for (const QString& ext : unsupported_ext)
  368. LOG_CRITICAL(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  369. return unsupported_ext.empty();
  370. }
  371. bool GMainWindow::LoadROM(const QString& filename) {
  372. // Shutdown previous session if the emu thread is still active...
  373. if (emu_thread != nullptr)
  374. ShutdownGame();
  375. render_window->InitRenderTarget();
  376. render_window->MakeCurrent();
  377. if (!gladLoadGL()) {
  378. QMessageBox::critical(this, tr("Error while initializing OpenGL 3.3 Core!"),
  379. tr("Your GPU may not support OpenGL 3.3, or you do not "
  380. "have the latest graphics driver."));
  381. return false;
  382. }
  383. if (!SupportsRequiredGLExtensions()) {
  384. QMessageBox::critical(
  385. this, tr("Error while initializing OpenGL Core!"),
  386. tr("Your GPU may not support one or more required OpenGL extensions. Please "
  387. "ensure you have the latest graphics driver. See the log for more details."));
  388. return false;
  389. }
  390. Core::System& system{Core::System::GetInstance()};
  391. system.SetFilesystem(vfs);
  392. system.SetGPUDebugContext(debug_context);
  393. const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
  394. render_window->DoneCurrent();
  395. if (result != Core::System::ResultStatus::Success) {
  396. switch (result) {
  397. case Core::System::ResultStatus::ErrorGetLoader:
  398. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  399. QMessageBox::critical(this, tr("Error while loading ROM!"),
  400. tr("The ROM format is not supported."));
  401. break;
  402. case Core::System::ResultStatus::ErrorSystemMode:
  403. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  404. QMessageBox::critical(this, tr("Error while loading ROM!"),
  405. tr("Could not determine the system mode."));
  406. break;
  407. case Core::System::ResultStatus::ErrorVideoCore:
  408. QMessageBox::critical(
  409. this, tr("An error occurred initializing the video core."),
  410. tr("yuzu has encountered an error while running the video core, please see the "
  411. "log for more details."
  412. "For more information on accessing the log, please see the following page: "
  413. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  414. "to "
  415. "Upload the Log File</a>."
  416. "Ensure that you have the latest graphics drivers for your GPU."));
  417. break;
  418. default:
  419. if (static_cast<u32>(result) >
  420. static_cast<u32>(Core::System::ResultStatus::ErrorLoader)) {
  421. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  422. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  423. const u16 error_id = static_cast<u16>(result) - loader_id;
  424. QMessageBox::critical(
  425. this, tr("Error while loading ROM!"),
  426. QString::fromStdString(fmt::format(
  427. "While attempting to load the ROM requested, an error occured. Please "
  428. "refer to the yuzu wiki for more information or the yuzu discord for "
  429. "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
  430. loader_id, error_id, static_cast<Loader::ResultStatus>(error_id))));
  431. } else {
  432. QMessageBox::critical(
  433. this, tr("Error while loading ROM!"),
  434. tr("An unknown error occurred. Please see the log for more details."));
  435. }
  436. break;
  437. }
  438. return false;
  439. }
  440. game_path = filename;
  441. Core::Telemetry().AddField(Telemetry::FieldType::App, "Frontend", "Qt");
  442. return true;
  443. }
  444. void GMainWindow::BootGame(const QString& filename) {
  445. LOG_INFO(Frontend, "yuzu starting...");
  446. StoreRecentFile(filename); // Put the filename on top of the list
  447. if (!LoadROM(filename))
  448. return;
  449. // Create and start the emulation thread
  450. emu_thread = std::make_unique<EmuThread>(render_window);
  451. emit EmulationStarting(emu_thread.get());
  452. render_window->moveContext();
  453. emu_thread->start();
  454. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  455. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  456. // before the CPU continues
  457. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  458. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  459. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  460. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  461. // Update the GUI
  462. if (ui.action_Single_Window_Mode->isChecked()) {
  463. game_list->hide();
  464. }
  465. status_bar_update_timer.start(2000);
  466. render_window->show();
  467. render_window->setFocus();
  468. emulation_running = true;
  469. if (ui.action_Fullscreen->isChecked()) {
  470. ShowFullscreen();
  471. }
  472. OnStartGame();
  473. }
  474. void GMainWindow::ShutdownGame() {
  475. emu_thread->RequestStop();
  476. emit EmulationStopping();
  477. // Wait for emulation thread to complete and delete it
  478. emu_thread->wait();
  479. emu_thread = nullptr;
  480. // The emulation is stopped, so closing the window or not does not matter anymore
  481. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  482. // Update the GUI
  483. ui.action_Start->setEnabled(false);
  484. ui.action_Start->setText(tr("Start"));
  485. ui.action_Pause->setEnabled(false);
  486. ui.action_Stop->setEnabled(false);
  487. ui.action_Restart->setEnabled(false);
  488. render_window->hide();
  489. game_list->show();
  490. game_list->setFilterFocus();
  491. // Disable status bar updates
  492. status_bar_update_timer.stop();
  493. message_label->setVisible(false);
  494. emu_speed_label->setVisible(false);
  495. game_fps_label->setVisible(false);
  496. emu_frametime_label->setVisible(false);
  497. emulation_running = false;
  498. game_path.clear();
  499. }
  500. void GMainWindow::StoreRecentFile(const QString& filename) {
  501. UISettings::values.recent_files.prepend(filename);
  502. UISettings::values.recent_files.removeDuplicates();
  503. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  504. UISettings::values.recent_files.removeLast();
  505. }
  506. UpdateRecentFiles();
  507. }
  508. void GMainWindow::UpdateRecentFiles() {
  509. const int num_recent_files =
  510. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  511. for (int i = 0; i < num_recent_files; i++) {
  512. const QString text = QString("&%1. %2").arg(i + 1).arg(
  513. QFileInfo(UISettings::values.recent_files[i]).fileName());
  514. actions_recent_files[i]->setText(text);
  515. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  516. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  517. actions_recent_files[i]->setVisible(true);
  518. }
  519. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  520. actions_recent_files[j]->setVisible(false);
  521. }
  522. // Enable the recent files menu if the list isn't empty
  523. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  524. }
  525. void GMainWindow::OnGameListLoadFile(QString game_path) {
  526. BootGame(game_path);
  527. }
  528. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target) {
  529. std::string path;
  530. std::string open_target;
  531. switch (target) {
  532. case GameListOpenTarget::SaveData: {
  533. open_target = "Save Data";
  534. const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
  535. ASSERT(program_id != 0);
  536. // TODO(tech4me): Update this to work with arbitrary user profile
  537. // Refer to core/hle/service/acc/profile_manager.cpp ProfileManager constructor
  538. constexpr u128 user_id = {1, 0};
  539. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser,
  540. FileSys::SaveDataType::SaveData,
  541. program_id, user_id, 0);
  542. break;
  543. }
  544. default:
  545. UNIMPLEMENTED();
  546. }
  547. const QString qpath = QString::fromStdString(path);
  548. const QDir dir(qpath);
  549. if (!dir.exists()) {
  550. QMessageBox::warning(this,
  551. tr("Error Opening %1 Folder").arg(QString::fromStdString(open_target)),
  552. tr("Folder does not exist!"));
  553. return;
  554. }
  555. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target, program_id);
  556. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  557. }
  558. void GMainWindow::OnMenuLoadFile() {
  559. QString extensions;
  560. for (const auto& piece : game_list->supported_file_extensions)
  561. extensions += "*." + piece + " ";
  562. extensions += "main ";
  563. QString file_filter = tr("Switch Executable") + " (" + extensions + ")";
  564. file_filter += ";;" + tr("All Files (*.*)");
  565. QString filename = QFileDialog::getOpenFileName(this, tr("Load File"),
  566. UISettings::values.roms_path, file_filter);
  567. if (!filename.isEmpty()) {
  568. UISettings::values.roms_path = QFileInfo(filename).path();
  569. BootGame(filename);
  570. }
  571. }
  572. void GMainWindow::OnMenuLoadFolder() {
  573. const QString dir_path =
  574. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  575. if (dir_path.isNull()) {
  576. return;
  577. }
  578. const QDir dir{dir_path};
  579. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  580. if (matching_main.size() == 1) {
  581. BootGame(dir.path() + DIR_SEP + matching_main[0]);
  582. } else {
  583. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  584. tr("The directory you have selected does not contain a 'main' file."));
  585. }
  586. }
  587. void GMainWindow::OnMenuInstallToNAND() {
  588. const QString file_filter =
  589. tr("Installable Switch File (*.nca *.xci);;Nintendo Content Archive (*.nca);;NX Cartridge "
  590. "Image (*.xci)");
  591. QString filename = QFileDialog::getOpenFileName(this, tr("Install File"),
  592. UISettings::values.roms_path, file_filter);
  593. if (filename.isEmpty()) {
  594. return;
  595. }
  596. const auto qt_raw_copy = [this](FileSys::VirtualFile src, FileSys::VirtualFile dest) {
  597. if (src == nullptr || dest == nullptr)
  598. return false;
  599. if (!dest->Resize(src->GetSize()))
  600. return false;
  601. std::array<u8, 0x1000> buffer{};
  602. const int progress_maximum = static_cast<int>(src->GetSize() / buffer.size());
  603. QProgressDialog progress(
  604. tr("Installing file \"%1\"...").arg(QString::fromStdString(src->GetName())),
  605. tr("Cancel"), 0, progress_maximum, this);
  606. progress.setWindowModality(Qt::WindowModal);
  607. for (size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  608. if (progress.wasCanceled()) {
  609. dest->Resize(0);
  610. return false;
  611. }
  612. const int progress_value = static_cast<int>(i / buffer.size());
  613. progress.setValue(progress_value);
  614. const auto read = src->Read(buffer.data(), buffer.size(), i);
  615. dest->Write(buffer.data(), read, i);
  616. }
  617. return true;
  618. };
  619. const auto success = [this]() {
  620. QMessageBox::information(this, tr("Successfully Installed"),
  621. tr("The file was successfully installed."));
  622. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  623. };
  624. const auto failed = [this]() {
  625. QMessageBox::warning(
  626. this, tr("Failed to Install"),
  627. tr("There was an error while attempting to install the provided file. It "
  628. "could have an incorrect format or be missing metadata. Please "
  629. "double-check your file and try again."));
  630. };
  631. const auto overwrite = [this]() {
  632. return QMessageBox::question(this, tr("Failed to Install"),
  633. tr("The file you are attempting to install already exists "
  634. "in the cache. Would you like to overwrite it?")) ==
  635. QMessageBox::Yes;
  636. };
  637. if (filename.endsWith("xci", Qt::CaseInsensitive)) {
  638. const auto xci = std::make_shared<FileSys::XCI>(
  639. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  640. if (xci->GetStatus() != Loader::ResultStatus::Success) {
  641. failed();
  642. return;
  643. }
  644. const auto res =
  645. Service::FileSystem::GetUserNANDContents()->InstallEntry(xci, false, qt_raw_copy);
  646. if (res == FileSys::InstallResult::Success) {
  647. success();
  648. } else {
  649. if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  650. if (overwrite()) {
  651. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  652. xci, true, qt_raw_copy);
  653. if (res2 == FileSys::InstallResult::Success) {
  654. success();
  655. } else {
  656. failed();
  657. }
  658. }
  659. } else {
  660. failed();
  661. }
  662. }
  663. } else {
  664. const auto nca = std::make_shared<FileSys::NCA>(
  665. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  666. if (nca->GetStatus() != Loader::ResultStatus::Success) {
  667. failed();
  668. return;
  669. }
  670. const QStringList tt_options{tr("System Application"),
  671. tr("System Archive"),
  672. tr("System Application Update"),
  673. tr("Firmware Package (Type A)"),
  674. tr("Firmware Package (Type B)"),
  675. tr("Game"),
  676. tr("Game Update"),
  677. tr("Game DLC"),
  678. tr("Delta Title")};
  679. bool ok;
  680. const auto item = QInputDialog::getItem(
  681. this, tr("Select NCA Install Type..."),
  682. tr("Please select the type of title you would like to install this NCA as:\n(In "
  683. "most instances, the default 'Game' is fine.)"),
  684. tt_options, 5, false, &ok);
  685. auto index = tt_options.indexOf(item);
  686. if (!ok || index == -1) {
  687. QMessageBox::warning(this, tr("Failed to Install"),
  688. tr("The title type you selected for the NCA is invalid."));
  689. return;
  690. }
  691. if (index >= 5)
  692. index += 0x7B;
  693. const auto res = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  694. nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  695. if (res == FileSys::InstallResult::Success) {
  696. success();
  697. } else if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  698. if (overwrite()) {
  699. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  700. nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  701. if (res2 == FileSys::InstallResult::Success) {
  702. success();
  703. } else {
  704. failed();
  705. }
  706. }
  707. } else {
  708. failed();
  709. }
  710. }
  711. }
  712. void GMainWindow::OnMenuSelectGameListRoot() {
  713. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  714. if (!dir_path.isEmpty()) {
  715. UISettings::values.gamedir = dir_path;
  716. game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan);
  717. }
  718. }
  719. void GMainWindow::OnMenuRecentFile() {
  720. QAction* action = qobject_cast<QAction*>(sender());
  721. assert(action);
  722. const QString filename = action->data().toString();
  723. if (QFileInfo::exists(filename)) {
  724. BootGame(filename);
  725. } else {
  726. // Display an error message and remove the file from the list.
  727. QMessageBox::information(this, tr("File not found"),
  728. tr("File \"%1\" not found").arg(filename));
  729. UISettings::values.recent_files.removeOne(filename);
  730. UpdateRecentFiles();
  731. }
  732. }
  733. void GMainWindow::OnStartGame() {
  734. emu_thread->SetRunning(true);
  735. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  736. qRegisterMetaType<std::string>("std::string");
  737. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  738. ui.action_Start->setEnabled(false);
  739. ui.action_Start->setText(tr("Continue"));
  740. ui.action_Pause->setEnabled(true);
  741. ui.action_Stop->setEnabled(true);
  742. }
  743. void GMainWindow::OnPauseGame() {
  744. emu_thread->SetRunning(false);
  745. ui.action_Start->setEnabled(true);
  746. ui.action_Pause->setEnabled(false);
  747. ui.action_Stop->setEnabled(true);
  748. ui.action_Restart->setEnabled(true);
  749. }
  750. void GMainWindow::OnStopGame() {
  751. ShutdownGame();
  752. }
  753. void GMainWindow::ToggleFullscreen() {
  754. if (!emulation_running) {
  755. return;
  756. }
  757. if (ui.action_Fullscreen->isChecked()) {
  758. ShowFullscreen();
  759. } else {
  760. HideFullscreen();
  761. }
  762. }
  763. void GMainWindow::ShowFullscreen() {
  764. if (ui.action_Single_Window_Mode->isChecked()) {
  765. UISettings::values.geometry = saveGeometry();
  766. ui.menubar->hide();
  767. statusBar()->hide();
  768. showFullScreen();
  769. } else {
  770. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  771. render_window->showFullScreen();
  772. }
  773. }
  774. void GMainWindow::HideFullscreen() {
  775. if (ui.action_Single_Window_Mode->isChecked()) {
  776. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  777. ui.menubar->show();
  778. showNormal();
  779. restoreGeometry(UISettings::values.geometry);
  780. } else {
  781. render_window->showNormal();
  782. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  783. }
  784. }
  785. void GMainWindow::ToggleWindowMode() {
  786. if (ui.action_Single_Window_Mode->isChecked()) {
  787. // Render in the main window...
  788. render_window->BackupGeometry();
  789. ui.horizontalLayout->addWidget(render_window);
  790. render_window->setFocusPolicy(Qt::ClickFocus);
  791. if (emulation_running) {
  792. render_window->setVisible(true);
  793. render_window->setFocus();
  794. game_list->hide();
  795. }
  796. } else {
  797. // Render in a separate window...
  798. ui.horizontalLayout->removeWidget(render_window);
  799. render_window->setParent(nullptr);
  800. render_window->setFocusPolicy(Qt::NoFocus);
  801. if (emulation_running) {
  802. render_window->setVisible(true);
  803. render_window->RestoreGeometry();
  804. game_list->show();
  805. }
  806. }
  807. }
  808. void GMainWindow::OnConfigure() {
  809. ConfigureDialog configureDialog(this, hotkey_registry);
  810. auto old_theme = UISettings::values.theme;
  811. auto result = configureDialog.exec();
  812. if (result == QDialog::Accepted) {
  813. configureDialog.applyConfiguration();
  814. if (UISettings::values.theme != old_theme)
  815. UpdateUITheme();
  816. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  817. config->Save();
  818. }
  819. }
  820. void GMainWindow::OnAbout() {
  821. AboutDialog aboutDialog(this);
  822. aboutDialog.exec();
  823. }
  824. void GMainWindow::OnToggleFilterBar() {
  825. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  826. if (ui.action_Show_Filter_Bar->isChecked()) {
  827. game_list->setFilterFocus();
  828. } else {
  829. game_list->clearFilter();
  830. }
  831. }
  832. void GMainWindow::UpdateStatusBar() {
  833. if (emu_thread == nullptr) {
  834. status_bar_update_timer.stop();
  835. return;
  836. }
  837. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  838. if (Settings::values.use_frame_limit) {
  839. emu_speed_label->setText(tr("Speed: %1% / %2%")
  840. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  841. .arg(Settings::values.frame_limit));
  842. } else {
  843. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  844. }
  845. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  846. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  847. emu_speed_label->setVisible(true);
  848. game_fps_label->setVisible(true);
  849. emu_frametime_label->setVisible(true);
  850. }
  851. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  852. QMessageBox::StandardButton answer;
  853. QString status_message;
  854. const QString common_message = tr(
  855. "The game you are trying to load requires additional files from your Switch to be dumped "
  856. "before playing.<br/><br/>For more information on dumping these files, please see the "
  857. "following wiki page: <a "
  858. "href='https://yuzu-emu.org/wiki/"
  859. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  860. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to quit "
  861. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  862. "data, or other bugs.");
  863. switch (result) {
  864. case Core::System::ResultStatus::ErrorSystemFiles: {
  865. QString message = "yuzu was unable to locate a Switch system archive";
  866. if (!details.empty()) {
  867. message.append(tr(": %1. ").arg(details.c_str()));
  868. } else {
  869. message.append(". ");
  870. }
  871. message.append(common_message);
  872. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  873. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  874. status_message = "System Archive Missing";
  875. break;
  876. }
  877. case Core::System::ResultStatus::ErrorSharedFont: {
  878. QString message = tr("yuzu was unable to locate the Switch shared fonts. ");
  879. message.append(common_message);
  880. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  881. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  882. status_message = "Shared Font Missing";
  883. break;
  884. }
  885. default:
  886. answer = QMessageBox::question(
  887. this, tr("Fatal Error"),
  888. tr("yuzu has encountered a fatal error, please see the log for more details. "
  889. "For more information on accessing the log, please see the following page: "
  890. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How to "
  891. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game list? "
  892. "Continuing emulation may result in crashes, corrupted save data, or other bugs."),
  893. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  894. status_message = "Fatal Error encountered";
  895. break;
  896. }
  897. if (answer == QMessageBox::Yes) {
  898. if (emu_thread) {
  899. ShutdownGame();
  900. }
  901. } else {
  902. // Only show the message if the game is still running.
  903. if (emu_thread) {
  904. emu_thread->SetRunning(true);
  905. message_label->setText(status_message);
  906. message_label->setVisible(true);
  907. }
  908. }
  909. }
  910. bool GMainWindow::ConfirmClose() {
  911. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  912. return true;
  913. QMessageBox::StandardButton answer =
  914. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  915. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  916. return answer != QMessageBox::No;
  917. }
  918. void GMainWindow::closeEvent(QCloseEvent* event) {
  919. if (!ConfirmClose()) {
  920. event->ignore();
  921. return;
  922. }
  923. if (ui.action_Fullscreen->isChecked()) {
  924. UISettings::values.geometry = saveGeometry();
  925. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  926. }
  927. UISettings::values.state = saveState();
  928. #if MICROPROFILE_ENABLED
  929. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  930. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  931. #endif
  932. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  933. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  934. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  935. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  936. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  937. UISettings::values.first_start = false;
  938. game_list->SaveInterfaceLayout();
  939. hotkey_registry.SaveHotkeys();
  940. // Shutdown session if the emu thread is active...
  941. if (emu_thread != nullptr)
  942. ShutdownGame();
  943. render_window->close();
  944. QWidget::closeEvent(event);
  945. }
  946. static bool IsSingleFileDropEvent(QDropEvent* event) {
  947. const QMimeData* mimeData = event->mimeData();
  948. return mimeData->hasUrls() && mimeData->urls().length() == 1;
  949. }
  950. void GMainWindow::dropEvent(QDropEvent* event) {
  951. if (IsSingleFileDropEvent(event) && ConfirmChangeGame()) {
  952. const QMimeData* mimeData = event->mimeData();
  953. QString filename = mimeData->urls().at(0).toLocalFile();
  954. BootGame(filename);
  955. }
  956. }
  957. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  958. if (IsSingleFileDropEvent(event)) {
  959. event->acceptProposedAction();
  960. }
  961. }
  962. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  963. event->acceptProposedAction();
  964. }
  965. bool GMainWindow::ConfirmChangeGame() {
  966. if (emu_thread == nullptr)
  967. return true;
  968. auto answer = QMessageBox::question(
  969. this, tr("yuzu"),
  970. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  971. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  972. return answer != QMessageBox::No;
  973. }
  974. void GMainWindow::filterBarSetChecked(bool state) {
  975. ui.action_Show_Filter_Bar->setChecked(state);
  976. emit(OnToggleFilterBar());
  977. }
  978. void GMainWindow::UpdateUITheme() {
  979. QStringList theme_paths(default_theme_paths);
  980. if (UISettings::values.theme != UISettings::themes[0].second &&
  981. !UISettings::values.theme.isEmpty()) {
  982. const QString theme_uri(":" + UISettings::values.theme + "/style.qss");
  983. QFile f(theme_uri);
  984. if (f.open(QFile::ReadOnly | QFile::Text)) {
  985. QTextStream ts(&f);
  986. qApp->setStyleSheet(ts.readAll());
  987. GMainWindow::setStyleSheet(ts.readAll());
  988. } else {
  989. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  990. }
  991. theme_paths.append(QStringList{":/icons/default", ":/icons/" + UISettings::values.theme});
  992. QIcon::setThemeName(":/icons/" + UISettings::values.theme);
  993. } else {
  994. qApp->setStyleSheet("");
  995. GMainWindow::setStyleSheet("");
  996. theme_paths.append(QStringList{":/icons/default"});
  997. QIcon::setThemeName(":/icons/default");
  998. }
  999. QIcon::setThemeSearchPaths(theme_paths);
  1000. emit UpdateThemedIcons();
  1001. }
  1002. #ifdef main
  1003. #undef main
  1004. #endif
  1005. static void InitializeLogging() {
  1006. Log::Filter log_filter;
  1007. log_filter.ParseFilterString(Settings::values.log_filter);
  1008. Log::SetGlobalFilter(log_filter);
  1009. const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
  1010. FileUtil::CreateFullPath(log_dir);
  1011. Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
  1012. }
  1013. int main(int argc, char* argv[]) {
  1014. MicroProfileOnThreadCreate("Frontend");
  1015. SCOPE_EXIT({ MicroProfileShutdown(); });
  1016. // Init settings params
  1017. QCoreApplication::setOrganizationName("yuzu team");
  1018. QCoreApplication::setApplicationName("yuzu");
  1019. QApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  1020. QApplication app(argc, argv);
  1021. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  1022. // generating shaders
  1023. setlocale(LC_ALL, "C");
  1024. GMainWindow main_window;
  1025. // After settings have been loaded by GMainWindow, apply the filter
  1026. InitializeLogging();
  1027. main_window.show();
  1028. return app.exec();
  1029. }