main.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  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_program_interface_query)
  451. unsupported_ext.append("ARB_program_interface_query");
  452. if (!GLAD_GL_ARB_separate_shader_objects)
  453. unsupported_ext.append("ARB_separate_shader_objects");
  454. if (!GLAD_GL_ARB_vertex_attrib_binding)
  455. unsupported_ext.append("ARB_vertex_attrib_binding");
  456. if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
  457. unsupported_ext.append("ARB_vertex_type_10f_11f_11f_rev");
  458. if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
  459. unsupported_ext.append("ARB_texture_mirror_clamp_to_edge");
  460. if (!GLAD_GL_ARB_base_instance)
  461. unsupported_ext.append("ARB_base_instance");
  462. if (!GLAD_GL_ARB_texture_storage)
  463. unsupported_ext.append("ARB_texture_storage");
  464. if (!GLAD_GL_ARB_multi_bind)
  465. unsupported_ext.append("ARB_multi_bind");
  466. if (!GLAD_GL_ARB_copy_image)
  467. unsupported_ext.append("ARB_copy_image");
  468. // Extensions required to support some texture formats.
  469. if (!GLAD_GL_EXT_texture_compression_s3tc)
  470. unsupported_ext.append("EXT_texture_compression_s3tc");
  471. if (!GLAD_GL_ARB_texture_compression_rgtc)
  472. unsupported_ext.append("ARB_texture_compression_rgtc");
  473. if (!GLAD_GL_ARB_texture_compression_bptc)
  474. unsupported_ext.append("ARB_texture_compression_bptc");
  475. if (!GLAD_GL_ARB_depth_buffer_float)
  476. unsupported_ext.append("ARB_depth_buffer_float");
  477. for (const QString& ext : unsupported_ext)
  478. LOG_CRITICAL(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  479. return unsupported_ext;
  480. }
  481. bool GMainWindow::LoadROM(const QString& filename) {
  482. // Shutdown previous session if the emu thread is still active...
  483. if (emu_thread != nullptr)
  484. ShutdownGame();
  485. render_window->InitRenderTarget();
  486. render_window->MakeCurrent();
  487. if (!gladLoadGL()) {
  488. QMessageBox::critical(this, tr("Error while initializing OpenGL 4.3 Core!"),
  489. tr("Your GPU may not support OpenGL 4.3, or you do not "
  490. "have the latest graphics driver."));
  491. return false;
  492. }
  493. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  494. if (!unsupported_gl_extensions.empty()) {
  495. QMessageBox::critical(this, tr("Error while initializing OpenGL Core!"),
  496. tr("Your GPU may not support one or more required OpenGL"
  497. "extensions. Please ensure you have the latest graphics "
  498. "driver.<br><br>Unsupported extensions:<br>") +
  499. unsupported_gl_extensions.join("<br>"));
  500. return false;
  501. }
  502. Core::System& system{Core::System::GetInstance()};
  503. system.SetFilesystem(vfs);
  504. system.SetGPUDebugContext(debug_context);
  505. system.SetSoftwareKeyboard(std::make_unique<QtSoftwareKeyboard>(*this));
  506. const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
  507. const auto drd_callout =
  508. (UISettings::values.callout_flags & static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  509. if (result == Core::System::ResultStatus::Success &&
  510. system.GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  511. drd_callout) {
  512. UISettings::values.callout_flags |= static_cast<u32>(CalloutFlag::DRDDeprecation);
  513. QMessageBox::warning(
  514. this, tr("Warning Outdated Game Format"),
  515. tr("You are using the deconstructed ROM directory format for this game, which is an "
  516. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  517. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  518. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  519. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  520. "wiki</a>. This message will not be shown again."));
  521. }
  522. render_window->DoneCurrent();
  523. if (result != Core::System::ResultStatus::Success) {
  524. switch (result) {
  525. case Core::System::ResultStatus::ErrorGetLoader:
  526. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  527. QMessageBox::critical(this, tr("Error while loading ROM!"),
  528. tr("The ROM format is not supported."));
  529. break;
  530. case Core::System::ResultStatus::ErrorSystemMode:
  531. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  532. QMessageBox::critical(this, tr("Error while loading ROM!"),
  533. tr("Could not determine the system mode."));
  534. break;
  535. case Core::System::ResultStatus::ErrorVideoCore:
  536. QMessageBox::critical(
  537. this, tr("An error occurred initializing the video core."),
  538. tr("yuzu has encountered an error while running the video core, please see the "
  539. "log for more details."
  540. "For more information on accessing the log, please see the following page: "
  541. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  542. "to "
  543. "Upload the Log File</a>."
  544. "Ensure that you have the latest graphics drivers for your GPU."));
  545. break;
  546. default:
  547. if (static_cast<u32>(result) >
  548. static_cast<u32>(Core::System::ResultStatus::ErrorLoader)) {
  549. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  550. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  551. const u16 error_id = static_cast<u16>(result) - loader_id;
  552. QMessageBox::critical(
  553. this, tr("Error while loading ROM!"),
  554. QString::fromStdString(fmt::format(
  555. "While attempting to load the ROM requested, an error occured. Please "
  556. "refer to the yuzu wiki for more information or the yuzu discord for "
  557. "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
  558. loader_id, error_id, static_cast<Loader::ResultStatus>(error_id))));
  559. } else {
  560. QMessageBox::critical(
  561. this, tr("Error while loading ROM!"),
  562. tr("An unknown error occurred. Please see the log for more details."));
  563. }
  564. break;
  565. }
  566. return false;
  567. }
  568. game_path = filename;
  569. Core::Telemetry().AddField(Telemetry::FieldType::App, "Frontend", "Qt");
  570. return true;
  571. }
  572. void GMainWindow::BootGame(const QString& filename) {
  573. LOG_INFO(Frontend, "yuzu starting...");
  574. StoreRecentFile(filename); // Put the filename on top of the list
  575. if (!LoadROM(filename))
  576. return;
  577. // Create and start the emulation thread
  578. emu_thread = std::make_unique<EmuThread>(render_window);
  579. emit EmulationStarting(emu_thread.get());
  580. render_window->moveContext();
  581. emu_thread->start();
  582. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  583. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  584. // before the CPU continues
  585. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  586. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  587. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  588. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  589. // Update the GUI
  590. if (ui.action_Single_Window_Mode->isChecked()) {
  591. game_list->hide();
  592. }
  593. status_bar_update_timer.start(2000);
  594. std::string title_name;
  595. const auto res = Core::System::GetInstance().GetGameName(title_name);
  596. if (res != Loader::ResultStatus::Success) {
  597. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  598. const auto [nacp, icon_file] = FileSys::PatchManager(title_id).GetControlMetadata();
  599. if (nacp != nullptr)
  600. title_name = nacp->GetApplicationName();
  601. if (title_name.empty())
  602. title_name = FileUtil::GetFilename(filename.toStdString());
  603. }
  604. setWindowTitle(QString("yuzu %1| %4 | %2-%3")
  605. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc,
  606. QString::fromStdString(title_name)));
  607. render_window->show();
  608. render_window->setFocus();
  609. emulation_running = true;
  610. if (ui.action_Fullscreen->isChecked()) {
  611. ShowFullscreen();
  612. }
  613. OnStartGame();
  614. }
  615. void GMainWindow::ShutdownGame() {
  616. discord_rpc->Pause();
  617. emu_thread->RequestStop();
  618. emit EmulationStopping();
  619. // Wait for emulation thread to complete and delete it
  620. emu_thread->wait();
  621. emu_thread = nullptr;
  622. discord_rpc->Update();
  623. // The emulation is stopped, so closing the window or not does not matter anymore
  624. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  625. // Update the GUI
  626. ui.action_Start->setEnabled(false);
  627. ui.action_Start->setText(tr("Start"));
  628. ui.action_Pause->setEnabled(false);
  629. ui.action_Stop->setEnabled(false);
  630. ui.action_Restart->setEnabled(false);
  631. ui.action_Report_Compatibility->setEnabled(false);
  632. ui.action_Load_Amiibo->setEnabled(false);
  633. render_window->hide();
  634. game_list->show();
  635. game_list->setFilterFocus();
  636. setWindowTitle(QString("yuzu %1| %2-%3")
  637. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc));
  638. // Disable status bar updates
  639. status_bar_update_timer.stop();
  640. message_label->setVisible(false);
  641. emu_speed_label->setVisible(false);
  642. game_fps_label->setVisible(false);
  643. emu_frametime_label->setVisible(false);
  644. emulation_running = false;
  645. game_path.clear();
  646. }
  647. void GMainWindow::StoreRecentFile(const QString& filename) {
  648. UISettings::values.recent_files.prepend(filename);
  649. UISettings::values.recent_files.removeDuplicates();
  650. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  651. UISettings::values.recent_files.removeLast();
  652. }
  653. UpdateRecentFiles();
  654. }
  655. void GMainWindow::UpdateRecentFiles() {
  656. const int num_recent_files =
  657. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  658. for (int i = 0; i < num_recent_files; i++) {
  659. const QString text = QString("&%1. %2").arg(i + 1).arg(
  660. QFileInfo(UISettings::values.recent_files[i]).fileName());
  661. actions_recent_files[i]->setText(text);
  662. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  663. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  664. actions_recent_files[i]->setVisible(true);
  665. }
  666. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  667. actions_recent_files[j]->setVisible(false);
  668. }
  669. // Enable the recent files menu if the list isn't empty
  670. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  671. }
  672. void GMainWindow::OnGameListLoadFile(QString game_path) {
  673. BootGame(game_path);
  674. }
  675. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target) {
  676. std::string path;
  677. std::string open_target;
  678. switch (target) {
  679. case GameListOpenTarget::SaveData: {
  680. open_target = "Save Data";
  681. const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
  682. ASSERT(program_id != 0);
  683. Service::Account::ProfileManager manager{};
  684. const auto user_ids = manager.GetAllUsers();
  685. QStringList list;
  686. for (const auto& user_id : user_ids) {
  687. if (user_id == Service::Account::UUID{})
  688. continue;
  689. Service::Account::ProfileBase base;
  690. if (!manager.GetProfileBase(user_id, base))
  691. continue;
  692. list.push_back(QString::fromStdString(Common::StringFromFixedZeroTerminatedBuffer(
  693. reinterpret_cast<const char*>(base.username.data()), base.username.size())));
  694. }
  695. bool ok = false;
  696. const auto index_string =
  697. QInputDialog::getItem(this, tr("Select User"),
  698. tr("Please select the user's save data you would like to open."),
  699. list, Settings::values.current_user, false, &ok);
  700. if (!ok)
  701. return;
  702. const auto index = list.indexOf(index_string);
  703. ASSERT(index != -1 && index < 8);
  704. const auto user_id = manager.GetUser(index);
  705. ASSERT(user_id);
  706. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser,
  707. FileSys::SaveDataType::SaveData,
  708. program_id, user_id->uuid, 0);
  709. if (!FileUtil::Exists(path)) {
  710. FileUtil::CreateFullPath(path);
  711. FileUtil::CreateDir(path);
  712. }
  713. break;
  714. }
  715. case GameListOpenTarget::ModData: {
  716. open_target = "Mod Data";
  717. const auto load_dir = FileUtil::GetUserPath(FileUtil::UserPath::LoadDir);
  718. path = fmt::format("{}{:016X}", load_dir, program_id);
  719. break;
  720. }
  721. default:
  722. UNIMPLEMENTED();
  723. }
  724. const QString qpath = QString::fromStdString(path);
  725. const QDir dir(qpath);
  726. if (!dir.exists()) {
  727. QMessageBox::warning(this,
  728. tr("Error Opening %1 Folder").arg(QString::fromStdString(open_target)),
  729. tr("Folder does not exist!"));
  730. return;
  731. }
  732. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target, program_id);
  733. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  734. }
  735. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  736. std::size_t out = 0;
  737. for (const auto& subdir : dir->GetSubdirectories()) {
  738. out += 1 + CalculateRomFSEntrySize(subdir, full);
  739. }
  740. return out + (full ? dir->GetFiles().size() : 0);
  741. }
  742. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  743. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  744. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  745. return false;
  746. if (dialog.wasCanceled())
  747. return false;
  748. if (full) {
  749. for (const auto& file : src->GetFiles()) {
  750. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  751. if (!FileSys::VfsRawCopy(file, out, block_size))
  752. return false;
  753. dialog.setValue(dialog.value() + 1);
  754. if (dialog.wasCanceled())
  755. return false;
  756. }
  757. }
  758. for (const auto& dir : src->GetSubdirectories()) {
  759. const auto out = dest->CreateSubdirectory(dir->GetName());
  760. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  761. return false;
  762. dialog.setValue(dialog.value() + 1);
  763. if (dialog.wasCanceled())
  764. return false;
  765. }
  766. return true;
  767. }
  768. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path) {
  769. const auto failed = [this] {
  770. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  771. tr("There was an error copying the RomFS files or the user "
  772. "cancelled the operation."));
  773. };
  774. const auto loader = Loader::GetLoader(vfs->OpenFile(game_path, FileSys::Mode::Read));
  775. if (loader == nullptr) {
  776. failed();
  777. return;
  778. }
  779. FileSys::VirtualFile file;
  780. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  781. failed();
  782. return;
  783. }
  784. const auto installed = Service::FileSystem::GetUnionContents();
  785. auto romfs_title_id = SelectRomFSDumpTarget(*installed, program_id);
  786. if (!romfs_title_id) {
  787. failed();
  788. return;
  789. }
  790. const auto path = fmt::format(
  791. "{}{:016X}/romfs", FileUtil::GetUserPath(FileUtil::UserPath::DumpDir), *romfs_title_id);
  792. FileSys::VirtualFile romfs;
  793. if (*romfs_title_id == program_id) {
  794. romfs = file;
  795. } else {
  796. romfs = installed->GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  797. }
  798. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  799. if (extracted == nullptr) {
  800. failed();
  801. return;
  802. }
  803. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  804. if (out == nullptr) {
  805. failed();
  806. vfs->DeleteDirectory(path);
  807. return;
  808. }
  809. bool ok;
  810. const auto res = QInputDialog::getItem(
  811. this, tr("Select RomFS Dump Mode"),
  812. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  813. "files into the new directory while <br>skeleton will only create the directory "
  814. "structure."),
  815. {"Full", "Skeleton"}, 0, false, &ok);
  816. if (!ok) {
  817. failed();
  818. vfs->DeleteDirectory(path);
  819. return;
  820. }
  821. const auto full = res == "Full";
  822. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  823. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  824. static_cast<s32>(entry_size), this);
  825. progress.setWindowModality(Qt::WindowModal);
  826. progress.setMinimumDuration(100);
  827. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  828. progress.close();
  829. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  830. tr("The operation completed successfully."));
  831. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  832. } else {
  833. progress.close();
  834. failed();
  835. vfs->DeleteDirectory(path);
  836. }
  837. }
  838. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  839. QClipboard* clipboard = QGuiApplication::clipboard();
  840. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  841. }
  842. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  843. const CompatibilityList& compatibility_list) {
  844. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  845. QString directory;
  846. if (it != compatibility_list.end())
  847. directory = it->second.second;
  848. QDesktopServices::openUrl(QUrl("https://yuzu-emu.org/game/" + directory));
  849. }
  850. void GMainWindow::OnMenuLoadFile() {
  851. const QString extensions =
  852. QString("*.").append(GameList::supported_file_extensions.join(" *.")).append(" main");
  853. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  854. "%1 is an identifier for the Switch executable file extensions.")
  855. .arg(extensions);
  856. const QString filename = QFileDialog::getOpenFileName(
  857. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  858. if (filename.isEmpty()) {
  859. return;
  860. }
  861. UISettings::values.roms_path = QFileInfo(filename).path();
  862. BootGame(filename);
  863. }
  864. void GMainWindow::OnMenuLoadFolder() {
  865. const QString dir_path =
  866. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  867. if (dir_path.isNull()) {
  868. return;
  869. }
  870. const QDir dir{dir_path};
  871. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  872. if (matching_main.size() == 1) {
  873. BootGame(dir.path() + DIR_SEP + matching_main[0]);
  874. } else {
  875. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  876. tr("The directory you have selected does not contain a 'main' file."));
  877. }
  878. }
  879. void GMainWindow::OnMenuInstallToNAND() {
  880. const QString file_filter =
  881. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  882. "(*.nca);;Nintendo Submissions Package (*.nsp);;NX Cartridge "
  883. "Image (*.xci)");
  884. QString filename = QFileDialog::getOpenFileName(this, tr("Install File"),
  885. UISettings::values.roms_path, file_filter);
  886. if (filename.isEmpty()) {
  887. return;
  888. }
  889. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  890. const FileSys::VirtualFile& dest, std::size_t block_size) {
  891. if (src == nullptr || dest == nullptr)
  892. return false;
  893. if (!dest->Resize(src->GetSize()))
  894. return false;
  895. std::array<u8, 0x1000> buffer{};
  896. const int progress_maximum = static_cast<int>(src->GetSize() / buffer.size());
  897. QProgressDialog progress(
  898. tr("Installing file \"%1\"...").arg(QString::fromStdString(src->GetName())),
  899. tr("Cancel"), 0, progress_maximum, this);
  900. progress.setWindowModality(Qt::WindowModal);
  901. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  902. if (progress.wasCanceled()) {
  903. dest->Resize(0);
  904. return false;
  905. }
  906. const int progress_value = static_cast<int>(i / buffer.size());
  907. progress.setValue(progress_value);
  908. const auto read = src->Read(buffer.data(), buffer.size(), i);
  909. dest->Write(buffer.data(), read, i);
  910. }
  911. return true;
  912. };
  913. const auto success = [this]() {
  914. QMessageBox::information(this, tr("Successfully Installed"),
  915. tr("The file was successfully installed."));
  916. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  917. };
  918. const auto failed = [this]() {
  919. QMessageBox::warning(
  920. this, tr("Failed to Install"),
  921. tr("There was an error while attempting to install the provided file. It "
  922. "could have an incorrect format or be missing metadata. Please "
  923. "double-check your file and try again."));
  924. };
  925. const auto overwrite = [this]() {
  926. return QMessageBox::question(this, tr("Failed to Install"),
  927. tr("The file you are attempting to install already exists "
  928. "in the cache. Would you like to overwrite it?")) ==
  929. QMessageBox::Yes;
  930. };
  931. if (filename.endsWith("xci", Qt::CaseInsensitive) ||
  932. filename.endsWith("nsp", Qt::CaseInsensitive)) {
  933. std::shared_ptr<FileSys::NSP> nsp;
  934. if (filename.endsWith("nsp", Qt::CaseInsensitive)) {
  935. nsp = std::make_shared<FileSys::NSP>(
  936. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  937. if (nsp->IsExtractedType())
  938. failed();
  939. } else {
  940. const auto xci = std::make_shared<FileSys::XCI>(
  941. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  942. nsp = xci->GetSecurePartitionNSP();
  943. }
  944. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  945. failed();
  946. return;
  947. }
  948. const auto res =
  949. Service::FileSystem::GetUserNANDContents()->InstallEntry(nsp, false, qt_raw_copy);
  950. if (res == FileSys::InstallResult::Success) {
  951. success();
  952. } else {
  953. if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  954. if (overwrite()) {
  955. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  956. nsp, true, qt_raw_copy);
  957. if (res2 == FileSys::InstallResult::Success) {
  958. success();
  959. } else {
  960. failed();
  961. }
  962. }
  963. } else {
  964. failed();
  965. }
  966. }
  967. } else {
  968. const auto nca = std::make_shared<FileSys::NCA>(
  969. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  970. const auto id = nca->GetStatus();
  971. // Game updates necessary are missing base RomFS
  972. if (id != Loader::ResultStatus::Success &&
  973. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  974. failed();
  975. return;
  976. }
  977. const QStringList tt_options{tr("System Application"),
  978. tr("System Archive"),
  979. tr("System Application Update"),
  980. tr("Firmware Package (Type A)"),
  981. tr("Firmware Package (Type B)"),
  982. tr("Game"),
  983. tr("Game Update"),
  984. tr("Game DLC"),
  985. tr("Delta Title")};
  986. bool ok;
  987. const auto item = QInputDialog::getItem(
  988. this, tr("Select NCA Install Type..."),
  989. tr("Please select the type of title you would like to install this NCA as:\n(In "
  990. "most instances, the default 'Game' is fine.)"),
  991. tt_options, 5, false, &ok);
  992. auto index = tt_options.indexOf(item);
  993. if (!ok || index == -1) {
  994. QMessageBox::warning(this, tr("Failed to Install"),
  995. tr("The title type you selected for the NCA is invalid."));
  996. return;
  997. }
  998. // If index is equal to or past Game, add the jump in TitleType.
  999. if (index >= 5) {
  1000. index += static_cast<size_t>(FileSys::TitleType::Application) -
  1001. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  1002. }
  1003. FileSys::InstallResult res;
  1004. if (index >= static_cast<size_t>(FileSys::TitleType::Application)) {
  1005. res = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  1006. nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  1007. } else {
  1008. res = Service::FileSystem::GetSystemNANDContents()->InstallEntry(
  1009. nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  1010. }
  1011. if (res == FileSys::InstallResult::Success) {
  1012. success();
  1013. } else if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  1014. if (overwrite()) {
  1015. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  1016. nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1017. if (res2 == FileSys::InstallResult::Success) {
  1018. success();
  1019. } else {
  1020. failed();
  1021. }
  1022. }
  1023. } else {
  1024. failed();
  1025. }
  1026. }
  1027. }
  1028. void GMainWindow::OnMenuSelectGameListRoot() {
  1029. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1030. if (!dir_path.isEmpty()) {
  1031. UISettings::values.gamedir = dir_path;
  1032. game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan);
  1033. }
  1034. }
  1035. void GMainWindow::OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget target) {
  1036. const auto res = QMessageBox::information(
  1037. this, tr("Changing Emulated Directory"),
  1038. tr("You are about to change the emulated %1 directory of the system. Please note "
  1039. "that this does not also move the contents of the previous directory to the "
  1040. "new one and you will have to do that yourself.")
  1041. .arg(target == EmulatedDirectoryTarget::SDMC ? tr("SD card") : tr("NAND")),
  1042. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1043. if (res == QMessageBox::Cancel)
  1044. return;
  1045. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1046. if (!dir_path.isEmpty()) {
  1047. FileUtil::GetUserPath(target == EmulatedDirectoryTarget::SDMC ? FileUtil::UserPath::SDMCDir
  1048. : FileUtil::UserPath::NANDDir,
  1049. dir_path.toStdString());
  1050. Service::FileSystem::CreateFactories(*vfs);
  1051. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1052. }
  1053. }
  1054. void GMainWindow::OnMenuRecentFile() {
  1055. QAction* action = qobject_cast<QAction*>(sender());
  1056. assert(action);
  1057. const QString filename = action->data().toString();
  1058. if (QFileInfo::exists(filename)) {
  1059. BootGame(filename);
  1060. } else {
  1061. // Display an error message and remove the file from the list.
  1062. QMessageBox::information(this, tr("File not found"),
  1063. tr("File \"%1\" not found").arg(filename));
  1064. UISettings::values.recent_files.removeOne(filename);
  1065. UpdateRecentFiles();
  1066. }
  1067. }
  1068. void GMainWindow::OnStartGame() {
  1069. emu_thread->SetRunning(true);
  1070. qRegisterMetaType<Core::Frontend::SoftwareKeyboardParameters>(
  1071. "Core::Frontend::SoftwareKeyboardParameters");
  1072. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  1073. qRegisterMetaType<std::string>("std::string");
  1074. qRegisterMetaType<std::optional<std::u16string>>("std::optional<std::u16string>");
  1075. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  1076. ui.action_Start->setEnabled(false);
  1077. ui.action_Start->setText(tr("Continue"));
  1078. ui.action_Pause->setEnabled(true);
  1079. ui.action_Stop->setEnabled(true);
  1080. ui.action_Restart->setEnabled(true);
  1081. ui.action_Report_Compatibility->setEnabled(true);
  1082. discord_rpc->Update();
  1083. ui.action_Load_Amiibo->setEnabled(true);
  1084. }
  1085. void GMainWindow::OnPauseGame() {
  1086. emu_thread->SetRunning(false);
  1087. ui.action_Start->setEnabled(true);
  1088. ui.action_Pause->setEnabled(false);
  1089. ui.action_Stop->setEnabled(true);
  1090. }
  1091. void GMainWindow::OnStopGame() {
  1092. ShutdownGame();
  1093. }
  1094. void GMainWindow::OnMenuReportCompatibility() {
  1095. if (!Settings::values.yuzu_token.empty() && !Settings::values.yuzu_username.empty()) {
  1096. CompatDB compatdb{this};
  1097. compatdb.exec();
  1098. } else {
  1099. QMessageBox::critical(
  1100. this, tr("Missing yuzu Account"),
  1101. tr("In order to submit a game compatibility test case, you must link your yuzu "
  1102. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  1103. "&gt; "
  1104. "Web."));
  1105. }
  1106. }
  1107. void GMainWindow::ToggleFullscreen() {
  1108. if (!emulation_running) {
  1109. return;
  1110. }
  1111. if (ui.action_Fullscreen->isChecked()) {
  1112. ShowFullscreen();
  1113. } else {
  1114. HideFullscreen();
  1115. }
  1116. }
  1117. void GMainWindow::ShowFullscreen() {
  1118. if (ui.action_Single_Window_Mode->isChecked()) {
  1119. UISettings::values.geometry = saveGeometry();
  1120. ui.menubar->hide();
  1121. statusBar()->hide();
  1122. showFullScreen();
  1123. } else {
  1124. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1125. render_window->showFullScreen();
  1126. }
  1127. }
  1128. void GMainWindow::HideFullscreen() {
  1129. if (ui.action_Single_Window_Mode->isChecked()) {
  1130. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  1131. ui.menubar->show();
  1132. showNormal();
  1133. restoreGeometry(UISettings::values.geometry);
  1134. } else {
  1135. render_window->showNormal();
  1136. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  1137. }
  1138. }
  1139. void GMainWindow::ToggleWindowMode() {
  1140. if (ui.action_Single_Window_Mode->isChecked()) {
  1141. // Render in the main window...
  1142. render_window->BackupGeometry();
  1143. ui.horizontalLayout->addWidget(render_window);
  1144. render_window->setFocusPolicy(Qt::ClickFocus);
  1145. if (emulation_running) {
  1146. render_window->setVisible(true);
  1147. render_window->setFocus();
  1148. game_list->hide();
  1149. }
  1150. } else {
  1151. // Render in a separate window...
  1152. ui.horizontalLayout->removeWidget(render_window);
  1153. render_window->setParent(nullptr);
  1154. render_window->setFocusPolicy(Qt::NoFocus);
  1155. if (emulation_running) {
  1156. render_window->setVisible(true);
  1157. render_window->RestoreGeometry();
  1158. game_list->show();
  1159. }
  1160. }
  1161. }
  1162. void GMainWindow::OnConfigure() {
  1163. ConfigureDialog configureDialog(this, hotkey_registry);
  1164. auto old_theme = UISettings::values.theme;
  1165. const bool old_discord_presence = UISettings::values.enable_discord_presence;
  1166. auto result = configureDialog.exec();
  1167. if (result == QDialog::Accepted) {
  1168. configureDialog.applyConfiguration();
  1169. if (UISettings::values.theme != old_theme)
  1170. UpdateUITheme();
  1171. if (UISettings::values.enable_discord_presence != old_discord_presence)
  1172. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  1173. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1174. if (reload) {
  1175. game_list->PopulateAsync(UISettings::values.gamedir,
  1176. UISettings::values.gamedir_deepscan);
  1177. }
  1178. config->Save();
  1179. }
  1180. }
  1181. void GMainWindow::OnLoadAmiibo() {
  1182. const QString extensions{"*.bin"};
  1183. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  1184. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), "", file_filter);
  1185. if (filename.isEmpty()) {
  1186. return;
  1187. }
  1188. Core::System& system{Core::System::GetInstance()};
  1189. Service::SM::ServiceManager& sm = system.ServiceManager();
  1190. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  1191. if (nfc == nullptr) {
  1192. return;
  1193. }
  1194. QFile nfc_file{filename};
  1195. if (!nfc_file.open(QIODevice::ReadOnly)) {
  1196. QMessageBox::warning(this, tr("Error opening Amiibo data file"),
  1197. tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
  1198. return;
  1199. }
  1200. const u64 nfc_file_size = nfc_file.size();
  1201. std::vector<u8> buffer(nfc_file_size);
  1202. const u64 read_size = nfc_file.read(reinterpret_cast<char*>(buffer.data()), nfc_file_size);
  1203. if (nfc_file_size != read_size) {
  1204. QMessageBox::warning(this, tr("Error reading Amiibo data file"),
  1205. tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
  1206. "was only able to read %2 bytes.")
  1207. .arg(nfc_file_size)
  1208. .arg(read_size));
  1209. return;
  1210. }
  1211. if (!nfc->LoadAmiibo(buffer)) {
  1212. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  1213. tr("Unable to load Amiibo data."));
  1214. }
  1215. }
  1216. void GMainWindow::OnOpenYuzuFolder() {
  1217. QDesktopServices::openUrl(QUrl::fromLocalFile(
  1218. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::UserDir))));
  1219. }
  1220. void GMainWindow::OnAbout() {
  1221. AboutDialog aboutDialog(this);
  1222. aboutDialog.exec();
  1223. }
  1224. void GMainWindow::OnToggleFilterBar() {
  1225. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  1226. if (ui.action_Show_Filter_Bar->isChecked()) {
  1227. game_list->setFilterFocus();
  1228. } else {
  1229. game_list->clearFilter();
  1230. }
  1231. }
  1232. void GMainWindow::UpdateStatusBar() {
  1233. if (emu_thread == nullptr) {
  1234. status_bar_update_timer.stop();
  1235. return;
  1236. }
  1237. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  1238. if (Settings::values.use_frame_limit) {
  1239. emu_speed_label->setText(tr("Speed: %1% / %2%")
  1240. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  1241. .arg(Settings::values.frame_limit));
  1242. } else {
  1243. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  1244. }
  1245. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  1246. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  1247. emu_speed_label->setVisible(true);
  1248. game_fps_label->setVisible(true);
  1249. emu_frametime_label->setVisible(true);
  1250. }
  1251. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  1252. QMessageBox::StandardButton answer;
  1253. QString status_message;
  1254. const QString common_message =
  1255. tr("The game you are trying to load requires additional files from your Switch to be "
  1256. "dumped "
  1257. "before playing.<br/><br/>For more information on dumping these files, please see the "
  1258. "following wiki page: <a "
  1259. "href='https://yuzu-emu.org/wiki/"
  1260. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  1261. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  1262. "quit "
  1263. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  1264. "data, or other bugs.");
  1265. switch (result) {
  1266. case Core::System::ResultStatus::ErrorSystemFiles: {
  1267. QString message = "yuzu was unable to locate a Switch system archive";
  1268. if (!details.empty()) {
  1269. message.append(tr(": %1. ").arg(details.c_str()));
  1270. } else {
  1271. message.append(". ");
  1272. }
  1273. message.append(common_message);
  1274. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  1275. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1276. status_message = "System Archive Missing";
  1277. break;
  1278. }
  1279. case Core::System::ResultStatus::ErrorSharedFont: {
  1280. QString message = tr("yuzu was unable to locate the Switch shared fonts. ");
  1281. message.append(common_message);
  1282. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  1283. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1284. status_message = "Shared Font Missing";
  1285. break;
  1286. }
  1287. default:
  1288. answer = QMessageBox::question(
  1289. this, tr("Fatal Error"),
  1290. tr("yuzu has encountered a fatal error, please see the log for more details. "
  1291. "For more information on accessing the log, please see the following page: "
  1292. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  1293. "to "
  1294. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  1295. "list? "
  1296. "Continuing emulation may result in crashes, corrupted save data, or other "
  1297. "bugs."),
  1298. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1299. status_message = "Fatal Error encountered";
  1300. break;
  1301. }
  1302. if (answer == QMessageBox::Yes) {
  1303. if (emu_thread) {
  1304. ShutdownGame();
  1305. }
  1306. } else {
  1307. // Only show the message if the game is still running.
  1308. if (emu_thread) {
  1309. emu_thread->SetRunning(true);
  1310. message_label->setText(status_message);
  1311. message_label->setVisible(true);
  1312. }
  1313. }
  1314. }
  1315. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  1316. if (behavior == ReinitializeKeyBehavior::Warning) {
  1317. const auto res = QMessageBox::information(
  1318. this, tr("Confirm Key Rederivation"),
  1319. tr("You are about to force rederive all of your keys. \nIf you do not know what this "
  1320. "means or what you are doing, \nthis is a potentially destructive action. \nPlease "
  1321. "make "
  1322. "sure this is what you want \nand optionally make backups.\n\nThis will delete your "
  1323. "autogenerated key files and re-run the key derivation module."),
  1324. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1325. if (res == QMessageBox::Cancel)
  1326. return;
  1327. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1328. "prod.keys_autogenerated");
  1329. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1330. "console.keys_autogenerated");
  1331. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1332. "title.keys_autogenerated");
  1333. }
  1334. Core::Crypto::KeyManager keys{};
  1335. if (keys.BaseDeriveNecessary()) {
  1336. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory(
  1337. FileUtil::GetUserPath(FileUtil::UserPath::SysDataDir), FileSys::Mode::Read)};
  1338. const auto function = [this, &keys, &pdm] {
  1339. keys.PopulateFromPartitionData(pdm);
  1340. Service::FileSystem::CreateFactories(*vfs);
  1341. keys.DeriveETicket(pdm);
  1342. };
  1343. QString errors;
  1344. if (!pdm.HasFuses())
  1345. errors += tr("- Missing fuses - Cannot derive SBK\n");
  1346. if (!pdm.HasBoot0())
  1347. errors += tr("- Missing BOOT0 - Cannot derive master keys\n");
  1348. if (!pdm.HasPackage2())
  1349. errors += tr("- Missing BCPKG2-1-Normal-Main - Cannot derive general keys\n");
  1350. if (!pdm.HasProdInfo())
  1351. errors += tr("- Missing PRODINFO - Cannot derive title keys\n");
  1352. if (!errors.isEmpty()) {
  1353. QMessageBox::warning(
  1354. this, tr("Warning Missing Derivation Components"),
  1355. tr("The following are missing from your configuration that may hinder key "
  1356. "derivation. It will be attempted but may not complete.<br><br>") +
  1357. errors +
  1358. tr("<br><br>You can get all of these and dump all of your games easily by "
  1359. "following <a href='https://yuzu-emu.org/help/quickstart/'>the "
  1360. "quickstart guide</a>. Alternatively, you can use another method of dumping "
  1361. "to obtain all of your keys."));
  1362. }
  1363. QProgressDialog prog;
  1364. prog.setRange(0, 0);
  1365. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  1366. "system's performance."));
  1367. prog.setWindowTitle(tr("Deriving Keys"));
  1368. prog.show();
  1369. auto future = QtConcurrent::run(function);
  1370. while (!future.isFinished()) {
  1371. QCoreApplication::processEvents();
  1372. }
  1373. prog.close();
  1374. }
  1375. Service::FileSystem::CreateFactories(*vfs);
  1376. if (behavior == ReinitializeKeyBehavior::Warning) {
  1377. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1378. }
  1379. }
  1380. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(
  1381. const FileSys::RegisteredCacheUnion& installed, u64 program_id) {
  1382. const auto dlc_entries =
  1383. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1384. std::vector<FileSys::RegisteredCacheEntry> dlc_match;
  1385. dlc_match.reserve(dlc_entries.size());
  1386. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  1387. [&program_id, &installed](const FileSys::RegisteredCacheEntry& entry) {
  1388. return (entry.title_id & DLC_BASE_TITLE_ID_MASK) == program_id &&
  1389. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  1390. });
  1391. std::vector<u64> romfs_tids;
  1392. romfs_tids.push_back(program_id);
  1393. for (const auto& entry : dlc_match)
  1394. romfs_tids.push_back(entry.title_id);
  1395. if (romfs_tids.size() > 1) {
  1396. QStringList list{"Base"};
  1397. for (std::size_t i = 1; i < romfs_tids.size(); ++i)
  1398. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  1399. bool ok;
  1400. const auto res = QInputDialog::getItem(
  1401. this, tr("Select RomFS Dump Target"),
  1402. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  1403. if (!ok) {
  1404. return {};
  1405. }
  1406. return romfs_tids[list.indexOf(res)];
  1407. }
  1408. return program_id;
  1409. }
  1410. bool GMainWindow::ConfirmClose() {
  1411. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  1412. return true;
  1413. QMessageBox::StandardButton answer =
  1414. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  1415. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1416. return answer != QMessageBox::No;
  1417. }
  1418. void GMainWindow::closeEvent(QCloseEvent* event) {
  1419. if (!ConfirmClose()) {
  1420. event->ignore();
  1421. return;
  1422. }
  1423. if (!ui.action_Fullscreen->isChecked()) {
  1424. UISettings::values.geometry = saveGeometry();
  1425. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1426. }
  1427. UISettings::values.state = saveState();
  1428. #if MICROPROFILE_ENABLED
  1429. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  1430. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  1431. #endif
  1432. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  1433. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  1434. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  1435. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  1436. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  1437. UISettings::values.first_start = false;
  1438. game_list->SaveInterfaceLayout();
  1439. hotkey_registry.SaveHotkeys();
  1440. // Shutdown session if the emu thread is active...
  1441. if (emu_thread != nullptr)
  1442. ShutdownGame();
  1443. render_window->close();
  1444. QWidget::closeEvent(event);
  1445. }
  1446. static bool IsSingleFileDropEvent(QDropEvent* event) {
  1447. const QMimeData* mimeData = event->mimeData();
  1448. return mimeData->hasUrls() && mimeData->urls().length() == 1;
  1449. }
  1450. void GMainWindow::dropEvent(QDropEvent* event) {
  1451. if (IsSingleFileDropEvent(event) && ConfirmChangeGame()) {
  1452. const QMimeData* mimeData = event->mimeData();
  1453. QString filename = mimeData->urls().at(0).toLocalFile();
  1454. BootGame(filename);
  1455. }
  1456. }
  1457. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  1458. if (IsSingleFileDropEvent(event)) {
  1459. event->acceptProposedAction();
  1460. }
  1461. }
  1462. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  1463. event->acceptProposedAction();
  1464. }
  1465. bool GMainWindow::ConfirmChangeGame() {
  1466. if (emu_thread == nullptr)
  1467. return true;
  1468. auto answer = QMessageBox::question(
  1469. this, tr("yuzu"),
  1470. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  1471. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1472. return answer != QMessageBox::No;
  1473. }
  1474. void GMainWindow::filterBarSetChecked(bool state) {
  1475. ui.action_Show_Filter_Bar->setChecked(state);
  1476. emit(OnToggleFilterBar());
  1477. }
  1478. void GMainWindow::UpdateUITheme() {
  1479. QStringList theme_paths(default_theme_paths);
  1480. if (UISettings::values.theme != UISettings::themes[0].second &&
  1481. !UISettings::values.theme.isEmpty()) {
  1482. const QString theme_uri(":" + UISettings::values.theme + "/style.qss");
  1483. QFile f(theme_uri);
  1484. if (f.open(QFile::ReadOnly | QFile::Text)) {
  1485. QTextStream ts(&f);
  1486. qApp->setStyleSheet(ts.readAll());
  1487. GMainWindow::setStyleSheet(ts.readAll());
  1488. } else {
  1489. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  1490. }
  1491. theme_paths.append(QStringList{":/icons/default", ":/icons/" + UISettings::values.theme});
  1492. QIcon::setThemeName(":/icons/" + UISettings::values.theme);
  1493. } else {
  1494. qApp->setStyleSheet("");
  1495. GMainWindow::setStyleSheet("");
  1496. theme_paths.append(QStringList{":/icons/default"});
  1497. QIcon::setThemeName(":/icons/default");
  1498. }
  1499. QIcon::setThemeSearchPaths(theme_paths);
  1500. emit UpdateThemedIcons();
  1501. }
  1502. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  1503. #ifdef USE_DISCORD_PRESENCE
  1504. if (state) {
  1505. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  1506. } else {
  1507. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1508. }
  1509. #else
  1510. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1511. #endif
  1512. discord_rpc->Update();
  1513. }
  1514. #ifdef main
  1515. #undef main
  1516. #endif
  1517. int main(int argc, char* argv[]) {
  1518. Common::DetachedTasks detached_tasks;
  1519. MicroProfileOnThreadCreate("Frontend");
  1520. SCOPE_EXIT({ MicroProfileShutdown(); });
  1521. // Init settings params
  1522. QCoreApplication::setOrganizationName("yuzu team");
  1523. QCoreApplication::setApplicationName("yuzu");
  1524. QApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  1525. QApplication app(argc, argv);
  1526. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  1527. // generating shaders
  1528. setlocale(LC_ALL, "C");
  1529. GMainWindow main_window;
  1530. // After settings have been loaded by GMainWindow, apply the filter
  1531. main_window.show();
  1532. int result = app.exec();
  1533. detached_tasks.WaitForAllTasks();
  1534. return result;
  1535. }