main.cpp 91 KB

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