main.cpp 90 KB

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