main.cpp 83 KB

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