main.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  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. // VFS includes must be before glad as they will conflict with Windows file api, which uses defines.
  9. #include "applets/software_keyboard.h"
  10. #include "core/file_sys/vfs.h"
  11. #include "core/file_sys/vfs_real.h"
  12. #include "core/hle/service/acc/profile_manager.h"
  13. #include "core/hle/service/am/applets/applets.h"
  14. // These are wrappers to avoid the calls to CreateDirectory and CreateFile because of the Windows
  15. // defines.
  16. static FileSys::VirtualDir VfsFilesystemCreateDirectoryWrapper(
  17. const FileSys::VirtualFilesystem& vfs, const std::string& path, FileSys::Mode mode) {
  18. return vfs->CreateDirectory(path, mode);
  19. }
  20. static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::VirtualDir& dir,
  21. const std::string& path) {
  22. return dir->CreateFile(path);
  23. }
  24. #include <fmt/ostream.h>
  25. #include <glad/glad.h>
  26. #define QT_NO_OPENGL
  27. #include <QDesktopWidget>
  28. #include <QDialogButtonBox>
  29. #include <QFile>
  30. #include <QFileDialog>
  31. #include <QMessageBox>
  32. #include <QtConcurrent/QtConcurrent>
  33. #include <QtGui>
  34. #include <QtWidgets>
  35. #include <fmt/format.h>
  36. #include "common/common_paths.h"
  37. #include "common/detached_tasks.h"
  38. #include "common/file_util.h"
  39. #include "common/logging/backend.h"
  40. #include "common/logging/filter.h"
  41. #include "common/logging/log.h"
  42. #include "common/microprofile.h"
  43. #include "common/scm_rev.h"
  44. #include "common/scope_exit.h"
  45. #include "common/string_util.h"
  46. #include "common/telemetry.h"
  47. #include "core/core.h"
  48. #include "core/crypto/key_manager.h"
  49. #include "core/file_sys/bis_factory.h"
  50. #include "core/file_sys/card_image.h"
  51. #include "core/file_sys/content_archive.h"
  52. #include "core/file_sys/control_metadata.h"
  53. #include "core/file_sys/patch_manager.h"
  54. #include "core/file_sys/registered_cache.h"
  55. #include "core/file_sys/romfs.h"
  56. #include "core/file_sys/savedata_factory.h"
  57. #include "core/file_sys/submission_package.h"
  58. #include "core/frontend/applets/software_keyboard.h"
  59. #include "core/hle/kernel/process.h"
  60. #include "core/hle/service/filesystem/filesystem.h"
  61. #include "core/hle/service/filesystem/fsp_ldr.h"
  62. #include "core/hle/service/nfp/nfp.h"
  63. #include "core/hle/service/sm/sm.h"
  64. #include "core/loader/loader.h"
  65. #include "core/perf_stats.h"
  66. #include "core/settings.h"
  67. #include "core/telemetry_session.h"
  68. #include "video_core/debug_utils/debug_utils.h"
  69. #include "yuzu/about_dialog.h"
  70. #include "yuzu/bootmanager.h"
  71. #include "yuzu/compatdb.h"
  72. #include "yuzu/compatibility_list.h"
  73. #include "yuzu/configuration/config.h"
  74. #include "yuzu/configuration/configure_dialog.h"
  75. #include "yuzu/debugger/console.h"
  76. #include "yuzu/debugger/graphics/graphics_breakpoints.h"
  77. #include "yuzu/debugger/graphics/graphics_surface.h"
  78. #include "yuzu/debugger/profiler.h"
  79. #include "yuzu/debugger/wait_tree.h"
  80. #include "yuzu/discord.h"
  81. #include "yuzu/game_list.h"
  82. #include "yuzu/game_list_p.h"
  83. #include "yuzu/hotkeys.h"
  84. #include "yuzu/main.h"
  85. #include "yuzu/ui_settings.h"
  86. #ifdef USE_DISCORD_PRESENCE
  87. #include "yuzu/discord_impl.h"
  88. #endif
  89. #ifdef QT_STATICPLUGIN
  90. Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
  91. #endif
  92. #ifdef _WIN32
  93. extern "C" {
  94. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  95. // graphics
  96. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  97. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  98. }
  99. #endif
  100. constexpr u64 DLC_BASE_TITLE_ID_MASK = 0xFFFFFFFFFFFFE000;
  101. /**
  102. * "Callouts" are one-time instructional messages shown to the user. In the config settings, there
  103. * is a bitfield "callout_flags" options, used to track if a message has already been shown to the
  104. * user. This is 32-bits - if we have more than 32 callouts, we should retire and recyle old ones.
  105. */
  106. enum class CalloutFlag : uint32_t {
  107. Telemetry = 0x1,
  108. DRDDeprecation = 0x2,
  109. };
  110. void GMainWindow::ShowTelemetryCallout() {
  111. if (UISettings::values.callout_flags & static_cast<uint32_t>(CalloutFlag::Telemetry)) {
  112. return;
  113. }
  114. UISettings::values.callout_flags |= static_cast<uint32_t>(CalloutFlag::Telemetry);
  115. const QString telemetry_message =
  116. tr("<a href='https://yuzu-emu.org/help/feature/telemetry/'>Anonymous "
  117. "data is collected</a> to help improve yuzu. "
  118. "<br/><br/>Would you like to share your usage data with us?");
  119. if (QMessageBox::question(this, tr("Telemetry"), telemetry_message) != QMessageBox::Yes) {
  120. Settings::values.enable_telemetry = false;
  121. Settings::Apply();
  122. }
  123. }
  124. const int GMainWindow::max_recent_files_item;
  125. static void InitializeLogging() {
  126. Log::Filter log_filter;
  127. log_filter.ParseFilterString(Settings::values.log_filter);
  128. Log::SetGlobalFilter(log_filter);
  129. const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
  130. FileUtil::CreateFullPath(log_dir);
  131. Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
  132. #ifdef _WIN32
  133. Log::AddBackend(std::make_unique<Log::DebuggerBackend>());
  134. #endif
  135. }
  136. GMainWindow::GMainWindow()
  137. : config(new Config()), emu_thread(nullptr),
  138. vfs(std::make_shared<FileSys::RealVfsFilesystem>()) {
  139. InitializeLogging();
  140. debug_context = Tegra::DebugContext::Construct();
  141. setAcceptDrops(true);
  142. ui.setupUi(this);
  143. statusBar()->hide();
  144. default_theme_paths = QIcon::themeSearchPaths();
  145. UpdateUITheme();
  146. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  147. discord_rpc->Update();
  148. InitializeWidgets();
  149. InitializeDebugWidgets();
  150. InitializeRecentFileMenuActions();
  151. InitializeHotkeys();
  152. SetDefaultUIGeometry();
  153. RestoreUIState();
  154. ConnectMenuEvents();
  155. ConnectWidgetEvents();
  156. LOG_INFO(Frontend, "yuzu Version: {} | {}-{}", Common::g_build_fullname, Common::g_scm_branch,
  157. Common::g_scm_desc);
  158. setWindowTitle(QString("yuzu %1| %2-%3")
  159. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc));
  160. show();
  161. // Gen keys if necessary
  162. OnReinitializeKeys(ReinitializeKeyBehavior::NoWarning);
  163. // Necessary to load titles from nand in gamelist.
  164. Service::FileSystem::CreateFactories(*vfs);
  165. game_list->LoadCompatibilityList();
  166. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  167. // Show one-time "callout" messages to the user
  168. ShowTelemetryCallout();
  169. QStringList args = QApplication::arguments();
  170. if (args.length() >= 2) {
  171. BootGame(args[1]);
  172. }
  173. }
  174. GMainWindow::~GMainWindow() {
  175. // will get automatically deleted otherwise
  176. if (render_window->parent() == nullptr)
  177. delete render_window;
  178. }
  179. void GMainWindow::SoftwareKeyboardGetText(
  180. const Core::Frontend::SoftwareKeyboardParameters& parameters) {
  181. QtSoftwareKeyboardDialog dialog(this, parameters);
  182. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  183. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  184. dialog.setWindowModality(Qt::WindowModal);
  185. dialog.exec();
  186. if (!dialog.GetStatus()) {
  187. emit SoftwareKeyboardFinishedText(std::nullopt);
  188. return;
  189. }
  190. emit SoftwareKeyboardFinishedText(dialog.GetText());
  191. }
  192. void GMainWindow::SoftwareKeyboardInvokeCheckDialog(std::u16string error_message) {
  193. QMessageBox::warning(this, tr("Text Check Failed"), QString::fromStdU16String(error_message));
  194. emit SoftwareKeyboardFinishedCheckDialog();
  195. }
  196. void GMainWindow::InitializeWidgets() {
  197. #ifdef YUZU_ENABLE_COMPATIBILITY_REPORTING
  198. ui.action_Report_Compatibility->setVisible(true);
  199. #endif
  200. render_window = new GRenderWindow(this, emu_thread.get());
  201. render_window->hide();
  202. game_list = new GameList(vfs, this);
  203. ui.horizontalLayout->addWidget(game_list);
  204. // Create status bar
  205. message_label = new QLabel();
  206. // Configured separately for left alignment
  207. message_label->setVisible(false);
  208. message_label->setFrameStyle(QFrame::NoFrame);
  209. message_label->setContentsMargins(4, 0, 4, 0);
  210. message_label->setAlignment(Qt::AlignLeft);
  211. statusBar()->addPermanentWidget(message_label, 1);
  212. emu_speed_label = new QLabel();
  213. emu_speed_label->setToolTip(
  214. tr("Current emulation speed. Values higher or lower than 100% "
  215. "indicate emulation is running faster or slower than a Switch."));
  216. game_fps_label = new QLabel();
  217. game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
  218. "This will vary from game to game and scene to scene."));
  219. emu_frametime_label = new QLabel();
  220. emu_frametime_label->setToolTip(
  221. tr("Time taken to emulate a Switch frame, not counting framelimiting or v-sync. For "
  222. "full-speed emulation this should be at most 16.67 ms."));
  223. for (auto& label : {emu_speed_label, game_fps_label, emu_frametime_label}) {
  224. label->setVisible(false);
  225. label->setFrameStyle(QFrame::NoFrame);
  226. label->setContentsMargins(4, 0, 4, 0);
  227. statusBar()->addPermanentWidget(label, 0);
  228. }
  229. statusBar()->setVisible(true);
  230. setStyleSheet("QStatusBar::item{border: none;}");
  231. }
  232. void GMainWindow::InitializeDebugWidgets() {
  233. QMenu* debug_menu = ui.menu_View_Debugging;
  234. #if MICROPROFILE_ENABLED
  235. microProfileDialog = new MicroProfileDialog(this);
  236. microProfileDialog->hide();
  237. debug_menu->addAction(microProfileDialog->toggleViewAction());
  238. #endif
  239. graphicsBreakpointsWidget = new GraphicsBreakPointsWidget(debug_context, this);
  240. addDockWidget(Qt::RightDockWidgetArea, graphicsBreakpointsWidget);
  241. graphicsBreakpointsWidget->hide();
  242. debug_menu->addAction(graphicsBreakpointsWidget->toggleViewAction());
  243. graphicsSurfaceWidget = new GraphicsSurfaceWidget(debug_context, this);
  244. addDockWidget(Qt::RightDockWidgetArea, graphicsSurfaceWidget);
  245. graphicsSurfaceWidget->hide();
  246. debug_menu->addAction(graphicsSurfaceWidget->toggleViewAction());
  247. waitTreeWidget = new WaitTreeWidget(this);
  248. addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
  249. waitTreeWidget->hide();
  250. debug_menu->addAction(waitTreeWidget->toggleViewAction());
  251. connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
  252. &WaitTreeWidget::OnEmulationStarting);
  253. connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
  254. &WaitTreeWidget::OnEmulationStopping);
  255. }
  256. void GMainWindow::InitializeRecentFileMenuActions() {
  257. for (int i = 0; i < max_recent_files_item; ++i) {
  258. actions_recent_files[i] = new QAction(this);
  259. actions_recent_files[i]->setVisible(false);
  260. connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile);
  261. ui.menu_recent_files->addAction(actions_recent_files[i]);
  262. }
  263. ui.menu_recent_files->addSeparator();
  264. QAction* action_clear_recent_files = new QAction(this);
  265. action_clear_recent_files->setText(tr("Clear Recent Files"));
  266. connect(action_clear_recent_files, &QAction::triggered, this, [this] {
  267. UISettings::values.recent_files.clear();
  268. UpdateRecentFiles();
  269. });
  270. ui.menu_recent_files->addAction(action_clear_recent_files);
  271. UpdateRecentFiles();
  272. }
  273. void GMainWindow::InitializeHotkeys() {
  274. hotkey_registry.RegisterHotkey("Main Window", "Load File", QKeySequence::Open);
  275. hotkey_registry.RegisterHotkey("Main Window", "Start Emulation");
  276. hotkey_registry.RegisterHotkey("Main Window", "Continue/Pause", QKeySequence(Qt::Key_F4));
  277. hotkey_registry.RegisterHotkey("Main Window", "Restart", QKeySequence(Qt::Key_F5));
  278. hotkey_registry.RegisterHotkey("Main Window", "Fullscreen", QKeySequence::FullScreen);
  279. hotkey_registry.RegisterHotkey("Main Window", "Exit Fullscreen", QKeySequence(Qt::Key_Escape),
  280. Qt::ApplicationShortcut);
  281. hotkey_registry.RegisterHotkey("Main Window", "Toggle Speed Limit", QKeySequence("CTRL+Z"),
  282. Qt::ApplicationShortcut);
  283. hotkey_registry.RegisterHotkey("Main Window", "Increase Speed Limit", QKeySequence("+"),
  284. Qt::ApplicationShortcut);
  285. hotkey_registry.RegisterHotkey("Main Window", "Decrease Speed Limit", QKeySequence("-"),
  286. Qt::ApplicationShortcut);
  287. hotkey_registry.RegisterHotkey("Main Window", "Load Amiibo", QKeySequence(Qt::Key_F2),
  288. Qt::ApplicationShortcut);
  289. hotkey_registry.LoadHotkeys();
  290. connect(hotkey_registry.GetHotkey("Main Window", "Load File", this), &QShortcut::activated,
  291. this, &GMainWindow::OnMenuLoadFile);
  292. connect(hotkey_registry.GetHotkey("Main Window", "Start Emulation", this),
  293. &QShortcut::activated, this, &GMainWindow::OnStartGame);
  294. connect(hotkey_registry.GetHotkey("Main Window", "Continue/Pause", this), &QShortcut::activated,
  295. this, [&] {
  296. if (emulation_running) {
  297. if (emu_thread->IsRunning()) {
  298. OnPauseGame();
  299. } else {
  300. OnStartGame();
  301. }
  302. }
  303. });
  304. connect(hotkey_registry.GetHotkey("Main Window", "Restart", this), &QShortcut::activated, this,
  305. [this] {
  306. if (!Core::System::GetInstance().IsPoweredOn())
  307. return;
  308. BootGame(QString(game_path));
  309. });
  310. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  311. &QShortcut::activated, ui.action_Fullscreen, &QAction::trigger);
  312. connect(hotkey_registry.GetHotkey("Main Window", "Fullscreen", render_window),
  313. &QShortcut::activatedAmbiguously, ui.action_Fullscreen, &QAction::trigger);
  314. connect(hotkey_registry.GetHotkey("Main Window", "Exit Fullscreen", this),
  315. &QShortcut::activated, this, [&] {
  316. if (emulation_running) {
  317. ui.action_Fullscreen->setChecked(false);
  318. ToggleFullscreen();
  319. }
  320. });
  321. connect(hotkey_registry.GetHotkey("Main Window", "Toggle Speed Limit", this),
  322. &QShortcut::activated, this, [&] {
  323. Settings::values.use_frame_limit = !Settings::values.use_frame_limit;
  324. UpdateStatusBar();
  325. });
  326. constexpr u16 SPEED_LIMIT_STEP = 5;
  327. connect(hotkey_registry.GetHotkey("Main Window", "Increase Speed Limit", this),
  328. &QShortcut::activated, this, [&] {
  329. if (Settings::values.frame_limit < 9999 - SPEED_LIMIT_STEP) {
  330. Settings::values.frame_limit += SPEED_LIMIT_STEP;
  331. UpdateStatusBar();
  332. }
  333. });
  334. connect(hotkey_registry.GetHotkey("Main Window", "Decrease Speed Limit", this),
  335. &QShortcut::activated, this, [&] {
  336. if (Settings::values.frame_limit > SPEED_LIMIT_STEP) {
  337. Settings::values.frame_limit -= SPEED_LIMIT_STEP;
  338. UpdateStatusBar();
  339. }
  340. });
  341. connect(hotkey_registry.GetHotkey("Main Window", "Load Amiibo", this), &QShortcut::activated,
  342. this, [&] {
  343. if (ui.action_Load_Amiibo->isEnabled()) {
  344. OnLoadAmiibo();
  345. }
  346. });
  347. }
  348. void GMainWindow::SetDefaultUIGeometry() {
  349. // geometry: 55% of the window contents are in the upper screen half, 45% in the lower half
  350. const QRect screenRect = QApplication::desktop()->screenGeometry(this);
  351. const int w = screenRect.width() * 2 / 3;
  352. const int h = screenRect.height() / 2;
  353. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  354. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 55 / 100;
  355. setGeometry(x, y, w, h);
  356. }
  357. void GMainWindow::RestoreUIState() {
  358. restoreGeometry(UISettings::values.geometry);
  359. restoreState(UISettings::values.state);
  360. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  361. #if MICROPROFILE_ENABLED
  362. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  363. microProfileDialog->setVisible(UISettings::values.microprofile_visible);
  364. #endif
  365. game_list->LoadInterfaceLayout();
  366. ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode);
  367. ToggleWindowMode();
  368. ui.action_Fullscreen->setChecked(UISettings::values.fullscreen);
  369. ui.action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);
  370. OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked());
  371. ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar);
  372. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  373. ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);
  374. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  375. Debugger::ToggleConsole();
  376. }
  377. void GMainWindow::ConnectWidgetEvents() {
  378. connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
  379. connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
  380. connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS);
  381. connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID);
  382. connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
  383. &GMainWindow::OnGameListNavigateToGamedbEntry);
  384. connect(this, &GMainWindow::EmulationStarting, render_window,
  385. &GRenderWindow::OnEmulationStarting);
  386. connect(this, &GMainWindow::EmulationStopping, render_window,
  387. &GRenderWindow::OnEmulationStopping);
  388. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  389. }
  390. void GMainWindow::ConnectMenuEvents() {
  391. // File
  392. connect(ui.action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
  393. connect(ui.action_Load_Folder, &QAction::triggered, this, &GMainWindow::OnMenuLoadFolder);
  394. connect(ui.action_Install_File_NAND, &QAction::triggered, this,
  395. &GMainWindow::OnMenuInstallToNAND);
  396. connect(ui.action_Select_Game_List_Root, &QAction::triggered, this,
  397. &GMainWindow::OnMenuSelectGameListRoot);
  398. connect(ui.action_Select_NAND_Directory, &QAction::triggered, this,
  399. [this] { OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget::NAND); });
  400. connect(ui.action_Select_SDMC_Directory, &QAction::triggered, this,
  401. [this] { OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget::SDMC); });
  402. connect(ui.action_Exit, &QAction::triggered, this, &QMainWindow::close);
  403. connect(ui.action_Load_Amiibo, &QAction::triggered, this, &GMainWindow::OnLoadAmiibo);
  404. // Emulation
  405. connect(ui.action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
  406. connect(ui.action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
  407. connect(ui.action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
  408. connect(ui.action_Report_Compatibility, &QAction::triggered, this,
  409. &GMainWindow::OnMenuReportCompatibility);
  410. connect(ui.action_Restart, &QAction::triggered, this, [this] { BootGame(QString(game_path)); });
  411. connect(ui.action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
  412. // View
  413. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  414. &GMainWindow::ToggleWindowMode);
  415. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  416. &GMainWindow::OnDisplayTitleBars);
  417. ui.action_Show_Filter_Bar->setShortcut(tr("CTRL+F"));
  418. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  419. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  420. // Fullscreen
  421. ui.action_Fullscreen->setShortcut(
  422. hotkey_registry.GetHotkey("Main Window", "Fullscreen", this)->key());
  423. connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
  424. // Help
  425. connect(ui.action_Open_yuzu_Folder, &QAction::triggered, this, &GMainWindow::OnOpenYuzuFolder);
  426. connect(ui.action_Rederive, &QAction::triggered, this,
  427. std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning));
  428. connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
  429. }
  430. void GMainWindow::OnDisplayTitleBars(bool show) {
  431. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  432. if (show) {
  433. for (QDockWidget* widget : widgets) {
  434. QWidget* old = widget->titleBarWidget();
  435. widget->setTitleBarWidget(nullptr);
  436. if (old != nullptr)
  437. delete old;
  438. }
  439. } else {
  440. for (QDockWidget* widget : widgets) {
  441. QWidget* old = widget->titleBarWidget();
  442. widget->setTitleBarWidget(new QWidget());
  443. if (old != nullptr)
  444. delete old;
  445. }
  446. }
  447. }
  448. QStringList GMainWindow::GetUnsupportedGLExtensions() {
  449. QStringList unsupported_ext;
  450. if (!GLAD_GL_ARB_direct_state_access)
  451. unsupported_ext.append("ARB_direct_state_access");
  452. if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
  453. unsupported_ext.append("ARB_vertex_type_10f_11f_11f_rev");
  454. if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
  455. unsupported_ext.append("ARB_texture_mirror_clamp_to_edge");
  456. if (!GLAD_GL_ARB_multi_bind)
  457. unsupported_ext.append("ARB_multi_bind");
  458. // Extensions required to support some texture formats.
  459. if (!GLAD_GL_EXT_texture_compression_s3tc)
  460. unsupported_ext.append("EXT_texture_compression_s3tc");
  461. if (!GLAD_GL_ARB_texture_compression_rgtc)
  462. unsupported_ext.append("ARB_texture_compression_rgtc");
  463. if (!GLAD_GL_ARB_depth_buffer_float)
  464. unsupported_ext.append("ARB_depth_buffer_float");
  465. for (const QString& ext : unsupported_ext)
  466. LOG_CRITICAL(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  467. return unsupported_ext;
  468. }
  469. bool GMainWindow::LoadROM(const QString& filename) {
  470. // Shutdown previous session if the emu thread is still active...
  471. if (emu_thread != nullptr)
  472. ShutdownGame();
  473. render_window->InitRenderTarget();
  474. render_window->MakeCurrent();
  475. if (!gladLoadGL()) {
  476. QMessageBox::critical(this, tr("Error while initializing OpenGL 4.3 Core!"),
  477. tr("Your GPU may not support OpenGL 4.3, or you do not "
  478. "have the latest graphics driver."));
  479. return false;
  480. }
  481. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  482. if (!unsupported_gl_extensions.empty()) {
  483. QMessageBox::critical(this, tr("Error while initializing OpenGL Core!"),
  484. tr("Your GPU may not support one or more required OpenGL"
  485. "extensions. Please ensure you have the latest graphics "
  486. "driver.<br><br>Unsupported extensions:<br>") +
  487. unsupported_gl_extensions.join("<br>"));
  488. return false;
  489. }
  490. Core::System& system{Core::System::GetInstance()};
  491. system.SetFilesystem(vfs);
  492. system.SetGPUDebugContext(debug_context);
  493. system.SetSoftwareKeyboard(std::make_unique<QtSoftwareKeyboard>(*this));
  494. const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
  495. const auto drd_callout =
  496. (UISettings::values.callout_flags & static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  497. if (result == Core::System::ResultStatus::Success &&
  498. system.GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  499. drd_callout) {
  500. UISettings::values.callout_flags |= static_cast<u32>(CalloutFlag::DRDDeprecation);
  501. QMessageBox::warning(
  502. this, tr("Warning Outdated Game Format"),
  503. tr("You are using the deconstructed ROM directory format for this game, which is an "
  504. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  505. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  506. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  507. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  508. "wiki</a>. This message will not be shown again."));
  509. }
  510. render_window->DoneCurrent();
  511. if (result != Core::System::ResultStatus::Success) {
  512. switch (result) {
  513. case Core::System::ResultStatus::ErrorGetLoader:
  514. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  515. QMessageBox::critical(this, tr("Error while loading ROM!"),
  516. tr("The ROM format is not supported."));
  517. break;
  518. case Core::System::ResultStatus::ErrorSystemMode:
  519. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  520. QMessageBox::critical(this, tr("Error while loading ROM!"),
  521. tr("Could not determine the system mode."));
  522. break;
  523. case Core::System::ResultStatus::ErrorVideoCore:
  524. QMessageBox::critical(
  525. this, tr("An error occurred initializing the video core."),
  526. tr("yuzu has encountered an error while running the video core, please see the "
  527. "log for more details."
  528. "For more information on accessing the log, please see the following page: "
  529. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  530. "to "
  531. "Upload the Log File</a>."
  532. "Ensure that you have the latest graphics drivers for your GPU."));
  533. break;
  534. default:
  535. if (static_cast<u32>(result) >
  536. static_cast<u32>(Core::System::ResultStatus::ErrorLoader)) {
  537. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  538. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  539. const u16 error_id = static_cast<u16>(result) - loader_id;
  540. QMessageBox::critical(
  541. this, tr("Error while loading ROM!"),
  542. QString::fromStdString(fmt::format(
  543. "While attempting to load the ROM requested, an error occured. Please "
  544. "refer to the yuzu wiki for more information or the yuzu discord for "
  545. "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
  546. loader_id, error_id, static_cast<Loader::ResultStatus>(error_id))));
  547. } else {
  548. QMessageBox::critical(
  549. this, tr("Error while loading ROM!"),
  550. tr("An unknown error occurred. Please see the log for more details."));
  551. }
  552. break;
  553. }
  554. return false;
  555. }
  556. game_path = filename;
  557. Core::Telemetry().AddField(Telemetry::FieldType::App, "Frontend", "Qt");
  558. return true;
  559. }
  560. void GMainWindow::BootGame(const QString& filename) {
  561. LOG_INFO(Frontend, "yuzu starting...");
  562. StoreRecentFile(filename); // Put the filename on top of the list
  563. if (!LoadROM(filename))
  564. return;
  565. // Create and start the emulation thread
  566. emu_thread = std::make_unique<EmuThread>(render_window);
  567. emit EmulationStarting(emu_thread.get());
  568. render_window->moveContext();
  569. emu_thread->start();
  570. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  571. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  572. // before the CPU continues
  573. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  574. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  575. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  576. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  577. // Update the GUI
  578. if (ui.action_Single_Window_Mode->isChecked()) {
  579. game_list->hide();
  580. }
  581. status_bar_update_timer.start(2000);
  582. std::string title_name;
  583. const auto res = Core::System::GetInstance().GetGameName(title_name);
  584. if (res != Loader::ResultStatus::Success) {
  585. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  586. const auto [nacp, icon_file] = FileSys::PatchManager(title_id).GetControlMetadata();
  587. if (nacp != nullptr)
  588. title_name = nacp->GetApplicationName();
  589. if (title_name.empty())
  590. title_name = FileUtil::GetFilename(filename.toStdString());
  591. }
  592. setWindowTitle(QString("yuzu %1| %4 | %2-%3")
  593. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc,
  594. QString::fromStdString(title_name)));
  595. render_window->show();
  596. render_window->setFocus();
  597. emulation_running = true;
  598. if (ui.action_Fullscreen->isChecked()) {
  599. ShowFullscreen();
  600. }
  601. OnStartGame();
  602. }
  603. void GMainWindow::ShutdownGame() {
  604. discord_rpc->Pause();
  605. emu_thread->RequestStop();
  606. emit EmulationStopping();
  607. // Wait for emulation thread to complete and delete it
  608. emu_thread->wait();
  609. emu_thread = nullptr;
  610. discord_rpc->Update();
  611. // The emulation is stopped, so closing the window or not does not matter anymore
  612. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  613. // Update the GUI
  614. ui.action_Start->setEnabled(false);
  615. ui.action_Start->setText(tr("Start"));
  616. ui.action_Pause->setEnabled(false);
  617. ui.action_Stop->setEnabled(false);
  618. ui.action_Restart->setEnabled(false);
  619. ui.action_Report_Compatibility->setEnabled(false);
  620. ui.action_Load_Amiibo->setEnabled(false);
  621. render_window->hide();
  622. game_list->show();
  623. game_list->setFilterFocus();
  624. setWindowTitle(QString("yuzu %1| %2-%3")
  625. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc));
  626. // Disable status bar updates
  627. status_bar_update_timer.stop();
  628. message_label->setVisible(false);
  629. emu_speed_label->setVisible(false);
  630. game_fps_label->setVisible(false);
  631. emu_frametime_label->setVisible(false);
  632. emulation_running = false;
  633. game_path.clear();
  634. }
  635. void GMainWindow::StoreRecentFile(const QString& filename) {
  636. UISettings::values.recent_files.prepend(filename);
  637. UISettings::values.recent_files.removeDuplicates();
  638. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  639. UISettings::values.recent_files.removeLast();
  640. }
  641. UpdateRecentFiles();
  642. }
  643. void GMainWindow::UpdateRecentFiles() {
  644. const int num_recent_files =
  645. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  646. for (int i = 0; i < num_recent_files; i++) {
  647. const QString text = QString("&%1. %2").arg(i + 1).arg(
  648. QFileInfo(UISettings::values.recent_files[i]).fileName());
  649. actions_recent_files[i]->setText(text);
  650. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  651. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  652. actions_recent_files[i]->setVisible(true);
  653. }
  654. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  655. actions_recent_files[j]->setVisible(false);
  656. }
  657. // Enable the recent files menu if the list isn't empty
  658. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  659. }
  660. void GMainWindow::OnGameListLoadFile(QString game_path) {
  661. BootGame(game_path);
  662. }
  663. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target) {
  664. std::string path;
  665. std::string open_target;
  666. switch (target) {
  667. case GameListOpenTarget::SaveData: {
  668. open_target = "Save Data";
  669. const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
  670. ASSERT(program_id != 0);
  671. Service::Account::ProfileManager manager{};
  672. const auto user_ids = manager.GetAllUsers();
  673. QStringList list;
  674. for (const auto& user_id : user_ids) {
  675. if (user_id == Service::Account::UUID{})
  676. continue;
  677. Service::Account::ProfileBase base;
  678. if (!manager.GetProfileBase(user_id, base))
  679. continue;
  680. list.push_back(QString::fromStdString(Common::StringFromFixedZeroTerminatedBuffer(
  681. reinterpret_cast<const char*>(base.username.data()), base.username.size())));
  682. }
  683. bool ok = false;
  684. const auto index_string =
  685. QInputDialog::getItem(this, tr("Select User"),
  686. tr("Please select the user's save data you would like to open."),
  687. list, Settings::values.current_user, false, &ok);
  688. if (!ok)
  689. return;
  690. const auto index = list.indexOf(index_string);
  691. ASSERT(index != -1 && index < 8);
  692. const auto user_id = manager.GetUser(index);
  693. ASSERT(user_id);
  694. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser,
  695. FileSys::SaveDataType::SaveData,
  696. program_id, user_id->uuid, 0);
  697. if (!FileUtil::Exists(path)) {
  698. FileUtil::CreateFullPath(path);
  699. FileUtil::CreateDir(path);
  700. }
  701. break;
  702. }
  703. case GameListOpenTarget::ModData: {
  704. open_target = "Mod Data";
  705. const auto load_dir = FileUtil::GetUserPath(FileUtil::UserPath::LoadDir);
  706. path = fmt::format("{}{:016X}", load_dir, program_id);
  707. break;
  708. }
  709. default:
  710. UNIMPLEMENTED();
  711. }
  712. const QString qpath = QString::fromStdString(path);
  713. const QDir dir(qpath);
  714. if (!dir.exists()) {
  715. QMessageBox::warning(this,
  716. tr("Error Opening %1 Folder").arg(QString::fromStdString(open_target)),
  717. tr("Folder does not exist!"));
  718. return;
  719. }
  720. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target, program_id);
  721. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  722. }
  723. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  724. std::size_t out = 0;
  725. for (const auto& subdir : dir->GetSubdirectories()) {
  726. out += 1 + CalculateRomFSEntrySize(subdir, full);
  727. }
  728. return out + (full ? dir->GetFiles().size() : 0);
  729. }
  730. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  731. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  732. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  733. return false;
  734. if (dialog.wasCanceled())
  735. return false;
  736. if (full) {
  737. for (const auto& file : src->GetFiles()) {
  738. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  739. if (!FileSys::VfsRawCopy(file, out, block_size))
  740. return false;
  741. dialog.setValue(dialog.value() + 1);
  742. if (dialog.wasCanceled())
  743. return false;
  744. }
  745. }
  746. for (const auto& dir : src->GetSubdirectories()) {
  747. const auto out = dest->CreateSubdirectory(dir->GetName());
  748. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  749. return false;
  750. dialog.setValue(dialog.value() + 1);
  751. if (dialog.wasCanceled())
  752. return false;
  753. }
  754. return true;
  755. }
  756. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path) {
  757. const auto failed = [this] {
  758. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  759. tr("There was an error copying the RomFS files or the user "
  760. "cancelled the operation."));
  761. };
  762. const auto loader = Loader::GetLoader(vfs->OpenFile(game_path, FileSys::Mode::Read));
  763. if (loader == nullptr) {
  764. failed();
  765. return;
  766. }
  767. FileSys::VirtualFile file;
  768. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  769. failed();
  770. return;
  771. }
  772. const auto installed = Service::FileSystem::GetUnionContents();
  773. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  774. if (!romfs_title_id) {
  775. failed();
  776. return;
  777. }
  778. const auto path = fmt::format(
  779. "{}{:016X}/romfs", FileUtil::GetUserPath(FileUtil::UserPath::DumpDir), *romfs_title_id);
  780. FileSys::VirtualFile romfs;
  781. if (*romfs_title_id == program_id) {
  782. romfs = file;
  783. } else {
  784. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  785. }
  786. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  787. if (extracted == nullptr) {
  788. failed();
  789. return;
  790. }
  791. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  792. if (out == nullptr) {
  793. failed();
  794. vfs->DeleteDirectory(path);
  795. return;
  796. }
  797. bool ok;
  798. const auto res = QInputDialog::getItem(
  799. this, tr("Select RomFS Dump Mode"),
  800. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  801. "files into the new directory while <br>skeleton will only create the directory "
  802. "structure."),
  803. {"Full", "Skeleton"}, 0, false, &ok);
  804. if (!ok) {
  805. failed();
  806. vfs->DeleteDirectory(path);
  807. return;
  808. }
  809. const auto full = res == "Full";
  810. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  811. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  812. static_cast<s32>(entry_size), this);
  813. progress.setWindowModality(Qt::WindowModal);
  814. progress.setMinimumDuration(100);
  815. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  816. progress.close();
  817. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  818. tr("The operation completed successfully."));
  819. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  820. } else {
  821. progress.close();
  822. failed();
  823. vfs->DeleteDirectory(path);
  824. }
  825. }
  826. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  827. QClipboard* clipboard = QGuiApplication::clipboard();
  828. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  829. }
  830. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  831. const CompatibilityList& compatibility_list) {
  832. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  833. QString directory;
  834. if (it != compatibility_list.end())
  835. directory = it->second.second;
  836. QDesktopServices::openUrl(QUrl("https://yuzu-emu.org/game/" + directory));
  837. }
  838. void GMainWindow::OnMenuLoadFile() {
  839. const QString extensions =
  840. QString("*.").append(GameList::supported_file_extensions.join(" *.")).append(" main");
  841. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  842. "%1 is an identifier for the Switch executable file extensions.")
  843. .arg(extensions);
  844. const QString filename = QFileDialog::getOpenFileName(
  845. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  846. if (filename.isEmpty()) {
  847. return;
  848. }
  849. UISettings::values.roms_path = QFileInfo(filename).path();
  850. BootGame(filename);
  851. }
  852. void GMainWindow::OnMenuLoadFolder() {
  853. const QString dir_path =
  854. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  855. if (dir_path.isNull()) {
  856. return;
  857. }
  858. const QDir dir{dir_path};
  859. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  860. if (matching_main.size() == 1) {
  861. BootGame(dir.path() + DIR_SEP + matching_main[0]);
  862. } else {
  863. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  864. tr("The directory you have selected does not contain a 'main' file."));
  865. }
  866. }
  867. void GMainWindow::OnMenuInstallToNAND() {
  868. const QString file_filter =
  869. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  870. "(*.nca);;Nintendo Submissions Package (*.nsp);;NX Cartridge "
  871. "Image (*.xci)");
  872. QString filename = QFileDialog::getOpenFileName(this, tr("Install File"),
  873. UISettings::values.roms_path, file_filter);
  874. if (filename.isEmpty()) {
  875. return;
  876. }
  877. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  878. const FileSys::VirtualFile& dest, std::size_t block_size) {
  879. if (src == nullptr || dest == nullptr)
  880. return false;
  881. if (!dest->Resize(src->GetSize()))
  882. return false;
  883. std::array<u8, 0x1000> buffer{};
  884. const int progress_maximum = static_cast<int>(src->GetSize() / buffer.size());
  885. QProgressDialog progress(
  886. tr("Installing file \"%1\"...").arg(QString::fromStdString(src->GetName())),
  887. tr("Cancel"), 0, progress_maximum, this);
  888. progress.setWindowModality(Qt::WindowModal);
  889. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  890. if (progress.wasCanceled()) {
  891. dest->Resize(0);
  892. return false;
  893. }
  894. const int progress_value = static_cast<int>(i / buffer.size());
  895. progress.setValue(progress_value);
  896. const auto read = src->Read(buffer.data(), buffer.size(), i);
  897. dest->Write(buffer.data(), read, i);
  898. }
  899. return true;
  900. };
  901. const auto success = [this]() {
  902. QMessageBox::information(this, tr("Successfully Installed"),
  903. tr("The file was successfully installed."));
  904. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  905. };
  906. const auto failed = [this]() {
  907. QMessageBox::warning(
  908. this, tr("Failed to Install"),
  909. tr("There was an error while attempting to install the provided file. It "
  910. "could have an incorrect format or be missing metadata. Please "
  911. "double-check your file and try again."));
  912. };
  913. const auto overwrite = [this]() {
  914. return QMessageBox::question(this, tr("Failed to Install"),
  915. tr("The file you are attempting to install already exists "
  916. "in the cache. Would you like to overwrite it?")) ==
  917. QMessageBox::Yes;
  918. };
  919. if (filename.endsWith("xci", Qt::CaseInsensitive) ||
  920. filename.endsWith("nsp", Qt::CaseInsensitive)) {
  921. std::shared_ptr<FileSys::NSP> nsp;
  922. if (filename.endsWith("nsp", Qt::CaseInsensitive)) {
  923. nsp = std::make_shared<FileSys::NSP>(
  924. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  925. if (nsp->IsExtractedType())
  926. failed();
  927. } else {
  928. const auto xci = std::make_shared<FileSys::XCI>(
  929. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  930. nsp = xci->GetSecurePartitionNSP();
  931. }
  932. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  933. failed();
  934. return;
  935. }
  936. const auto res =
  937. Service::FileSystem::GetUserNANDContents()->InstallEntry(*nsp, false, qt_raw_copy);
  938. if (res == FileSys::InstallResult::Success) {
  939. success();
  940. } else {
  941. if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  942. if (overwrite()) {
  943. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  944. *nsp, true, qt_raw_copy);
  945. if (res2 == FileSys::InstallResult::Success) {
  946. success();
  947. } else {
  948. failed();
  949. }
  950. }
  951. } else {
  952. failed();
  953. }
  954. }
  955. } else {
  956. const auto nca = std::make_shared<FileSys::NCA>(
  957. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  958. const auto id = nca->GetStatus();
  959. // Game updates necessary are missing base RomFS
  960. if (id != Loader::ResultStatus::Success &&
  961. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  962. failed();
  963. return;
  964. }
  965. const QStringList tt_options{tr("System Application"),
  966. tr("System Archive"),
  967. tr("System Application Update"),
  968. tr("Firmware Package (Type A)"),
  969. tr("Firmware Package (Type B)"),
  970. tr("Game"),
  971. tr("Game Update"),
  972. tr("Game DLC"),
  973. tr("Delta Title")};
  974. bool ok;
  975. const auto item = QInputDialog::getItem(
  976. this, tr("Select NCA Install Type..."),
  977. tr("Please select the type of title you would like to install this NCA as:\n(In "
  978. "most instances, the default 'Game' is fine.)"),
  979. tt_options, 5, false, &ok);
  980. auto index = tt_options.indexOf(item);
  981. if (!ok || index == -1) {
  982. QMessageBox::warning(this, tr("Failed to Install"),
  983. tr("The title type you selected for the NCA is invalid."));
  984. return;
  985. }
  986. // If index is equal to or past Game, add the jump in TitleType.
  987. if (index >= 5) {
  988. index += static_cast<size_t>(FileSys::TitleType::Application) -
  989. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  990. }
  991. FileSys::InstallResult res;
  992. if (index >= static_cast<size_t>(FileSys::TitleType::Application)) {
  993. res = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  994. *nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  995. } else {
  996. res = Service::FileSystem::GetSystemNANDContents()->InstallEntry(
  997. *nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  998. }
  999. if (res == FileSys::InstallResult::Success) {
  1000. success();
  1001. } else if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  1002. if (overwrite()) {
  1003. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  1004. *nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1005. if (res2 == FileSys::InstallResult::Success) {
  1006. success();
  1007. } else {
  1008. failed();
  1009. }
  1010. }
  1011. } else {
  1012. failed();
  1013. }
  1014. }
  1015. }
  1016. void GMainWindow::OnMenuSelectGameListRoot() {
  1017. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1018. if (!dir_path.isEmpty()) {
  1019. UISettings::values.gamedir = dir_path;
  1020. game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan);
  1021. }
  1022. }
  1023. void GMainWindow::OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget target) {
  1024. const auto res = QMessageBox::information(
  1025. this, tr("Changing Emulated Directory"),
  1026. tr("You are about to change the emulated %1 directory of the system. Please note "
  1027. "that this does not also move the contents of the previous directory to the "
  1028. "new one and you will have to do that yourself.")
  1029. .arg(target == EmulatedDirectoryTarget::SDMC ? tr("SD card") : tr("NAND")),
  1030. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1031. if (res == QMessageBox::Cancel)
  1032. return;
  1033. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1034. if (!dir_path.isEmpty()) {
  1035. FileUtil::GetUserPath(target == EmulatedDirectoryTarget::SDMC ? FileUtil::UserPath::SDMCDir
  1036. : FileUtil::UserPath::NANDDir,
  1037. dir_path.toStdString());
  1038. Service::FileSystem::CreateFactories(*vfs);
  1039. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1040. }
  1041. }
  1042. void GMainWindow::OnMenuRecentFile() {
  1043. QAction* action = qobject_cast<QAction*>(sender());
  1044. assert(action);
  1045. const QString filename = action->data().toString();
  1046. if (QFileInfo::exists(filename)) {
  1047. BootGame(filename);
  1048. } else {
  1049. // Display an error message and remove the file from the list.
  1050. QMessageBox::information(this, tr("File not found"),
  1051. tr("File \"%1\" not found").arg(filename));
  1052. UISettings::values.recent_files.removeOne(filename);
  1053. UpdateRecentFiles();
  1054. }
  1055. }
  1056. void GMainWindow::OnStartGame() {
  1057. emu_thread->SetRunning(true);
  1058. qRegisterMetaType<Core::Frontend::SoftwareKeyboardParameters>(
  1059. "Core::Frontend::SoftwareKeyboardParameters");
  1060. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  1061. qRegisterMetaType<std::string>("std::string");
  1062. qRegisterMetaType<std::optional<std::u16string>>("std::optional<std::u16string>");
  1063. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  1064. ui.action_Start->setEnabled(false);
  1065. ui.action_Start->setText(tr("Continue"));
  1066. ui.action_Pause->setEnabled(true);
  1067. ui.action_Stop->setEnabled(true);
  1068. ui.action_Restart->setEnabled(true);
  1069. ui.action_Report_Compatibility->setEnabled(true);
  1070. discord_rpc->Update();
  1071. ui.action_Load_Amiibo->setEnabled(true);
  1072. }
  1073. void GMainWindow::OnPauseGame() {
  1074. emu_thread->SetRunning(false);
  1075. ui.action_Start->setEnabled(true);
  1076. ui.action_Pause->setEnabled(false);
  1077. ui.action_Stop->setEnabled(true);
  1078. }
  1079. void GMainWindow::OnStopGame() {
  1080. ShutdownGame();
  1081. }
  1082. void GMainWindow::OnMenuReportCompatibility() {
  1083. if (!Settings::values.yuzu_token.empty() && !Settings::values.yuzu_username.empty()) {
  1084. CompatDB compatdb{this};
  1085. compatdb.exec();
  1086. } else {
  1087. QMessageBox::critical(
  1088. this, tr("Missing yuzu Account"),
  1089. tr("In order to submit a game compatibility test case, you must link your yuzu "
  1090. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  1091. "&gt; "
  1092. "Web."));
  1093. }
  1094. }
  1095. void GMainWindow::ToggleFullscreen() {
  1096. if (!emulation_running) {
  1097. return;
  1098. }
  1099. if (ui.action_Fullscreen->isChecked()) {
  1100. ShowFullscreen();
  1101. } else {
  1102. HideFullscreen();
  1103. }
  1104. }
  1105. void GMainWindow::ShowFullscreen() {
  1106. if (ui.action_Single_Window_Mode->isChecked()) {
  1107. UISettings::values.geometry = saveGeometry();
  1108. ui.menubar->hide();
  1109. statusBar()->hide();
  1110. showFullScreen();
  1111. } else {
  1112. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1113. render_window->showFullScreen();
  1114. }
  1115. }
  1116. void GMainWindow::HideFullscreen() {
  1117. if (ui.action_Single_Window_Mode->isChecked()) {
  1118. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  1119. ui.menubar->show();
  1120. showNormal();
  1121. restoreGeometry(UISettings::values.geometry);
  1122. } else {
  1123. render_window->showNormal();
  1124. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  1125. }
  1126. }
  1127. void GMainWindow::ToggleWindowMode() {
  1128. if (ui.action_Single_Window_Mode->isChecked()) {
  1129. // Render in the main window...
  1130. render_window->BackupGeometry();
  1131. ui.horizontalLayout->addWidget(render_window);
  1132. render_window->setFocusPolicy(Qt::ClickFocus);
  1133. if (emulation_running) {
  1134. render_window->setVisible(true);
  1135. render_window->setFocus();
  1136. game_list->hide();
  1137. }
  1138. } else {
  1139. // Render in a separate window...
  1140. ui.horizontalLayout->removeWidget(render_window);
  1141. render_window->setParent(nullptr);
  1142. render_window->setFocusPolicy(Qt::NoFocus);
  1143. if (emulation_running) {
  1144. render_window->setVisible(true);
  1145. render_window->RestoreGeometry();
  1146. game_list->show();
  1147. }
  1148. }
  1149. }
  1150. void GMainWindow::OnConfigure() {
  1151. ConfigureDialog configureDialog(this, hotkey_registry);
  1152. auto old_theme = UISettings::values.theme;
  1153. const bool old_discord_presence = UISettings::values.enable_discord_presence;
  1154. auto result = configureDialog.exec();
  1155. if (result == QDialog::Accepted) {
  1156. configureDialog.applyConfiguration();
  1157. if (UISettings::values.theme != old_theme)
  1158. UpdateUITheme();
  1159. if (UISettings::values.enable_discord_presence != old_discord_presence)
  1160. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  1161. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1162. if (reload) {
  1163. game_list->PopulateAsync(UISettings::values.gamedir,
  1164. UISettings::values.gamedir_deepscan);
  1165. }
  1166. config->Save();
  1167. }
  1168. }
  1169. void GMainWindow::OnLoadAmiibo() {
  1170. const QString extensions{"*.bin"};
  1171. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  1172. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), "", file_filter);
  1173. if (filename.isEmpty()) {
  1174. return;
  1175. }
  1176. Core::System& system{Core::System::GetInstance()};
  1177. Service::SM::ServiceManager& sm = system.ServiceManager();
  1178. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  1179. if (nfc == nullptr) {
  1180. return;
  1181. }
  1182. QFile nfc_file{filename};
  1183. if (!nfc_file.open(QIODevice::ReadOnly)) {
  1184. QMessageBox::warning(this, tr("Error opening Amiibo data file"),
  1185. tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
  1186. return;
  1187. }
  1188. const u64 nfc_file_size = nfc_file.size();
  1189. std::vector<u8> buffer(nfc_file_size);
  1190. const u64 read_size = nfc_file.read(reinterpret_cast<char*>(buffer.data()), nfc_file_size);
  1191. if (nfc_file_size != read_size) {
  1192. QMessageBox::warning(this, tr("Error reading Amiibo data file"),
  1193. tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
  1194. "was only able to read %2 bytes.")
  1195. .arg(nfc_file_size)
  1196. .arg(read_size));
  1197. return;
  1198. }
  1199. if (!nfc->LoadAmiibo(buffer)) {
  1200. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  1201. tr("Unable to load Amiibo data."));
  1202. }
  1203. }
  1204. void GMainWindow::OnOpenYuzuFolder() {
  1205. QDesktopServices::openUrl(QUrl::fromLocalFile(
  1206. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::UserDir))));
  1207. }
  1208. void GMainWindow::OnAbout() {
  1209. AboutDialog aboutDialog(this);
  1210. aboutDialog.exec();
  1211. }
  1212. void GMainWindow::OnToggleFilterBar() {
  1213. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  1214. if (ui.action_Show_Filter_Bar->isChecked()) {
  1215. game_list->setFilterFocus();
  1216. } else {
  1217. game_list->clearFilter();
  1218. }
  1219. }
  1220. void GMainWindow::UpdateStatusBar() {
  1221. if (emu_thread == nullptr) {
  1222. status_bar_update_timer.stop();
  1223. return;
  1224. }
  1225. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  1226. if (Settings::values.use_frame_limit) {
  1227. emu_speed_label->setText(tr("Speed: %1% / %2%")
  1228. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  1229. .arg(Settings::values.frame_limit));
  1230. } else {
  1231. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  1232. }
  1233. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  1234. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  1235. emu_speed_label->setVisible(true);
  1236. game_fps_label->setVisible(true);
  1237. emu_frametime_label->setVisible(true);
  1238. }
  1239. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  1240. QMessageBox::StandardButton answer;
  1241. QString status_message;
  1242. const QString common_message =
  1243. tr("The game you are trying to load requires additional files from your Switch to be "
  1244. "dumped "
  1245. "before playing.<br/><br/>For more information on dumping these files, please see the "
  1246. "following wiki page: <a "
  1247. "href='https://yuzu-emu.org/wiki/"
  1248. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  1249. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  1250. "quit "
  1251. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  1252. "data, or other bugs.");
  1253. switch (result) {
  1254. case Core::System::ResultStatus::ErrorSystemFiles: {
  1255. QString message = "yuzu was unable to locate a Switch system archive";
  1256. if (!details.empty()) {
  1257. message.append(tr(": %1. ").arg(details.c_str()));
  1258. } else {
  1259. message.append(". ");
  1260. }
  1261. message.append(common_message);
  1262. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  1263. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1264. status_message = "System Archive Missing";
  1265. break;
  1266. }
  1267. case Core::System::ResultStatus::ErrorSharedFont: {
  1268. QString message = tr("yuzu was unable to locate the Switch shared fonts. ");
  1269. message.append(common_message);
  1270. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  1271. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1272. status_message = "Shared Font Missing";
  1273. break;
  1274. }
  1275. default:
  1276. answer = QMessageBox::question(
  1277. this, tr("Fatal Error"),
  1278. tr("yuzu has encountered a fatal error, please see the log for more details. "
  1279. "For more information on accessing the log, please see the following page: "
  1280. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  1281. "to "
  1282. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  1283. "list? "
  1284. "Continuing emulation may result in crashes, corrupted save data, or other "
  1285. "bugs."),
  1286. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1287. status_message = "Fatal Error encountered";
  1288. break;
  1289. }
  1290. if (answer == QMessageBox::Yes) {
  1291. if (emu_thread) {
  1292. ShutdownGame();
  1293. }
  1294. } else {
  1295. // Only show the message if the game is still running.
  1296. if (emu_thread) {
  1297. emu_thread->SetRunning(true);
  1298. message_label->setText(status_message);
  1299. message_label->setVisible(true);
  1300. }
  1301. }
  1302. }
  1303. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  1304. if (behavior == ReinitializeKeyBehavior::Warning) {
  1305. const auto res = QMessageBox::information(
  1306. this, tr("Confirm Key Rederivation"),
  1307. tr("You are about to force rederive all of your keys. \nIf you do not know what this "
  1308. "means or what you are doing, \nthis is a potentially destructive action. \nPlease "
  1309. "make "
  1310. "sure this is what you want \nand optionally make backups.\n\nThis will delete your "
  1311. "autogenerated key files and re-run the key derivation module."),
  1312. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1313. if (res == QMessageBox::Cancel)
  1314. return;
  1315. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1316. "prod.keys_autogenerated");
  1317. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1318. "console.keys_autogenerated");
  1319. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1320. "title.keys_autogenerated");
  1321. }
  1322. Core::Crypto::KeyManager keys{};
  1323. if (keys.BaseDeriveNecessary()) {
  1324. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory(
  1325. FileUtil::GetUserPath(FileUtil::UserPath::SysDataDir), FileSys::Mode::Read)};
  1326. const auto function = [this, &keys, &pdm] {
  1327. keys.PopulateFromPartitionData(pdm);
  1328. Service::FileSystem::CreateFactories(*vfs);
  1329. keys.DeriveETicket(pdm);
  1330. };
  1331. QString errors;
  1332. if (!pdm.HasFuses())
  1333. errors += tr("- Missing fuses - Cannot derive SBK\n");
  1334. if (!pdm.HasBoot0())
  1335. errors += tr("- Missing BOOT0 - Cannot derive master keys\n");
  1336. if (!pdm.HasPackage2())
  1337. errors += tr("- Missing BCPKG2-1-Normal-Main - Cannot derive general keys\n");
  1338. if (!pdm.HasProdInfo())
  1339. errors += tr("- Missing PRODINFO - Cannot derive title keys\n");
  1340. if (!errors.isEmpty()) {
  1341. QMessageBox::warning(
  1342. this, tr("Warning Missing Derivation Components"),
  1343. tr("The following are missing from your configuration that may hinder key "
  1344. "derivation. It will be attempted but may not complete.<br><br>") +
  1345. errors +
  1346. tr("<br><br>You can get all of these and dump all of your games easily by "
  1347. "following <a href='https://yuzu-emu.org/help/quickstart/'>the "
  1348. "quickstart guide</a>. Alternatively, you can use another method of dumping "
  1349. "to obtain all of your keys."));
  1350. }
  1351. QProgressDialog prog;
  1352. prog.setRange(0, 0);
  1353. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  1354. "system's performance."));
  1355. prog.setWindowTitle(tr("Deriving Keys"));
  1356. prog.show();
  1357. auto future = QtConcurrent::run(function);
  1358. while (!future.isFinished()) {
  1359. QCoreApplication::processEvents();
  1360. }
  1361. prog.close();
  1362. }
  1363. Service::FileSystem::CreateFactories(*vfs);
  1364. if (behavior == ReinitializeKeyBehavior::Warning) {
  1365. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1366. }
  1367. }
  1368. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(
  1369. const FileSys::RegisteredCacheUnion& installed, u64 program_id) {
  1370. const auto dlc_entries =
  1371. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1372. std::vector<FileSys::RegisteredCacheEntry> dlc_match;
  1373. dlc_match.reserve(dlc_entries.size());
  1374. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  1375. [&program_id, &installed](const FileSys::RegisteredCacheEntry& entry) {
  1376. return (entry.title_id & DLC_BASE_TITLE_ID_MASK) == program_id &&
  1377. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  1378. });
  1379. std::vector<u64> romfs_tids;
  1380. romfs_tids.push_back(program_id);
  1381. for (const auto& entry : dlc_match)
  1382. romfs_tids.push_back(entry.title_id);
  1383. if (romfs_tids.size() > 1) {
  1384. QStringList list{"Base"};
  1385. for (std::size_t i = 1; i < romfs_tids.size(); ++i)
  1386. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  1387. bool ok;
  1388. const auto res = QInputDialog::getItem(
  1389. this, tr("Select RomFS Dump Target"),
  1390. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  1391. if (!ok) {
  1392. return {};
  1393. }
  1394. return romfs_tids[list.indexOf(res)];
  1395. }
  1396. return program_id;
  1397. }
  1398. bool GMainWindow::ConfirmClose() {
  1399. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  1400. return true;
  1401. QMessageBox::StandardButton answer =
  1402. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  1403. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1404. return answer != QMessageBox::No;
  1405. }
  1406. void GMainWindow::closeEvent(QCloseEvent* event) {
  1407. if (!ConfirmClose()) {
  1408. event->ignore();
  1409. return;
  1410. }
  1411. if (!ui.action_Fullscreen->isChecked()) {
  1412. UISettings::values.geometry = saveGeometry();
  1413. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1414. }
  1415. UISettings::values.state = saveState();
  1416. #if MICROPROFILE_ENABLED
  1417. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  1418. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  1419. #endif
  1420. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  1421. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  1422. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  1423. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  1424. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  1425. UISettings::values.first_start = false;
  1426. game_list->SaveInterfaceLayout();
  1427. hotkey_registry.SaveHotkeys();
  1428. // Shutdown session if the emu thread is active...
  1429. if (emu_thread != nullptr)
  1430. ShutdownGame();
  1431. render_window->close();
  1432. QWidget::closeEvent(event);
  1433. }
  1434. static bool IsSingleFileDropEvent(QDropEvent* event) {
  1435. const QMimeData* mimeData = event->mimeData();
  1436. return mimeData->hasUrls() && mimeData->urls().length() == 1;
  1437. }
  1438. void GMainWindow::dropEvent(QDropEvent* event) {
  1439. if (IsSingleFileDropEvent(event) && ConfirmChangeGame()) {
  1440. const QMimeData* mimeData = event->mimeData();
  1441. QString filename = mimeData->urls().at(0).toLocalFile();
  1442. BootGame(filename);
  1443. }
  1444. }
  1445. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  1446. if (IsSingleFileDropEvent(event)) {
  1447. event->acceptProposedAction();
  1448. }
  1449. }
  1450. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  1451. event->acceptProposedAction();
  1452. }
  1453. bool GMainWindow::ConfirmChangeGame() {
  1454. if (emu_thread == nullptr)
  1455. return true;
  1456. auto answer = QMessageBox::question(
  1457. this, tr("yuzu"),
  1458. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  1459. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1460. return answer != QMessageBox::No;
  1461. }
  1462. void GMainWindow::filterBarSetChecked(bool state) {
  1463. ui.action_Show_Filter_Bar->setChecked(state);
  1464. emit(OnToggleFilterBar());
  1465. }
  1466. void GMainWindow::UpdateUITheme() {
  1467. QStringList theme_paths(default_theme_paths);
  1468. if (UISettings::values.theme != UISettings::themes[0].second &&
  1469. !UISettings::values.theme.isEmpty()) {
  1470. const QString theme_uri(":" + UISettings::values.theme + "/style.qss");
  1471. QFile f(theme_uri);
  1472. if (f.open(QFile::ReadOnly | QFile::Text)) {
  1473. QTextStream ts(&f);
  1474. qApp->setStyleSheet(ts.readAll());
  1475. GMainWindow::setStyleSheet(ts.readAll());
  1476. } else {
  1477. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  1478. }
  1479. theme_paths.append(QStringList{":/icons/default", ":/icons/" + UISettings::values.theme});
  1480. QIcon::setThemeName(":/icons/" + UISettings::values.theme);
  1481. } else {
  1482. qApp->setStyleSheet("");
  1483. GMainWindow::setStyleSheet("");
  1484. theme_paths.append(QStringList{":/icons/default"});
  1485. QIcon::setThemeName(":/icons/default");
  1486. }
  1487. QIcon::setThemeSearchPaths(theme_paths);
  1488. emit UpdateThemedIcons();
  1489. }
  1490. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  1491. #ifdef USE_DISCORD_PRESENCE
  1492. if (state) {
  1493. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  1494. } else {
  1495. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1496. }
  1497. #else
  1498. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1499. #endif
  1500. discord_rpc->Update();
  1501. }
  1502. #ifdef main
  1503. #undef main
  1504. #endif
  1505. int main(int argc, char* argv[]) {
  1506. Common::DetachedTasks detached_tasks;
  1507. MicroProfileOnThreadCreate("Frontend");
  1508. SCOPE_EXIT({ MicroProfileShutdown(); });
  1509. // Init settings params
  1510. QCoreApplication::setOrganizationName("yuzu team");
  1511. QCoreApplication::setApplicationName("yuzu");
  1512. QApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  1513. QApplication app(argc, argv);
  1514. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  1515. // generating shaders
  1516. setlocale(LC_ALL, "C");
  1517. GMainWindow main_window;
  1518. // After settings have been loaded by GMainWindow, apply the filter
  1519. main_window.show();
  1520. int result = app.exec();
  1521. detached_tasks.WaitForAllTasks();
  1522. return result;
  1523. }