main.cpp 133 KB

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