main.cpp 50 KB

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