main.cpp 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435
  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/qt_controller.h"
  13. #include "applets/qt_error.h"
  14. #include "applets/qt_profile_select.h"
  15. #include "applets/qt_software_keyboard.h"
  16. #include "applets/qt_web_browser.h"
  17. #include "common/nvidia_flags.h"
  18. #include "configuration/configure_input.h"
  19. #include "configuration/configure_per_game.h"
  20. #include "configuration/configure_vibration.h"
  21. #include "core/file_sys/vfs.h"
  22. #include "core/file_sys/vfs_real.h"
  23. #include "core/frontend/applets/controller.h"
  24. #include "core/frontend/applets/general_frontend.h"
  25. #include "core/frontend/applets/software_keyboard.h"
  26. #include "core/hle/service/acc/profile_manager.h"
  27. #include "core/hle/service/am/applet_ae.h"
  28. #include "core/hle/service/am/applet_oe.h"
  29. #include "core/hle/service/am/applets/applets.h"
  30. // These are wrappers to avoid the calls to CreateDirectory and CreateFile because of the Windows
  31. // defines.
  32. static FileSys::VirtualDir VfsFilesystemCreateDirectoryWrapper(
  33. const FileSys::VirtualFilesystem& vfs, const std::string& path, FileSys::Mode mode) {
  34. return vfs->CreateDirectory(path, mode);
  35. }
  36. static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::VirtualDir& dir,
  37. const std::string& path) {
  38. return dir->CreateFile(path);
  39. }
  40. #include <fmt/ostream.h>
  41. #include <glad/glad.h>
  42. #define QT_NO_OPENGL
  43. #include <QClipboard>
  44. #include <QDesktopServices>
  45. #include <QDesktopWidget>
  46. #include <QDialogButtonBox>
  47. #include <QDir>
  48. #include <QFile>
  49. #include <QFileDialog>
  50. #include <QInputDialog>
  51. #include <QMessageBox>
  52. #include <QProgressBar>
  53. #include <QProgressDialog>
  54. #include <QPushButton>
  55. #include <QShortcut>
  56. #include <QStatusBar>
  57. #include <QString>
  58. #include <QSysInfo>
  59. #include <QUrl>
  60. #include <QtConcurrent/QtConcurrent>
  61. #include <fmt/format.h>
  62. #include "common/detached_tasks.h"
  63. #include "common/fs/fs.h"
  64. #include "common/fs/fs_paths.h"
  65. #include "common/fs/path_util.h"
  66. #include "common/logging/backend.h"
  67. #include "common/logging/filter.h"
  68. #include "common/logging/log.h"
  69. #include "common/memory_detect.h"
  70. #include "common/microprofile.h"
  71. #include "common/scm_rev.h"
  72. #include "common/scope_exit.h"
  73. #ifdef ARCHITECTURE_x86_64
  74. #include "common/x64/cpu_detect.h"
  75. #endif
  76. #include "common/settings.h"
  77. #include "common/telemetry.h"
  78. #include "core/core.h"
  79. #include "core/crypto/key_manager.h"
  80. #include "core/file_sys/card_image.h"
  81. #include "core/file_sys/common_funcs.h"
  82. #include "core/file_sys/content_archive.h"
  83. #include "core/file_sys/control_metadata.h"
  84. #include "core/file_sys/patch_manager.h"
  85. #include "core/file_sys/registered_cache.h"
  86. #include "core/file_sys/romfs.h"
  87. #include "core/file_sys/savedata_factory.h"
  88. #include "core/file_sys/submission_package.h"
  89. #include "core/hle/kernel/k_process.h"
  90. #include "core/hle/service/am/am.h"
  91. #include "core/hle/service/filesystem/filesystem.h"
  92. #include "core/hle/service/nfp/nfp.h"
  93. #include "core/hle/service/sm/sm.h"
  94. #include "core/loader/loader.h"
  95. #include "core/perf_stats.h"
  96. #include "core/telemetry_session.h"
  97. #include "input_common/main.h"
  98. #include "util/overlay_dialog.h"
  99. #include "video_core/gpu.h"
  100. #include "video_core/renderer_base.h"
  101. #include "video_core/shader_notify.h"
  102. #include "yuzu/about_dialog.h"
  103. #include "yuzu/bootmanager.h"
  104. #include "yuzu/compatdb.h"
  105. #include "yuzu/compatibility_list.h"
  106. #include "yuzu/configuration/config.h"
  107. #include "yuzu/configuration/configure_dialog.h"
  108. #include "yuzu/debugger/console.h"
  109. #include "yuzu/debugger/controller.h"
  110. #include "yuzu/debugger/profiler.h"
  111. #include "yuzu/debugger/wait_tree.h"
  112. #include "yuzu/discord.h"
  113. #include "yuzu/game_list.h"
  114. #include "yuzu/game_list_p.h"
  115. #include "yuzu/hotkeys.h"
  116. #include "yuzu/install_dialog.h"
  117. #include "yuzu/loading_screen.h"
  118. #include "yuzu/main.h"
  119. #include "yuzu/uisettings.h"
  120. #ifdef USE_DISCORD_PRESENCE
  121. #include "yuzu/discord_impl.h"
  122. #endif
  123. #ifdef QT_STATICPLUGIN
  124. Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
  125. #endif
  126. #ifdef _WIN32
  127. #include <windows.h>
  128. extern "C" {
  129. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  130. // graphics
  131. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  132. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  133. }
  134. #endif
  135. constexpr int default_mouse_timeout = 2500;
  136. /**
  137. * "Callouts" are one-time instructional messages shown to the user. In the config settings, there
  138. * is a bitfield "callout_flags" options, used to track if a message has already been shown to the
  139. * user. This is 32-bits - if we have more than 32 callouts, we should retire and recycle old ones.
  140. */
  141. enum class CalloutFlag : uint32_t {
  142. Telemetry = 0x1,
  143. DRDDeprecation = 0x2,
  144. };
  145. void GMainWindow::ShowTelemetryCallout() {
  146. if (UISettings::values.callout_flags.GetValue() &
  147. static_cast<uint32_t>(CalloutFlag::Telemetry)) {
  148. return;
  149. }
  150. UISettings::values.callout_flags =
  151. UISettings::values.callout_flags.GetValue() | static_cast<uint32_t>(CalloutFlag::Telemetry);
  152. const QString telemetry_message =
  153. tr("<a href='https://yuzu-emu.org/help/feature/telemetry/'>Anonymous "
  154. "data is collected</a> to help improve yuzu. "
  155. "<br/><br/>Would you like to share your usage data with us?");
  156. if (QMessageBox::question(this, tr("Telemetry"), telemetry_message) != QMessageBox::Yes) {
  157. Settings::values.enable_telemetry = false;
  158. Core::System::GetInstance().ApplySettings();
  159. }
  160. }
  161. const int GMainWindow::max_recent_files_item;
  162. static void RemoveCachedContents() {
  163. const auto cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir);
  164. const auto offline_fonts = cache_dir / "fonts";
  165. const auto offline_manual = cache_dir / "offline_web_applet_manual";
  166. const auto offline_legal_information = cache_dir / "offline_web_applet_legal_information";
  167. const auto offline_system_data = cache_dir / "offline_web_applet_system_data";
  168. Common::FS::RemoveDirRecursively(offline_fonts);
  169. Common::FS::RemoveDirRecursively(offline_manual);
  170. Common::FS::RemoveDirRecursively(offline_legal_information);
  171. Common::FS::RemoveDirRecursively(offline_system_data);
  172. }
  173. GMainWindow::GMainWindow()
  174. : input_subsystem{std::make_shared<InputCommon::InputSubsystem>()},
  175. config{std::make_unique<Config>()}, vfs{std::make_shared<FileSys::RealVfsFilesystem>()},
  176. provider{std::make_unique<FileSys::ManualContentProvider>()} {
  177. Common::Log::Initialize();
  178. LoadTranslation();
  179. setAcceptDrops(true);
  180. ui.setupUi(this);
  181. statusBar()->hide();
  182. default_theme_paths = QIcon::themeSearchPaths();
  183. UpdateUITheme();
  184. SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue());
  185. discord_rpc->Update();
  186. RegisterMetaTypes();
  187. InitializeWidgets();
  188. InitializeDebugWidgets();
  189. InitializeRecentFileMenuActions();
  190. InitializeHotkeys();
  191. SetDefaultUIGeometry();
  192. RestoreUIState();
  193. ConnectMenuEvents();
  194. ConnectWidgetEvents();
  195. const auto branch_name = std::string(Common::g_scm_branch);
  196. const auto description = std::string(Common::g_scm_desc);
  197. const auto build_id = std::string(Common::g_build_id);
  198. const auto yuzu_build = fmt::format("yuzu Development Build | {}-{}", branch_name, description);
  199. const auto override_build =
  200. fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id);
  201. const auto yuzu_build_version = override_build.empty() ? yuzu_build : override_build;
  202. LOG_INFO(Frontend, "yuzu Version: {}", yuzu_build_version);
  203. #ifdef ARCHITECTURE_x86_64
  204. const auto& caps = Common::GetCPUCaps();
  205. std::string cpu_string = caps.cpu_string;
  206. if (caps.avx || caps.avx2 || caps.avx512) {
  207. cpu_string += " | AVX";
  208. if (caps.avx512) {
  209. cpu_string += "512";
  210. } else if (caps.avx2) {
  211. cpu_string += '2';
  212. }
  213. if (caps.fma || caps.fma4) {
  214. cpu_string += " | FMA";
  215. }
  216. }
  217. LOG_INFO(Frontend, "Host CPU: {}", cpu_string);
  218. #endif
  219. LOG_INFO(Frontend, "Host OS: {}", QSysInfo::prettyProductName().toStdString());
  220. LOG_INFO(Frontend, "Host RAM: {:.2f} GB",
  221. Common::GetMemInfo().TotalPhysicalMemory / 1024.0f / 1024 / 1024);
  222. LOG_INFO(Frontend, "Host Swap: {:.2f} GB",
  223. Common::GetMemInfo().TotalSwapMemory / 1024.0f / 1024 / 1024);
  224. UpdateWindowTitle();
  225. show();
  226. Core::System::GetInstance().SetContentProvider(
  227. std::make_unique<FileSys::ContentProviderUnion>());
  228. Core::System::GetInstance().RegisterContentProvider(
  229. FileSys::ContentProviderUnionSlot::FrontendManual, provider.get());
  230. Core::System::GetInstance().GetFileSystemController().CreateFactories(*vfs);
  231. // Remove cached contents generated during the previous session
  232. RemoveCachedContents();
  233. // Gen keys if necessary
  234. OnReinitializeKeys(ReinitializeKeyBehavior::NoWarning);
  235. game_list->LoadCompatibilityList();
  236. game_list->PopulateAsync(UISettings::values.game_dirs);
  237. // Show one-time "callout" messages to the user
  238. ShowTelemetryCallout();
  239. // make sure menubar has the arrow cursor instead of inheriting from this
  240. ui.menubar->setCursor(QCursor());
  241. statusBar()->setCursor(QCursor());
  242. mouse_hide_timer.setInterval(default_mouse_timeout);
  243. connect(&mouse_hide_timer, &QTimer::timeout, this, &GMainWindow::HideMouseCursor);
  244. connect(ui.menubar, &QMenuBar::hovered, this, &GMainWindow::ShowMouseCursor);
  245. MigrateConfigFiles();
  246. ui.action_Fullscreen->setChecked(false);
  247. QStringList args = QApplication::arguments();
  248. if (args.size() < 2) {
  249. return;
  250. }
  251. QString game_path;
  252. for (int i = 1; i < args.size(); ++i) {
  253. // Preserves drag/drop functionality
  254. if (args.size() == 2 && !args[1].startsWith(QChar::fromLatin1('-'))) {
  255. game_path = args[1];
  256. break;
  257. }
  258. // Launch game in fullscreen mode
  259. if (args[i] == QStringLiteral("-f")) {
  260. ui.action_Fullscreen->setChecked(true);
  261. continue;
  262. }
  263. // Launch game with a specific user
  264. if (args[i] == QStringLiteral("-u")) {
  265. if (i >= args.size() - 1) {
  266. continue;
  267. }
  268. if (args[i + 1].startsWith(QChar::fromLatin1('-'))) {
  269. continue;
  270. }
  271. bool argument_ok;
  272. const std::size_t selected_user = args[++i].toUInt(&argument_ok);
  273. if (!argument_ok) {
  274. LOG_ERROR(Frontend, "Invalid user argument");
  275. continue;
  276. }
  277. const Service::Account::ProfileManager manager;
  278. if (!manager.UserExistsIndex(selected_user)) {
  279. LOG_ERROR(Frontend, "Selected user doesn't exist");
  280. continue;
  281. }
  282. Settings::values.current_user = static_cast<s32>(selected_user);
  283. continue;
  284. }
  285. // Launch game at path
  286. if (args[i] == QStringLiteral("-g")) {
  287. if (i >= args.size() - 1) {
  288. continue;
  289. }
  290. if (args[i + 1].startsWith(QChar::fromLatin1('-'))) {
  291. continue;
  292. }
  293. game_path = args[++i];
  294. }
  295. }
  296. if (!game_path.isEmpty()) {
  297. BootGame(game_path);
  298. }
  299. }
  300. GMainWindow::~GMainWindow() {
  301. // will get automatically deleted otherwise
  302. if (render_window->parent() == nullptr)
  303. delete render_window;
  304. }
  305. void GMainWindow::RegisterMetaTypes() {
  306. // Register integral and floating point types
  307. qRegisterMetaType<u8>("u8");
  308. qRegisterMetaType<u16>("u16");
  309. qRegisterMetaType<u32>("u32");
  310. qRegisterMetaType<u64>("u64");
  311. qRegisterMetaType<u128>("u128");
  312. qRegisterMetaType<s8>("s8");
  313. qRegisterMetaType<s16>("s16");
  314. qRegisterMetaType<s32>("s32");
  315. qRegisterMetaType<s64>("s64");
  316. qRegisterMetaType<f32>("f32");
  317. qRegisterMetaType<f64>("f64");
  318. // Register string types
  319. qRegisterMetaType<std::string>("std::string");
  320. qRegisterMetaType<std::wstring>("std::wstring");
  321. qRegisterMetaType<std::u8string>("std::u8string");
  322. qRegisterMetaType<std::u16string>("std::u16string");
  323. qRegisterMetaType<std::u32string>("std::u32string");
  324. qRegisterMetaType<std::string_view>("std::string_view");
  325. qRegisterMetaType<std::wstring_view>("std::wstring_view");
  326. qRegisterMetaType<std::u8string_view>("std::u8string_view");
  327. qRegisterMetaType<std::u16string_view>("std::u16string_view");
  328. qRegisterMetaType<std::u32string_view>("std::u32string_view");
  329. // Register applet types
  330. // Controller Applet
  331. qRegisterMetaType<Core::Frontend::ControllerParameters>("Core::Frontend::ControllerParameters");
  332. // Software Keyboard Applet
  333. qRegisterMetaType<Core::Frontend::KeyboardInitializeParameters>(
  334. "Core::Frontend::KeyboardInitializeParameters");
  335. qRegisterMetaType<Core::Frontend::InlineAppearParameters>(
  336. "Core::Frontend::InlineAppearParameters");
  337. qRegisterMetaType<Core::Frontend::InlineTextParameters>("Core::Frontend::InlineTextParameters");
  338. qRegisterMetaType<Service::AM::Applets::SwkbdResult>("Service::AM::Applets::SwkbdResult");
  339. qRegisterMetaType<Service::AM::Applets::SwkbdTextCheckResult>(
  340. "Service::AM::Applets::SwkbdTextCheckResult");
  341. qRegisterMetaType<Service::AM::Applets::SwkbdReplyType>("Service::AM::Applets::SwkbdReplyType");
  342. // Web Browser Applet
  343. qRegisterMetaType<Service::AM::Applets::WebExitReason>("Service::AM::Applets::WebExitReason");
  344. // Register loader types
  345. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  346. }
  347. void GMainWindow::ControllerSelectorReconfigureControllers(
  348. const Core::Frontend::ControllerParameters& parameters) {
  349. QtControllerSelectorDialog dialog(this, parameters, input_subsystem.get());
  350. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint |
  351. Qt::WindowTitleHint | Qt::WindowSystemMenuHint);
  352. dialog.setWindowModality(Qt::WindowModal);
  353. dialog.exec();
  354. emit ControllerSelectorReconfigureFinished();
  355. // Don't forget to apply settings.
  356. Core::System::GetInstance().ApplySettings();
  357. config->Save();
  358. UpdateStatusButtons();
  359. }
  360. void GMainWindow::ProfileSelectorSelectProfile() {
  361. QtProfileSelectionDialog dialog(this);
  362. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint |
  363. Qt::WindowTitleHint | Qt::WindowSystemMenuHint |
  364. Qt::WindowCloseButtonHint);
  365. dialog.setWindowModality(Qt::WindowModal);
  366. if (dialog.exec() == QDialog::Rejected) {
  367. emit ProfileSelectorFinishedSelection(std::nullopt);
  368. return;
  369. }
  370. const Service::Account::ProfileManager manager;
  371. const auto uuid = manager.GetUser(static_cast<std::size_t>(dialog.GetIndex()));
  372. if (!uuid.has_value()) {
  373. emit ProfileSelectorFinishedSelection(std::nullopt);
  374. return;
  375. }
  376. emit ProfileSelectorFinishedSelection(uuid);
  377. }
  378. void GMainWindow::SoftwareKeyboardInitialize(
  379. bool is_inline, Core::Frontend::KeyboardInitializeParameters initialize_parameters) {
  380. if (software_keyboard) {
  381. LOG_ERROR(Frontend, "The software keyboard is already initialized!");
  382. return;
  383. }
  384. software_keyboard = new QtSoftwareKeyboardDialog(render_window, Core::System::GetInstance(),
  385. is_inline, std::move(initialize_parameters));
  386. if (is_inline) {
  387. connect(
  388. software_keyboard, &QtSoftwareKeyboardDialog::SubmitInlineText, this,
  389. [this](Service::AM::Applets::SwkbdReplyType reply_type, std::u16string submitted_text,
  390. s32 cursor_position) {
  391. emit SoftwareKeyboardSubmitInlineText(reply_type, submitted_text, cursor_position);
  392. },
  393. Qt::QueuedConnection);
  394. } else {
  395. connect(
  396. software_keyboard, &QtSoftwareKeyboardDialog::SubmitNormalText, this,
  397. [this](Service::AM::Applets::SwkbdResult result, std::u16string submitted_text) {
  398. emit SoftwareKeyboardSubmitNormalText(result, submitted_text);
  399. },
  400. Qt::QueuedConnection);
  401. }
  402. }
  403. void GMainWindow::SoftwareKeyboardShowNormal() {
  404. if (!software_keyboard) {
  405. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  406. return;
  407. }
  408. const auto& layout = render_window->GetFramebufferLayout();
  409. const auto x = layout.screen.left;
  410. const auto y = layout.screen.top;
  411. const auto w = layout.screen.GetWidth();
  412. const auto h = layout.screen.GetHeight();
  413. software_keyboard->ShowNormalKeyboard(render_window->mapToGlobal(QPoint(x, y)), QSize(w, h));
  414. }
  415. void GMainWindow::SoftwareKeyboardShowTextCheck(
  416. Service::AM::Applets::SwkbdTextCheckResult text_check_result,
  417. std::u16string text_check_message) {
  418. if (!software_keyboard) {
  419. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  420. return;
  421. }
  422. software_keyboard->ShowTextCheckDialog(text_check_result, text_check_message);
  423. }
  424. void GMainWindow::SoftwareKeyboardShowInline(
  425. Core::Frontend::InlineAppearParameters appear_parameters) {
  426. if (!software_keyboard) {
  427. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  428. return;
  429. }
  430. const auto& layout = render_window->GetFramebufferLayout();
  431. const auto x =
  432. static_cast<int>(layout.screen.left + (0.5f * layout.screen.GetWidth() *
  433. ((2.0f * appear_parameters.key_top_translate_x) +
  434. (1.0f - appear_parameters.key_top_scale_x))));
  435. const auto y =
  436. static_cast<int>(layout.screen.top + (layout.screen.GetHeight() *
  437. ((2.0f * appear_parameters.key_top_translate_y) +
  438. (1.0f - appear_parameters.key_top_scale_y))));
  439. const auto w = static_cast<int>(layout.screen.GetWidth() * appear_parameters.key_top_scale_x);
  440. const auto h = static_cast<int>(layout.screen.GetHeight() * appear_parameters.key_top_scale_y);
  441. software_keyboard->ShowInlineKeyboard(std::move(appear_parameters),
  442. render_window->mapToGlobal(QPoint(x, y)), QSize(w, h));
  443. }
  444. void GMainWindow::SoftwareKeyboardHideInline() {
  445. if (!software_keyboard) {
  446. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  447. return;
  448. }
  449. software_keyboard->HideInlineKeyboard();
  450. }
  451. void GMainWindow::SoftwareKeyboardInlineTextChanged(
  452. Core::Frontend::InlineTextParameters text_parameters) {
  453. if (!software_keyboard) {
  454. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  455. return;
  456. }
  457. software_keyboard->InlineTextChanged(std::move(text_parameters));
  458. }
  459. void GMainWindow::SoftwareKeyboardExit() {
  460. if (!software_keyboard) {
  461. return;
  462. }
  463. software_keyboard->ExitKeyboard();
  464. software_keyboard = nullptr;
  465. }
  466. void GMainWindow::WebBrowserOpenWebPage(const std::string& main_url,
  467. const std::string& additional_args, bool is_local) {
  468. #ifdef YUZU_USE_QT_WEB_ENGINE
  469. if (disable_web_applet) {
  470. emit WebBrowserClosed(Service::AM::Applets::WebExitReason::WindowClosed,
  471. "http://localhost/");
  472. return;
  473. }
  474. QtNXWebEngineView web_browser_view(this, Core::System::GetInstance(), input_subsystem.get());
  475. ui.action_Pause->setEnabled(false);
  476. ui.action_Restart->setEnabled(false);
  477. ui.action_Stop->setEnabled(false);
  478. {
  479. QProgressDialog loading_progress(this);
  480. loading_progress.setLabelText(tr("Loading Web Applet..."));
  481. loading_progress.setRange(0, 3);
  482. loading_progress.setValue(0);
  483. if (is_local && !Common::FS::Exists(main_url)) {
  484. loading_progress.show();
  485. auto future = QtConcurrent::run([this] { emit WebBrowserExtractOfflineRomFS(); });
  486. while (!future.isFinished()) {
  487. QCoreApplication::processEvents();
  488. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  489. }
  490. }
  491. loading_progress.setValue(1);
  492. if (is_local) {
  493. web_browser_view.LoadLocalWebPage(main_url, additional_args);
  494. } else {
  495. web_browser_view.LoadExternalWebPage(main_url, additional_args);
  496. }
  497. if (render_window->IsLoadingComplete()) {
  498. render_window->hide();
  499. }
  500. const auto& layout = render_window->GetFramebufferLayout();
  501. web_browser_view.resize(layout.screen.GetWidth(), layout.screen.GetHeight());
  502. web_browser_view.move(layout.screen.left, layout.screen.top + menuBar()->height());
  503. web_browser_view.setZoomFactor(static_cast<qreal>(layout.screen.GetWidth()) /
  504. static_cast<qreal>(Layout::ScreenUndocked::Width));
  505. web_browser_view.setFocus();
  506. web_browser_view.show();
  507. loading_progress.setValue(2);
  508. QCoreApplication::processEvents();
  509. loading_progress.setValue(3);
  510. }
  511. bool exit_check = false;
  512. // TODO (Morph): Remove this
  513. QAction* exit_action = new QAction(tr("Disable Web Applet"), this);
  514. connect(exit_action, &QAction::triggered, this, [this, &web_browser_view] {
  515. const auto result = QMessageBox::warning(
  516. this, tr("Disable Web Applet"),
  517. tr("Disabling the web applet will cause it to not be shown again for the rest of the "
  518. "emulated session. This can lead to undefined behavior and should only be used with "
  519. "Super Mario 3D All-Stars. Are you sure you want to disable the web applet?"),
  520. QMessageBox::Yes | QMessageBox::No);
  521. if (result == QMessageBox::Yes) {
  522. disable_web_applet = true;
  523. web_browser_view.SetFinished(true);
  524. }
  525. });
  526. ui.menubar->addAction(exit_action);
  527. while (!web_browser_view.IsFinished()) {
  528. QCoreApplication::processEvents();
  529. if (!exit_check) {
  530. web_browser_view.page()->runJavaScript(
  531. QStringLiteral("end_applet;"), [&](const QVariant& variant) {
  532. exit_check = false;
  533. if (variant.toBool()) {
  534. web_browser_view.SetFinished(true);
  535. web_browser_view.SetExitReason(
  536. Service::AM::Applets::WebExitReason::EndButtonPressed);
  537. }
  538. });
  539. exit_check = true;
  540. }
  541. if (web_browser_view.GetCurrentURL().contains(QStringLiteral("localhost"))) {
  542. if (!web_browser_view.IsFinished()) {
  543. web_browser_view.SetFinished(true);
  544. web_browser_view.SetExitReason(Service::AM::Applets::WebExitReason::CallbackURL);
  545. }
  546. web_browser_view.SetLastURL(web_browser_view.GetCurrentURL().toStdString());
  547. }
  548. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  549. }
  550. const auto exit_reason = web_browser_view.GetExitReason();
  551. const auto last_url = web_browser_view.GetLastURL();
  552. web_browser_view.hide();
  553. render_window->setFocus();
  554. if (render_window->IsLoadingComplete()) {
  555. render_window->show();
  556. }
  557. ui.action_Pause->setEnabled(true);
  558. ui.action_Restart->setEnabled(true);
  559. ui.action_Stop->setEnabled(true);
  560. ui.menubar->removeAction(exit_action);
  561. QCoreApplication::processEvents();
  562. emit WebBrowserClosed(exit_reason, last_url);
  563. #else
  564. // Utilize the same fallback as the default web browser applet.
  565. emit WebBrowserClosed(Service::AM::Applets::WebExitReason::WindowClosed, "http://localhost/");
  566. #endif
  567. }
  568. void GMainWindow::InitializeWidgets() {
  569. #ifdef YUZU_ENABLE_COMPATIBILITY_REPORTING
  570. ui.action_Report_Compatibility->setVisible(true);
  571. #endif
  572. render_window = new GRenderWindow(this, emu_thread.get(), input_subsystem);
  573. render_window->hide();
  574. game_list = new GameList(vfs, provider.get(), this);
  575. ui.horizontalLayout->addWidget(game_list);
  576. game_list_placeholder = new GameListPlaceholder(this);
  577. ui.horizontalLayout->addWidget(game_list_placeholder);
  578. game_list_placeholder->setVisible(false);
  579. loading_screen = new LoadingScreen(this);
  580. loading_screen->hide();
  581. ui.horizontalLayout->addWidget(loading_screen);
  582. connect(loading_screen, &LoadingScreen::Hidden, [&] {
  583. loading_screen->Clear();
  584. if (emulation_running) {
  585. render_window->show();
  586. render_window->setFocus();
  587. }
  588. });
  589. // Create status bar
  590. message_label = new QLabel();
  591. // Configured separately for left alignment
  592. message_label->setFrameStyle(QFrame::NoFrame);
  593. message_label->setContentsMargins(4, 0, 4, 0);
  594. message_label->setAlignment(Qt::AlignLeft);
  595. statusBar()->addPermanentWidget(message_label, 1);
  596. shader_building_label = new QLabel();
  597. shader_building_label->setToolTip(tr("The amount of shaders currently being built"));
  598. emu_speed_label = new QLabel();
  599. emu_speed_label->setToolTip(
  600. tr("Current emulation speed. Values higher or lower than 100% "
  601. "indicate emulation is running faster or slower than a Switch."));
  602. game_fps_label = new QLabel();
  603. game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
  604. "This will vary from game to game and scene to scene."));
  605. emu_frametime_label = new QLabel();
  606. emu_frametime_label->setToolTip(
  607. tr("Time taken to emulate a Switch frame, not counting framelimiting or v-sync. For "
  608. "full-speed emulation this should be at most 16.67 ms."));
  609. for (auto& label :
  610. {shader_building_label, emu_speed_label, game_fps_label, emu_frametime_label}) {
  611. label->setVisible(false);
  612. label->setFrameStyle(QFrame::NoFrame);
  613. label->setContentsMargins(4, 0, 4, 0);
  614. statusBar()->addPermanentWidget(label);
  615. }
  616. // Setup Dock button
  617. dock_status_button = new QPushButton();
  618. dock_status_button->setObjectName(QStringLiteral("TogglableStatusBarButton"));
  619. dock_status_button->setFocusPolicy(Qt::NoFocus);
  620. connect(dock_status_button, &QPushButton::clicked, [&] {
  621. const bool is_docked = Settings::values.use_docked_mode.GetValue();
  622. auto& controller_type = Settings::values.players.GetValue()[0].controller_type;
  623. if (!is_docked && controller_type == Settings::ControllerType::Handheld) {
  624. QMessageBox::warning(this, tr("Invalid config detected"),
  625. tr("Handheld controller can't be used on docked mode. Pro "
  626. "controller will be selected."));
  627. controller_type = Settings::ControllerType::ProController;
  628. ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get());
  629. configure_dialog.ApplyConfiguration();
  630. controller_dialog->refreshConfiguration();
  631. }
  632. Settings::values.use_docked_mode.SetValue(!is_docked);
  633. dock_status_button->setChecked(!is_docked);
  634. OnDockedModeChanged(is_docked, !is_docked);
  635. });
  636. dock_status_button->setText(tr("DOCK"));
  637. dock_status_button->setCheckable(true);
  638. dock_status_button->setChecked(Settings::values.use_docked_mode.GetValue());
  639. statusBar()->insertPermanentWidget(0, dock_status_button);
  640. gpu_accuracy_button = new QPushButton();
  641. gpu_accuracy_button->setObjectName(QStringLiteral("GPUStatusBarButton"));
  642. gpu_accuracy_button->setCheckable(true);
  643. gpu_accuracy_button->setFocusPolicy(Qt::NoFocus);
  644. connect(gpu_accuracy_button, &QPushButton::clicked, [this] {
  645. switch (Settings::values.gpu_accuracy.GetValue()) {
  646. case Settings::GPUAccuracy::High: {
  647. Settings::values.gpu_accuracy.SetValue(Settings::GPUAccuracy::Normal);
  648. break;
  649. }
  650. case Settings::GPUAccuracy::Normal:
  651. case Settings::GPUAccuracy::Extreme:
  652. default: {
  653. Settings::values.gpu_accuracy.SetValue(Settings::GPUAccuracy::High);
  654. }
  655. }
  656. Core::System::GetInstance().ApplySettings();
  657. UpdateGPUAccuracyButton();
  658. });
  659. UpdateGPUAccuracyButton();
  660. statusBar()->insertPermanentWidget(0, gpu_accuracy_button);
  661. // Setup Renderer API button
  662. renderer_status_button = new QPushButton();
  663. renderer_status_button->setObjectName(QStringLiteral("RendererStatusBarButton"));
  664. renderer_status_button->setCheckable(true);
  665. renderer_status_button->setFocusPolicy(Qt::NoFocus);
  666. connect(renderer_status_button, &QPushButton::toggled, [this](bool checked) {
  667. renderer_status_button->setText(checked ? tr("VULKAN") : tr("OPENGL"));
  668. });
  669. renderer_status_button->toggle();
  670. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  671. Settings::RendererBackend::Vulkan);
  672. connect(renderer_status_button, &QPushButton::clicked, [this] {
  673. if (emulation_running) {
  674. return;
  675. }
  676. if (renderer_status_button->isChecked()) {
  677. Settings::values.renderer_backend.SetValue(Settings::RendererBackend::Vulkan);
  678. } else {
  679. Settings::values.renderer_backend.SetValue(Settings::RendererBackend::OpenGL);
  680. }
  681. Core::System::GetInstance().ApplySettings();
  682. });
  683. statusBar()->insertPermanentWidget(0, renderer_status_button);
  684. statusBar()->setVisible(true);
  685. setStyleSheet(QStringLiteral("QStatusBar::item{border: none;}"));
  686. }
  687. void GMainWindow::InitializeDebugWidgets() {
  688. QMenu* debug_menu = ui.menu_View_Debugging;
  689. #if MICROPROFILE_ENABLED
  690. microProfileDialog = new MicroProfileDialog(this);
  691. microProfileDialog->hide();
  692. debug_menu->addAction(microProfileDialog->toggleViewAction());
  693. #endif
  694. waitTreeWidget = new WaitTreeWidget(this);
  695. addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
  696. waitTreeWidget->hide();
  697. debug_menu->addAction(waitTreeWidget->toggleViewAction());
  698. controller_dialog = new ControllerDialog(this);
  699. controller_dialog->hide();
  700. debug_menu->addAction(controller_dialog->toggleViewAction());
  701. connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
  702. &WaitTreeWidget::OnEmulationStarting);
  703. connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
  704. &WaitTreeWidget::OnEmulationStopping);
  705. }
  706. void GMainWindow::InitializeRecentFileMenuActions() {
  707. for (int i = 0; i < max_recent_files_item; ++i) {
  708. actions_recent_files[i] = new QAction(this);
  709. actions_recent_files[i]->setVisible(false);
  710. connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile);
  711. ui.menu_recent_files->addAction(actions_recent_files[i]);
  712. }
  713. ui.menu_recent_files->addSeparator();
  714. QAction* action_clear_recent_files = new QAction(this);
  715. action_clear_recent_files->setText(tr("&Clear Recent Files"));
  716. connect(action_clear_recent_files, &QAction::triggered, this, [this] {
  717. UISettings::values.recent_files.clear();
  718. UpdateRecentFiles();
  719. });
  720. ui.menu_recent_files->addAction(action_clear_recent_files);
  721. UpdateRecentFiles();
  722. }
  723. void GMainWindow::InitializeHotkeys() {
  724. hotkey_registry.LoadHotkeys();
  725. const QString main_window = QStringLiteral("Main Window");
  726. const QString load_file = QStringLiteral("Load File");
  727. const QString load_amiibo = QStringLiteral("Load Amiibo");
  728. const QString exit_yuzu = QStringLiteral("Exit yuzu");
  729. const QString restart_emulation = QStringLiteral("Restart Emulation");
  730. const QString stop_emulation = QStringLiteral("Stop Emulation");
  731. const QString toggle_filter_bar = QStringLiteral("Toggle Filter Bar");
  732. const QString toggle_status_bar = QStringLiteral("Toggle Status Bar");
  733. const QString fullscreen = QStringLiteral("Fullscreen");
  734. const QString capture_screenshot = QStringLiteral("Capture Screenshot");
  735. ui.action_Load_File->setShortcut(hotkey_registry.GetKeySequence(main_window, load_file));
  736. ui.action_Load_File->setShortcutContext(
  737. hotkey_registry.GetShortcutContext(main_window, load_file));
  738. ui.action_Load_Amiibo->setShortcut(hotkey_registry.GetKeySequence(main_window, load_amiibo));
  739. ui.action_Load_Amiibo->setShortcutContext(
  740. hotkey_registry.GetShortcutContext(main_window, load_amiibo));
  741. ui.action_Exit->setShortcut(hotkey_registry.GetKeySequence(main_window, exit_yuzu));
  742. ui.action_Exit->setShortcutContext(hotkey_registry.GetShortcutContext(main_window, exit_yuzu));
  743. ui.action_Restart->setShortcut(hotkey_registry.GetKeySequence(main_window, restart_emulation));
  744. ui.action_Restart->setShortcutContext(
  745. hotkey_registry.GetShortcutContext(main_window, restart_emulation));
  746. ui.action_Stop->setShortcut(hotkey_registry.GetKeySequence(main_window, stop_emulation));
  747. ui.action_Stop->setShortcutContext(
  748. hotkey_registry.GetShortcutContext(main_window, stop_emulation));
  749. ui.action_Show_Filter_Bar->setShortcut(
  750. hotkey_registry.GetKeySequence(main_window, toggle_filter_bar));
  751. ui.action_Show_Filter_Bar->setShortcutContext(
  752. hotkey_registry.GetShortcutContext(main_window, toggle_filter_bar));
  753. ui.action_Show_Status_Bar->setShortcut(
  754. hotkey_registry.GetKeySequence(main_window, toggle_status_bar));
  755. ui.action_Show_Status_Bar->setShortcutContext(
  756. hotkey_registry.GetShortcutContext(main_window, toggle_status_bar));
  757. ui.action_Capture_Screenshot->setShortcut(
  758. hotkey_registry.GetKeySequence(main_window, capture_screenshot));
  759. ui.action_Capture_Screenshot->setShortcutContext(
  760. hotkey_registry.GetShortcutContext(main_window, capture_screenshot));
  761. ui.action_Fullscreen->setShortcut(
  762. hotkey_registry.GetHotkey(main_window, fullscreen, this)->key());
  763. ui.action_Fullscreen->setShortcutContext(
  764. hotkey_registry.GetShortcutContext(main_window, fullscreen));
  765. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Load File"), this),
  766. &QShortcut::activated, this, &GMainWindow::OnMenuLoadFile);
  767. connect(
  768. hotkey_registry.GetHotkey(main_window, QStringLiteral("Continue/Pause Emulation"), this),
  769. &QShortcut::activated, this, [&] {
  770. if (emulation_running) {
  771. if (emu_thread->IsRunning()) {
  772. OnPauseGame();
  773. } else {
  774. OnStartGame();
  775. }
  776. }
  777. });
  778. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Restart Emulation"), this),
  779. &QShortcut::activated, this, [this] {
  780. if (!Core::System::GetInstance().IsPoweredOn()) {
  781. return;
  782. }
  783. BootGame(game_path);
  784. });
  785. connect(hotkey_registry.GetHotkey(main_window, fullscreen, render_window),
  786. &QShortcut::activated, ui.action_Fullscreen, &QAction::trigger);
  787. connect(hotkey_registry.GetHotkey(main_window, fullscreen, render_window),
  788. &QShortcut::activatedAmbiguously, ui.action_Fullscreen, &QAction::trigger);
  789. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Exit Fullscreen"), this),
  790. &QShortcut::activated, this, [&] {
  791. if (emulation_running) {
  792. ui.action_Fullscreen->setChecked(false);
  793. ToggleFullscreen();
  794. }
  795. });
  796. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Toggle Speed Limit"), this),
  797. &QShortcut::activated, this, [&] {
  798. Settings::values.use_speed_limit.SetValue(
  799. !Settings::values.use_speed_limit.GetValue());
  800. UpdateStatusBar();
  801. });
  802. constexpr u16 SPEED_LIMIT_STEP = 5;
  803. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Increase Speed Limit"), this),
  804. &QShortcut::activated, this, [&] {
  805. if (Settings::values.speed_limit.GetValue() < 9999 - SPEED_LIMIT_STEP) {
  806. Settings::values.speed_limit.SetValue(SPEED_LIMIT_STEP +
  807. Settings::values.speed_limit.GetValue());
  808. UpdateStatusBar();
  809. }
  810. });
  811. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Decrease Speed Limit"), this),
  812. &QShortcut::activated, this, [&] {
  813. if (Settings::values.speed_limit.GetValue() > SPEED_LIMIT_STEP) {
  814. Settings::values.speed_limit.SetValue(Settings::values.speed_limit.GetValue() -
  815. SPEED_LIMIT_STEP);
  816. UpdateStatusBar();
  817. }
  818. });
  819. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Load Amiibo"), this),
  820. &QShortcut::activated, this, [&] {
  821. if (ui.action_Load_Amiibo->isEnabled()) {
  822. OnLoadAmiibo();
  823. }
  824. });
  825. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Capture Screenshot"), this),
  826. &QShortcut::activated, this, [&] {
  827. if (emu_thread != nullptr && emu_thread->IsRunning()) {
  828. OnCaptureScreenshot();
  829. }
  830. });
  831. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Change Docked Mode"), this),
  832. &QShortcut::activated, this, [&] {
  833. Settings::values.use_docked_mode.SetValue(
  834. !Settings::values.use_docked_mode.GetValue());
  835. OnDockedModeChanged(!Settings::values.use_docked_mode.GetValue(),
  836. Settings::values.use_docked_mode.GetValue());
  837. dock_status_button->setChecked(Settings::values.use_docked_mode.GetValue());
  838. });
  839. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Mute Audio"), this),
  840. &QShortcut::activated, this,
  841. [] { Settings::values.audio_muted = !Settings::values.audio_muted; });
  842. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Toggle Framerate Limit"), this),
  843. &QShortcut::activated, this, [] {
  844. Settings::values.disable_fps_limit.SetValue(
  845. !Settings::values.disable_fps_limit.GetValue());
  846. });
  847. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Toggle Mouse Panning"), this),
  848. &QShortcut::activated, this, [&] {
  849. Settings::values.mouse_panning = !Settings::values.mouse_panning;
  850. if (Settings::values.mouse_panning) {
  851. render_window->installEventFilter(render_window);
  852. render_window->setAttribute(Qt::WA_Hover, true);
  853. }
  854. });
  855. }
  856. void GMainWindow::SetDefaultUIGeometry() {
  857. // geometry: 53% of the window contents are in the upper screen half, 47% in the lower half
  858. const QRect screenRect = QApplication::desktop()->screenGeometry(this);
  859. const int w = screenRect.width() * 2 / 3;
  860. const int h = screenRect.height() * 2 / 3;
  861. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  862. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 53 / 100;
  863. setGeometry(x, y, w, h);
  864. }
  865. void GMainWindow::RestoreUIState() {
  866. restoreGeometry(UISettings::values.geometry);
  867. restoreState(UISettings::values.state);
  868. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  869. #if MICROPROFILE_ENABLED
  870. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  871. microProfileDialog->setVisible(UISettings::values.microprofile_visible.GetValue());
  872. #endif
  873. game_list->LoadInterfaceLayout();
  874. ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode.GetValue());
  875. ToggleWindowMode();
  876. ui.action_Fullscreen->setChecked(UISettings::values.fullscreen.GetValue());
  877. ui.action_Display_Dock_Widget_Headers->setChecked(
  878. UISettings::values.display_titlebar.GetValue());
  879. OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked());
  880. ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar.GetValue());
  881. game_list->SetFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  882. ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar.GetValue());
  883. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  884. Debugger::ToggleConsole();
  885. }
  886. void GMainWindow::OnAppFocusStateChanged(Qt::ApplicationState state) {
  887. if (!UISettings::values.pause_when_in_background) {
  888. return;
  889. }
  890. if (state != Qt::ApplicationHidden && state != Qt::ApplicationInactive &&
  891. state != Qt::ApplicationActive) {
  892. LOG_DEBUG(Frontend, "ApplicationState unusual flag: {} ", state);
  893. }
  894. if (ui.action_Pause->isEnabled() &&
  895. (state & (Qt::ApplicationHidden | Qt::ApplicationInactive))) {
  896. auto_paused = true;
  897. OnPauseGame();
  898. } else if (ui.action_Start->isEnabled() && auto_paused && state == Qt::ApplicationActive) {
  899. auto_paused = false;
  900. OnStartGame();
  901. }
  902. }
  903. void GMainWindow::ConnectWidgetEvents() {
  904. connect(game_list, &GameList::BootGame, this, &GMainWindow::BootGame);
  905. connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
  906. connect(game_list, &GameList::OpenDirectory, this, &GMainWindow::OnGameListOpenDirectory);
  907. connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
  908. connect(game_list, &GameList::OpenTransferableShaderCacheRequested, this,
  909. &GMainWindow::OnTransferableShaderCacheOpenFile);
  910. connect(game_list, &GameList::RemoveInstalledEntryRequested, this,
  911. &GMainWindow::OnGameListRemoveInstalledEntry);
  912. connect(game_list, &GameList::RemoveFileRequested, this, &GMainWindow::OnGameListRemoveFile);
  913. connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS);
  914. connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID);
  915. connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
  916. &GMainWindow::OnGameListNavigateToGamedbEntry);
  917. connect(game_list, &GameList::AddDirectory, this, &GMainWindow::OnGameListAddDirectory);
  918. connect(game_list_placeholder, &GameListPlaceholder::AddDirectory, this,
  919. &GMainWindow::OnGameListAddDirectory);
  920. connect(game_list, &GameList::ShowList, this, &GMainWindow::OnGameListShowList);
  921. connect(game_list, &GameList::OpenPerGameGeneralRequested, this,
  922. &GMainWindow::OnGameListOpenPerGameProperties);
  923. connect(this, &GMainWindow::UpdateInstallProgress, this,
  924. &GMainWindow::IncrementInstallProgress);
  925. connect(this, &GMainWindow::EmulationStarting, render_window,
  926. &GRenderWindow::OnEmulationStarting);
  927. connect(this, &GMainWindow::EmulationStopping, render_window,
  928. &GRenderWindow::OnEmulationStopping);
  929. // Software Keyboard Applet
  930. connect(this, &GMainWindow::EmulationStarting, this, &GMainWindow::SoftwareKeyboardExit);
  931. connect(this, &GMainWindow::EmulationStopping, this, &GMainWindow::SoftwareKeyboardExit);
  932. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  933. }
  934. void GMainWindow::ConnectMenuEvents() {
  935. // File
  936. connect(ui.action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
  937. connect(ui.action_Load_Folder, &QAction::triggered, this, &GMainWindow::OnMenuLoadFolder);
  938. connect(ui.action_Install_File_NAND, &QAction::triggered, this,
  939. &GMainWindow::OnMenuInstallToNAND);
  940. connect(ui.action_Exit, &QAction::triggered, this, &QMainWindow::close);
  941. connect(ui.action_Load_Amiibo, &QAction::triggered, this, &GMainWindow::OnLoadAmiibo);
  942. // Emulation
  943. connect(ui.action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
  944. connect(ui.action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
  945. connect(ui.action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
  946. connect(ui.action_Report_Compatibility, &QAction::triggered, this,
  947. &GMainWindow::OnMenuReportCompatibility);
  948. connect(ui.action_Open_Mods_Page, &QAction::triggered, this, &GMainWindow::OnOpenModsPage);
  949. connect(ui.action_Open_Quickstart_Guide, &QAction::triggered, this,
  950. &GMainWindow::OnOpenQuickstartGuide);
  951. connect(ui.action_Open_FAQ, &QAction::triggered, this, &GMainWindow::OnOpenFAQ);
  952. connect(ui.action_Restart, &QAction::triggered, this, [this] { BootGame(QString(game_path)); });
  953. connect(ui.action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
  954. connect(ui.action_Configure_Current_Game, &QAction::triggered, this,
  955. &GMainWindow::OnConfigurePerGame);
  956. // View
  957. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  958. &GMainWindow::ToggleWindowMode);
  959. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  960. &GMainWindow::OnDisplayTitleBars);
  961. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  962. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  963. connect(ui.action_Reset_Window_Size_720, &QAction::triggered, this,
  964. &GMainWindow::ResetWindowSize720);
  965. connect(ui.action_Reset_Window_Size_1080, &QAction::triggered, this,
  966. &GMainWindow::ResetWindowSize1080);
  967. // Fullscreen
  968. connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
  969. // Movie
  970. connect(ui.action_Capture_Screenshot, &QAction::triggered, this,
  971. &GMainWindow::OnCaptureScreenshot);
  972. // Help
  973. connect(ui.action_Open_yuzu_Folder, &QAction::triggered, this, &GMainWindow::OnOpenYuzuFolder);
  974. connect(ui.action_Rederive, &QAction::triggered, this,
  975. std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning));
  976. connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
  977. }
  978. void GMainWindow::OnDisplayTitleBars(bool show) {
  979. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  980. if (show) {
  981. for (QDockWidget* widget : widgets) {
  982. QWidget* old = widget->titleBarWidget();
  983. widget->setTitleBarWidget(nullptr);
  984. if (old != nullptr)
  985. delete old;
  986. }
  987. } else {
  988. for (QDockWidget* widget : widgets) {
  989. QWidget* old = widget->titleBarWidget();
  990. widget->setTitleBarWidget(new QWidget());
  991. if (old != nullptr)
  992. delete old;
  993. }
  994. }
  995. }
  996. void GMainWindow::PreventOSSleep() {
  997. #ifdef _WIN32
  998. SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
  999. #endif
  1000. }
  1001. void GMainWindow::AllowOSSleep() {
  1002. #ifdef _WIN32
  1003. SetThreadExecutionState(ES_CONTINUOUS);
  1004. #endif
  1005. }
  1006. bool GMainWindow::LoadROM(const QString& filename, u64 program_id, std::size_t program_index) {
  1007. // Shutdown previous session if the emu thread is still active...
  1008. if (emu_thread != nullptr)
  1009. ShutdownGame();
  1010. if (!render_window->InitRenderTarget()) {
  1011. return false;
  1012. }
  1013. Core::System& system{Core::System::GetInstance()};
  1014. system.SetFilesystem(vfs);
  1015. system.SetAppletFrontendSet({
  1016. std::make_unique<QtControllerSelector>(*this), // Controller Selector
  1017. std::make_unique<QtErrorDisplay>(*this), // Error Display
  1018. nullptr, // Parental Controls
  1019. nullptr, // Photo Viewer
  1020. std::make_unique<QtProfileSelector>(*this), // Profile Selector
  1021. std::make_unique<QtSoftwareKeyboard>(*this), // Software Keyboard
  1022. std::make_unique<QtWebBrowser>(*this), // Web Browser
  1023. });
  1024. const Core::System::ResultStatus result{
  1025. system.Load(*render_window, filename.toStdString(), program_id, program_index)};
  1026. const auto drd_callout = (UISettings::values.callout_flags.GetValue() &
  1027. static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  1028. if (result == Core::System::ResultStatus::Success &&
  1029. system.GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  1030. drd_callout) {
  1031. UISettings::values.callout_flags = UISettings::values.callout_flags.GetValue() |
  1032. static_cast<u32>(CalloutFlag::DRDDeprecation);
  1033. QMessageBox::warning(
  1034. this, tr("Warning Outdated Game Format"),
  1035. tr("You are using the deconstructed ROM directory format for this game, which is an "
  1036. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  1037. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  1038. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  1039. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  1040. "wiki</a>. This message will not be shown again."));
  1041. }
  1042. if (result != Core::System::ResultStatus::Success) {
  1043. switch (result) {
  1044. case Core::System::ResultStatus::ErrorGetLoader:
  1045. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  1046. QMessageBox::critical(this, tr("Error while loading ROM!"),
  1047. tr("The ROM format is not supported."));
  1048. break;
  1049. case Core::System::ResultStatus::ErrorVideoCore:
  1050. QMessageBox::critical(
  1051. this, tr("An error occurred initializing the video core."),
  1052. tr("yuzu has encountered an error while running the video core, please see the "
  1053. "log for more details."
  1054. "For more information on accessing the log, please see the following page: "
  1055. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  1056. "to "
  1057. "Upload the Log File</a>."
  1058. "Ensure that you have the latest graphics drivers for your GPU."));
  1059. break;
  1060. default:
  1061. if (result > Core::System::ResultStatus::ErrorLoader) {
  1062. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  1063. const u16 error_id = static_cast<u16>(result) - loader_id;
  1064. const std::string error_code = fmt::format("({:04X}-{:04X})", loader_id, error_id);
  1065. LOG_CRITICAL(Frontend, "Failed to load ROM! {}", error_code);
  1066. const auto title =
  1067. tr("Error while loading ROM! %1", "%1 signifies a numeric error code.")
  1068. .arg(QString::fromStdString(error_code));
  1069. const auto description =
  1070. tr("%1<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the "
  1071. "yuzu quickstart guide</a> to redump your files.<br>You can refer "
  1072. "to the yuzu wiki</a> or the yuzu Discord</a> for help.",
  1073. "%1 signifies an error string.")
  1074. .arg(QString::fromStdString(
  1075. GetResultStatusString(static_cast<Loader::ResultStatus>(error_id))));
  1076. QMessageBox::critical(this, title, description);
  1077. } else {
  1078. QMessageBox::critical(
  1079. this, tr("Error while loading ROM!"),
  1080. tr("An unknown error occurred. Please see the log for more details."));
  1081. }
  1082. break;
  1083. }
  1084. return false;
  1085. }
  1086. game_path = filename;
  1087. system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "Qt");
  1088. return true;
  1089. }
  1090. void GMainWindow::SelectAndSetCurrentUser() {
  1091. QtProfileSelectionDialog dialog(this);
  1092. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1093. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1094. dialog.setWindowModality(Qt::WindowModal);
  1095. if (dialog.exec() == QDialog::Rejected) {
  1096. return;
  1097. }
  1098. Settings::values.current_user = dialog.GetIndex();
  1099. }
  1100. void GMainWindow::BootGame(const QString& filename, u64 program_id, std::size_t program_index,
  1101. StartGameType type) {
  1102. LOG_INFO(Frontend, "yuzu starting...");
  1103. StoreRecentFile(filename); // Put the filename on top of the list
  1104. u64 title_id{0};
  1105. last_filename_booted = filename;
  1106. auto& system = Core::System::GetInstance();
  1107. const auto v_file = Core::GetGameFileFromPath(vfs, filename.toUtf8().constData());
  1108. const auto loader = Loader::GetLoader(system, v_file, program_id, program_index);
  1109. if (loader != nullptr && loader->ReadProgramId(title_id) == Loader::ResultStatus::Success &&
  1110. type == StartGameType::Normal) {
  1111. // Load per game settings
  1112. const auto file_path = std::filesystem::path{filename.toStdU16String()};
  1113. const auto config_file_name = title_id == 0
  1114. ? Common::FS::PathToUTF8String(file_path.filename())
  1115. : fmt::format("{:016X}", title_id);
  1116. Config per_game_config(config_file_name, Config::ConfigType::PerGameConfig);
  1117. }
  1118. ConfigureVibration::SetAllVibrationDevices();
  1119. // Disable fps limit toggle when booting a new title
  1120. Settings::values.disable_fps_limit.SetValue(false);
  1121. // Save configurations
  1122. UpdateUISettings();
  1123. game_list->SaveInterfaceLayout();
  1124. config->Save();
  1125. Settings::LogSettings();
  1126. if (UISettings::values.select_user_on_boot) {
  1127. SelectAndSetCurrentUser();
  1128. }
  1129. if (!LoadROM(filename, program_id, program_index))
  1130. return;
  1131. // Create and start the emulation thread
  1132. emu_thread = std::make_unique<EmuThread>();
  1133. emit EmulationStarting(emu_thread.get());
  1134. emu_thread->start();
  1135. // Register an ExecuteProgram callback such that Core can execute a sub-program
  1136. system.RegisterExecuteProgramCallback(
  1137. [this](std::size_t program_index) { render_window->ExecuteProgram(program_index); });
  1138. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1139. connect(render_window, &GRenderWindow::MouseActivity, this, &GMainWindow::OnMouseActivity);
  1140. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  1141. // before the CPU continues
  1142. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  1143. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  1144. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  1145. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  1146. connect(emu_thread.get(), &EmuThread::LoadProgress, loading_screen,
  1147. &LoadingScreen::OnLoadProgress, Qt::QueuedConnection);
  1148. // Update the GUI
  1149. UpdateStatusButtons();
  1150. if (ui.action_Single_Window_Mode->isChecked()) {
  1151. game_list->hide();
  1152. game_list_placeholder->hide();
  1153. }
  1154. status_bar_update_timer.start(500);
  1155. renderer_status_button->setDisabled(true);
  1156. if (UISettings::values.hide_mouse || Settings::values.mouse_panning) {
  1157. render_window->installEventFilter(render_window);
  1158. render_window->setAttribute(Qt::WA_Hover, true);
  1159. }
  1160. if (UISettings::values.hide_mouse) {
  1161. mouse_hide_timer.start();
  1162. }
  1163. std::string title_name;
  1164. std::string title_version;
  1165. const auto res = system.GetGameName(title_name);
  1166. const auto metadata = [&system, title_id] {
  1167. const FileSys::PatchManager pm(title_id, system.GetFileSystemController(),
  1168. system.GetContentProvider());
  1169. return pm.GetControlMetadata();
  1170. }();
  1171. if (metadata.first != nullptr) {
  1172. title_version = metadata.first->GetVersionString();
  1173. title_name = metadata.first->GetApplicationName();
  1174. }
  1175. if (res != Loader::ResultStatus::Success || title_name.empty()) {
  1176. title_name = Common::FS::PathToUTF8String(
  1177. std::filesystem::path{filename.toStdU16String()}.filename());
  1178. }
  1179. const bool is_64bit = system.Kernel().CurrentProcess()->Is64BitProcess();
  1180. const auto instruction_set_suffix = is_64bit ? tr("(64-bit)") : tr("(32-bit)");
  1181. title_name = tr("%1 %2", "%1 is the title name. %2 indicates if the title is 64-bit or 32-bit")
  1182. .arg(QString::fromStdString(title_name), instruction_set_suffix)
  1183. .toStdString();
  1184. LOG_INFO(Frontend, "Booting game: {:016X} | {} | {}", title_id, title_name, title_version);
  1185. const auto gpu_vendor = system.GPU().Renderer().GetDeviceVendor();
  1186. UpdateWindowTitle(title_name, title_version, gpu_vendor);
  1187. loading_screen->Prepare(system.GetAppLoader());
  1188. loading_screen->show();
  1189. emulation_running = true;
  1190. if (ui.action_Fullscreen->isChecked()) {
  1191. ShowFullscreen();
  1192. }
  1193. OnStartGame();
  1194. }
  1195. void GMainWindow::ShutdownGame() {
  1196. if (!emulation_running) {
  1197. return;
  1198. }
  1199. if (ui.action_Fullscreen->isChecked()) {
  1200. HideFullscreen();
  1201. }
  1202. AllowOSSleep();
  1203. discord_rpc->Pause();
  1204. emu_thread->RequestStop();
  1205. emit EmulationStopping();
  1206. // Wait for emulation thread to complete and delete it
  1207. emu_thread->wait();
  1208. emu_thread = nullptr;
  1209. discord_rpc->Update();
  1210. // The emulation is stopped, so closing the window or not does not matter anymore
  1211. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1212. // Update the GUI
  1213. ui.action_Start->setEnabled(false);
  1214. ui.action_Start->setText(tr("Start"));
  1215. ui.action_Pause->setEnabled(false);
  1216. ui.action_Stop->setEnabled(false);
  1217. ui.action_Restart->setEnabled(false);
  1218. ui.action_Configure_Current_Game->setEnabled(false);
  1219. ui.action_Report_Compatibility->setEnabled(false);
  1220. ui.action_Load_Amiibo->setEnabled(false);
  1221. ui.action_Capture_Screenshot->setEnabled(false);
  1222. render_window->hide();
  1223. loading_screen->hide();
  1224. loading_screen->Clear();
  1225. if (game_list->IsEmpty()) {
  1226. game_list_placeholder->show();
  1227. } else {
  1228. game_list->show();
  1229. }
  1230. game_list->SetFilterFocus();
  1231. render_window->removeEventFilter(render_window);
  1232. render_window->setAttribute(Qt::WA_Hover, false);
  1233. UpdateWindowTitle();
  1234. // Disable status bar updates
  1235. status_bar_update_timer.stop();
  1236. shader_building_label->setVisible(false);
  1237. emu_speed_label->setVisible(false);
  1238. game_fps_label->setVisible(false);
  1239. emu_frametime_label->setVisible(false);
  1240. renderer_status_button->setEnabled(true);
  1241. emulation_running = false;
  1242. game_path.clear();
  1243. // When closing the game, destroy the GLWindow to clear the context after the game is closed
  1244. render_window->ReleaseRenderTarget();
  1245. }
  1246. void GMainWindow::StoreRecentFile(const QString& filename) {
  1247. UISettings::values.recent_files.prepend(filename);
  1248. UISettings::values.recent_files.removeDuplicates();
  1249. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  1250. UISettings::values.recent_files.removeLast();
  1251. }
  1252. UpdateRecentFiles();
  1253. }
  1254. void GMainWindow::UpdateRecentFiles() {
  1255. const int num_recent_files =
  1256. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  1257. for (int i = 0; i < num_recent_files; i++) {
  1258. const QString text = QStringLiteral("&%1. %2").arg(i + 1).arg(
  1259. QFileInfo(UISettings::values.recent_files[i]).fileName());
  1260. actions_recent_files[i]->setText(text);
  1261. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  1262. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  1263. actions_recent_files[i]->setVisible(true);
  1264. }
  1265. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  1266. actions_recent_files[j]->setVisible(false);
  1267. }
  1268. // Enable the recent files menu if the list isn't empty
  1269. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  1270. }
  1271. void GMainWindow::OnGameListLoadFile(QString game_path, u64 program_id) {
  1272. BootGame(game_path, program_id);
  1273. }
  1274. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target,
  1275. const std::string& game_path) {
  1276. std::filesystem::path path;
  1277. QString open_target;
  1278. auto& system = Core::System::GetInstance();
  1279. const auto [user_save_size, device_save_size] = [this, &game_path, &program_id, &system] {
  1280. const FileSys::PatchManager pm{program_id, system.GetFileSystemController(),
  1281. system.GetContentProvider()};
  1282. const auto control = pm.GetControlMetadata().first;
  1283. if (control != nullptr) {
  1284. return std::make_pair(control->GetDefaultNormalSaveSize(),
  1285. control->GetDeviceSaveDataSize());
  1286. } else {
  1287. const auto file = Core::GetGameFileFromPath(vfs, game_path);
  1288. const auto loader = Loader::GetLoader(system, file);
  1289. FileSys::NACP nacp{};
  1290. loader->ReadControlData(nacp);
  1291. return std::make_pair(nacp.GetDefaultNormalSaveSize(), nacp.GetDeviceSaveDataSize());
  1292. }
  1293. }();
  1294. const bool has_user_save{user_save_size > 0};
  1295. const bool has_device_save{device_save_size > 0};
  1296. ASSERT_MSG(has_user_save != has_device_save, "Game uses both user and device savedata?");
  1297. switch (target) {
  1298. case GameListOpenTarget::SaveData: {
  1299. open_target = tr("Save Data");
  1300. const auto nand_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir);
  1301. if (has_user_save) {
  1302. // User save data
  1303. const auto select_profile = [this] {
  1304. QtProfileSelectionDialog dialog(this);
  1305. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1306. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1307. dialog.setWindowModality(Qt::WindowModal);
  1308. if (dialog.exec() == QDialog::Rejected) {
  1309. return -1;
  1310. }
  1311. return dialog.GetIndex();
  1312. };
  1313. const auto index = select_profile();
  1314. if (index == -1) {
  1315. return;
  1316. }
  1317. Service::Account::ProfileManager manager;
  1318. const auto user_id = manager.GetUser(static_cast<std::size_t>(index));
  1319. ASSERT(user_id);
  1320. const auto user_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1321. system, FileSys::SaveDataSpaceId::NandUser, FileSys::SaveDataType::SaveData,
  1322. program_id, user_id->uuid, 0);
  1323. path = Common::FS::ConcatPathSafe(nand_dir, user_save_data_path);
  1324. } else {
  1325. // Device save data
  1326. const auto device_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1327. system, FileSys::SaveDataSpaceId::NandUser, FileSys::SaveDataType::SaveData,
  1328. program_id, {}, 0);
  1329. path = Common::FS::ConcatPathSafe(nand_dir, device_save_data_path);
  1330. }
  1331. if (!Common::FS::CreateDirs(path)) {
  1332. LOG_ERROR(Frontend, "Unable to create the directories for save data");
  1333. }
  1334. break;
  1335. }
  1336. case GameListOpenTarget::ModData: {
  1337. open_target = tr("Mod Data");
  1338. path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::LoadDir) /
  1339. fmt::format("{:016X}", program_id);
  1340. break;
  1341. }
  1342. default:
  1343. UNIMPLEMENTED();
  1344. }
  1345. const QString qpath = QString::fromStdString(Common::FS::PathToUTF8String(path));
  1346. const QDir dir(qpath);
  1347. if (!dir.exists()) {
  1348. QMessageBox::warning(this, tr("Error Opening %1 Folder").arg(open_target),
  1349. tr("Folder does not exist!"));
  1350. return;
  1351. }
  1352. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target.toStdString(),
  1353. program_id);
  1354. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  1355. }
  1356. void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
  1357. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1358. const auto shader_cache_folder_path{shader_cache_dir / fmt::format("{:016x}", program_id)};
  1359. if (!Common::FS::CreateDirs(shader_cache_folder_path)) {
  1360. QMessageBox::warning(this, tr("Error Opening Transferable Shader Cache"),
  1361. tr("Filed to create the shader cache directory for this title."));
  1362. return;
  1363. }
  1364. const auto shader_path_string{Common::FS::PathToUTF8String(shader_cache_folder_path)};
  1365. const auto qt_shader_cache_path = QString::fromStdString(shader_path_string);
  1366. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_shader_cache_path));
  1367. }
  1368. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  1369. std::size_t out = 0;
  1370. for (const auto& subdir : dir->GetSubdirectories()) {
  1371. out += 1 + CalculateRomFSEntrySize(subdir, full);
  1372. }
  1373. return out + (full ? dir->GetFiles().size() : 0);
  1374. }
  1375. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  1376. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  1377. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  1378. return false;
  1379. if (dialog.wasCanceled())
  1380. return false;
  1381. if (full) {
  1382. for (const auto& file : src->GetFiles()) {
  1383. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  1384. if (!FileSys::VfsRawCopy(file, out, block_size))
  1385. return false;
  1386. dialog.setValue(dialog.value() + 1);
  1387. if (dialog.wasCanceled())
  1388. return false;
  1389. }
  1390. }
  1391. for (const auto& dir : src->GetSubdirectories()) {
  1392. const auto out = dest->CreateSubdirectory(dir->GetName());
  1393. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  1394. return false;
  1395. dialog.setValue(dialog.value() + 1);
  1396. if (dialog.wasCanceled())
  1397. return false;
  1398. }
  1399. return true;
  1400. }
  1401. void GMainWindow::OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type) {
  1402. const QString entry_type = [this, type] {
  1403. switch (type) {
  1404. case InstalledEntryType::Game:
  1405. return tr("Contents");
  1406. case InstalledEntryType::Update:
  1407. return tr("Update");
  1408. case InstalledEntryType::AddOnContent:
  1409. return tr("DLC");
  1410. default:
  1411. return QString{};
  1412. }
  1413. }();
  1414. if (QMessageBox::question(
  1415. this, tr("Remove Entry"), tr("Remove Installed Game %1?").arg(entry_type),
  1416. QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
  1417. return;
  1418. }
  1419. switch (type) {
  1420. case InstalledEntryType::Game:
  1421. RemoveBaseContent(program_id, entry_type);
  1422. [[fallthrough]];
  1423. case InstalledEntryType::Update:
  1424. RemoveUpdateContent(program_id, entry_type);
  1425. if (type != InstalledEntryType::Game) {
  1426. break;
  1427. }
  1428. [[fallthrough]];
  1429. case InstalledEntryType::AddOnContent:
  1430. RemoveAddOnContent(program_id, entry_type);
  1431. break;
  1432. }
  1433. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  1434. "game_list");
  1435. game_list->PopulateAsync(UISettings::values.game_dirs);
  1436. }
  1437. void GMainWindow::RemoveBaseContent(u64 program_id, const QString& entry_type) {
  1438. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1439. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(program_id) ||
  1440. fs_controller.GetSDMCContents()->RemoveExistingEntry(program_id);
  1441. if (res) {
  1442. QMessageBox::information(this, tr("Successfully Removed"),
  1443. tr("Successfully removed the installed base game."));
  1444. } else {
  1445. QMessageBox::warning(
  1446. this, tr("Error Removing %1").arg(entry_type),
  1447. tr("The base game is not installed in the NAND and cannot be removed."));
  1448. }
  1449. }
  1450. void GMainWindow::RemoveUpdateContent(u64 program_id, const QString& entry_type) {
  1451. const auto update_id = program_id | 0x800;
  1452. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1453. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(update_id) ||
  1454. fs_controller.GetSDMCContents()->RemoveExistingEntry(update_id);
  1455. if (res) {
  1456. QMessageBox::information(this, tr("Successfully Removed"),
  1457. tr("Successfully removed the installed update."));
  1458. } else {
  1459. QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
  1460. tr("There is no update installed for this title."));
  1461. }
  1462. }
  1463. void GMainWindow::RemoveAddOnContent(u64 program_id, const QString& entry_type) {
  1464. u32 count{};
  1465. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1466. const auto dlc_entries = Core::System::GetInstance().GetContentProvider().ListEntriesFilter(
  1467. FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1468. for (const auto& entry : dlc_entries) {
  1469. if (FileSys::GetBaseTitleID(entry.title_id) == program_id) {
  1470. const auto res =
  1471. fs_controller.GetUserNANDContents()->RemoveExistingEntry(entry.title_id) ||
  1472. fs_controller.GetSDMCContents()->RemoveExistingEntry(entry.title_id);
  1473. if (res) {
  1474. ++count;
  1475. }
  1476. }
  1477. }
  1478. if (count == 0) {
  1479. QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
  1480. tr("There are no DLC installed for this title."));
  1481. return;
  1482. }
  1483. QMessageBox::information(this, tr("Successfully Removed"),
  1484. tr("Successfully removed %1 installed DLC.").arg(count));
  1485. }
  1486. void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target,
  1487. const std::string& game_path) {
  1488. const QString question = [this, target] {
  1489. switch (target) {
  1490. case GameListRemoveTarget::GlShaderCache:
  1491. return tr("Delete OpenGL Transferable Shader Cache?");
  1492. case GameListRemoveTarget::VkShaderCache:
  1493. return tr("Delete Vulkan Transferable Shader Cache?");
  1494. case GameListRemoveTarget::AllShaderCache:
  1495. return tr("Delete All Transferable Shader Caches?");
  1496. case GameListRemoveTarget::CustomConfiguration:
  1497. return tr("Remove Custom Game Configuration?");
  1498. default:
  1499. return QString{};
  1500. }
  1501. }();
  1502. if (QMessageBox::question(this, tr("Remove File"), question, QMessageBox::Yes | QMessageBox::No,
  1503. QMessageBox::No) != QMessageBox::Yes) {
  1504. return;
  1505. }
  1506. switch (target) {
  1507. case GameListRemoveTarget::GlShaderCache:
  1508. case GameListRemoveTarget::VkShaderCache:
  1509. RemoveTransferableShaderCache(program_id, target);
  1510. break;
  1511. case GameListRemoveTarget::AllShaderCache:
  1512. RemoveAllTransferableShaderCaches(program_id);
  1513. break;
  1514. case GameListRemoveTarget::CustomConfiguration:
  1515. RemoveCustomConfiguration(program_id, game_path);
  1516. break;
  1517. }
  1518. }
  1519. void GMainWindow::RemoveTransferableShaderCache(u64 program_id, GameListRemoveTarget target) {
  1520. const auto target_file_name = [target] {
  1521. switch (target) {
  1522. case GameListRemoveTarget::GlShaderCache:
  1523. return "opengl.bin";
  1524. case GameListRemoveTarget::VkShaderCache:
  1525. return "vulkan.bin";
  1526. default:
  1527. return "";
  1528. }
  1529. }();
  1530. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1531. const auto shader_cache_folder_path = shader_cache_dir / fmt::format("{:016x}", program_id);
  1532. const auto target_file = shader_cache_folder_path / target_file_name;
  1533. if (!Common::FS::Exists(target_file)) {
  1534. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1535. tr("A shader cache for this title does not exist."));
  1536. return;
  1537. }
  1538. if (Common::FS::RemoveFile(target_file)) {
  1539. QMessageBox::information(this, tr("Successfully Removed"),
  1540. tr("Successfully removed the transferable shader cache."));
  1541. } else {
  1542. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1543. tr("Failed to remove the transferable shader cache."));
  1544. }
  1545. }
  1546. void GMainWindow::RemoveAllTransferableShaderCaches(u64 program_id) {
  1547. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1548. const auto program_shader_cache_dir = shader_cache_dir / fmt::format("{:016x}", program_id);
  1549. if (!Common::FS::Exists(program_shader_cache_dir)) {
  1550. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  1551. tr("A shader cache for this title does not exist."));
  1552. return;
  1553. }
  1554. if (Common::FS::RemoveDirRecursively(program_shader_cache_dir)) {
  1555. QMessageBox::information(this, tr("Successfully Removed"),
  1556. tr("Successfully removed the transferable shader caches."));
  1557. } else {
  1558. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  1559. tr("Failed to remove the transferable shader cache directory."));
  1560. }
  1561. }
  1562. void GMainWindow::RemoveCustomConfiguration(u64 program_id, const std::string& game_path) {
  1563. const auto file_path = std::filesystem::path(Common::FS::ToU8String(game_path));
  1564. const auto config_file_name =
  1565. program_id == 0 ? Common::FS::PathToUTF8String(file_path.filename()).append(".ini")
  1566. : fmt::format("{:016X}.ini", program_id);
  1567. const auto custom_config_file_path =
  1568. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom" / config_file_name;
  1569. if (!Common::FS::Exists(custom_config_file_path)) {
  1570. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1571. tr("A custom configuration for this title does not exist."));
  1572. return;
  1573. }
  1574. if (Common::FS::RemoveFile(custom_config_file_path)) {
  1575. QMessageBox::information(this, tr("Successfully Removed"),
  1576. tr("Successfully removed the custom game configuration."));
  1577. } else {
  1578. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1579. tr("Failed to remove the custom game configuration."));
  1580. }
  1581. }
  1582. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path,
  1583. DumpRomFSTarget target) {
  1584. const auto failed = [this] {
  1585. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1586. tr("There was an error copying the RomFS files or the user "
  1587. "cancelled the operation."));
  1588. };
  1589. auto& system = Core::System::GetInstance();
  1590. const auto loader = Loader::GetLoader(system, vfs->OpenFile(game_path, FileSys::Mode::Read));
  1591. if (loader == nullptr) {
  1592. failed();
  1593. return;
  1594. }
  1595. FileSys::VirtualFile file;
  1596. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  1597. failed();
  1598. return;
  1599. }
  1600. const auto& installed = system.GetContentProvider();
  1601. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  1602. if (!romfs_title_id) {
  1603. failed();
  1604. return;
  1605. }
  1606. const auto dump_dir =
  1607. target == DumpRomFSTarget::Normal
  1608. ? Common::FS::GetYuzuPath(Common::FS::YuzuPath::DumpDir)
  1609. : Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "atmosphere" / "contents";
  1610. const auto romfs_dir = fmt::format("{:016X}/romfs", *romfs_title_id);
  1611. const auto path = Common::FS::PathToUTF8String(dump_dir / romfs_dir);
  1612. FileSys::VirtualFile romfs;
  1613. if (*romfs_title_id == program_id) {
  1614. const u64 ivfc_offset = loader->ReadRomFSIVFCOffset();
  1615. const FileSys::PatchManager pm{program_id, system.GetFileSystemController(), installed};
  1616. romfs =
  1617. pm.PatchRomFS(file, ivfc_offset, FileSys::ContentRecordType::Program, nullptr, false);
  1618. } else {
  1619. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  1620. }
  1621. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  1622. if (extracted == nullptr) {
  1623. failed();
  1624. return;
  1625. }
  1626. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  1627. if (out == nullptr) {
  1628. failed();
  1629. vfs->DeleteDirectory(path);
  1630. return;
  1631. }
  1632. bool ok = false;
  1633. const QStringList selections{tr("Full"), tr("Skeleton")};
  1634. const auto res = QInputDialog::getItem(
  1635. this, tr("Select RomFS Dump Mode"),
  1636. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  1637. "files into the new directory while <br>skeleton will only create the directory "
  1638. "structure."),
  1639. selections, 0, false, &ok);
  1640. if (!ok) {
  1641. failed();
  1642. vfs->DeleteDirectory(path);
  1643. return;
  1644. }
  1645. const auto full = res == selections.constFirst();
  1646. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  1647. // The minimum required space is the size of the extracted RomFS + 1 GiB
  1648. const auto minimum_free_space = extracted->GetSize() + 0x40000000;
  1649. if (full && Common::FS::GetFreeSpaceSize(path) < minimum_free_space) {
  1650. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1651. tr("There is not enough free space at %1 to extract the RomFS. Please "
  1652. "free up space or select a different dump directory at "
  1653. "Emulation > Configure > System > Filesystem > Dump Root")
  1654. .arg(QString::fromStdString(path)));
  1655. return;
  1656. }
  1657. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  1658. static_cast<s32>(entry_size), this);
  1659. progress.setWindowModality(Qt::WindowModal);
  1660. progress.setMinimumDuration(100);
  1661. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  1662. progress.close();
  1663. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  1664. tr("The operation completed successfully."));
  1665. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  1666. } else {
  1667. progress.close();
  1668. failed();
  1669. vfs->DeleteDirectory(path);
  1670. }
  1671. }
  1672. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  1673. QClipboard* clipboard = QGuiApplication::clipboard();
  1674. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  1675. }
  1676. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  1677. const CompatibilityList& compatibility_list) {
  1678. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  1679. QString directory;
  1680. if (it != compatibility_list.end()) {
  1681. directory = it->second.second;
  1682. }
  1683. QDesktopServices::openUrl(QUrl(QStringLiteral("https://yuzu-emu.org/game/") + directory));
  1684. }
  1685. void GMainWindow::OnGameListOpenDirectory(const QString& directory) {
  1686. std::filesystem::path fs_path;
  1687. if (directory == QStringLiteral("SDMC")) {
  1688. fs_path =
  1689. Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "Nintendo/Contents/registered";
  1690. } else if (directory == QStringLiteral("UserNAND")) {
  1691. fs_path =
  1692. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "user/Contents/registered";
  1693. } else if (directory == QStringLiteral("SysNAND")) {
  1694. fs_path =
  1695. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "system/Contents/registered";
  1696. } else {
  1697. fs_path = directory.toStdString();
  1698. }
  1699. const auto qt_path = QString::fromStdString(Common::FS::PathToUTF8String(fs_path));
  1700. if (!Common::FS::IsDir(fs_path)) {
  1701. QMessageBox::critical(this, tr("Error Opening %1").arg(qt_path),
  1702. tr("Folder does not exist!"));
  1703. return;
  1704. }
  1705. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_path));
  1706. }
  1707. void GMainWindow::OnGameListAddDirectory() {
  1708. const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1709. if (dir_path.isEmpty()) {
  1710. return;
  1711. }
  1712. UISettings::GameDir game_dir{dir_path, false, true};
  1713. if (!UISettings::values.game_dirs.contains(game_dir)) {
  1714. UISettings::values.game_dirs.append(game_dir);
  1715. game_list->PopulateAsync(UISettings::values.game_dirs);
  1716. } else {
  1717. LOG_WARNING(Frontend, "Selected directory is already in the game list");
  1718. }
  1719. }
  1720. void GMainWindow::OnGameListShowList(bool show) {
  1721. if (emulation_running && ui.action_Single_Window_Mode->isChecked())
  1722. return;
  1723. game_list->setVisible(show);
  1724. game_list_placeholder->setVisible(!show);
  1725. };
  1726. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  1727. u64 title_id{};
  1728. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  1729. const auto loader = Loader::GetLoader(Core::System::GetInstance(), v_file);
  1730. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  1731. QMessageBox::information(this, tr("Properties"),
  1732. tr("The game properties could not be loaded."));
  1733. return;
  1734. }
  1735. OpenPerGameConfiguration(title_id, file);
  1736. }
  1737. void GMainWindow::OnMenuLoadFile() {
  1738. const QString extensions =
  1739. QStringLiteral("*.")
  1740. .append(GameList::supported_file_extensions.join(QStringLiteral(" *.")))
  1741. .append(QStringLiteral(" main"));
  1742. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  1743. "%1 is an identifier for the Switch executable file extensions.")
  1744. .arg(extensions);
  1745. const QString filename = QFileDialog::getOpenFileName(
  1746. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  1747. if (filename.isEmpty()) {
  1748. return;
  1749. }
  1750. UISettings::values.roms_path = QFileInfo(filename).path();
  1751. BootGame(filename);
  1752. }
  1753. void GMainWindow::OnMenuLoadFolder() {
  1754. const QString dir_path =
  1755. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  1756. if (dir_path.isNull()) {
  1757. return;
  1758. }
  1759. const QDir dir{dir_path};
  1760. const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files);
  1761. if (matching_main.size() == 1) {
  1762. BootGame(dir.path() + QDir::separator() + matching_main[0]);
  1763. } else {
  1764. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  1765. tr("The directory you have selected does not contain a 'main' file."));
  1766. }
  1767. }
  1768. void GMainWindow::IncrementInstallProgress() {
  1769. install_progress->setValue(install_progress->value() + 1);
  1770. }
  1771. void GMainWindow::OnMenuInstallToNAND() {
  1772. const QString file_filter =
  1773. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  1774. "(*.nca);;Nintendo Submission Package (*.nsp);;NX Cartridge "
  1775. "Image (*.xci)");
  1776. QStringList filenames = QFileDialog::getOpenFileNames(
  1777. this, tr("Install Files"), UISettings::values.roms_path, file_filter);
  1778. if (filenames.isEmpty()) {
  1779. return;
  1780. }
  1781. InstallDialog installDialog(this, filenames);
  1782. if (installDialog.exec() == QDialog::Rejected) {
  1783. return;
  1784. }
  1785. const QStringList files = installDialog.GetFiles();
  1786. if (files.isEmpty()) {
  1787. return;
  1788. }
  1789. int remaining = filenames.size();
  1790. // This would only overflow above 2^43 bytes (8.796 TB)
  1791. int total_size = 0;
  1792. for (const QString& file : files) {
  1793. total_size += static_cast<int>(QFile(file).size() / 0x1000);
  1794. }
  1795. if (total_size < 0) {
  1796. LOG_CRITICAL(Frontend, "Attempting to install too many files, aborting.");
  1797. return;
  1798. }
  1799. QStringList new_files{}; // Newly installed files that do not yet exist in the NAND
  1800. QStringList overwritten_files{}; // Files that overwrote those existing in the NAND
  1801. QStringList failed_files{}; // Files that failed to install due to errors
  1802. bool detected_base_install{}; // Whether a base game was attempted to be installed
  1803. ui.action_Install_File_NAND->setEnabled(false);
  1804. install_progress = new QProgressDialog(QString{}, tr("Cancel"), 0, total_size, this);
  1805. install_progress->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint &
  1806. ~Qt::WindowMaximizeButtonHint);
  1807. install_progress->setAttribute(Qt::WA_DeleteOnClose, true);
  1808. install_progress->setFixedWidth(installDialog.GetMinimumWidth() + 40);
  1809. install_progress->show();
  1810. for (const QString& file : files) {
  1811. install_progress->setWindowTitle(tr("%n file(s) remaining", "", remaining));
  1812. install_progress->setLabelText(
  1813. tr("Installing file \"%1\"...").arg(QFileInfo(file).fileName()));
  1814. QFuture<InstallResult> future;
  1815. InstallResult result;
  1816. if (file.endsWith(QStringLiteral("xci"), Qt::CaseInsensitive) ||
  1817. file.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1818. future = QtConcurrent::run([this, &file] { return InstallNSPXCI(file); });
  1819. while (!future.isFinished()) {
  1820. QCoreApplication::processEvents();
  1821. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1822. }
  1823. result = future.result();
  1824. } else {
  1825. result = InstallNCA(file);
  1826. }
  1827. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1828. switch (result) {
  1829. case InstallResult::Success:
  1830. new_files.append(QFileInfo(file).fileName());
  1831. break;
  1832. case InstallResult::Overwrite:
  1833. overwritten_files.append(QFileInfo(file).fileName());
  1834. break;
  1835. case InstallResult::Failure:
  1836. failed_files.append(QFileInfo(file).fileName());
  1837. break;
  1838. case InstallResult::BaseInstallAttempted:
  1839. failed_files.append(QFileInfo(file).fileName());
  1840. detected_base_install = true;
  1841. break;
  1842. }
  1843. --remaining;
  1844. }
  1845. install_progress->close();
  1846. if (detected_base_install) {
  1847. QMessageBox::warning(
  1848. this, tr("Install Results"),
  1849. tr("To avoid possible conflicts, we discourage users from installing base games to the "
  1850. "NAND.\nPlease, only use this feature to install updates and DLC."));
  1851. }
  1852. const QString install_results =
  1853. (new_files.isEmpty() ? QString{}
  1854. : tr("%n file(s) were newly installed\n", "", new_files.size())) +
  1855. (overwritten_files.isEmpty()
  1856. ? QString{}
  1857. : tr("%n file(s) were overwritten\n", "", overwritten_files.size())) +
  1858. (failed_files.isEmpty() ? QString{}
  1859. : tr("%n file(s) failed to install\n", "", failed_files.size()));
  1860. QMessageBox::information(this, tr("Install Results"), install_results);
  1861. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  1862. "game_list");
  1863. game_list->PopulateAsync(UISettings::values.game_dirs);
  1864. ui.action_Install_File_NAND->setEnabled(true);
  1865. }
  1866. InstallResult GMainWindow::InstallNSPXCI(const QString& filename) {
  1867. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1868. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1869. if (src == nullptr || dest == nullptr) {
  1870. return false;
  1871. }
  1872. if (!dest->Resize(src->GetSize())) {
  1873. return false;
  1874. }
  1875. std::array<u8, 0x1000> buffer{};
  1876. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1877. if (install_progress->wasCanceled()) {
  1878. dest->Resize(0);
  1879. return false;
  1880. }
  1881. emit UpdateInstallProgress();
  1882. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1883. dest->Write(buffer.data(), read, i);
  1884. }
  1885. return true;
  1886. };
  1887. std::shared_ptr<FileSys::NSP> nsp;
  1888. if (filename.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1889. nsp = std::make_shared<FileSys::NSP>(
  1890. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1891. if (nsp->IsExtractedType()) {
  1892. return InstallResult::Failure;
  1893. }
  1894. } else {
  1895. const auto xci = std::make_shared<FileSys::XCI>(
  1896. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1897. nsp = xci->GetSecurePartitionNSP();
  1898. }
  1899. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  1900. return InstallResult::Failure;
  1901. }
  1902. const auto res =
  1903. Core::System::GetInstance().GetFileSystemController().GetUserNANDContents()->InstallEntry(
  1904. *nsp, true, qt_raw_copy);
  1905. switch (res) {
  1906. case FileSys::InstallResult::Success:
  1907. return InstallResult::Success;
  1908. case FileSys::InstallResult::OverwriteExisting:
  1909. return InstallResult::Overwrite;
  1910. case FileSys::InstallResult::ErrorBaseInstall:
  1911. return InstallResult::BaseInstallAttempted;
  1912. default:
  1913. return InstallResult::Failure;
  1914. }
  1915. }
  1916. InstallResult GMainWindow::InstallNCA(const QString& filename) {
  1917. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1918. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1919. if (src == nullptr || dest == nullptr) {
  1920. return false;
  1921. }
  1922. if (!dest->Resize(src->GetSize())) {
  1923. return false;
  1924. }
  1925. std::array<u8, 0x1000> buffer{};
  1926. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1927. if (install_progress->wasCanceled()) {
  1928. dest->Resize(0);
  1929. return false;
  1930. }
  1931. emit UpdateInstallProgress();
  1932. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1933. dest->Write(buffer.data(), read, i);
  1934. }
  1935. return true;
  1936. };
  1937. const auto nca =
  1938. std::make_shared<FileSys::NCA>(vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1939. const auto id = nca->GetStatus();
  1940. // Game updates necessary are missing base RomFS
  1941. if (id != Loader::ResultStatus::Success &&
  1942. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  1943. return InstallResult::Failure;
  1944. }
  1945. const QStringList tt_options{tr("System Application"),
  1946. tr("System Archive"),
  1947. tr("System Application Update"),
  1948. tr("Firmware Package (Type A)"),
  1949. tr("Firmware Package (Type B)"),
  1950. tr("Game"),
  1951. tr("Game Update"),
  1952. tr("Game DLC"),
  1953. tr("Delta Title")};
  1954. bool ok;
  1955. const auto item = QInputDialog::getItem(
  1956. this, tr("Select NCA Install Type..."),
  1957. tr("Please select the type of title you would like to install this NCA as:\n(In "
  1958. "most instances, the default 'Game' is fine.)"),
  1959. tt_options, 5, false, &ok);
  1960. auto index = tt_options.indexOf(item);
  1961. if (!ok || index == -1) {
  1962. QMessageBox::warning(this, tr("Failed to Install"),
  1963. tr("The title type you selected for the NCA is invalid."));
  1964. return InstallResult::Failure;
  1965. }
  1966. // If index is equal to or past Game, add the jump in TitleType.
  1967. if (index >= 5) {
  1968. index += static_cast<size_t>(FileSys::TitleType::Application) -
  1969. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  1970. }
  1971. FileSys::InstallResult res;
  1972. if (index >= static_cast<s32>(FileSys::TitleType::Application)) {
  1973. res = Core::System::GetInstance()
  1974. .GetFileSystemController()
  1975. .GetUserNANDContents()
  1976. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1977. } else {
  1978. res = Core::System::GetInstance()
  1979. .GetFileSystemController()
  1980. .GetSystemNANDContents()
  1981. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1982. }
  1983. if (res == FileSys::InstallResult::Success) {
  1984. return InstallResult::Success;
  1985. } else if (res == FileSys::InstallResult::OverwriteExisting) {
  1986. return InstallResult::Overwrite;
  1987. } else {
  1988. return InstallResult::Failure;
  1989. }
  1990. }
  1991. void GMainWindow::OnMenuRecentFile() {
  1992. QAction* action = qobject_cast<QAction*>(sender());
  1993. assert(action);
  1994. const QString filename = action->data().toString();
  1995. if (QFileInfo::exists(filename)) {
  1996. BootGame(filename);
  1997. } else {
  1998. // Display an error message and remove the file from the list.
  1999. QMessageBox::information(this, tr("File not found"),
  2000. tr("File \"%1\" not found").arg(filename));
  2001. UISettings::values.recent_files.removeOne(filename);
  2002. UpdateRecentFiles();
  2003. }
  2004. }
  2005. void GMainWindow::OnStartGame() {
  2006. PreventOSSleep();
  2007. emu_thread->SetRunning(true);
  2008. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  2009. ui.action_Start->setEnabled(false);
  2010. ui.action_Start->setText(tr("&Continue"));
  2011. ui.action_Pause->setEnabled(true);
  2012. ui.action_Stop->setEnabled(true);
  2013. ui.action_Restart->setEnabled(true);
  2014. ui.action_Configure_Current_Game->setEnabled(true);
  2015. ui.action_Report_Compatibility->setEnabled(true);
  2016. discord_rpc->Update();
  2017. ui.action_Load_Amiibo->setEnabled(true);
  2018. ui.action_Capture_Screenshot->setEnabled(true);
  2019. }
  2020. void GMainWindow::OnPauseGame() {
  2021. emu_thread->SetRunning(false);
  2022. ui.action_Start->setEnabled(true);
  2023. ui.action_Pause->setEnabled(false);
  2024. ui.action_Stop->setEnabled(true);
  2025. ui.action_Capture_Screenshot->setEnabled(false);
  2026. AllowOSSleep();
  2027. }
  2028. void GMainWindow::OnStopGame() {
  2029. auto& system{Core::System::GetInstance()};
  2030. if (system.GetExitLock() && !ConfirmForceLockedExit()) {
  2031. return;
  2032. }
  2033. ShutdownGame();
  2034. Settings::RestoreGlobalState(system.IsPoweredOn());
  2035. UpdateStatusButtons();
  2036. }
  2037. void GMainWindow::OnLoadComplete() {
  2038. loading_screen->OnLoadComplete();
  2039. }
  2040. void GMainWindow::OnExecuteProgram(std::size_t program_index) {
  2041. ShutdownGame();
  2042. BootGame(last_filename_booted, 0, program_index);
  2043. }
  2044. void GMainWindow::ErrorDisplayDisplayError(QString error_code, QString error_text) {
  2045. OverlayDialog dialog(render_window, Core::System::GetInstance(), error_code, error_text,
  2046. QString{}, tr("OK"), Qt::AlignLeft | Qt::AlignVCenter);
  2047. dialog.exec();
  2048. emit ErrorDisplayFinished();
  2049. }
  2050. void GMainWindow::OnMenuReportCompatibility() {
  2051. if (!Settings::values.yuzu_token.GetValue().empty() &&
  2052. !Settings::values.yuzu_username.GetValue().empty()) {
  2053. CompatDB compatdb{this};
  2054. compatdb.exec();
  2055. } else {
  2056. QMessageBox::critical(
  2057. this, tr("Missing yuzu Account"),
  2058. tr("In order to submit a game compatibility test case, you must link your yuzu "
  2059. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  2060. "&gt; "
  2061. "Web."));
  2062. }
  2063. }
  2064. void GMainWindow::OpenURL(const QUrl& url) {
  2065. const bool open = QDesktopServices::openUrl(url);
  2066. if (!open) {
  2067. QMessageBox::warning(this, tr("Error opening URL"),
  2068. tr("Unable to open the URL \"%1\".").arg(url.toString()));
  2069. }
  2070. }
  2071. void GMainWindow::OnOpenModsPage() {
  2072. OpenURL(QUrl(QStringLiteral("https://github.com/yuzu-emu/yuzu/wiki/Switch-Mods")));
  2073. }
  2074. void GMainWindow::OnOpenQuickstartGuide() {
  2075. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/help/quickstart/")));
  2076. }
  2077. void GMainWindow::OnOpenFAQ() {
  2078. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/wiki/faq/")));
  2079. }
  2080. void GMainWindow::ToggleFullscreen() {
  2081. if (!emulation_running) {
  2082. return;
  2083. }
  2084. if (ui.action_Fullscreen->isChecked()) {
  2085. ShowFullscreen();
  2086. } else {
  2087. HideFullscreen();
  2088. }
  2089. }
  2090. void GMainWindow::ShowFullscreen() {
  2091. if (ui.action_Single_Window_Mode->isChecked()) {
  2092. UISettings::values.geometry = saveGeometry();
  2093. ui.menubar->hide();
  2094. statusBar()->hide();
  2095. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2096. showFullScreen();
  2097. return;
  2098. }
  2099. hide();
  2100. setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
  2101. const auto screen_geometry = QApplication::desktop()->screenGeometry(this);
  2102. setGeometry(screen_geometry.x(), screen_geometry.y(), screen_geometry.width(),
  2103. screen_geometry.height() + 1);
  2104. raise();
  2105. showNormal();
  2106. } else {
  2107. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2108. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2109. render_window->showFullScreen();
  2110. return;
  2111. }
  2112. render_window->hide();
  2113. render_window->setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
  2114. const auto screen_geometry = QApplication::desktop()->screenGeometry(this);
  2115. render_window->setGeometry(screen_geometry.x(), screen_geometry.y(),
  2116. screen_geometry.width(), screen_geometry.height() + 1);
  2117. render_window->raise();
  2118. render_window->showNormal();
  2119. }
  2120. }
  2121. void GMainWindow::HideFullscreen() {
  2122. if (ui.action_Single_Window_Mode->isChecked()) {
  2123. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2124. showNormal();
  2125. restoreGeometry(UISettings::values.geometry);
  2126. } else {
  2127. hide();
  2128. setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2129. restoreGeometry(UISettings::values.geometry);
  2130. raise();
  2131. show();
  2132. }
  2133. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  2134. ui.menubar->show();
  2135. } else {
  2136. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2137. render_window->showNormal();
  2138. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2139. } else {
  2140. render_window->hide();
  2141. render_window->setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2142. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2143. render_window->raise();
  2144. render_window->show();
  2145. }
  2146. }
  2147. }
  2148. void GMainWindow::ToggleWindowMode() {
  2149. if (ui.action_Single_Window_Mode->isChecked()) {
  2150. // Render in the main window...
  2151. render_window->BackupGeometry();
  2152. ui.horizontalLayout->addWidget(render_window);
  2153. render_window->setFocusPolicy(Qt::StrongFocus);
  2154. if (emulation_running) {
  2155. render_window->setVisible(true);
  2156. render_window->setFocus();
  2157. game_list->hide();
  2158. }
  2159. } else {
  2160. // Render in a separate window...
  2161. ui.horizontalLayout->removeWidget(render_window);
  2162. render_window->setParent(nullptr);
  2163. render_window->setFocusPolicy(Qt::NoFocus);
  2164. if (emulation_running) {
  2165. render_window->setVisible(true);
  2166. render_window->RestoreGeometry();
  2167. game_list->show();
  2168. }
  2169. }
  2170. }
  2171. void GMainWindow::ResetWindowSize720() {
  2172. const auto aspect_ratio = Layout::EmulationAspectRatio(
  2173. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  2174. static_cast<float>(Layout::ScreenUndocked::Height) / Layout::ScreenUndocked::Width);
  2175. if (!ui.action_Single_Window_Mode->isChecked()) {
  2176. render_window->resize(Layout::ScreenUndocked::Height / aspect_ratio,
  2177. Layout::ScreenUndocked::Height);
  2178. } else {
  2179. resize(Layout::ScreenUndocked::Height / aspect_ratio,
  2180. Layout::ScreenUndocked::Height + menuBar()->height() +
  2181. (ui.action_Show_Status_Bar->isChecked() ? statusBar()->height() : 0));
  2182. }
  2183. }
  2184. void GMainWindow::ResetWindowSize1080() {
  2185. const auto aspect_ratio = Layout::EmulationAspectRatio(
  2186. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  2187. static_cast<float>(Layout::ScreenDocked::Height) / Layout::ScreenDocked::Width);
  2188. if (!ui.action_Single_Window_Mode->isChecked()) {
  2189. render_window->resize(Layout::ScreenDocked::Height / aspect_ratio,
  2190. Layout::ScreenDocked::Height);
  2191. } else {
  2192. resize(Layout::ScreenDocked::Height / aspect_ratio,
  2193. Layout::ScreenDocked::Height + menuBar()->height() +
  2194. (ui.action_Show_Status_Bar->isChecked() ? statusBar()->height() : 0));
  2195. }
  2196. }
  2197. void GMainWindow::OnConfigure() {
  2198. const auto old_theme = UISettings::values.theme;
  2199. const bool old_discord_presence = UISettings::values.enable_discord_presence.GetValue();
  2200. ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get());
  2201. connect(&configure_dialog, &ConfigureDialog::LanguageChanged, this,
  2202. &GMainWindow::OnLanguageChanged);
  2203. const auto result = configure_dialog.exec();
  2204. if (result != QDialog::Accepted && !UISettings::values.configuration_applied &&
  2205. !UISettings::values.reset_to_defaults) {
  2206. // Runs if the user hit Cancel or closed the window, and did not ever press the Apply button
  2207. // or `Reset to Defaults` button
  2208. return;
  2209. } else if (result == QDialog::Accepted) {
  2210. // Only apply new changes if user hit Okay
  2211. // This is here to avoid applying changes if the user hit Apply, made some changes, then hit
  2212. // Cancel
  2213. configure_dialog.ApplyConfiguration();
  2214. } else if (UISettings::values.reset_to_defaults) {
  2215. LOG_INFO(Frontend, "Resetting all settings to defaults");
  2216. if (!Common::FS::RemoveFile(config->GetConfigFilePath())) {
  2217. LOG_WARNING(Frontend, "Failed to remove configuration file");
  2218. }
  2219. if (!Common::FS::RemoveDirContentsRecursively(
  2220. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom")) {
  2221. LOG_WARNING(Frontend, "Failed to remove custom configuration files");
  2222. }
  2223. if (!Common::FS::RemoveDirRecursively(
  2224. Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) / "game_list")) {
  2225. LOG_WARNING(Frontend, "Failed to remove game metadata cache files");
  2226. }
  2227. // Explicitly save the game directories, since reinitializing config does not explicitly do
  2228. // so.
  2229. QVector<UISettings::GameDir> old_game_dirs = std::move(UISettings::values.game_dirs);
  2230. QVector<u64> old_favorited_ids = std::move(UISettings::values.favorited_ids);
  2231. Settings::values.disabled_addons.clear();
  2232. config = std::make_unique<Config>();
  2233. UISettings::values.reset_to_defaults = false;
  2234. UISettings::values.game_dirs = std::move(old_game_dirs);
  2235. UISettings::values.favorited_ids = std::move(old_favorited_ids);
  2236. InitializeRecentFileMenuActions();
  2237. SetDefaultUIGeometry();
  2238. RestoreUIState();
  2239. ShowTelemetryCallout();
  2240. }
  2241. controller_dialog->refreshConfiguration();
  2242. InitializeHotkeys();
  2243. if (UISettings::values.theme != old_theme) {
  2244. UpdateUITheme();
  2245. }
  2246. if (UISettings::values.enable_discord_presence.GetValue() != old_discord_presence) {
  2247. SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue());
  2248. }
  2249. emit UpdateThemedIcons();
  2250. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2251. if (reload) {
  2252. game_list->PopulateAsync(UISettings::values.game_dirs);
  2253. }
  2254. UISettings::values.configuration_applied = false;
  2255. config->Save();
  2256. if ((UISettings::values.hide_mouse || Settings::values.mouse_panning) && emulation_running) {
  2257. render_window->installEventFilter(render_window);
  2258. render_window->setAttribute(Qt::WA_Hover, true);
  2259. } else {
  2260. render_window->removeEventFilter(render_window);
  2261. render_window->setAttribute(Qt::WA_Hover, false);
  2262. }
  2263. if (UISettings::values.hide_mouse) {
  2264. mouse_hide_timer.start();
  2265. }
  2266. UpdateStatusButtons();
  2267. }
  2268. void GMainWindow::OnConfigurePerGame() {
  2269. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  2270. OpenPerGameConfiguration(title_id, game_path.toStdString());
  2271. }
  2272. void GMainWindow::OpenPerGameConfiguration(u64 title_id, const std::string& file_name) {
  2273. const auto v_file = Core::GetGameFileFromPath(vfs, file_name);
  2274. const auto& system = Core::System::GetInstance();
  2275. ConfigurePerGame dialog(this, title_id, file_name);
  2276. dialog.LoadFromFile(v_file);
  2277. const auto result = dialog.exec();
  2278. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  2279. Settings::RestoreGlobalState(system.IsPoweredOn());
  2280. return;
  2281. } else if (result == QDialog::Accepted) {
  2282. dialog.ApplyConfiguration();
  2283. }
  2284. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2285. if (reload) {
  2286. game_list->PopulateAsync(UISettings::values.game_dirs);
  2287. }
  2288. // Do not cause the global config to write local settings into the config file
  2289. const bool is_powered_on = system.IsPoweredOn();
  2290. Settings::RestoreGlobalState(is_powered_on);
  2291. UISettings::values.configuration_applied = false;
  2292. if (!is_powered_on) {
  2293. config->Save();
  2294. }
  2295. }
  2296. void GMainWindow::OnLoadAmiibo() {
  2297. const QString extensions{QStringLiteral("*.bin")};
  2298. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  2299. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter);
  2300. if (filename.isEmpty()) {
  2301. return;
  2302. }
  2303. LoadAmiibo(filename);
  2304. }
  2305. void GMainWindow::LoadAmiibo(const QString& filename) {
  2306. Core::System& system{Core::System::GetInstance()};
  2307. Service::SM::ServiceManager& sm = system.ServiceManager();
  2308. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  2309. if (nfc == nullptr) {
  2310. return;
  2311. }
  2312. QFile nfc_file{filename};
  2313. if (!nfc_file.open(QIODevice::ReadOnly)) {
  2314. QMessageBox::warning(this, tr("Error opening Amiibo data file"),
  2315. tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
  2316. return;
  2317. }
  2318. const u64 nfc_file_size = nfc_file.size();
  2319. std::vector<u8> buffer(nfc_file_size);
  2320. const u64 read_size = nfc_file.read(reinterpret_cast<char*>(buffer.data()), nfc_file_size);
  2321. if (nfc_file_size != read_size) {
  2322. QMessageBox::warning(this, tr("Error reading Amiibo data file"),
  2323. tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
  2324. "was only able to read %2 bytes.")
  2325. .arg(nfc_file_size)
  2326. .arg(read_size));
  2327. return;
  2328. }
  2329. if (!nfc->LoadAmiibo(buffer)) {
  2330. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  2331. tr("Unable to load Amiibo data."));
  2332. }
  2333. }
  2334. void GMainWindow::OnOpenYuzuFolder() {
  2335. QDesktopServices::openUrl(QUrl::fromLocalFile(
  2336. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::YuzuDir))));
  2337. }
  2338. void GMainWindow::OnAbout() {
  2339. AboutDialog aboutDialog(this);
  2340. aboutDialog.exec();
  2341. }
  2342. void GMainWindow::OnToggleFilterBar() {
  2343. game_list->SetFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  2344. if (ui.action_Show_Filter_Bar->isChecked()) {
  2345. game_list->SetFilterFocus();
  2346. } else {
  2347. game_list->ClearFilter();
  2348. }
  2349. }
  2350. void GMainWindow::OnCaptureScreenshot() {
  2351. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  2352. const auto screenshot_path =
  2353. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::ScreenshotsDir));
  2354. const auto date =
  2355. QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd_hh-mm-ss-zzz"));
  2356. QString filename = QStringLiteral("%1/%2_%3.png")
  2357. .arg(screenshot_path)
  2358. .arg(title_id, 16, 16, QLatin1Char{'0'})
  2359. .arg(date);
  2360. if (!Common::FS::CreateDir(screenshot_path.toStdString())) {
  2361. return;
  2362. }
  2363. #ifdef _WIN32
  2364. if (UISettings::values.enable_screenshot_save_as) {
  2365. OnPauseGame();
  2366. filename = QFileDialog::getSaveFileName(this, tr("Capture Screenshot"), filename,
  2367. tr("PNG Image (*.png)"));
  2368. OnStartGame();
  2369. if (filename.isEmpty()) {
  2370. return;
  2371. }
  2372. }
  2373. #endif
  2374. render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor.GetValue(),
  2375. filename);
  2376. }
  2377. // TODO: Written 2020-10-01: Remove per-game config migration code when it is irrelevant
  2378. void GMainWindow::MigrateConfigFiles() {
  2379. const auto config_dir_fs_path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir);
  2380. const QDir config_dir =
  2381. QDir(QString::fromStdString(Common::FS::PathToUTF8String(config_dir_fs_path)));
  2382. const QStringList config_dir_list = config_dir.entryList(QStringList(QStringLiteral("*.ini")));
  2383. if (!Common::FS::CreateDirs(config_dir_fs_path / "custom")) {
  2384. LOG_ERROR(Frontend, "Failed to create new config file directory");
  2385. }
  2386. for (auto it = config_dir_list.constBegin(); it != config_dir_list.constEnd(); ++it) {
  2387. const auto filename = it->toStdString();
  2388. if (filename.find_first_not_of("0123456789abcdefACBDEF", 0) < 16) {
  2389. continue;
  2390. }
  2391. const auto origin = config_dir_fs_path / filename;
  2392. const auto destination = config_dir_fs_path / "custom" / filename;
  2393. LOG_INFO(Frontend, "Migrating config file from {} to {}", origin, destination);
  2394. if (!Common::FS::RenameFile(origin, destination)) {
  2395. // Delete the old config file if one already exists in the new location.
  2396. Common::FS::RemoveFile(origin);
  2397. }
  2398. }
  2399. }
  2400. void GMainWindow::UpdateWindowTitle(std::string_view title_name, std::string_view title_version,
  2401. std::string_view gpu_vendor) {
  2402. const auto branch_name = std::string(Common::g_scm_branch);
  2403. const auto description = std::string(Common::g_scm_desc);
  2404. const auto build_id = std::string(Common::g_build_id);
  2405. const auto yuzu_title = fmt::format("yuzu | {}-{}", branch_name, description);
  2406. const auto override_title =
  2407. fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id);
  2408. const auto window_title = override_title.empty() ? yuzu_title : override_title;
  2409. if (title_name.empty()) {
  2410. setWindowTitle(QString::fromStdString(window_title));
  2411. } else {
  2412. const auto run_title =
  2413. fmt::format("{} | {} | {} | {}", window_title, title_name, title_version, gpu_vendor);
  2414. setWindowTitle(QString::fromStdString(run_title));
  2415. }
  2416. }
  2417. void GMainWindow::UpdateStatusBar() {
  2418. if (emu_thread == nullptr) {
  2419. status_bar_update_timer.stop();
  2420. return;
  2421. }
  2422. auto& system = Core::System::GetInstance();
  2423. auto results = system.GetAndResetPerfStats();
  2424. auto& shader_notify = system.GPU().ShaderNotify();
  2425. const int shaders_building = shader_notify.ShadersBuilding();
  2426. if (shaders_building > 0) {
  2427. shader_building_label->setText(tr("Building: %n shader(s)", "", shaders_building));
  2428. shader_building_label->setVisible(true);
  2429. } else {
  2430. shader_building_label->setVisible(false);
  2431. }
  2432. if (Settings::values.use_speed_limit.GetValue()) {
  2433. emu_speed_label->setText(tr("Speed: %1% / %2%")
  2434. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  2435. .arg(Settings::values.speed_limit.GetValue()));
  2436. } else {
  2437. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  2438. }
  2439. if (Settings::values.disable_fps_limit) {
  2440. game_fps_label->setText(
  2441. tr("Game: %1 FPS (Unlocked)").arg(results.average_game_fps, 0, 'f', 0));
  2442. } else {
  2443. game_fps_label->setText(tr("Game: %1 FPS").arg(results.average_game_fps, 0, 'f', 0));
  2444. }
  2445. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  2446. emu_speed_label->setVisible(!Settings::values.use_multi_core.GetValue());
  2447. game_fps_label->setVisible(true);
  2448. emu_frametime_label->setVisible(true);
  2449. }
  2450. void GMainWindow::UpdateGPUAccuracyButton() {
  2451. switch (Settings::values.gpu_accuracy.GetValue()) {
  2452. case Settings::GPUAccuracy::Normal: {
  2453. gpu_accuracy_button->setText(tr("GPU NORMAL"));
  2454. gpu_accuracy_button->setChecked(false);
  2455. break;
  2456. }
  2457. case Settings::GPUAccuracy::High: {
  2458. gpu_accuracy_button->setText(tr("GPU HIGH"));
  2459. gpu_accuracy_button->setChecked(true);
  2460. break;
  2461. }
  2462. case Settings::GPUAccuracy::Extreme: {
  2463. gpu_accuracy_button->setText(tr("GPU EXTREME"));
  2464. gpu_accuracy_button->setChecked(true);
  2465. break;
  2466. }
  2467. default: {
  2468. gpu_accuracy_button->setText(tr("GPU ERROR"));
  2469. gpu_accuracy_button->setChecked(true);
  2470. }
  2471. }
  2472. }
  2473. void GMainWindow::UpdateStatusButtons() {
  2474. dock_status_button->setChecked(Settings::values.use_docked_mode.GetValue());
  2475. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  2476. Settings::RendererBackend::Vulkan);
  2477. UpdateGPUAccuracyButton();
  2478. }
  2479. void GMainWindow::UpdateUISettings() {
  2480. if (!ui.action_Fullscreen->isChecked()) {
  2481. UISettings::values.geometry = saveGeometry();
  2482. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2483. }
  2484. UISettings::values.state = saveState();
  2485. #if MICROPROFILE_ENABLED
  2486. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  2487. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  2488. #endif
  2489. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  2490. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  2491. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  2492. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  2493. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  2494. UISettings::values.first_start = false;
  2495. }
  2496. void GMainWindow::HideMouseCursor() {
  2497. if (emu_thread == nullptr && UISettings::values.hide_mouse) {
  2498. mouse_hide_timer.stop();
  2499. ShowMouseCursor();
  2500. return;
  2501. }
  2502. render_window->setCursor(QCursor(Qt::BlankCursor));
  2503. }
  2504. void GMainWindow::ShowMouseCursor() {
  2505. render_window->unsetCursor();
  2506. if (emu_thread != nullptr && UISettings::values.hide_mouse) {
  2507. mouse_hide_timer.start();
  2508. }
  2509. }
  2510. void GMainWindow::OnMouseActivity() {
  2511. if (!Settings::values.mouse_panning) {
  2512. ShowMouseCursor();
  2513. }
  2514. }
  2515. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  2516. QMessageBox::StandardButton answer;
  2517. QString status_message;
  2518. const QString common_message =
  2519. tr("The game you are trying to load requires additional files from your Switch to be "
  2520. "dumped "
  2521. "before playing.<br/><br/>For more information on dumping these files, please see the "
  2522. "following wiki page: <a "
  2523. "href='https://yuzu-emu.org/wiki/"
  2524. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  2525. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  2526. "quit "
  2527. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  2528. "data, or other bugs.");
  2529. switch (result) {
  2530. case Core::System::ResultStatus::ErrorSystemFiles: {
  2531. QString message;
  2532. if (details.empty()) {
  2533. message =
  2534. tr("yuzu was unable to locate a Switch system archive. %1").arg(common_message);
  2535. } else {
  2536. message = tr("yuzu was unable to locate a Switch system archive: %1. %2")
  2537. .arg(QString::fromStdString(details), common_message);
  2538. }
  2539. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  2540. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2541. status_message = tr("System Archive Missing");
  2542. break;
  2543. }
  2544. case Core::System::ResultStatus::ErrorSharedFont: {
  2545. const QString message =
  2546. tr("yuzu was unable to locate the Switch shared fonts. %1").arg(common_message);
  2547. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  2548. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2549. status_message = tr("Shared Font Missing");
  2550. break;
  2551. }
  2552. default:
  2553. answer = QMessageBox::question(
  2554. this, tr("Fatal Error"),
  2555. tr("yuzu has encountered a fatal error, please see the log for more details. "
  2556. "For more information on accessing the log, please see the following page: "
  2557. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  2558. "to "
  2559. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  2560. "list? "
  2561. "Continuing emulation may result in crashes, corrupted save data, or other "
  2562. "bugs."),
  2563. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2564. status_message = tr("Fatal Error encountered");
  2565. break;
  2566. }
  2567. if (answer == QMessageBox::Yes) {
  2568. if (emu_thread) {
  2569. ShutdownGame();
  2570. Settings::RestoreGlobalState(Core::System::GetInstance().IsPoweredOn());
  2571. UpdateStatusButtons();
  2572. }
  2573. } else {
  2574. // Only show the message if the game is still running.
  2575. if (emu_thread) {
  2576. emu_thread->SetRunning(true);
  2577. message_label->setText(status_message);
  2578. }
  2579. }
  2580. }
  2581. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  2582. if (behavior == ReinitializeKeyBehavior::Warning) {
  2583. const auto res = QMessageBox::information(
  2584. this, tr("Confirm Key Rederivation"),
  2585. tr("You are about to force rederive all of your keys. \nIf you do not know what "
  2586. "this "
  2587. "means or what you are doing, \nthis is a potentially destructive action. "
  2588. "\nPlease "
  2589. "make sure this is what you want \nand optionally make backups.\n\nThis will "
  2590. "delete "
  2591. "your autogenerated key files and re-run the key derivation module."),
  2592. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  2593. if (res == QMessageBox::Cancel)
  2594. return;
  2595. const auto keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
  2596. Common::FS::RemoveFile(keys_dir / "prod.keys_autogenerated");
  2597. Common::FS::RemoveFile(keys_dir / "console.keys_autogenerated");
  2598. Common::FS::RemoveFile(keys_dir / "title.keys_autogenerated");
  2599. }
  2600. Core::Crypto::KeyManager& keys = Core::Crypto::KeyManager::Instance();
  2601. if (keys.BaseDeriveNecessary()) {
  2602. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory("", FileSys::Mode::Read)};
  2603. const auto function = [this, &keys, &pdm] {
  2604. keys.PopulateFromPartitionData(pdm);
  2605. auto& system = Core::System::GetInstance();
  2606. system.GetFileSystemController().CreateFactories(*vfs);
  2607. keys.DeriveETicket(pdm, system.GetContentProvider());
  2608. };
  2609. QString errors;
  2610. if (!pdm.HasFuses()) {
  2611. errors += tr("Missing fuses");
  2612. }
  2613. if (!pdm.HasBoot0()) {
  2614. errors += tr(" - Missing BOOT0");
  2615. }
  2616. if (!pdm.HasPackage2()) {
  2617. errors += tr(" - Missing BCPKG2-1-Normal-Main");
  2618. }
  2619. if (!pdm.HasProdInfo()) {
  2620. errors += tr(" - Missing PRODINFO");
  2621. }
  2622. if (!errors.isEmpty()) {
  2623. QMessageBox::warning(
  2624. this, tr("Derivation Components Missing"),
  2625. tr("Components are missing that may hinder key derivation from completing. "
  2626. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  2627. "quickstart guide</a> to get all your keys and "
  2628. "games.<br><br><small>(%1)</small>")
  2629. .arg(errors));
  2630. }
  2631. QProgressDialog prog(this);
  2632. prog.setRange(0, 0);
  2633. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  2634. "system's performance."));
  2635. prog.setWindowTitle(tr("Deriving Keys"));
  2636. prog.show();
  2637. auto future = QtConcurrent::run(function);
  2638. while (!future.isFinished()) {
  2639. QCoreApplication::processEvents();
  2640. }
  2641. prog.close();
  2642. }
  2643. Core::System::GetInstance().GetFileSystemController().CreateFactories(*vfs);
  2644. if (behavior == ReinitializeKeyBehavior::Warning) {
  2645. game_list->PopulateAsync(UISettings::values.game_dirs);
  2646. }
  2647. }
  2648. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
  2649. u64 program_id) {
  2650. const auto dlc_entries =
  2651. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  2652. std::vector<FileSys::ContentProviderEntry> dlc_match;
  2653. dlc_match.reserve(dlc_entries.size());
  2654. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  2655. [&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
  2656. return FileSys::GetBaseTitleID(entry.title_id) == program_id &&
  2657. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  2658. });
  2659. std::vector<u64> romfs_tids;
  2660. romfs_tids.push_back(program_id);
  2661. for (const auto& entry : dlc_match) {
  2662. romfs_tids.push_back(entry.title_id);
  2663. }
  2664. if (romfs_tids.size() > 1) {
  2665. QStringList list{QStringLiteral("Base")};
  2666. for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
  2667. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  2668. }
  2669. bool ok;
  2670. const auto res = QInputDialog::getItem(
  2671. this, tr("Select RomFS Dump Target"),
  2672. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  2673. if (!ok) {
  2674. return {};
  2675. }
  2676. return romfs_tids[list.indexOf(res)];
  2677. }
  2678. return program_id;
  2679. }
  2680. bool GMainWindow::ConfirmClose() {
  2681. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  2682. return true;
  2683. QMessageBox::StandardButton answer =
  2684. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  2685. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2686. return answer != QMessageBox::No;
  2687. }
  2688. void GMainWindow::closeEvent(QCloseEvent* event) {
  2689. if (!ConfirmClose()) {
  2690. event->ignore();
  2691. return;
  2692. }
  2693. UpdateUISettings();
  2694. game_list->SaveInterfaceLayout();
  2695. hotkey_registry.SaveHotkeys();
  2696. // Shutdown session if the emu thread is active...
  2697. if (emu_thread != nullptr) {
  2698. ShutdownGame();
  2699. Settings::RestoreGlobalState(Core::System::GetInstance().IsPoweredOn());
  2700. UpdateStatusButtons();
  2701. }
  2702. render_window->close();
  2703. QWidget::closeEvent(event);
  2704. }
  2705. static bool IsSingleFileDropEvent(const QMimeData* mime) {
  2706. return mime->hasUrls() && mime->urls().length() == 1;
  2707. }
  2708. void GMainWindow::AcceptDropEvent(QDropEvent* event) {
  2709. if (IsSingleFileDropEvent(event->mimeData())) {
  2710. event->setDropAction(Qt::DropAction::LinkAction);
  2711. event->accept();
  2712. }
  2713. }
  2714. bool GMainWindow::DropAction(QDropEvent* event) {
  2715. if (!IsSingleFileDropEvent(event->mimeData())) {
  2716. return false;
  2717. }
  2718. const QMimeData* mime_data = event->mimeData();
  2719. const QString& filename = mime_data->urls().at(0).toLocalFile();
  2720. if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
  2721. // Amiibo
  2722. LoadAmiibo(filename);
  2723. } else {
  2724. // Game
  2725. if (ConfirmChangeGame()) {
  2726. BootGame(filename);
  2727. }
  2728. }
  2729. return true;
  2730. }
  2731. void GMainWindow::dropEvent(QDropEvent* event) {
  2732. DropAction(event);
  2733. }
  2734. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  2735. AcceptDropEvent(event);
  2736. }
  2737. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  2738. AcceptDropEvent(event);
  2739. }
  2740. bool GMainWindow::ConfirmChangeGame() {
  2741. if (emu_thread == nullptr)
  2742. return true;
  2743. const auto answer = QMessageBox::question(
  2744. this, tr("yuzu"),
  2745. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  2746. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2747. return answer != QMessageBox::No;
  2748. }
  2749. bool GMainWindow::ConfirmForceLockedExit() {
  2750. if (emu_thread == nullptr)
  2751. return true;
  2752. const auto answer =
  2753. QMessageBox::question(this, tr("yuzu"),
  2754. tr("The currently running application has requested yuzu to not "
  2755. "exit.\n\nWould you like to bypass this and exit anyway?"),
  2756. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2757. return answer != QMessageBox::No;
  2758. }
  2759. void GMainWindow::RequestGameExit() {
  2760. auto& sm{Core::System::GetInstance().ServiceManager()};
  2761. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  2762. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  2763. bool has_signalled = false;
  2764. if (applet_oe != nullptr) {
  2765. applet_oe->GetMessageQueue()->RequestExit();
  2766. has_signalled = true;
  2767. }
  2768. if (applet_ae != nullptr && !has_signalled) {
  2769. applet_ae->GetMessageQueue()->RequestExit();
  2770. }
  2771. }
  2772. void GMainWindow::filterBarSetChecked(bool state) {
  2773. ui.action_Show_Filter_Bar->setChecked(state);
  2774. emit(OnToggleFilterBar());
  2775. }
  2776. void GMainWindow::UpdateUITheme() {
  2777. const QString default_icons = QStringLiteral("default");
  2778. const QString& current_theme = UISettings::values.theme;
  2779. const bool is_default_theme = current_theme == QString::fromUtf8(UISettings::themes[0].second);
  2780. QStringList theme_paths(default_theme_paths);
  2781. if (is_default_theme || current_theme.isEmpty()) {
  2782. const QString theme_uri(QStringLiteral(":default/style.qss"));
  2783. QFile f(theme_uri);
  2784. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2785. QTextStream ts(&f);
  2786. qApp->setStyleSheet(ts.readAll());
  2787. setStyleSheet(ts.readAll());
  2788. } else {
  2789. qApp->setStyleSheet({});
  2790. setStyleSheet({});
  2791. }
  2792. QIcon::setThemeName(default_icons);
  2793. } else {
  2794. const QString theme_uri(QLatin1Char{':'} + current_theme + QStringLiteral("/style.qss"));
  2795. QFile f(theme_uri);
  2796. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2797. QTextStream ts(&f);
  2798. qApp->setStyleSheet(ts.readAll());
  2799. setStyleSheet(ts.readAll());
  2800. } else {
  2801. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  2802. }
  2803. QIcon::setThemeName(current_theme);
  2804. }
  2805. QIcon::setThemeSearchPaths(theme_paths);
  2806. }
  2807. void GMainWindow::LoadTranslation() {
  2808. // If the selected language is English, no need to install any translation
  2809. if (UISettings::values.language == QStringLiteral("en")) {
  2810. return;
  2811. }
  2812. bool loaded;
  2813. if (UISettings::values.language.isEmpty()) {
  2814. // If the selected language is empty, use system locale
  2815. loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/"));
  2816. } else {
  2817. // Otherwise load from the specified file
  2818. loaded = translator.load(UISettings::values.language, QStringLiteral(":/languages/"));
  2819. }
  2820. if (loaded) {
  2821. qApp->installTranslator(&translator);
  2822. } else {
  2823. UISettings::values.language = QStringLiteral("en");
  2824. }
  2825. }
  2826. void GMainWindow::OnLanguageChanged(const QString& locale) {
  2827. if (UISettings::values.language != QStringLiteral("en")) {
  2828. qApp->removeTranslator(&translator);
  2829. }
  2830. UISettings::values.language = locale;
  2831. LoadTranslation();
  2832. ui.retranslateUi(this);
  2833. UpdateWindowTitle();
  2834. if (emulation_running)
  2835. ui.action_Start->setText(tr("&Continue"));
  2836. }
  2837. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  2838. #ifdef USE_DISCORD_PRESENCE
  2839. if (state) {
  2840. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  2841. } else {
  2842. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2843. }
  2844. #else
  2845. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2846. #endif
  2847. discord_rpc->Update();
  2848. }
  2849. #ifdef main
  2850. #undef main
  2851. #endif
  2852. int main(int argc, char* argv[]) {
  2853. Common::DetachedTasks detached_tasks;
  2854. MicroProfileOnThreadCreate("Frontend");
  2855. SCOPE_EXIT({ MicroProfileShutdown(); });
  2856. Common::ConfigureNvidiaEnvironmentFlags();
  2857. // Init settings params
  2858. QCoreApplication::setOrganizationName(QStringLiteral("yuzu team"));
  2859. QCoreApplication::setApplicationName(QStringLiteral("yuzu"));
  2860. #ifdef _WIN32
  2861. // Increases the maximum open file limit to 4096
  2862. _setmaxstdio(4096);
  2863. #endif
  2864. #ifdef __APPLE__
  2865. // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/".
  2866. // But since we require the working directory to be the executable path for the location of
  2867. // the user folder in the Qt Frontend, we need to cd into that working directory
  2868. const auto bin_path = Common::FS::GetBundleDirectory() / "..";
  2869. chdir(Common::FS::PathToUTF8String(bin_path).c_str());
  2870. #endif
  2871. #ifdef __linux__
  2872. // Set the DISPLAY variable in order to open web browsers
  2873. // TODO (lat9nq): Find a better solution for AppImages to start external applications
  2874. if (QString::fromLocal8Bit(qgetenv("DISPLAY")).isEmpty()) {
  2875. qputenv("DISPLAY", ":0");
  2876. }
  2877. #endif
  2878. // Enables the core to make the qt created contexts current on std::threads
  2879. QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  2880. QApplication app(argc, argv);
  2881. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  2882. // generating shaders
  2883. setlocale(LC_ALL, "C");
  2884. Core::System::InitializeGlobalInstance();
  2885. GMainWindow main_window;
  2886. // After settings have been loaded by GMainWindow, apply the filter
  2887. main_window.show();
  2888. QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
  2889. &GMainWindow::OnAppFocusStateChanged);
  2890. int result = app.exec();
  2891. detached_tasks.WaitForAllTasks();
  2892. return result;
  2893. }