main.cpp 68 KB

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