main.cpp 92 KB

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