main.cpp 50 KB

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