main.cpp 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239
  1. // SPDX-FileCopyrightText: 2014 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <cinttypes>
  4. #include <clocale>
  5. #include <cmath>
  6. #include <memory>
  7. #include <thread>
  8. #ifdef __APPLE__
  9. #include <unistd.h> // for chdir
  10. #endif
  11. #ifdef __unix__
  12. #include <csignal>
  13. #include <sys/socket.h>
  14. #endif
  15. // VFS includes must be before glad as they will conflict with Windows file api, which uses defines.
  16. #include "applets/qt_amiibo_settings.h"
  17. #include "applets/qt_controller.h"
  18. #include "applets/qt_error.h"
  19. #include "applets/qt_profile_select.h"
  20. #include "applets/qt_software_keyboard.h"
  21. #include "applets/qt_web_browser.h"
  22. #include "common/nvidia_flags.h"
  23. #include "configuration/configure_input.h"
  24. #include "configuration/configure_per_game.h"
  25. #include "configuration/configure_tas.h"
  26. #include "core/file_sys/vfs.h"
  27. #include "core/file_sys/vfs_real.h"
  28. #include "core/frontend/applets/cabinet.h"
  29. #include "core/frontend/applets/controller.h"
  30. #include "core/frontend/applets/general_frontend.h"
  31. #include "core/frontend/applets/mii_edit.h"
  32. #include "core/frontend/applets/software_keyboard.h"
  33. #include "core/hid/emulated_controller.h"
  34. #include "core/hid/hid_core.h"
  35. #include "core/hle/service/acc/profile_manager.h"
  36. #include "core/hle/service/am/applet_ae.h"
  37. #include "core/hle/service/am/applet_oe.h"
  38. #include "core/hle/service/am/applets/applets.h"
  39. #include "yuzu/multiplayer/state.h"
  40. #include "yuzu/util/controller_navigation.h"
  41. // These are wrappers to avoid the calls to CreateDirectory and CreateFile because of the Windows
  42. // defines.
  43. static FileSys::VirtualDir VfsFilesystemCreateDirectoryWrapper(
  44. const FileSys::VirtualFilesystem& vfs, const std::string& path, FileSys::Mode mode) {
  45. return vfs->CreateDirectory(path, mode);
  46. }
  47. static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::VirtualDir& dir,
  48. const std::string& path) {
  49. return dir->CreateFile(path);
  50. }
  51. #include <fmt/ostream.h>
  52. #include <glad/glad.h>
  53. #define QT_NO_OPENGL
  54. #include <QClipboard>
  55. #include <QDesktopServices>
  56. #include <QFile>
  57. #include <QFileDialog>
  58. #include <QInputDialog>
  59. #include <QMessageBox>
  60. #include <QProgressBar>
  61. #include <QProgressDialog>
  62. #include <QPushButton>
  63. #include <QScreen>
  64. #include <QShortcut>
  65. #include <QStatusBar>
  66. #include <QString>
  67. #include <QSysInfo>
  68. #include <QUrl>
  69. #include <QtConcurrent/QtConcurrent>
  70. #ifdef HAVE_SDL2
  71. #include <SDL.h> // For SDL ScreenSaver functions
  72. #endif
  73. #include <fmt/format.h>
  74. #include "common/detached_tasks.h"
  75. #include "common/fs/fs.h"
  76. #include "common/fs/path_util.h"
  77. #include "common/literals.h"
  78. #include "common/logging/backend.h"
  79. #include "common/logging/log.h"
  80. #include "common/memory_detect.h"
  81. #include "common/microprofile.h"
  82. #include "common/scm_rev.h"
  83. #include "common/scope_exit.h"
  84. #ifdef ARCHITECTURE_x86_64
  85. #include "common/x64/cpu_detect.h"
  86. #endif
  87. #include "common/settings.h"
  88. #include "common/telemetry.h"
  89. #include "core/core.h"
  90. #include "core/crypto/key_manager.h"
  91. #include "core/file_sys/card_image.h"
  92. #include "core/file_sys/common_funcs.h"
  93. #include "core/file_sys/content_archive.h"
  94. #include "core/file_sys/control_metadata.h"
  95. #include "core/file_sys/patch_manager.h"
  96. #include "core/file_sys/registered_cache.h"
  97. #include "core/file_sys/romfs.h"
  98. #include "core/file_sys/savedata_factory.h"
  99. #include "core/file_sys/submission_package.h"
  100. #include "core/hle/kernel/k_process.h"
  101. #include "core/hle/service/am/am.h"
  102. #include "core/hle/service/filesystem/filesystem.h"
  103. #include "core/hle/service/sm/sm.h"
  104. #include "core/loader/loader.h"
  105. #include "core/perf_stats.h"
  106. #include "core/telemetry_session.h"
  107. #include "input_common/drivers/tas_input.h"
  108. #include "input_common/drivers/virtual_amiibo.h"
  109. #include "input_common/main.h"
  110. #include "ui_main.h"
  111. #include "util/overlay_dialog.h"
  112. #include "video_core/gpu.h"
  113. #include "video_core/renderer_base.h"
  114. #include "video_core/shader_notify.h"
  115. #include "yuzu/about_dialog.h"
  116. #include "yuzu/bootmanager.h"
  117. #include "yuzu/compatdb.h"
  118. #include "yuzu/compatibility_list.h"
  119. #include "yuzu/configuration/config.h"
  120. #include "yuzu/configuration/configure_dialog.h"
  121. #include "yuzu/debugger/console.h"
  122. #include "yuzu/debugger/controller.h"
  123. #include "yuzu/debugger/profiler.h"
  124. #include "yuzu/debugger/wait_tree.h"
  125. #include "yuzu/discord.h"
  126. #include "yuzu/game_list.h"
  127. #include "yuzu/game_list_p.h"
  128. #include "yuzu/hotkeys.h"
  129. #include "yuzu/install_dialog.h"
  130. #include "yuzu/loading_screen.h"
  131. #include "yuzu/main.h"
  132. #include "yuzu/startup_checks.h"
  133. #include "yuzu/uisettings.h"
  134. #include "yuzu/util/clickable_label.h"
  135. #ifdef YUZU_DBGHELP
  136. #include "yuzu/mini_dump.h"
  137. #endif
  138. using namespace Common::Literals;
  139. #ifdef USE_DISCORD_PRESENCE
  140. #include "yuzu/discord_impl.h"
  141. #endif
  142. #ifdef QT_STATICPLUGIN
  143. Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
  144. #endif
  145. #ifdef _WIN32
  146. #include <windows.h>
  147. extern "C" {
  148. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  149. // graphics
  150. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  151. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  152. }
  153. #endif
  154. constexpr int default_mouse_hide_timeout = 2500;
  155. constexpr int default_mouse_center_timeout = 10;
  156. /**
  157. * "Callouts" are one-time instructional messages shown to the user. In the config settings, there
  158. * is a bitfield "callout_flags" options, used to track if a message has already been shown to the
  159. * user. This is 32-bits - if we have more than 32 callouts, we should retire and recycle old ones.
  160. */
  161. enum class CalloutFlag : uint32_t {
  162. Telemetry = 0x1,
  163. DRDDeprecation = 0x2,
  164. };
  165. void GMainWindow::ShowTelemetryCallout() {
  166. if (UISettings::values.callout_flags.GetValue() &
  167. static_cast<uint32_t>(CalloutFlag::Telemetry)) {
  168. return;
  169. }
  170. UISettings::values.callout_flags =
  171. UISettings::values.callout_flags.GetValue() | static_cast<uint32_t>(CalloutFlag::Telemetry);
  172. const QString telemetry_message =
  173. tr("<a href='https://yuzu-emu.org/help/feature/telemetry/'>Anonymous "
  174. "data is collected</a> to help improve yuzu. "
  175. "<br/><br/>Would you like to share your usage data with us?");
  176. if (QMessageBox::question(this, tr("Telemetry"), telemetry_message) != QMessageBox::Yes) {
  177. Settings::values.enable_telemetry = false;
  178. system->ApplySettings();
  179. }
  180. }
  181. const int GMainWindow::max_recent_files_item;
  182. static void RemoveCachedContents() {
  183. const auto cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir);
  184. const auto offline_fonts = cache_dir / "fonts";
  185. const auto offline_manual = cache_dir / "offline_web_applet_manual";
  186. const auto offline_legal_information = cache_dir / "offline_web_applet_legal_information";
  187. const auto offline_system_data = cache_dir / "offline_web_applet_system_data";
  188. Common::FS::RemoveDirRecursively(offline_fonts);
  189. Common::FS::RemoveDirRecursively(offline_manual);
  190. Common::FS::RemoveDirRecursively(offline_legal_information);
  191. Common::FS::RemoveDirRecursively(offline_system_data);
  192. }
  193. static void LogRuntimes() {
  194. #ifdef _MSC_VER
  195. // It is possible that the name of the dll will change.
  196. // vcruntime140.dll is for 2015 and onwards
  197. constexpr char runtime_dll_name[] = "vcruntime140.dll";
  198. UINT sz = GetFileVersionInfoSizeA(runtime_dll_name, nullptr);
  199. bool runtime_version_inspection_worked = false;
  200. if (sz > 0) {
  201. std::vector<u8> buf(sz);
  202. if (GetFileVersionInfoA(runtime_dll_name, 0, sz, buf.data())) {
  203. VS_FIXEDFILEINFO* pvi;
  204. sz = sizeof(VS_FIXEDFILEINFO);
  205. if (VerQueryValueA(buf.data(), "\\", reinterpret_cast<LPVOID*>(&pvi), &sz)) {
  206. if (pvi->dwSignature == VS_FFI_SIGNATURE) {
  207. runtime_version_inspection_worked = true;
  208. LOG_INFO(Frontend, "MSVC Compiler: {} Runtime: {}.{}.{}.{}", _MSC_VER,
  209. pvi->dwProductVersionMS >> 16, pvi->dwProductVersionMS & 0xFFFF,
  210. pvi->dwProductVersionLS >> 16, pvi->dwProductVersionLS & 0xFFFF);
  211. }
  212. }
  213. }
  214. }
  215. if (!runtime_version_inspection_worked) {
  216. LOG_INFO(Frontend, "Unable to inspect {}", runtime_dll_name);
  217. }
  218. #endif
  219. }
  220. static QString PrettyProductName() {
  221. #ifdef _WIN32
  222. // After Windows 10 Version 2004, Microsoft decided to switch to a different notation: 20H2
  223. // With that notation change they changed the registry key used to denote the current version
  224. QSettings windows_registry(
  225. QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"),
  226. QSettings::NativeFormat);
  227. const QString release_id = windows_registry.value(QStringLiteral("ReleaseId")).toString();
  228. if (release_id == QStringLiteral("2009")) {
  229. const u32 current_build = windows_registry.value(QStringLiteral("CurrentBuild")).toUInt();
  230. const QString display_version =
  231. windows_registry.value(QStringLiteral("DisplayVersion")).toString();
  232. const u32 ubr = windows_registry.value(QStringLiteral("UBR")).toUInt();
  233. u32 version = 10;
  234. if (current_build >= 22000) {
  235. version = 11;
  236. }
  237. return QStringLiteral("Windows %1 Version %2 (Build %3.%4)")
  238. .arg(QString::number(version), display_version, QString::number(current_build),
  239. QString::number(ubr));
  240. }
  241. #endif
  242. return QSysInfo::prettyProductName();
  243. }
  244. #ifdef _WIN32
  245. static void OverrideWindowsFont() {
  246. // Qt5 chooses these fonts on Windows and they have fairly ugly alphanumeric/cyrllic characters
  247. // Asking to use "MS Shell Dlg 2" gives better other chars while leaving the Chinese Characters.
  248. const QString startup_font = QApplication::font().family();
  249. const QStringList ugly_fonts = {QStringLiteral("SimSun"), QStringLiteral("PMingLiU")};
  250. if (ugly_fonts.contains(startup_font)) {
  251. QApplication::setFont(QFont(QStringLiteral("MS Shell Dlg 2"), 9, QFont::Normal));
  252. }
  253. }
  254. #endif
  255. bool GMainWindow::CheckDarkMode() {
  256. #ifdef __unix__
  257. const QPalette test_palette(qApp->palette());
  258. const QColor text_color = test_palette.color(QPalette::Active, QPalette::Text);
  259. const QColor window_color = test_palette.color(QPalette::Active, QPalette::Window);
  260. return (text_color.value() > window_color.value());
  261. #else
  262. // TODO: Windows
  263. return false;
  264. #endif // __unix__
  265. }
  266. GMainWindow::GMainWindow(std::unique_ptr<Config> config_, bool has_broken_vulkan)
  267. : ui{std::make_unique<Ui::MainWindow>()}, system{std::make_unique<Core::System>()},
  268. input_subsystem{std::make_shared<InputCommon::InputSubsystem>()}, config{std::move(config_)},
  269. vfs{std::make_shared<FileSys::RealVfsFilesystem>()},
  270. provider{std::make_unique<FileSys::ManualContentProvider>()} {
  271. #ifdef __unix__
  272. SetupSigInterrupts();
  273. #endif
  274. system->Initialize();
  275. Common::Log::Initialize();
  276. LoadTranslation();
  277. setAcceptDrops(true);
  278. ui->setupUi(this);
  279. statusBar()->hide();
  280. // Check dark mode before a theme is loaded
  281. os_dark_mode = CheckDarkMode();
  282. startup_icon_theme = QIcon::themeName();
  283. // fallback can only be set once, colorful theme icons are okay on both light/dark
  284. QIcon::setFallbackThemeName(QStringLiteral("colorful"));
  285. QIcon::setFallbackSearchPaths(QStringList(QStringLiteral(":/icons")));
  286. default_theme_paths = QIcon::themeSearchPaths();
  287. UpdateUITheme();
  288. SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue());
  289. discord_rpc->Update();
  290. system->GetRoomNetwork().Init();
  291. RegisterMetaTypes();
  292. InitializeWidgets();
  293. InitializeDebugWidgets();
  294. InitializeRecentFileMenuActions();
  295. InitializeHotkeys();
  296. SetDefaultUIGeometry();
  297. RestoreUIState();
  298. ConnectMenuEvents();
  299. ConnectWidgetEvents();
  300. system->HIDCore().ReloadInputDevices();
  301. controller_dialog->refreshConfiguration();
  302. const auto branch_name = std::string(Common::g_scm_branch);
  303. const auto description = std::string(Common::g_scm_desc);
  304. const auto build_id = std::string(Common::g_build_id);
  305. const auto yuzu_build = fmt::format("yuzu Development Build | {}-{}", branch_name, description);
  306. const auto override_build =
  307. fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id);
  308. const auto yuzu_build_version = override_build.empty() ? yuzu_build : override_build;
  309. const auto processor_count = std::thread::hardware_concurrency();
  310. LOG_INFO(Frontend, "yuzu Version: {}", yuzu_build_version);
  311. LogRuntimes();
  312. #ifdef ARCHITECTURE_x86_64
  313. const auto& caps = Common::GetCPUCaps();
  314. std::string cpu_string = caps.cpu_string;
  315. if (caps.avx || caps.avx2 || caps.avx512f) {
  316. cpu_string += " | AVX";
  317. if (caps.avx512f) {
  318. cpu_string += "512";
  319. } else if (caps.avx2) {
  320. cpu_string += '2';
  321. }
  322. if (caps.fma || caps.fma4) {
  323. cpu_string += " | FMA";
  324. }
  325. }
  326. LOG_INFO(Frontend, "Host CPU: {}", cpu_string);
  327. if (std::optional<int> processor_core = Common::GetProcessorCount()) {
  328. LOG_INFO(Frontend, "Host CPU Cores: {}", *processor_core);
  329. }
  330. #endif
  331. LOG_INFO(Frontend, "Host CPU Threads: {}", processor_count);
  332. LOG_INFO(Frontend, "Host OS: {}", PrettyProductName().toStdString());
  333. LOG_INFO(Frontend, "Host RAM: {:.2f} GiB",
  334. Common::GetMemInfo().TotalPhysicalMemory / f64{1_GiB});
  335. LOG_INFO(Frontend, "Host Swap: {:.2f} GiB", Common::GetMemInfo().TotalSwapMemory / f64{1_GiB});
  336. UpdateWindowTitle();
  337. show();
  338. system->SetContentProvider(std::make_unique<FileSys::ContentProviderUnion>());
  339. system->RegisterContentProvider(FileSys::ContentProviderUnionSlot::FrontendManual,
  340. provider.get());
  341. system->GetFileSystemController().CreateFactories(*vfs);
  342. // Remove cached contents generated during the previous session
  343. RemoveCachedContents();
  344. // Gen keys if necessary
  345. OnReinitializeKeys(ReinitializeKeyBehavior::NoWarning);
  346. game_list->LoadCompatibilityList();
  347. game_list->PopulateAsync(UISettings::values.game_dirs);
  348. // Show one-time "callout" messages to the user
  349. ShowTelemetryCallout();
  350. // make sure menubar has the arrow cursor instead of inheriting from this
  351. ui->menubar->setCursor(QCursor());
  352. statusBar()->setCursor(QCursor());
  353. mouse_hide_timer.setInterval(default_mouse_hide_timeout);
  354. connect(&mouse_hide_timer, &QTimer::timeout, this, &GMainWindow::HideMouseCursor);
  355. connect(ui->menubar, &QMenuBar::hovered, this, &GMainWindow::ShowMouseCursor);
  356. mouse_center_timer.setInterval(default_mouse_center_timeout);
  357. connect(&mouse_center_timer, &QTimer::timeout, this, &GMainWindow::CenterMouseCursor);
  358. MigrateConfigFiles();
  359. if (has_broken_vulkan) {
  360. UISettings::values.has_broken_vulkan = true;
  361. QMessageBox::warning(this, tr("Broken Vulkan Installation Detected"),
  362. tr("Vulkan initialization failed during boot.<br><br>Click <a "
  363. "href='https://yuzu-emu.org/wiki/faq/"
  364. "#yuzu-starts-with-the-error-broken-vulkan-installation-detected'>"
  365. "here for instructions to fix the issue</a>."));
  366. Settings::values.renderer_backend = Settings::RendererBackend::OpenGL;
  367. renderer_status_button->setDisabled(true);
  368. renderer_status_button->setChecked(false);
  369. }
  370. #if defined(HAVE_SDL2) && !defined(_WIN32)
  371. SDL_InitSubSystem(SDL_INIT_VIDEO);
  372. // SDL disables the screen saver by default, and setting the hint
  373. // SDL_HINT_VIDEO_ALLOW_SCREENSAVER doesn't seem to work, so we just enable the screen saver
  374. // for now.
  375. SDL_EnableScreenSaver();
  376. #endif
  377. SetupPrepareForSleep();
  378. Common::Log::Start();
  379. QStringList args = QApplication::arguments();
  380. if (args.size() < 2) {
  381. return;
  382. }
  383. QString game_path;
  384. bool has_gamepath = false;
  385. bool is_fullscreen = false;
  386. for (int i = 1; i < args.size(); ++i) {
  387. // Preserves drag/drop functionality
  388. if (args.size() == 2 && !args[1].startsWith(QChar::fromLatin1('-'))) {
  389. game_path = args[1];
  390. has_gamepath = true;
  391. break;
  392. }
  393. // Launch game in fullscreen mode
  394. if (args[i] == QStringLiteral("-f")) {
  395. is_fullscreen = true;
  396. continue;
  397. }
  398. // Launch game with a specific user
  399. if (args[i] == QStringLiteral("-u")) {
  400. if (i >= args.size() - 1) {
  401. continue;
  402. }
  403. if (args[i + 1].startsWith(QChar::fromLatin1('-'))) {
  404. continue;
  405. }
  406. bool argument_ok;
  407. const std::size_t selected_user = args[++i].toUInt(&argument_ok);
  408. if (!argument_ok) {
  409. LOG_ERROR(Frontend, "Invalid user argument");
  410. continue;
  411. }
  412. const Service::Account::ProfileManager manager;
  413. if (!manager.UserExistsIndex(selected_user)) {
  414. LOG_ERROR(Frontend, "Selected user doesn't exist");
  415. continue;
  416. }
  417. Settings::values.current_user = static_cast<s32>(selected_user);
  418. continue;
  419. }
  420. // Launch game at path
  421. if (args[i] == QStringLiteral("-g")) {
  422. if (i >= args.size() - 1) {
  423. continue;
  424. }
  425. if (args[i + 1].startsWith(QChar::fromLatin1('-'))) {
  426. continue;
  427. }
  428. game_path = args[++i];
  429. has_gamepath = true;
  430. }
  431. }
  432. // Override fullscreen setting if gamepath or argument is provided
  433. if (has_gamepath || is_fullscreen) {
  434. ui->action_Fullscreen->setChecked(is_fullscreen);
  435. }
  436. if (!game_path.isEmpty()) {
  437. BootGame(game_path);
  438. }
  439. }
  440. GMainWindow::~GMainWindow() {
  441. // will get automatically deleted otherwise
  442. if (render_window->parent() == nullptr) {
  443. delete render_window;
  444. }
  445. #ifdef __unix__
  446. ::close(sig_interrupt_fds[0]);
  447. ::close(sig_interrupt_fds[1]);
  448. #endif
  449. }
  450. void GMainWindow::RegisterMetaTypes() {
  451. // Register integral and floating point types
  452. qRegisterMetaType<u8>("u8");
  453. qRegisterMetaType<u16>("u16");
  454. qRegisterMetaType<u32>("u32");
  455. qRegisterMetaType<u64>("u64");
  456. qRegisterMetaType<u128>("u128");
  457. qRegisterMetaType<s8>("s8");
  458. qRegisterMetaType<s16>("s16");
  459. qRegisterMetaType<s32>("s32");
  460. qRegisterMetaType<s64>("s64");
  461. qRegisterMetaType<f32>("f32");
  462. qRegisterMetaType<f64>("f64");
  463. // Register string types
  464. qRegisterMetaType<std::string>("std::string");
  465. qRegisterMetaType<std::wstring>("std::wstring");
  466. qRegisterMetaType<std::u8string>("std::u8string");
  467. qRegisterMetaType<std::u16string>("std::u16string");
  468. qRegisterMetaType<std::u32string>("std::u32string");
  469. qRegisterMetaType<std::string_view>("std::string_view");
  470. qRegisterMetaType<std::wstring_view>("std::wstring_view");
  471. qRegisterMetaType<std::u8string_view>("std::u8string_view");
  472. qRegisterMetaType<std::u16string_view>("std::u16string_view");
  473. qRegisterMetaType<std::u32string_view>("std::u32string_view");
  474. // Register applet types
  475. // Cabinet Applet
  476. qRegisterMetaType<Core::Frontend::CabinetParameters>("Core::Frontend::CabinetParameters");
  477. qRegisterMetaType<std::shared_ptr<Service::NFP::NfpDevice>>(
  478. "std::shared_ptr<Service::NFP::NfpDevice>");
  479. // Controller Applet
  480. qRegisterMetaType<Core::Frontend::ControllerParameters>("Core::Frontend::ControllerParameters");
  481. // Software Keyboard Applet
  482. qRegisterMetaType<Core::Frontend::KeyboardInitializeParameters>(
  483. "Core::Frontend::KeyboardInitializeParameters");
  484. qRegisterMetaType<Core::Frontend::InlineAppearParameters>(
  485. "Core::Frontend::InlineAppearParameters");
  486. qRegisterMetaType<Core::Frontend::InlineTextParameters>("Core::Frontend::InlineTextParameters");
  487. qRegisterMetaType<Service::AM::Applets::SwkbdResult>("Service::AM::Applets::SwkbdResult");
  488. qRegisterMetaType<Service::AM::Applets::SwkbdTextCheckResult>(
  489. "Service::AM::Applets::SwkbdTextCheckResult");
  490. qRegisterMetaType<Service::AM::Applets::SwkbdReplyType>("Service::AM::Applets::SwkbdReplyType");
  491. // Web Browser Applet
  492. qRegisterMetaType<Service::AM::Applets::WebExitReason>("Service::AM::Applets::WebExitReason");
  493. // Register loader types
  494. qRegisterMetaType<Core::SystemResultStatus>("Core::SystemResultStatus");
  495. }
  496. void GMainWindow::AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters,
  497. std::shared_ptr<Service::NFP::NfpDevice> nfp_device) {
  498. QtAmiiboSettingsDialog dialog(this, parameters, input_subsystem.get(), nfp_device);
  499. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint |
  500. Qt::WindowTitleHint | Qt::WindowSystemMenuHint);
  501. dialog.setWindowModality(Qt::WindowModal);
  502. if (dialog.exec() == QDialog::Rejected) {
  503. emit AmiiboSettingsFinished(false, {});
  504. return;
  505. }
  506. emit AmiiboSettingsFinished(true, dialog.GetName());
  507. }
  508. void GMainWindow::ControllerSelectorReconfigureControllers(
  509. const Core::Frontend::ControllerParameters& parameters) {
  510. QtControllerSelectorDialog dialog(this, parameters, input_subsystem.get(), *system);
  511. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint |
  512. Qt::WindowTitleHint | Qt::WindowSystemMenuHint);
  513. dialog.setWindowModality(Qt::WindowModal);
  514. dialog.exec();
  515. emit ControllerSelectorReconfigureFinished();
  516. // Don't forget to apply settings.
  517. system->ApplySettings();
  518. config->Save();
  519. UpdateStatusButtons();
  520. }
  521. void GMainWindow::ProfileSelectorSelectProfile() {
  522. QtProfileSelectionDialog dialog(system->HIDCore(), this);
  523. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint |
  524. Qt::WindowTitleHint | Qt::WindowSystemMenuHint |
  525. Qt::WindowCloseButtonHint);
  526. dialog.setWindowModality(Qt::WindowModal);
  527. if (dialog.exec() == QDialog::Rejected) {
  528. emit ProfileSelectorFinishedSelection(std::nullopt);
  529. return;
  530. }
  531. const Service::Account::ProfileManager manager;
  532. const auto uuid = manager.GetUser(static_cast<std::size_t>(dialog.GetIndex()));
  533. if (!uuid.has_value()) {
  534. emit ProfileSelectorFinishedSelection(std::nullopt);
  535. return;
  536. }
  537. emit ProfileSelectorFinishedSelection(uuid);
  538. }
  539. void GMainWindow::SoftwareKeyboardInitialize(
  540. bool is_inline, Core::Frontend::KeyboardInitializeParameters initialize_parameters) {
  541. if (software_keyboard) {
  542. LOG_ERROR(Frontend, "The software keyboard is already initialized!");
  543. return;
  544. }
  545. software_keyboard = new QtSoftwareKeyboardDialog(render_window, *system, is_inline,
  546. std::move(initialize_parameters));
  547. if (is_inline) {
  548. connect(
  549. software_keyboard, &QtSoftwareKeyboardDialog::SubmitInlineText, this,
  550. [this](Service::AM::Applets::SwkbdReplyType reply_type, std::u16string submitted_text,
  551. s32 cursor_position) {
  552. emit SoftwareKeyboardSubmitInlineText(reply_type, submitted_text, cursor_position);
  553. },
  554. Qt::QueuedConnection);
  555. } else {
  556. connect(
  557. software_keyboard, &QtSoftwareKeyboardDialog::SubmitNormalText, this,
  558. [this](Service::AM::Applets::SwkbdResult result, std::u16string submitted_text,
  559. bool confirmed) {
  560. emit SoftwareKeyboardSubmitNormalText(result, submitted_text, confirmed);
  561. },
  562. Qt::QueuedConnection);
  563. }
  564. }
  565. void GMainWindow::SoftwareKeyboardShowNormal() {
  566. if (!software_keyboard) {
  567. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  568. return;
  569. }
  570. const auto& layout = render_window->GetFramebufferLayout();
  571. const auto x = layout.screen.left;
  572. const auto y = layout.screen.top;
  573. const auto w = layout.screen.GetWidth();
  574. const auto h = layout.screen.GetHeight();
  575. software_keyboard->ShowNormalKeyboard(render_window->mapToGlobal(QPoint(x, y)), QSize(w, h));
  576. }
  577. void GMainWindow::SoftwareKeyboardShowTextCheck(
  578. Service::AM::Applets::SwkbdTextCheckResult text_check_result,
  579. std::u16string text_check_message) {
  580. if (!software_keyboard) {
  581. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  582. return;
  583. }
  584. software_keyboard->ShowTextCheckDialog(text_check_result, text_check_message);
  585. }
  586. void GMainWindow::SoftwareKeyboardShowInline(
  587. Core::Frontend::InlineAppearParameters appear_parameters) {
  588. if (!software_keyboard) {
  589. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  590. return;
  591. }
  592. const auto& layout = render_window->GetFramebufferLayout();
  593. const auto x =
  594. static_cast<int>(layout.screen.left + (0.5f * layout.screen.GetWidth() *
  595. ((2.0f * appear_parameters.key_top_translate_x) +
  596. (1.0f - appear_parameters.key_top_scale_x))));
  597. const auto y =
  598. static_cast<int>(layout.screen.top + (layout.screen.GetHeight() *
  599. ((2.0f * appear_parameters.key_top_translate_y) +
  600. (1.0f - appear_parameters.key_top_scale_y))));
  601. const auto w = static_cast<int>(layout.screen.GetWidth() * appear_parameters.key_top_scale_x);
  602. const auto h = static_cast<int>(layout.screen.GetHeight() * appear_parameters.key_top_scale_y);
  603. software_keyboard->ShowInlineKeyboard(std::move(appear_parameters),
  604. render_window->mapToGlobal(QPoint(x, y)), QSize(w, h));
  605. }
  606. void GMainWindow::SoftwareKeyboardHideInline() {
  607. if (!software_keyboard) {
  608. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  609. return;
  610. }
  611. software_keyboard->HideInlineKeyboard();
  612. }
  613. void GMainWindow::SoftwareKeyboardInlineTextChanged(
  614. Core::Frontend::InlineTextParameters text_parameters) {
  615. if (!software_keyboard) {
  616. LOG_ERROR(Frontend, "The software keyboard is not initialized!");
  617. return;
  618. }
  619. software_keyboard->InlineTextChanged(std::move(text_parameters));
  620. }
  621. void GMainWindow::SoftwareKeyboardExit() {
  622. if (!software_keyboard) {
  623. return;
  624. }
  625. software_keyboard->ExitKeyboard();
  626. software_keyboard = nullptr;
  627. }
  628. void GMainWindow::WebBrowserOpenWebPage(const std::string& main_url,
  629. const std::string& additional_args, bool is_local) {
  630. #ifdef YUZU_USE_QT_WEB_ENGINE
  631. // Raw input breaks with the web applet, Disable web applets if enabled
  632. if (UISettings::values.disable_web_applet || Settings::values.enable_raw_input) {
  633. emit WebBrowserClosed(Service::AM::Applets::WebExitReason::WindowClosed,
  634. "http://localhost/");
  635. return;
  636. }
  637. QtNXWebEngineView web_browser_view(this, *system, input_subsystem.get());
  638. ui->action_Pause->setEnabled(false);
  639. ui->action_Restart->setEnabled(false);
  640. ui->action_Stop->setEnabled(false);
  641. {
  642. QProgressDialog loading_progress(this);
  643. loading_progress.setLabelText(tr("Loading Web Applet..."));
  644. loading_progress.setRange(0, 3);
  645. loading_progress.setValue(0);
  646. if (is_local && !Common::FS::Exists(main_url)) {
  647. loading_progress.show();
  648. auto future = QtConcurrent::run([this] { emit WebBrowserExtractOfflineRomFS(); });
  649. while (!future.isFinished()) {
  650. QCoreApplication::processEvents();
  651. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  652. }
  653. }
  654. loading_progress.setValue(1);
  655. if (is_local) {
  656. web_browser_view.LoadLocalWebPage(main_url, additional_args);
  657. } else {
  658. web_browser_view.LoadExternalWebPage(main_url, additional_args);
  659. }
  660. if (render_window->IsLoadingComplete()) {
  661. render_window->hide();
  662. }
  663. const auto& layout = render_window->GetFramebufferLayout();
  664. web_browser_view.resize(layout.screen.GetWidth(), layout.screen.GetHeight());
  665. web_browser_view.move(layout.screen.left, layout.screen.top + menuBar()->height());
  666. web_browser_view.setZoomFactor(static_cast<qreal>(layout.screen.GetWidth()) /
  667. static_cast<qreal>(Layout::ScreenUndocked::Width));
  668. web_browser_view.setFocus();
  669. web_browser_view.show();
  670. loading_progress.setValue(2);
  671. QCoreApplication::processEvents();
  672. loading_progress.setValue(3);
  673. }
  674. bool exit_check = false;
  675. // TODO (Morph): Remove this
  676. QAction* exit_action = new QAction(tr("Disable Web Applet"), this);
  677. connect(exit_action, &QAction::triggered, this, [this, &web_browser_view] {
  678. const auto result = QMessageBox::warning(
  679. this, tr("Disable Web Applet"),
  680. tr("Disabling the web applet can lead to undefined behavior and should only be used "
  681. "with Super Mario 3D All-Stars. Are you sure you want to disable the web "
  682. "applet?\n(This can be re-enabled in the Debug settings.)"),
  683. QMessageBox::Yes | QMessageBox::No);
  684. if (result == QMessageBox::Yes) {
  685. UISettings::values.disable_web_applet = true;
  686. web_browser_view.SetFinished(true);
  687. }
  688. });
  689. ui->menubar->addAction(exit_action);
  690. while (!web_browser_view.IsFinished()) {
  691. QCoreApplication::processEvents();
  692. if (!exit_check) {
  693. web_browser_view.page()->runJavaScript(
  694. QStringLiteral("end_applet;"), [&](const QVariant& variant) {
  695. exit_check = false;
  696. if (variant.toBool()) {
  697. web_browser_view.SetFinished(true);
  698. web_browser_view.SetExitReason(
  699. Service::AM::Applets::WebExitReason::EndButtonPressed);
  700. }
  701. });
  702. exit_check = true;
  703. }
  704. if (web_browser_view.GetCurrentURL().contains(QStringLiteral("localhost"))) {
  705. if (!web_browser_view.IsFinished()) {
  706. web_browser_view.SetFinished(true);
  707. web_browser_view.SetExitReason(Service::AM::Applets::WebExitReason::CallbackURL);
  708. }
  709. web_browser_view.SetLastURL(web_browser_view.GetCurrentURL().toStdString());
  710. }
  711. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  712. }
  713. const auto exit_reason = web_browser_view.GetExitReason();
  714. const auto last_url = web_browser_view.GetLastURL();
  715. web_browser_view.hide();
  716. render_window->setFocus();
  717. if (render_window->IsLoadingComplete()) {
  718. render_window->show();
  719. }
  720. ui->action_Pause->setEnabled(true);
  721. ui->action_Restart->setEnabled(true);
  722. ui->action_Stop->setEnabled(true);
  723. ui->menubar->removeAction(exit_action);
  724. QCoreApplication::processEvents();
  725. emit WebBrowserClosed(exit_reason, last_url);
  726. #else
  727. // Utilize the same fallback as the default web browser applet.
  728. emit WebBrowserClosed(Service::AM::Applets::WebExitReason::WindowClosed, "http://localhost/");
  729. #endif
  730. }
  731. void GMainWindow::InitializeWidgets() {
  732. #ifdef YUZU_ENABLE_COMPATIBILITY_REPORTING
  733. ui->action_Report_Compatibility->setVisible(true);
  734. #endif
  735. render_window = new GRenderWindow(this, emu_thread.get(), input_subsystem, *system);
  736. render_window->hide();
  737. game_list = new GameList(vfs, provider.get(), *system, this);
  738. ui->horizontalLayout->addWidget(game_list);
  739. game_list_placeholder = new GameListPlaceholder(this);
  740. ui->horizontalLayout->addWidget(game_list_placeholder);
  741. game_list_placeholder->setVisible(false);
  742. loading_screen = new LoadingScreen(this);
  743. loading_screen->hide();
  744. ui->horizontalLayout->addWidget(loading_screen);
  745. connect(loading_screen, &LoadingScreen::Hidden, [&] {
  746. loading_screen->Clear();
  747. if (emulation_running) {
  748. render_window->show();
  749. render_window->setFocus();
  750. }
  751. });
  752. multiplayer_state = new MultiplayerState(this, game_list->GetModel(), ui->action_Leave_Room,
  753. ui->action_Show_Room, *system);
  754. multiplayer_state->setVisible(false);
  755. // Create status bar
  756. message_label = new QLabel();
  757. // Configured separately for left alignment
  758. message_label->setFrameStyle(QFrame::NoFrame);
  759. message_label->setContentsMargins(4, 0, 4, 0);
  760. message_label->setAlignment(Qt::AlignLeft);
  761. statusBar()->addPermanentWidget(message_label, 1);
  762. shader_building_label = new QLabel();
  763. shader_building_label->setToolTip(tr("The amount of shaders currently being built"));
  764. res_scale_label = new QLabel();
  765. res_scale_label->setToolTip(tr("The current selected resolution scaling multiplier."));
  766. emu_speed_label = new QLabel();
  767. emu_speed_label->setToolTip(
  768. tr("Current emulation speed. Values higher or lower than 100% "
  769. "indicate emulation is running faster or slower than a Switch."));
  770. game_fps_label = new QLabel();
  771. game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. "
  772. "This will vary from game to game and scene to scene."));
  773. emu_frametime_label = new QLabel();
  774. emu_frametime_label->setToolTip(
  775. tr("Time taken to emulate a Switch frame, not counting framelimiting or v-sync. For "
  776. "full-speed emulation this should be at most 16.67 ms."));
  777. for (auto& label : {shader_building_label, res_scale_label, emu_speed_label, game_fps_label,
  778. emu_frametime_label}) {
  779. label->setVisible(false);
  780. label->setFrameStyle(QFrame::NoFrame);
  781. label->setContentsMargins(4, 0, 4, 0);
  782. statusBar()->addPermanentWidget(label);
  783. }
  784. // TODO (flTobi): Add the widget when multiplayer is fully implemented
  785. statusBar()->addPermanentWidget(multiplayer_state->GetStatusText(), 0);
  786. statusBar()->addPermanentWidget(multiplayer_state->GetStatusIcon(), 0);
  787. tas_label = new QLabel();
  788. tas_label->setObjectName(QStringLiteral("TASlabel"));
  789. tas_label->setFocusPolicy(Qt::NoFocus);
  790. statusBar()->insertPermanentWidget(0, tas_label);
  791. // setup AA button
  792. aa_status_button = new QPushButton();
  793. aa_status_button->setObjectName(QStringLiteral("TogglableStatusBarButton"));
  794. aa_status_button->setFocusPolicy(Qt::NoFocus);
  795. connect(aa_status_button, &QPushButton::clicked, [&] {
  796. auto aa_mode = Settings::values.anti_aliasing.GetValue();
  797. if (aa_mode == Settings::AntiAliasing::LastAA) {
  798. aa_mode = Settings::AntiAliasing::None;
  799. } else {
  800. aa_mode = static_cast<Settings::AntiAliasing>(static_cast<u32>(aa_mode) + 1);
  801. }
  802. Settings::values.anti_aliasing.SetValue(aa_mode);
  803. aa_status_button->setChecked(true);
  804. UpdateAAText();
  805. });
  806. UpdateAAText();
  807. aa_status_button->setCheckable(true);
  808. aa_status_button->setChecked(true);
  809. statusBar()->insertPermanentWidget(0, aa_status_button);
  810. // Setup Filter button
  811. filter_status_button = new QPushButton();
  812. filter_status_button->setObjectName(QStringLiteral("TogglableStatusBarButton"));
  813. filter_status_button->setFocusPolicy(Qt::NoFocus);
  814. connect(filter_status_button, &QPushButton::clicked, this,
  815. &GMainWindow::OnToggleAdaptingFilter);
  816. auto filter = Settings::values.scaling_filter.GetValue();
  817. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL &&
  818. filter == Settings::ScalingFilter::Fsr) {
  819. Settings::values.scaling_filter.SetValue(Settings::ScalingFilter::NearestNeighbor);
  820. }
  821. UpdateFilterText();
  822. filter_status_button->setCheckable(true);
  823. filter_status_button->setChecked(true);
  824. statusBar()->insertPermanentWidget(0, filter_status_button);
  825. // Setup Dock button
  826. dock_status_button = new QPushButton();
  827. dock_status_button->setObjectName(QStringLiteral("DockingStatusBarButton"));
  828. dock_status_button->setFocusPolicy(Qt::NoFocus);
  829. connect(dock_status_button, &QPushButton::clicked, this, &GMainWindow::OnToggleDockedMode);
  830. dock_status_button->setCheckable(true);
  831. UpdateDockedButton();
  832. statusBar()->insertPermanentWidget(0, dock_status_button);
  833. gpu_accuracy_button = new QPushButton();
  834. gpu_accuracy_button->setObjectName(QStringLiteral("GPUStatusBarButton"));
  835. gpu_accuracy_button->setCheckable(true);
  836. gpu_accuracy_button->setFocusPolicy(Qt::NoFocus);
  837. connect(gpu_accuracy_button, &QPushButton::clicked, this, &GMainWindow::OnToggleGpuAccuracy);
  838. UpdateGPUAccuracyButton();
  839. statusBar()->insertPermanentWidget(0, gpu_accuracy_button);
  840. // Setup Renderer API button
  841. renderer_status_button = new QPushButton();
  842. renderer_status_button->setObjectName(QStringLiteral("RendererStatusBarButton"));
  843. renderer_status_button->setCheckable(true);
  844. renderer_status_button->setFocusPolicy(Qt::NoFocus);
  845. connect(renderer_status_button, &QPushButton::toggled, [this](bool checked) {
  846. renderer_status_button->setText(checked ? tr("VULKAN") : tr("OPENGL"));
  847. });
  848. renderer_status_button->toggle();
  849. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  850. Settings::RendererBackend::Vulkan);
  851. connect(renderer_status_button, &QPushButton::clicked, [this] {
  852. if (emulation_running) {
  853. return;
  854. }
  855. if (renderer_status_button->isChecked()) {
  856. Settings::values.renderer_backend.SetValue(Settings::RendererBackend::Vulkan);
  857. } else {
  858. Settings::values.renderer_backend.SetValue(Settings::RendererBackend::OpenGL);
  859. if (Settings::values.scaling_filter.GetValue() == Settings::ScalingFilter::Fsr) {
  860. Settings::values.scaling_filter.SetValue(Settings::ScalingFilter::NearestNeighbor);
  861. UpdateFilterText();
  862. }
  863. }
  864. system->ApplySettings();
  865. });
  866. statusBar()->insertPermanentWidget(0, renderer_status_button);
  867. statusBar()->setVisible(true);
  868. setStyleSheet(QStringLiteral("QStatusBar::item{border: none;}"));
  869. }
  870. void GMainWindow::InitializeDebugWidgets() {
  871. QMenu* debug_menu = ui->menu_View_Debugging;
  872. #if MICROPROFILE_ENABLED
  873. microProfileDialog = new MicroProfileDialog(this);
  874. microProfileDialog->hide();
  875. debug_menu->addAction(microProfileDialog->toggleViewAction());
  876. #endif
  877. waitTreeWidget = new WaitTreeWidget(*system, this);
  878. addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
  879. waitTreeWidget->hide();
  880. debug_menu->addAction(waitTreeWidget->toggleViewAction());
  881. controller_dialog = new ControllerDialog(system->HIDCore(), input_subsystem, this);
  882. controller_dialog->hide();
  883. debug_menu->addAction(controller_dialog->toggleViewAction());
  884. connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
  885. &WaitTreeWidget::OnEmulationStarting);
  886. connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
  887. &WaitTreeWidget::OnEmulationStopping);
  888. }
  889. void GMainWindow::InitializeRecentFileMenuActions() {
  890. for (int i = 0; i < max_recent_files_item; ++i) {
  891. actions_recent_files[i] = new QAction(this);
  892. actions_recent_files[i]->setVisible(false);
  893. connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile);
  894. ui->menu_recent_files->addAction(actions_recent_files[i]);
  895. }
  896. ui->menu_recent_files->addSeparator();
  897. QAction* action_clear_recent_files = new QAction(this);
  898. action_clear_recent_files->setText(tr("&Clear Recent Files"));
  899. connect(action_clear_recent_files, &QAction::triggered, this, [this] {
  900. UISettings::values.recent_files.clear();
  901. UpdateRecentFiles();
  902. });
  903. ui->menu_recent_files->addAction(action_clear_recent_files);
  904. UpdateRecentFiles();
  905. }
  906. void GMainWindow::LinkActionShortcut(QAction* action, const QString& action_name) {
  907. static const QString main_window = QStringLiteral("Main Window");
  908. action->setShortcut(hotkey_registry.GetKeySequence(main_window, action_name));
  909. action->setShortcutContext(hotkey_registry.GetShortcutContext(main_window, action_name));
  910. action->setAutoRepeat(false);
  911. this->addAction(action);
  912. auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  913. const auto* controller_hotkey =
  914. hotkey_registry.GetControllerHotkey(main_window, action_name, controller);
  915. connect(
  916. controller_hotkey, &ControllerShortcut::Activated, this, [action] { action->trigger(); },
  917. Qt::QueuedConnection);
  918. }
  919. void GMainWindow::InitializeHotkeys() {
  920. hotkey_registry.LoadHotkeys();
  921. LinkActionShortcut(ui->action_Load_File, QStringLiteral("Load File"));
  922. LinkActionShortcut(ui->action_Load_Amiibo, QStringLiteral("Load/Remove Amiibo"));
  923. LinkActionShortcut(ui->action_Exit, QStringLiteral("Exit yuzu"));
  924. LinkActionShortcut(ui->action_Restart, QStringLiteral("Restart Emulation"));
  925. LinkActionShortcut(ui->action_Pause, QStringLiteral("Continue/Pause Emulation"));
  926. LinkActionShortcut(ui->action_Stop, QStringLiteral("Stop Emulation"));
  927. LinkActionShortcut(ui->action_Show_Filter_Bar, QStringLiteral("Toggle Filter Bar"));
  928. LinkActionShortcut(ui->action_Show_Status_Bar, QStringLiteral("Toggle Status Bar"));
  929. LinkActionShortcut(ui->action_Fullscreen, QStringLiteral("Fullscreen"));
  930. LinkActionShortcut(ui->action_Capture_Screenshot, QStringLiteral("Capture Screenshot"));
  931. LinkActionShortcut(ui->action_TAS_Start, QStringLiteral("TAS Start/Stop"));
  932. LinkActionShortcut(ui->action_TAS_Record, QStringLiteral("TAS Record"));
  933. LinkActionShortcut(ui->action_TAS_Reset, QStringLiteral("TAS Reset"));
  934. static const QString main_window = QStringLiteral("Main Window");
  935. const auto connect_shortcut = [&]<typename Fn>(const QString& action_name, const Fn& function) {
  936. const auto* hotkey = hotkey_registry.GetHotkey(main_window, action_name, this);
  937. auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  938. const auto* controller_hotkey =
  939. hotkey_registry.GetControllerHotkey(main_window, action_name, controller);
  940. connect(hotkey, &QShortcut::activated, this, function);
  941. connect(controller_hotkey, &ControllerShortcut::Activated, this, function,
  942. Qt::QueuedConnection);
  943. };
  944. connect_shortcut(QStringLiteral("Exit Fullscreen"), [&] {
  945. if (emulation_running && ui->action_Fullscreen->isChecked()) {
  946. ui->action_Fullscreen->setChecked(false);
  947. ToggleFullscreen();
  948. }
  949. });
  950. connect_shortcut(QStringLiteral("Change Adapting Filter"),
  951. &GMainWindow::OnToggleAdaptingFilter);
  952. connect_shortcut(QStringLiteral("Change Docked Mode"), &GMainWindow::OnToggleDockedMode);
  953. connect_shortcut(QStringLiteral("Change GPU Accuracy"), &GMainWindow::OnToggleGpuAccuracy);
  954. connect_shortcut(QStringLiteral("Audio Mute/Unmute"),
  955. [] { Settings::values.audio_muted = !Settings::values.audio_muted; });
  956. connect_shortcut(QStringLiteral("Audio Volume Down"), [] {
  957. const auto current_volume = static_cast<s32>(Settings::values.volume.GetValue());
  958. int step = 5;
  959. if (current_volume <= 30) {
  960. step = 2;
  961. }
  962. if (current_volume <= 6) {
  963. step = 1;
  964. }
  965. Settings::values.volume.SetValue(std::max(current_volume - step, 0));
  966. });
  967. connect_shortcut(QStringLiteral("Audio Volume Up"), [] {
  968. const auto current_volume = static_cast<s32>(Settings::values.volume.GetValue());
  969. int step = 5;
  970. if (current_volume < 30) {
  971. step = 2;
  972. }
  973. if (current_volume < 6) {
  974. step = 1;
  975. }
  976. Settings::values.volume.SetValue(current_volume + step);
  977. });
  978. connect_shortcut(QStringLiteral("Toggle Framerate Limit"), [] {
  979. Settings::values.use_speed_limit.SetValue(!Settings::values.use_speed_limit.GetValue());
  980. });
  981. connect_shortcut(QStringLiteral("Toggle Mouse Panning"), [&] {
  982. Settings::values.mouse_panning = !Settings::values.mouse_panning;
  983. if (Settings::values.mouse_panning) {
  984. render_window->installEventFilter(render_window);
  985. render_window->setAttribute(Qt::WA_Hover, true);
  986. }
  987. });
  988. }
  989. void GMainWindow::SetDefaultUIGeometry() {
  990. // geometry: 53% of the window contents are in the upper screen half, 47% in the lower half
  991. const QRect screenRect = QGuiApplication::primaryScreen()->geometry();
  992. const int w = screenRect.width() * 2 / 3;
  993. const int h = screenRect.height() * 2 / 3;
  994. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  995. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 53 / 100;
  996. setGeometry(x, y, w, h);
  997. }
  998. void GMainWindow::RestoreUIState() {
  999. setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  1000. restoreGeometry(UISettings::values.geometry);
  1001. // Work-around because the games list isn't supposed to be full screen
  1002. if (isFullScreen()) {
  1003. showNormal();
  1004. }
  1005. restoreState(UISettings::values.state);
  1006. render_window->setWindowFlags(render_window->windowFlags() & ~Qt::FramelessWindowHint);
  1007. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  1008. #if MICROPROFILE_ENABLED
  1009. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  1010. microProfileDialog->setVisible(UISettings::values.microprofile_visible.GetValue());
  1011. #endif
  1012. game_list->LoadInterfaceLayout();
  1013. ui->action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode.GetValue());
  1014. ToggleWindowMode();
  1015. ui->action_Fullscreen->setChecked(UISettings::values.fullscreen.GetValue());
  1016. ui->action_Display_Dock_Widget_Headers->setChecked(
  1017. UISettings::values.display_titlebar.GetValue());
  1018. OnDisplayTitleBars(ui->action_Display_Dock_Widget_Headers->isChecked());
  1019. ui->action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar.GetValue());
  1020. game_list->SetFilterVisible(ui->action_Show_Filter_Bar->isChecked());
  1021. ui->action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar.GetValue());
  1022. statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
  1023. Debugger::ToggleConsole();
  1024. }
  1025. void GMainWindow::OnAppFocusStateChanged(Qt::ApplicationState state) {
  1026. if (state != Qt::ApplicationHidden && state != Qt::ApplicationInactive &&
  1027. state != Qt::ApplicationActive) {
  1028. LOG_DEBUG(Frontend, "ApplicationState unusual flag: {} ", state);
  1029. }
  1030. if (!emulation_running) {
  1031. return;
  1032. }
  1033. if (UISettings::values.pause_when_in_background) {
  1034. if (emu_thread->IsRunning() &&
  1035. (state & (Qt::ApplicationHidden | Qt::ApplicationInactive))) {
  1036. auto_paused = true;
  1037. OnPauseGame();
  1038. } else if (!emu_thread->IsRunning() && auto_paused && state == Qt::ApplicationActive) {
  1039. auto_paused = false;
  1040. RequestGameResume();
  1041. OnStartGame();
  1042. }
  1043. }
  1044. if (UISettings::values.mute_when_in_background) {
  1045. if (!Settings::values.audio_muted &&
  1046. (state & (Qt::ApplicationHidden | Qt::ApplicationInactive))) {
  1047. Settings::values.audio_muted = true;
  1048. auto_muted = true;
  1049. } else if (auto_muted && state == Qt::ApplicationActive) {
  1050. Settings::values.audio_muted = false;
  1051. auto_muted = false;
  1052. }
  1053. }
  1054. }
  1055. void GMainWindow::ConnectWidgetEvents() {
  1056. connect(game_list, &GameList::BootGame, this, &GMainWindow::BootGame);
  1057. connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
  1058. connect(game_list, &GameList::OpenDirectory, this, &GMainWindow::OnGameListOpenDirectory);
  1059. connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
  1060. connect(game_list, &GameList::OpenTransferableShaderCacheRequested, this,
  1061. &GMainWindow::OnTransferableShaderCacheOpenFile);
  1062. connect(game_list, &GameList::RemoveInstalledEntryRequested, this,
  1063. &GMainWindow::OnGameListRemoveInstalledEntry);
  1064. connect(game_list, &GameList::RemoveFileRequested, this, &GMainWindow::OnGameListRemoveFile);
  1065. connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS);
  1066. connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID);
  1067. connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
  1068. &GMainWindow::OnGameListNavigateToGamedbEntry);
  1069. connect(game_list, &GameList::AddDirectory, this, &GMainWindow::OnGameListAddDirectory);
  1070. connect(game_list_placeholder, &GameListPlaceholder::AddDirectory, this,
  1071. &GMainWindow::OnGameListAddDirectory);
  1072. connect(game_list, &GameList::ShowList, this, &GMainWindow::OnGameListShowList);
  1073. connect(game_list, &GameList::PopulatingCompleted,
  1074. [this] { multiplayer_state->UpdateGameList(game_list->GetModel()); });
  1075. connect(game_list, &GameList::OpenPerGameGeneralRequested, this,
  1076. &GMainWindow::OnGameListOpenPerGameProperties);
  1077. connect(this, &GMainWindow::UpdateInstallProgress, this,
  1078. &GMainWindow::IncrementInstallProgress);
  1079. connect(this, &GMainWindow::EmulationStarting, render_window,
  1080. &GRenderWindow::OnEmulationStarting);
  1081. connect(this, &GMainWindow::EmulationStopping, render_window,
  1082. &GRenderWindow::OnEmulationStopping);
  1083. // Software Keyboard Applet
  1084. connect(this, &GMainWindow::EmulationStarting, this, &GMainWindow::SoftwareKeyboardExit);
  1085. connect(this, &GMainWindow::EmulationStopping, this, &GMainWindow::SoftwareKeyboardExit);
  1086. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  1087. connect(this, &GMainWindow::UpdateThemedIcons, multiplayer_state,
  1088. &MultiplayerState::UpdateThemedIcons);
  1089. }
  1090. void GMainWindow::ConnectMenuEvents() {
  1091. const auto connect_menu = [&]<typename Fn>(QAction* action, const Fn& event_fn) {
  1092. connect(action, &QAction::triggered, this, event_fn);
  1093. // Add actions to this window so that hiding menus in fullscreen won't disable them
  1094. addAction(action);
  1095. // Add actions to the render window so that they work outside of single window mode
  1096. render_window->addAction(action);
  1097. };
  1098. // File
  1099. connect_menu(ui->action_Load_File, &GMainWindow::OnMenuLoadFile);
  1100. connect_menu(ui->action_Load_Folder, &GMainWindow::OnMenuLoadFolder);
  1101. connect_menu(ui->action_Install_File_NAND, &GMainWindow::OnMenuInstallToNAND);
  1102. connect_menu(ui->action_Exit, &QMainWindow::close);
  1103. connect_menu(ui->action_Load_Amiibo, &GMainWindow::OnLoadAmiibo);
  1104. // Emulation
  1105. connect_menu(ui->action_Pause, &GMainWindow::OnPauseContinueGame);
  1106. connect_menu(ui->action_Stop, &GMainWindow::OnStopGame);
  1107. connect_menu(ui->action_Report_Compatibility, &GMainWindow::OnMenuReportCompatibility);
  1108. connect_menu(ui->action_Open_Mods_Page, &GMainWindow::OnOpenModsPage);
  1109. connect_menu(ui->action_Open_Quickstart_Guide, &GMainWindow::OnOpenQuickstartGuide);
  1110. connect_menu(ui->action_Open_FAQ, &GMainWindow::OnOpenFAQ);
  1111. connect_menu(ui->action_Restart, &GMainWindow::OnRestartGame);
  1112. connect_menu(ui->action_Configure, &GMainWindow::OnConfigure);
  1113. connect_menu(ui->action_Configure_Current_Game, &GMainWindow::OnConfigurePerGame);
  1114. // View
  1115. connect_menu(ui->action_Fullscreen, &GMainWindow::ToggleFullscreen);
  1116. connect_menu(ui->action_Single_Window_Mode, &GMainWindow::ToggleWindowMode);
  1117. connect_menu(ui->action_Display_Dock_Widget_Headers, &GMainWindow::OnDisplayTitleBars);
  1118. connect_menu(ui->action_Show_Filter_Bar, &GMainWindow::OnToggleFilterBar);
  1119. connect_menu(ui->action_Show_Status_Bar, &GMainWindow::OnToggleStatusBar);
  1120. connect_menu(ui->action_Reset_Window_Size_720, &GMainWindow::ResetWindowSize720);
  1121. connect_menu(ui->action_Reset_Window_Size_900, &GMainWindow::ResetWindowSize900);
  1122. connect_menu(ui->action_Reset_Window_Size_1080, &GMainWindow::ResetWindowSize1080);
  1123. ui->menu_Reset_Window_Size->addActions({ui->action_Reset_Window_Size_720,
  1124. ui->action_Reset_Window_Size_900,
  1125. ui->action_Reset_Window_Size_1080});
  1126. // Multiplayer
  1127. connect(ui->action_View_Lobby, &QAction::triggered, multiplayer_state,
  1128. &MultiplayerState::OnViewLobby);
  1129. connect(ui->action_Start_Room, &QAction::triggered, multiplayer_state,
  1130. &MultiplayerState::OnCreateRoom);
  1131. connect(ui->action_Leave_Room, &QAction::triggered, multiplayer_state,
  1132. &MultiplayerState::OnCloseRoom);
  1133. connect(ui->action_Connect_To_Room, &QAction::triggered, multiplayer_state,
  1134. &MultiplayerState::OnDirectConnectToRoom);
  1135. connect(ui->action_Show_Room, &QAction::triggered, multiplayer_state,
  1136. &MultiplayerState::OnOpenNetworkRoom);
  1137. connect(multiplayer_state, &MultiplayerState::SaveConfig, this, &GMainWindow::OnSaveConfig);
  1138. // Tools
  1139. connect_menu(ui->action_Rederive, std::bind(&GMainWindow::OnReinitializeKeys, this,
  1140. ReinitializeKeyBehavior::Warning));
  1141. connect_menu(ui->action_Capture_Screenshot, &GMainWindow::OnCaptureScreenshot);
  1142. // TAS
  1143. connect_menu(ui->action_TAS_Start, &GMainWindow::OnTasStartStop);
  1144. connect_menu(ui->action_TAS_Record, &GMainWindow::OnTasRecord);
  1145. connect_menu(ui->action_TAS_Reset, &GMainWindow::OnTasReset);
  1146. connect_menu(ui->action_Configure_Tas, &GMainWindow::OnConfigureTas);
  1147. // Help
  1148. connect_menu(ui->action_Open_yuzu_Folder, &GMainWindow::OnOpenYuzuFolder);
  1149. connect_menu(ui->action_About, &GMainWindow::OnAbout);
  1150. }
  1151. void GMainWindow::UpdateMenuState() {
  1152. const bool is_paused = emu_thread == nullptr || !emu_thread->IsRunning();
  1153. const std::array running_actions{
  1154. ui->action_Stop,
  1155. ui->action_Restart,
  1156. ui->action_Configure_Current_Game,
  1157. ui->action_Report_Compatibility,
  1158. ui->action_Load_Amiibo,
  1159. ui->action_Pause,
  1160. };
  1161. for (QAction* action : running_actions) {
  1162. action->setEnabled(emulation_running);
  1163. }
  1164. ui->action_Capture_Screenshot->setEnabled(emulation_running && !is_paused);
  1165. if (emulation_running && is_paused) {
  1166. ui->action_Pause->setText(tr("&Continue"));
  1167. } else {
  1168. ui->action_Pause->setText(tr("&Pause"));
  1169. }
  1170. multiplayer_state->UpdateNotificationStatus();
  1171. }
  1172. void GMainWindow::OnDisplayTitleBars(bool show) {
  1173. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  1174. if (show) {
  1175. for (QDockWidget* widget : widgets) {
  1176. QWidget* old = widget->titleBarWidget();
  1177. widget->setTitleBarWidget(nullptr);
  1178. if (old != nullptr)
  1179. delete old;
  1180. }
  1181. } else {
  1182. for (QDockWidget* widget : widgets) {
  1183. QWidget* old = widget->titleBarWidget();
  1184. widget->setTitleBarWidget(new QWidget());
  1185. if (old != nullptr)
  1186. delete old;
  1187. }
  1188. }
  1189. }
  1190. void GMainWindow::SetupPrepareForSleep() {
  1191. #ifdef __unix__
  1192. auto bus = QDBusConnection::systemBus();
  1193. if (bus.isConnected()) {
  1194. const bool success = bus.connect(
  1195. QStringLiteral("org.freedesktop.login1"), QStringLiteral("/org/freedesktop/login1"),
  1196. QStringLiteral("org.freedesktop.login1.Manager"), QStringLiteral("PrepareForSleep"),
  1197. QStringLiteral("b"), this, SLOT(OnPrepareForSleep(bool)));
  1198. if (!success) {
  1199. LOG_WARNING(Frontend, "Couldn't register PrepareForSleep signal");
  1200. }
  1201. } else {
  1202. LOG_WARNING(Frontend, "QDBusConnection system bus is not connected");
  1203. }
  1204. #endif // __unix__
  1205. }
  1206. void GMainWindow::OnPrepareForSleep(bool prepare_sleep) {
  1207. if (emu_thread == nullptr) {
  1208. return;
  1209. }
  1210. if (prepare_sleep) {
  1211. if (emu_thread->IsRunning()) {
  1212. auto_paused = true;
  1213. OnPauseGame();
  1214. }
  1215. } else {
  1216. if (!emu_thread->IsRunning() && auto_paused) {
  1217. auto_paused = false;
  1218. RequestGameResume();
  1219. OnStartGame();
  1220. }
  1221. }
  1222. }
  1223. #ifdef __unix__
  1224. static std::optional<QDBusObjectPath> HoldWakeLockLinux(u32 window_id = 0) {
  1225. if (!QDBusConnection::sessionBus().isConnected()) {
  1226. return {};
  1227. }
  1228. // reference: https://flatpak.github.io/xdg-desktop-portal/#gdbus-org.freedesktop.portal.Inhibit
  1229. QDBusInterface xdp(QString::fromLatin1("org.freedesktop.portal.Desktop"),
  1230. QString::fromLatin1("/org/freedesktop/portal/desktop"),
  1231. QString::fromLatin1("org.freedesktop.portal.Inhibit"));
  1232. if (!xdp.isValid()) {
  1233. LOG_WARNING(Frontend, "Couldn't connect to XDP D-Bus endpoint");
  1234. return {};
  1235. }
  1236. QVariantMap options = {};
  1237. //: TRANSLATORS: This string is shown to the user to explain why yuzu needs to prevent the
  1238. //: computer from sleeping
  1239. options.insert(QString::fromLatin1("reason"),
  1240. QCoreApplication::translate("GMainWindow", "yuzu is running a game"));
  1241. // 0x4: Suspend lock; 0x8: Idle lock
  1242. QDBusReply<QDBusObjectPath> reply =
  1243. xdp.call(QString::fromLatin1("Inhibit"),
  1244. QString::fromLatin1("x11:") + QString::number(window_id, 16), 12U, options);
  1245. if (reply.isValid()) {
  1246. return reply.value();
  1247. }
  1248. LOG_WARNING(Frontend, "Couldn't read Inhibit reply from XDP: {}",
  1249. reply.error().message().toStdString());
  1250. return {};
  1251. }
  1252. static void ReleaseWakeLockLinux(QDBusObjectPath lock) {
  1253. if (!QDBusConnection::sessionBus().isConnected()) {
  1254. return;
  1255. }
  1256. QDBusInterface unlocker(QString::fromLatin1("org.freedesktop.portal.Desktop"), lock.path(),
  1257. QString::fromLatin1("org.freedesktop.portal.Request"));
  1258. unlocker.call(QString::fromLatin1("Close"));
  1259. }
  1260. std::array<int, 3> GMainWindow::sig_interrupt_fds{0, 0, 0};
  1261. void GMainWindow::SetupSigInterrupts() {
  1262. if (sig_interrupt_fds[2] == 1) {
  1263. return;
  1264. }
  1265. socketpair(AF_UNIX, SOCK_STREAM, 0, sig_interrupt_fds.data());
  1266. sig_interrupt_fds[2] = 1;
  1267. struct sigaction sa;
  1268. sa.sa_handler = &GMainWindow::HandleSigInterrupt;
  1269. sigemptyset(&sa.sa_mask);
  1270. sa.sa_flags = SA_RESETHAND;
  1271. sigaction(SIGINT, &sa, nullptr);
  1272. sigaction(SIGTERM, &sa, nullptr);
  1273. sig_interrupt_notifier = new QSocketNotifier(sig_interrupt_fds[1], QSocketNotifier::Read, this);
  1274. connect(sig_interrupt_notifier, &QSocketNotifier::activated, this,
  1275. &GMainWindow::OnSigInterruptNotifierActivated);
  1276. connect(this, &GMainWindow::SigInterrupt, this, &GMainWindow::close);
  1277. }
  1278. void GMainWindow::HandleSigInterrupt(int sig) {
  1279. if (sig == SIGINT) {
  1280. exit(1);
  1281. }
  1282. // Calling into Qt directly from a signal handler is not safe,
  1283. // so wake up a QSocketNotifier with this hacky write call instead.
  1284. char a = 1;
  1285. int ret = write(sig_interrupt_fds[0], &a, sizeof(a));
  1286. (void)ret;
  1287. }
  1288. void GMainWindow::OnSigInterruptNotifierActivated() {
  1289. sig_interrupt_notifier->setEnabled(false);
  1290. char a;
  1291. int ret = read(sig_interrupt_fds[1], &a, sizeof(a));
  1292. (void)ret;
  1293. sig_interrupt_notifier->setEnabled(true);
  1294. emit SigInterrupt();
  1295. }
  1296. #endif // __unix__
  1297. void GMainWindow::PreventOSSleep() {
  1298. #ifdef _WIN32
  1299. SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
  1300. #elif defined(HAVE_SDL2)
  1301. SDL_DisableScreenSaver();
  1302. #ifdef __unix__
  1303. auto reply = HoldWakeLockLinux(winId());
  1304. if (reply) {
  1305. wake_lock = std::move(reply.value());
  1306. }
  1307. #endif
  1308. #endif
  1309. }
  1310. void GMainWindow::AllowOSSleep() {
  1311. #ifdef _WIN32
  1312. SetThreadExecutionState(ES_CONTINUOUS);
  1313. #elif defined(HAVE_SDL2)
  1314. SDL_EnableScreenSaver();
  1315. #ifdef __unix__
  1316. if (!wake_lock.path().isEmpty()) {
  1317. ReleaseWakeLockLinux(wake_lock);
  1318. }
  1319. #endif
  1320. #endif
  1321. }
  1322. bool GMainWindow::LoadROM(const QString& filename, u64 program_id, std::size_t program_index) {
  1323. // Shutdown previous session if the emu thread is still active...
  1324. if (emu_thread != nullptr)
  1325. ShutdownGame();
  1326. if (!render_window->InitRenderTarget()) {
  1327. return false;
  1328. }
  1329. system->SetFilesystem(vfs);
  1330. system->SetAppletFrontendSet({
  1331. std::make_unique<QtAmiiboSettings>(*this), // Amiibo Settings
  1332. std::make_unique<QtControllerSelector>(*this), // Controller Selector
  1333. std::make_unique<QtErrorDisplay>(*this), // Error Display
  1334. nullptr, // Mii Editor
  1335. nullptr, // Parental Controls
  1336. nullptr, // Photo Viewer
  1337. std::make_unique<QtProfileSelector>(*this), // Profile Selector
  1338. std::make_unique<QtSoftwareKeyboard>(*this), // Software Keyboard
  1339. std::make_unique<QtWebBrowser>(*this), // Web Browser
  1340. });
  1341. const Core::SystemResultStatus result{
  1342. system->Load(*render_window, filename.toStdString(), program_id, program_index)};
  1343. const auto drd_callout = (UISettings::values.callout_flags.GetValue() &
  1344. static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  1345. if (result == Core::SystemResultStatus::Success &&
  1346. system->GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  1347. drd_callout) {
  1348. UISettings::values.callout_flags = UISettings::values.callout_flags.GetValue() |
  1349. static_cast<u32>(CalloutFlag::DRDDeprecation);
  1350. QMessageBox::warning(
  1351. this, tr("Warning Outdated Game Format"),
  1352. tr("You are using the deconstructed ROM directory format for this game, which is an "
  1353. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  1354. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  1355. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  1356. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  1357. "wiki</a>. This message will not be shown again."));
  1358. }
  1359. if (result != Core::SystemResultStatus::Success) {
  1360. switch (result) {
  1361. case Core::SystemResultStatus::ErrorGetLoader:
  1362. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  1363. QMessageBox::critical(this, tr("Error while loading ROM!"),
  1364. tr("The ROM format is not supported."));
  1365. break;
  1366. case Core::SystemResultStatus::ErrorVideoCore:
  1367. QMessageBox::critical(
  1368. this, tr("An error occurred initializing the video core."),
  1369. tr("yuzu has encountered an error while running the video core. "
  1370. "This is usually caused by outdated GPU drivers, including integrated ones. "
  1371. "Please see the log for more details. "
  1372. "For more information on accessing the log, please see the following page: "
  1373. "<a href='https://yuzu-emu.org/help/reference/log-files/'>"
  1374. "How to Upload the Log File</a>. "));
  1375. break;
  1376. default:
  1377. if (result > Core::SystemResultStatus::ErrorLoader) {
  1378. const u16 loader_id = static_cast<u16>(Core::SystemResultStatus::ErrorLoader);
  1379. const u16 error_id = static_cast<u16>(result) - loader_id;
  1380. const std::string error_code = fmt::format("({:04X}-{:04X})", loader_id, error_id);
  1381. LOG_CRITICAL(Frontend, "Failed to load ROM! {}", error_code);
  1382. const auto title =
  1383. tr("Error while loading ROM! %1", "%1 signifies a numeric error code.")
  1384. .arg(QString::fromStdString(error_code));
  1385. const auto description =
  1386. tr("%1<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the "
  1387. "yuzu quickstart guide</a> to redump your files.<br>You can refer "
  1388. "to the yuzu wiki</a> or the yuzu Discord</a> for help.",
  1389. "%1 signifies an error string.")
  1390. .arg(QString::fromStdString(
  1391. GetResultStatusString(static_cast<Loader::ResultStatus>(error_id))));
  1392. QMessageBox::critical(this, title, description);
  1393. } else {
  1394. QMessageBox::critical(
  1395. this, tr("Error while loading ROM!"),
  1396. tr("An unknown error occurred. Please see the log for more details."));
  1397. }
  1398. break;
  1399. }
  1400. return false;
  1401. }
  1402. current_game_path = filename;
  1403. system->TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "Qt");
  1404. return true;
  1405. }
  1406. bool GMainWindow::SelectAndSetCurrentUser() {
  1407. QtProfileSelectionDialog dialog(system->HIDCore(), this);
  1408. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1409. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1410. dialog.setWindowModality(Qt::WindowModal);
  1411. if (dialog.exec() == QDialog::Rejected) {
  1412. return false;
  1413. }
  1414. Settings::values.current_user = dialog.GetIndex();
  1415. return true;
  1416. }
  1417. void GMainWindow::BootGame(const QString& filename, u64 program_id, std::size_t program_index,
  1418. StartGameType type) {
  1419. LOG_INFO(Frontend, "yuzu starting...");
  1420. StoreRecentFile(filename); // Put the filename on top of the list
  1421. u64 title_id{0};
  1422. last_filename_booted = filename;
  1423. const auto v_file = Core::GetGameFileFromPath(vfs, filename.toUtf8().constData());
  1424. const auto loader = Loader::GetLoader(*system, v_file, program_id, program_index);
  1425. if (loader != nullptr && loader->ReadProgramId(title_id) == Loader::ResultStatus::Success &&
  1426. type == StartGameType::Normal) {
  1427. // Load per game settings
  1428. const auto file_path =
  1429. std::filesystem::path{Common::U16StringFromBuffer(filename.utf16(), filename.size())};
  1430. const auto config_file_name = title_id == 0
  1431. ? Common::FS::PathToUTF8String(file_path.filename())
  1432. : fmt::format("{:016X}", title_id);
  1433. Config per_game_config(config_file_name, Config::ConfigType::PerGameConfig);
  1434. system->ApplySettings();
  1435. }
  1436. // Save configurations
  1437. UpdateUISettings();
  1438. game_list->SaveInterfaceLayout();
  1439. config->Save();
  1440. Settings::LogSettings();
  1441. if (UISettings::values.select_user_on_boot) {
  1442. if (SelectAndSetCurrentUser() == false) {
  1443. return;
  1444. }
  1445. }
  1446. if (!LoadROM(filename, program_id, program_index)) {
  1447. return;
  1448. }
  1449. system->SetShuttingDown(false);
  1450. // Create and start the emulation thread
  1451. emu_thread = std::make_unique<EmuThread>(*system);
  1452. emit EmulationStarting(emu_thread.get());
  1453. emu_thread->start();
  1454. // Register an ExecuteProgram callback such that Core can execute a sub-program
  1455. system->RegisterExecuteProgramCallback(
  1456. [this](std::size_t program_index_) { render_window->ExecuteProgram(program_index_); });
  1457. // Register an Exit callback such that Core can exit the currently running application.
  1458. system->RegisterExitCallback([this]() { render_window->Exit(); });
  1459. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1460. connect(render_window, &GRenderWindow::MouseActivity, this, &GMainWindow::OnMouseActivity);
  1461. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  1462. // before the CPU continues
  1463. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  1464. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  1465. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  1466. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  1467. connect(emu_thread.get(), &EmuThread::LoadProgress, loading_screen,
  1468. &LoadingScreen::OnLoadProgress, Qt::QueuedConnection);
  1469. // Update the GUI
  1470. UpdateStatusButtons();
  1471. if (ui->action_Single_Window_Mode->isChecked()) {
  1472. game_list->hide();
  1473. game_list_placeholder->hide();
  1474. }
  1475. status_bar_update_timer.start(500);
  1476. renderer_status_button->setDisabled(true);
  1477. if (UISettings::values.hide_mouse || Settings::values.mouse_panning) {
  1478. render_window->installEventFilter(render_window);
  1479. render_window->setAttribute(Qt::WA_Hover, true);
  1480. }
  1481. if (UISettings::values.hide_mouse) {
  1482. mouse_hide_timer.start();
  1483. }
  1484. render_window->InitializeCamera();
  1485. std::string title_name;
  1486. std::string title_version;
  1487. const auto res = system->GetGameName(title_name);
  1488. const auto metadata = [this, title_id] {
  1489. const FileSys::PatchManager pm(title_id, system->GetFileSystemController(),
  1490. system->GetContentProvider());
  1491. return pm.GetControlMetadata();
  1492. }();
  1493. if (metadata.first != nullptr) {
  1494. title_version = metadata.first->GetVersionString();
  1495. title_name = metadata.first->GetApplicationName();
  1496. }
  1497. if (res != Loader::ResultStatus::Success || title_name.empty()) {
  1498. title_name = Common::FS::PathToUTF8String(
  1499. std::filesystem::path{Common::U16StringFromBuffer(filename.utf16(), filename.size())}
  1500. .filename());
  1501. }
  1502. const bool is_64bit = system->Kernel().CurrentProcess()->Is64BitProcess();
  1503. const auto instruction_set_suffix = is_64bit ? tr("(64-bit)") : tr("(32-bit)");
  1504. title_name = tr("%1 %2", "%1 is the title name. %2 indicates if the title is 64-bit or 32-bit")
  1505. .arg(QString::fromStdString(title_name), instruction_set_suffix)
  1506. .toStdString();
  1507. LOG_INFO(Frontend, "Booting game: {:016X} | {} | {}", title_id, title_name, title_version);
  1508. const auto gpu_vendor = system->GPU().Renderer().GetDeviceVendor();
  1509. UpdateWindowTitle(title_name, title_version, gpu_vendor);
  1510. loading_screen->Prepare(system->GetAppLoader());
  1511. loading_screen->show();
  1512. emulation_running = true;
  1513. if (ui->action_Fullscreen->isChecked()) {
  1514. ShowFullscreen();
  1515. }
  1516. OnStartGame();
  1517. }
  1518. void GMainWindow::ShutdownGame() {
  1519. if (!emulation_running) {
  1520. return;
  1521. }
  1522. if (ui->action_Fullscreen->isChecked()) {
  1523. HideFullscreen();
  1524. }
  1525. AllowOSSleep();
  1526. system->SetShuttingDown(true);
  1527. system->DetachDebugger();
  1528. discord_rpc->Pause();
  1529. emu_thread->RequestStop();
  1530. emit EmulationStopping();
  1531. // Wait for emulation thread to complete and delete it
  1532. emu_thread->wait();
  1533. emu_thread = nullptr;
  1534. emulation_running = false;
  1535. discord_rpc->Update();
  1536. // The emulation is stopped, so closing the window or not does not matter anymore
  1537. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1538. // Update the GUI
  1539. UpdateMenuState();
  1540. render_window->hide();
  1541. loading_screen->hide();
  1542. loading_screen->Clear();
  1543. if (game_list->IsEmpty()) {
  1544. game_list_placeholder->show();
  1545. } else {
  1546. game_list->show();
  1547. }
  1548. game_list->SetFilterFocus();
  1549. tas_label->clear();
  1550. input_subsystem->GetTas()->Stop();
  1551. OnTasStateChanged();
  1552. render_window->FinalizeCamera();
  1553. // Enable all controllers
  1554. system->HIDCore().SetSupportedStyleTag({Core::HID::NpadStyleSet::All});
  1555. render_window->removeEventFilter(render_window);
  1556. render_window->setAttribute(Qt::WA_Hover, false);
  1557. UpdateWindowTitle();
  1558. // Disable status bar updates
  1559. status_bar_update_timer.stop();
  1560. shader_building_label->setVisible(false);
  1561. res_scale_label->setVisible(false);
  1562. emu_speed_label->setVisible(false);
  1563. game_fps_label->setVisible(false);
  1564. emu_frametime_label->setVisible(false);
  1565. renderer_status_button->setEnabled(!UISettings::values.has_broken_vulkan);
  1566. current_game_path.clear();
  1567. // When closing the game, destroy the GLWindow to clear the context after the game is closed
  1568. render_window->ReleaseRenderTarget();
  1569. }
  1570. void GMainWindow::StoreRecentFile(const QString& filename) {
  1571. UISettings::values.recent_files.prepend(filename);
  1572. UISettings::values.recent_files.removeDuplicates();
  1573. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  1574. UISettings::values.recent_files.removeLast();
  1575. }
  1576. UpdateRecentFiles();
  1577. }
  1578. void GMainWindow::UpdateRecentFiles() {
  1579. const int num_recent_files =
  1580. std::min(static_cast<int>(UISettings::values.recent_files.size()), max_recent_files_item);
  1581. for (int i = 0; i < num_recent_files; i++) {
  1582. const QString text = QStringLiteral("&%1. %2").arg(i + 1).arg(
  1583. QFileInfo(UISettings::values.recent_files[i]).fileName());
  1584. actions_recent_files[i]->setText(text);
  1585. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  1586. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  1587. actions_recent_files[i]->setVisible(true);
  1588. }
  1589. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  1590. actions_recent_files[j]->setVisible(false);
  1591. }
  1592. // Enable the recent files menu if the list isn't empty
  1593. ui->menu_recent_files->setEnabled(num_recent_files != 0);
  1594. }
  1595. void GMainWindow::OnGameListLoadFile(QString game_path, u64 program_id) {
  1596. BootGame(game_path, program_id);
  1597. }
  1598. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target,
  1599. const std::string& game_path) {
  1600. std::filesystem::path path;
  1601. QString open_target;
  1602. const auto [user_save_size, device_save_size] = [this, &game_path, &program_id] {
  1603. const FileSys::PatchManager pm{program_id, system->GetFileSystemController(),
  1604. system->GetContentProvider()};
  1605. const auto control = pm.GetControlMetadata().first;
  1606. if (control != nullptr) {
  1607. return std::make_pair(control->GetDefaultNormalSaveSize(),
  1608. control->GetDeviceSaveDataSize());
  1609. } else {
  1610. const auto file = Core::GetGameFileFromPath(vfs, game_path);
  1611. const auto loader = Loader::GetLoader(*system, file);
  1612. FileSys::NACP nacp{};
  1613. loader->ReadControlData(nacp);
  1614. return std::make_pair(nacp.GetDefaultNormalSaveSize(), nacp.GetDeviceSaveDataSize());
  1615. }
  1616. }();
  1617. const bool has_user_save{user_save_size > 0};
  1618. const bool has_device_save{device_save_size > 0};
  1619. ASSERT_MSG(has_user_save != has_device_save, "Game uses both user and device savedata?");
  1620. switch (target) {
  1621. case GameListOpenTarget::SaveData: {
  1622. open_target = tr("Save Data");
  1623. const auto nand_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir);
  1624. auto vfs_nand_dir =
  1625. vfs->OpenDirectory(Common::FS::PathToUTF8String(nand_dir), FileSys::Mode::Read);
  1626. if (has_user_save) {
  1627. // User save data
  1628. const auto select_profile = [this] {
  1629. QtProfileSelectionDialog dialog(system->HIDCore(), this);
  1630. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1631. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1632. dialog.setWindowModality(Qt::WindowModal);
  1633. if (dialog.exec() == QDialog::Rejected) {
  1634. return -1;
  1635. }
  1636. return dialog.GetIndex();
  1637. };
  1638. const auto index = select_profile();
  1639. if (index == -1) {
  1640. return;
  1641. }
  1642. Service::Account::ProfileManager manager;
  1643. const auto user_id = manager.GetUser(static_cast<std::size_t>(index));
  1644. ASSERT(user_id);
  1645. const auto user_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1646. *system, vfs_nand_dir, FileSys::SaveDataSpaceId::NandUser,
  1647. FileSys::SaveDataType::SaveData, program_id, user_id->AsU128(), 0);
  1648. path = Common::FS::ConcatPathSafe(nand_dir, user_save_data_path);
  1649. } else {
  1650. // Device save data
  1651. const auto device_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1652. *system, vfs_nand_dir, FileSys::SaveDataSpaceId::NandUser,
  1653. FileSys::SaveDataType::SaveData, program_id, {}, 0);
  1654. path = Common::FS::ConcatPathSafe(nand_dir, device_save_data_path);
  1655. }
  1656. if (!Common::FS::CreateDirs(path)) {
  1657. LOG_ERROR(Frontend, "Unable to create the directories for save data");
  1658. }
  1659. break;
  1660. }
  1661. case GameListOpenTarget::ModData: {
  1662. open_target = tr("Mod Data");
  1663. path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::LoadDir) /
  1664. fmt::format("{:016X}", program_id);
  1665. break;
  1666. }
  1667. default:
  1668. UNIMPLEMENTED();
  1669. break;
  1670. }
  1671. const QString qpath = QString::fromStdString(Common::FS::PathToUTF8String(path));
  1672. const QDir dir(qpath);
  1673. if (!dir.exists()) {
  1674. QMessageBox::warning(this, tr("Error Opening %1 Folder").arg(open_target),
  1675. tr("Folder does not exist!"));
  1676. return;
  1677. }
  1678. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target.toStdString(),
  1679. program_id);
  1680. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  1681. }
  1682. void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
  1683. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1684. const auto shader_cache_folder_path{shader_cache_dir / fmt::format("{:016x}", program_id)};
  1685. if (!Common::FS::CreateDirs(shader_cache_folder_path)) {
  1686. QMessageBox::warning(this, tr("Error Opening Transferable Shader Cache"),
  1687. tr("Failed to create the shader cache directory for this title."));
  1688. return;
  1689. }
  1690. const auto shader_path_string{Common::FS::PathToUTF8String(shader_cache_folder_path)};
  1691. const auto qt_shader_cache_path = QString::fromStdString(shader_path_string);
  1692. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_shader_cache_path));
  1693. }
  1694. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  1695. std::size_t out = 0;
  1696. for (const auto& subdir : dir->GetSubdirectories()) {
  1697. out += 1 + CalculateRomFSEntrySize(subdir, full);
  1698. }
  1699. return out + (full ? dir->GetFiles().size() : 0);
  1700. }
  1701. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  1702. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  1703. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  1704. return false;
  1705. if (dialog.wasCanceled())
  1706. return false;
  1707. if (full) {
  1708. for (const auto& file : src->GetFiles()) {
  1709. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  1710. if (!FileSys::VfsRawCopy(file, out, block_size))
  1711. return false;
  1712. dialog.setValue(dialog.value() + 1);
  1713. if (dialog.wasCanceled())
  1714. return false;
  1715. }
  1716. }
  1717. for (const auto& dir : src->GetSubdirectories()) {
  1718. const auto out = dest->CreateSubdirectory(dir->GetName());
  1719. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  1720. return false;
  1721. dialog.setValue(dialog.value() + 1);
  1722. if (dialog.wasCanceled())
  1723. return false;
  1724. }
  1725. return true;
  1726. }
  1727. QString GMainWindow::GetGameListErrorRemoving(InstalledEntryType type) const {
  1728. switch (type) {
  1729. case InstalledEntryType::Game:
  1730. return tr("Error Removing Contents");
  1731. case InstalledEntryType::Update:
  1732. return tr("Error Removing Update");
  1733. case InstalledEntryType::AddOnContent:
  1734. return tr("Error Removing DLC");
  1735. default:
  1736. return QStringLiteral("Error Removing <Invalid Type>");
  1737. }
  1738. }
  1739. void GMainWindow::OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type) {
  1740. const QString entry_question = [type] {
  1741. switch (type) {
  1742. case InstalledEntryType::Game:
  1743. return tr("Remove Installed Game Contents?");
  1744. case InstalledEntryType::Update:
  1745. return tr("Remove Installed Game Update?");
  1746. case InstalledEntryType::AddOnContent:
  1747. return tr("Remove Installed Game DLC?");
  1748. default:
  1749. return QStringLiteral("Remove Installed Game <Invalid Type>?");
  1750. }
  1751. }();
  1752. if (QMessageBox::question(this, tr("Remove Entry"), entry_question,
  1753. QMessageBox::Yes | QMessageBox::No,
  1754. QMessageBox::No) != QMessageBox::Yes) {
  1755. return;
  1756. }
  1757. switch (type) {
  1758. case InstalledEntryType::Game:
  1759. RemoveBaseContent(program_id, type);
  1760. [[fallthrough]];
  1761. case InstalledEntryType::Update:
  1762. RemoveUpdateContent(program_id, type);
  1763. if (type != InstalledEntryType::Game) {
  1764. break;
  1765. }
  1766. [[fallthrough]];
  1767. case InstalledEntryType::AddOnContent:
  1768. RemoveAddOnContent(program_id, type);
  1769. break;
  1770. }
  1771. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  1772. "game_list");
  1773. game_list->PopulateAsync(UISettings::values.game_dirs);
  1774. }
  1775. void GMainWindow::RemoveBaseContent(u64 program_id, InstalledEntryType type) {
  1776. const auto& fs_controller = system->GetFileSystemController();
  1777. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(program_id) ||
  1778. fs_controller.GetSDMCContents()->RemoveExistingEntry(program_id);
  1779. if (res) {
  1780. QMessageBox::information(this, tr("Successfully Removed"),
  1781. tr("Successfully removed the installed base game."));
  1782. } else {
  1783. QMessageBox::warning(
  1784. this, GetGameListErrorRemoving(type),
  1785. tr("The base game is not installed in the NAND and cannot be removed."));
  1786. }
  1787. }
  1788. void GMainWindow::RemoveUpdateContent(u64 program_id, InstalledEntryType type) {
  1789. const auto update_id = program_id | 0x800;
  1790. const auto& fs_controller = system->GetFileSystemController();
  1791. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(update_id) ||
  1792. fs_controller.GetSDMCContents()->RemoveExistingEntry(update_id);
  1793. if (res) {
  1794. QMessageBox::information(this, tr("Successfully Removed"),
  1795. tr("Successfully removed the installed update."));
  1796. } else {
  1797. QMessageBox::warning(this, GetGameListErrorRemoving(type),
  1798. tr("There is no update installed for this title."));
  1799. }
  1800. }
  1801. void GMainWindow::RemoveAddOnContent(u64 program_id, InstalledEntryType type) {
  1802. u32 count{};
  1803. const auto& fs_controller = system->GetFileSystemController();
  1804. const auto dlc_entries = system->GetContentProvider().ListEntriesFilter(
  1805. FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1806. for (const auto& entry : dlc_entries) {
  1807. if (FileSys::GetBaseTitleID(entry.title_id) == program_id) {
  1808. const auto res =
  1809. fs_controller.GetUserNANDContents()->RemoveExistingEntry(entry.title_id) ||
  1810. fs_controller.GetSDMCContents()->RemoveExistingEntry(entry.title_id);
  1811. if (res) {
  1812. ++count;
  1813. }
  1814. }
  1815. }
  1816. if (count == 0) {
  1817. QMessageBox::warning(this, GetGameListErrorRemoving(type),
  1818. tr("There are no DLC installed for this title."));
  1819. return;
  1820. }
  1821. QMessageBox::information(this, tr("Successfully Removed"),
  1822. tr("Successfully removed %1 installed DLC.").arg(count));
  1823. }
  1824. void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target,
  1825. const std::string& game_path) {
  1826. const QString question = [target] {
  1827. switch (target) {
  1828. case GameListRemoveTarget::GlShaderCache:
  1829. return tr("Delete OpenGL Transferable Shader Cache?");
  1830. case GameListRemoveTarget::VkShaderCache:
  1831. return tr("Delete Vulkan Transferable Shader Cache?");
  1832. case GameListRemoveTarget::AllShaderCache:
  1833. return tr("Delete All Transferable Shader Caches?");
  1834. case GameListRemoveTarget::CustomConfiguration:
  1835. return tr("Remove Custom Game Configuration?");
  1836. default:
  1837. return QString{};
  1838. }
  1839. }();
  1840. if (QMessageBox::question(this, tr("Remove File"), question, QMessageBox::Yes | QMessageBox::No,
  1841. QMessageBox::No) != QMessageBox::Yes) {
  1842. return;
  1843. }
  1844. switch (target) {
  1845. case GameListRemoveTarget::GlShaderCache:
  1846. case GameListRemoveTarget::VkShaderCache:
  1847. RemoveTransferableShaderCache(program_id, target);
  1848. break;
  1849. case GameListRemoveTarget::AllShaderCache:
  1850. RemoveAllTransferableShaderCaches(program_id);
  1851. break;
  1852. case GameListRemoveTarget::CustomConfiguration:
  1853. RemoveCustomConfiguration(program_id, game_path);
  1854. break;
  1855. }
  1856. }
  1857. void GMainWindow::RemoveTransferableShaderCache(u64 program_id, GameListRemoveTarget target) {
  1858. const auto target_file_name = [target] {
  1859. switch (target) {
  1860. case GameListRemoveTarget::GlShaderCache:
  1861. return "opengl.bin";
  1862. case GameListRemoveTarget::VkShaderCache:
  1863. return "vulkan.bin";
  1864. default:
  1865. return "";
  1866. }
  1867. }();
  1868. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1869. const auto shader_cache_folder_path = shader_cache_dir / fmt::format("{:016x}", program_id);
  1870. const auto target_file = shader_cache_folder_path / target_file_name;
  1871. if (!Common::FS::Exists(target_file)) {
  1872. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1873. tr("A shader cache for this title does not exist."));
  1874. return;
  1875. }
  1876. if (Common::FS::RemoveFile(target_file)) {
  1877. QMessageBox::information(this, tr("Successfully Removed"),
  1878. tr("Successfully removed the transferable shader cache."));
  1879. } else {
  1880. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1881. tr("Failed to remove the transferable shader cache."));
  1882. }
  1883. }
  1884. void GMainWindow::RemoveAllTransferableShaderCaches(u64 program_id) {
  1885. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1886. const auto program_shader_cache_dir = shader_cache_dir / fmt::format("{:016x}", program_id);
  1887. if (!Common::FS::Exists(program_shader_cache_dir)) {
  1888. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  1889. tr("A shader cache for this title does not exist."));
  1890. return;
  1891. }
  1892. if (Common::FS::RemoveDirRecursively(program_shader_cache_dir)) {
  1893. QMessageBox::information(this, tr("Successfully Removed"),
  1894. tr("Successfully removed the transferable shader caches."));
  1895. } else {
  1896. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  1897. tr("Failed to remove the transferable shader cache directory."));
  1898. }
  1899. }
  1900. void GMainWindow::RemoveCustomConfiguration(u64 program_id, const std::string& game_path) {
  1901. const auto file_path = std::filesystem::path(Common::FS::ToU8String(game_path));
  1902. const auto config_file_name =
  1903. program_id == 0 ? Common::FS::PathToUTF8String(file_path.filename()).append(".ini")
  1904. : fmt::format("{:016X}.ini", program_id);
  1905. const auto custom_config_file_path =
  1906. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom" / config_file_name;
  1907. if (!Common::FS::Exists(custom_config_file_path)) {
  1908. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1909. tr("A custom configuration for this title does not exist."));
  1910. return;
  1911. }
  1912. if (Common::FS::RemoveFile(custom_config_file_path)) {
  1913. QMessageBox::information(this, tr("Successfully Removed"),
  1914. tr("Successfully removed the custom game configuration."));
  1915. } else {
  1916. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1917. tr("Failed to remove the custom game configuration."));
  1918. }
  1919. }
  1920. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path,
  1921. DumpRomFSTarget target) {
  1922. const auto failed = [this] {
  1923. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1924. tr("There was an error copying the RomFS files or the user "
  1925. "cancelled the operation."));
  1926. };
  1927. const auto loader = Loader::GetLoader(*system, vfs->OpenFile(game_path, FileSys::Mode::Read));
  1928. if (loader == nullptr) {
  1929. failed();
  1930. return;
  1931. }
  1932. FileSys::VirtualFile file;
  1933. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  1934. failed();
  1935. return;
  1936. }
  1937. const auto& installed = system->GetContentProvider();
  1938. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  1939. if (!romfs_title_id) {
  1940. failed();
  1941. return;
  1942. }
  1943. const auto dump_dir =
  1944. target == DumpRomFSTarget::Normal
  1945. ? Common::FS::GetYuzuPath(Common::FS::YuzuPath::DumpDir)
  1946. : Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "atmosphere" / "contents";
  1947. const auto romfs_dir = fmt::format("{:016X}/romfs", *romfs_title_id);
  1948. const auto path = Common::FS::PathToUTF8String(dump_dir / romfs_dir);
  1949. FileSys::VirtualFile romfs;
  1950. if (*romfs_title_id == program_id) {
  1951. const u64 ivfc_offset = loader->ReadRomFSIVFCOffset();
  1952. const FileSys::PatchManager pm{program_id, system->GetFileSystemController(), installed};
  1953. romfs =
  1954. pm.PatchRomFS(file, ivfc_offset, FileSys::ContentRecordType::Program, nullptr, false);
  1955. } else {
  1956. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  1957. }
  1958. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  1959. if (extracted == nullptr) {
  1960. failed();
  1961. return;
  1962. }
  1963. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  1964. if (out == nullptr) {
  1965. failed();
  1966. vfs->DeleteDirectory(path);
  1967. return;
  1968. }
  1969. bool ok = false;
  1970. const QStringList selections{tr("Full"), tr("Skeleton")};
  1971. const auto res = QInputDialog::getItem(
  1972. this, tr("Select RomFS Dump Mode"),
  1973. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  1974. "files into the new directory while <br>skeleton will only create the directory "
  1975. "structure."),
  1976. selections, 0, false, &ok);
  1977. if (!ok) {
  1978. failed();
  1979. vfs->DeleteDirectory(path);
  1980. return;
  1981. }
  1982. const auto full = res == selections.constFirst();
  1983. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  1984. // The minimum required space is the size of the extracted RomFS + 1 GiB
  1985. const auto minimum_free_space = extracted->GetSize() + 0x40000000;
  1986. if (full && Common::FS::GetFreeSpaceSize(path) < minimum_free_space) {
  1987. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1988. tr("There is not enough free space at %1 to extract the RomFS. Please "
  1989. "free up space or select a different dump directory at "
  1990. "Emulation > Configure > System > Filesystem > Dump Root")
  1991. .arg(QString::fromStdString(path)));
  1992. return;
  1993. }
  1994. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  1995. static_cast<s32>(entry_size), this);
  1996. progress.setWindowModality(Qt::WindowModal);
  1997. progress.setMinimumDuration(100);
  1998. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  1999. progress.close();
  2000. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  2001. tr("The operation completed successfully."));
  2002. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  2003. } else {
  2004. progress.close();
  2005. failed();
  2006. vfs->DeleteDirectory(path);
  2007. }
  2008. }
  2009. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  2010. QClipboard* clipboard = QGuiApplication::clipboard();
  2011. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  2012. }
  2013. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  2014. const CompatibilityList& compatibility_list) {
  2015. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  2016. QString directory;
  2017. if (it != compatibility_list.end()) {
  2018. directory = it->second.second;
  2019. }
  2020. QDesktopServices::openUrl(QUrl(QStringLiteral("https://yuzu-emu.org/game/") + directory));
  2021. }
  2022. void GMainWindow::OnGameListOpenDirectory(const QString& directory) {
  2023. std::filesystem::path fs_path;
  2024. if (directory == QStringLiteral("SDMC")) {
  2025. fs_path =
  2026. Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "Nintendo/Contents/registered";
  2027. } else if (directory == QStringLiteral("UserNAND")) {
  2028. fs_path =
  2029. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "user/Contents/registered";
  2030. } else if (directory == QStringLiteral("SysNAND")) {
  2031. fs_path =
  2032. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "system/Contents/registered";
  2033. } else {
  2034. fs_path = directory.toStdString();
  2035. }
  2036. const auto qt_path = QString::fromStdString(Common::FS::PathToUTF8String(fs_path));
  2037. if (!Common::FS::IsDir(fs_path)) {
  2038. QMessageBox::critical(this, tr("Error Opening %1").arg(qt_path),
  2039. tr("Folder does not exist!"));
  2040. return;
  2041. }
  2042. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_path));
  2043. }
  2044. void GMainWindow::OnGameListAddDirectory() {
  2045. const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  2046. if (dir_path.isEmpty()) {
  2047. return;
  2048. }
  2049. UISettings::GameDir game_dir{dir_path, false, true};
  2050. if (!UISettings::values.game_dirs.contains(game_dir)) {
  2051. UISettings::values.game_dirs.append(game_dir);
  2052. game_list->PopulateAsync(UISettings::values.game_dirs);
  2053. } else {
  2054. LOG_WARNING(Frontend, "Selected directory is already in the game list");
  2055. }
  2056. }
  2057. void GMainWindow::OnGameListShowList(bool show) {
  2058. if (emulation_running && ui->action_Single_Window_Mode->isChecked())
  2059. return;
  2060. game_list->setVisible(show);
  2061. game_list_placeholder->setVisible(!show);
  2062. };
  2063. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  2064. u64 title_id{};
  2065. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  2066. const auto loader = Loader::GetLoader(*system, v_file);
  2067. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  2068. QMessageBox::information(this, tr("Properties"),
  2069. tr("The game properties could not be loaded."));
  2070. return;
  2071. }
  2072. OpenPerGameConfiguration(title_id, file);
  2073. }
  2074. void GMainWindow::OnMenuLoadFile() {
  2075. if (is_load_file_select_active) {
  2076. return;
  2077. }
  2078. is_load_file_select_active = true;
  2079. const QString extensions =
  2080. QStringLiteral("*.")
  2081. .append(GameList::supported_file_extensions.join(QStringLiteral(" *.")))
  2082. .append(QStringLiteral(" main"));
  2083. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  2084. "%1 is an identifier for the Switch executable file extensions.")
  2085. .arg(extensions);
  2086. const QString filename = QFileDialog::getOpenFileName(
  2087. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  2088. is_load_file_select_active = false;
  2089. if (filename.isEmpty()) {
  2090. return;
  2091. }
  2092. UISettings::values.roms_path = QFileInfo(filename).path();
  2093. BootGame(filename);
  2094. }
  2095. void GMainWindow::OnMenuLoadFolder() {
  2096. const QString dir_path =
  2097. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  2098. if (dir_path.isNull()) {
  2099. return;
  2100. }
  2101. const QDir dir{dir_path};
  2102. const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files);
  2103. if (matching_main.size() == 1) {
  2104. BootGame(dir.path() + QDir::separator() + matching_main[0]);
  2105. } else {
  2106. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  2107. tr("The directory you have selected does not contain a 'main' file."));
  2108. }
  2109. }
  2110. void GMainWindow::IncrementInstallProgress() {
  2111. install_progress->setValue(install_progress->value() + 1);
  2112. }
  2113. void GMainWindow::OnMenuInstallToNAND() {
  2114. const QString file_filter =
  2115. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  2116. "(*.nca);;Nintendo Submission Package (*.nsp);;NX Cartridge "
  2117. "Image (*.xci)");
  2118. QStringList filenames = QFileDialog::getOpenFileNames(
  2119. this, tr("Install Files"), UISettings::values.roms_path, file_filter);
  2120. if (filenames.isEmpty()) {
  2121. return;
  2122. }
  2123. InstallDialog installDialog(this, filenames);
  2124. if (installDialog.exec() == QDialog::Rejected) {
  2125. return;
  2126. }
  2127. const QStringList files = installDialog.GetFiles();
  2128. if (files.isEmpty()) {
  2129. return;
  2130. }
  2131. int remaining = filenames.size();
  2132. // This would only overflow above 2^43 bytes (8.796 TB)
  2133. int total_size = 0;
  2134. for (const QString& file : files) {
  2135. total_size += static_cast<int>(QFile(file).size() / 0x1000);
  2136. }
  2137. if (total_size < 0) {
  2138. LOG_CRITICAL(Frontend, "Attempting to install too many files, aborting.");
  2139. return;
  2140. }
  2141. QStringList new_files{}; // Newly installed files that do not yet exist in the NAND
  2142. QStringList overwritten_files{}; // Files that overwrote those existing in the NAND
  2143. QStringList failed_files{}; // Files that failed to install due to errors
  2144. bool detected_base_install{}; // Whether a base game was attempted to be installed
  2145. ui->action_Install_File_NAND->setEnabled(false);
  2146. install_progress = new QProgressDialog(QString{}, tr("Cancel"), 0, total_size, this);
  2147. install_progress->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint &
  2148. ~Qt::WindowMaximizeButtonHint);
  2149. install_progress->setAttribute(Qt::WA_DeleteOnClose, true);
  2150. install_progress->setFixedWidth(installDialog.GetMinimumWidth() + 40);
  2151. install_progress->show();
  2152. for (const QString& file : files) {
  2153. install_progress->setWindowTitle(tr("%n file(s) remaining", "", remaining));
  2154. install_progress->setLabelText(
  2155. tr("Installing file \"%1\"...").arg(QFileInfo(file).fileName()));
  2156. QFuture<InstallResult> future;
  2157. InstallResult result;
  2158. if (file.endsWith(QStringLiteral("xci"), Qt::CaseInsensitive) ||
  2159. file.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  2160. future = QtConcurrent::run([this, &file] { return InstallNSPXCI(file); });
  2161. while (!future.isFinished()) {
  2162. QCoreApplication::processEvents();
  2163. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2164. }
  2165. result = future.result();
  2166. } else {
  2167. result = InstallNCA(file);
  2168. }
  2169. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2170. switch (result) {
  2171. case InstallResult::Success:
  2172. new_files.append(QFileInfo(file).fileName());
  2173. break;
  2174. case InstallResult::Overwrite:
  2175. overwritten_files.append(QFileInfo(file).fileName());
  2176. break;
  2177. case InstallResult::Failure:
  2178. failed_files.append(QFileInfo(file).fileName());
  2179. break;
  2180. case InstallResult::BaseInstallAttempted:
  2181. failed_files.append(QFileInfo(file).fileName());
  2182. detected_base_install = true;
  2183. break;
  2184. }
  2185. --remaining;
  2186. }
  2187. install_progress->close();
  2188. if (detected_base_install) {
  2189. QMessageBox::warning(
  2190. this, tr("Install Results"),
  2191. tr("To avoid possible conflicts, we discourage users from installing base games to the "
  2192. "NAND.\nPlease, only use this feature to install updates and DLC."));
  2193. }
  2194. const QString install_results =
  2195. (new_files.isEmpty() ? QString{}
  2196. : tr("%n file(s) were newly installed\n", "", new_files.size())) +
  2197. (overwritten_files.isEmpty()
  2198. ? QString{}
  2199. : tr("%n file(s) were overwritten\n", "", overwritten_files.size())) +
  2200. (failed_files.isEmpty() ? QString{}
  2201. : tr("%n file(s) failed to install\n", "", failed_files.size()));
  2202. QMessageBox::information(this, tr("Install Results"), install_results);
  2203. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  2204. "game_list");
  2205. game_list->PopulateAsync(UISettings::values.game_dirs);
  2206. ui->action_Install_File_NAND->setEnabled(true);
  2207. }
  2208. InstallResult GMainWindow::InstallNSPXCI(const QString& filename) {
  2209. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  2210. const FileSys::VirtualFile& dest, std::size_t block_size) {
  2211. if (src == nullptr || dest == nullptr) {
  2212. return false;
  2213. }
  2214. if (!dest->Resize(src->GetSize())) {
  2215. return false;
  2216. }
  2217. std::array<u8, 0x1000> buffer{};
  2218. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  2219. if (install_progress->wasCanceled()) {
  2220. dest->Resize(0);
  2221. return false;
  2222. }
  2223. emit UpdateInstallProgress();
  2224. const auto read = src->Read(buffer.data(), buffer.size(), i);
  2225. dest->Write(buffer.data(), read, i);
  2226. }
  2227. return true;
  2228. };
  2229. std::shared_ptr<FileSys::NSP> nsp;
  2230. if (filename.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  2231. nsp = std::make_shared<FileSys::NSP>(
  2232. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  2233. if (nsp->IsExtractedType()) {
  2234. return InstallResult::Failure;
  2235. }
  2236. } else {
  2237. const auto xci = std::make_shared<FileSys::XCI>(
  2238. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  2239. nsp = xci->GetSecurePartitionNSP();
  2240. }
  2241. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  2242. return InstallResult::Failure;
  2243. }
  2244. const auto res = system->GetFileSystemController().GetUserNANDContents()->InstallEntry(
  2245. *nsp, true, qt_raw_copy);
  2246. switch (res) {
  2247. case FileSys::InstallResult::Success:
  2248. return InstallResult::Success;
  2249. case FileSys::InstallResult::OverwriteExisting:
  2250. return InstallResult::Overwrite;
  2251. case FileSys::InstallResult::ErrorBaseInstall:
  2252. return InstallResult::BaseInstallAttempted;
  2253. default:
  2254. return InstallResult::Failure;
  2255. }
  2256. }
  2257. InstallResult GMainWindow::InstallNCA(const QString& filename) {
  2258. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  2259. const FileSys::VirtualFile& dest, std::size_t block_size) {
  2260. if (src == nullptr || dest == nullptr) {
  2261. return false;
  2262. }
  2263. if (!dest->Resize(src->GetSize())) {
  2264. return false;
  2265. }
  2266. std::array<u8, 0x1000> buffer{};
  2267. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  2268. if (install_progress->wasCanceled()) {
  2269. dest->Resize(0);
  2270. return false;
  2271. }
  2272. emit UpdateInstallProgress();
  2273. const auto read = src->Read(buffer.data(), buffer.size(), i);
  2274. dest->Write(buffer.data(), read, i);
  2275. }
  2276. return true;
  2277. };
  2278. const auto nca =
  2279. std::make_shared<FileSys::NCA>(vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  2280. const auto id = nca->GetStatus();
  2281. // Game updates necessary are missing base RomFS
  2282. if (id != Loader::ResultStatus::Success &&
  2283. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  2284. return InstallResult::Failure;
  2285. }
  2286. const QStringList tt_options{tr("System Application"),
  2287. tr("System Archive"),
  2288. tr("System Application Update"),
  2289. tr("Firmware Package (Type A)"),
  2290. tr("Firmware Package (Type B)"),
  2291. tr("Game"),
  2292. tr("Game Update"),
  2293. tr("Game DLC"),
  2294. tr("Delta Title")};
  2295. bool ok;
  2296. const auto item = QInputDialog::getItem(
  2297. this, tr("Select NCA Install Type..."),
  2298. tr("Please select the type of title you would like to install this NCA as:\n(In "
  2299. "most instances, the default 'Game' is fine.)"),
  2300. tt_options, 5, false, &ok);
  2301. auto index = tt_options.indexOf(item);
  2302. if (!ok || index == -1) {
  2303. QMessageBox::warning(this, tr("Failed to Install"),
  2304. tr("The title type you selected for the NCA is invalid."));
  2305. return InstallResult::Failure;
  2306. }
  2307. // If index is equal to or past Game, add the jump in TitleType.
  2308. if (index >= 5) {
  2309. index += static_cast<size_t>(FileSys::TitleType::Application) -
  2310. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  2311. }
  2312. const bool is_application = index >= static_cast<s32>(FileSys::TitleType::Application);
  2313. const auto& fs_controller = system->GetFileSystemController();
  2314. auto* registered_cache = is_application ? fs_controller.GetUserNANDContents()
  2315. : fs_controller.GetSystemNANDContents();
  2316. const auto res = registered_cache->InstallEntry(*nca, static_cast<FileSys::TitleType>(index),
  2317. true, qt_raw_copy);
  2318. if (res == FileSys::InstallResult::Success) {
  2319. return InstallResult::Success;
  2320. } else if (res == FileSys::InstallResult::OverwriteExisting) {
  2321. return InstallResult::Overwrite;
  2322. } else {
  2323. return InstallResult::Failure;
  2324. }
  2325. }
  2326. void GMainWindow::OnMenuRecentFile() {
  2327. QAction* action = qobject_cast<QAction*>(sender());
  2328. assert(action);
  2329. const QString filename = action->data().toString();
  2330. if (QFileInfo::exists(filename)) {
  2331. BootGame(filename);
  2332. } else {
  2333. // Display an error message and remove the file from the list.
  2334. QMessageBox::information(this, tr("File not found"),
  2335. tr("File \"%1\" not found").arg(filename));
  2336. UISettings::values.recent_files.removeOne(filename);
  2337. UpdateRecentFiles();
  2338. }
  2339. }
  2340. void GMainWindow::OnStartGame() {
  2341. PreventOSSleep();
  2342. emu_thread->SetRunning(true);
  2343. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  2344. UpdateMenuState();
  2345. OnTasStateChanged();
  2346. discord_rpc->Update();
  2347. }
  2348. void GMainWindow::OnRestartGame() {
  2349. if (!system->IsPoweredOn()) {
  2350. return;
  2351. }
  2352. // Make a copy since BootGame edits game_path
  2353. BootGame(QString(current_game_path));
  2354. }
  2355. void GMainWindow::OnPauseGame() {
  2356. emu_thread->SetRunning(false);
  2357. UpdateMenuState();
  2358. AllowOSSleep();
  2359. }
  2360. void GMainWindow::OnPauseContinueGame() {
  2361. if (emulation_running) {
  2362. if (emu_thread->IsRunning()) {
  2363. OnPauseGame();
  2364. } else {
  2365. RequestGameResume();
  2366. OnStartGame();
  2367. }
  2368. }
  2369. }
  2370. void GMainWindow::OnStopGame() {
  2371. if (system->GetExitLock() && !ConfirmForceLockedExit()) {
  2372. return;
  2373. }
  2374. ShutdownGame();
  2375. Settings::RestoreGlobalState(system->IsPoweredOn());
  2376. UpdateStatusButtons();
  2377. }
  2378. void GMainWindow::OnLoadComplete() {
  2379. loading_screen->OnLoadComplete();
  2380. }
  2381. void GMainWindow::OnExecuteProgram(std::size_t program_index) {
  2382. ShutdownGame();
  2383. BootGame(last_filename_booted, 0, program_index);
  2384. }
  2385. void GMainWindow::OnExit() {
  2386. OnStopGame();
  2387. }
  2388. void GMainWindow::OnSaveConfig() {
  2389. system->ApplySettings();
  2390. config->Save();
  2391. }
  2392. void GMainWindow::ErrorDisplayDisplayError(QString error_code, QString error_text) {
  2393. OverlayDialog dialog(render_window, *system, error_code, error_text, QString{}, tr("OK"),
  2394. Qt::AlignLeft | Qt::AlignVCenter);
  2395. dialog.exec();
  2396. emit ErrorDisplayFinished();
  2397. }
  2398. void GMainWindow::OnMenuReportCompatibility() {
  2399. const auto& caps = Common::GetCPUCaps();
  2400. const bool has_fma = caps.fma || caps.fma4;
  2401. const auto processor_count = std::thread::hardware_concurrency();
  2402. const bool has_4threads = processor_count == 0 || processor_count >= 4;
  2403. const bool has_8gb_ram = Common::GetMemInfo().TotalPhysicalMemory >= 8_GiB;
  2404. const bool has_broken_vulkan = UISettings::values.has_broken_vulkan;
  2405. if (!has_fma || !has_4threads || !has_8gb_ram || has_broken_vulkan) {
  2406. QMessageBox::critical(this, tr("Hardware requirements not met"),
  2407. tr("Your system does not meet the recommended hardware requirements. "
  2408. "Compatibility reporting has been disabled."));
  2409. return;
  2410. }
  2411. if (!Settings::values.yuzu_token.GetValue().empty() &&
  2412. !Settings::values.yuzu_username.GetValue().empty()) {
  2413. CompatDB compatdb{system->TelemetrySession(), this};
  2414. compatdb.exec();
  2415. } else {
  2416. QMessageBox::critical(
  2417. this, tr("Missing yuzu Account"),
  2418. tr("In order to submit a game compatibility test case, you must link your yuzu "
  2419. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  2420. "&gt; "
  2421. "Web."));
  2422. }
  2423. }
  2424. void GMainWindow::OpenURL(const QUrl& url) {
  2425. const bool open = QDesktopServices::openUrl(url);
  2426. if (!open) {
  2427. QMessageBox::warning(this, tr("Error opening URL"),
  2428. tr("Unable to open the URL \"%1\".").arg(url.toString()));
  2429. }
  2430. }
  2431. void GMainWindow::OnOpenModsPage() {
  2432. OpenURL(QUrl(QStringLiteral("https://github.com/yuzu-emu/yuzu/wiki/Switch-Mods")));
  2433. }
  2434. void GMainWindow::OnOpenQuickstartGuide() {
  2435. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/help/quickstart/")));
  2436. }
  2437. void GMainWindow::OnOpenFAQ() {
  2438. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/wiki/faq/")));
  2439. }
  2440. void GMainWindow::ToggleFullscreen() {
  2441. if (!emulation_running) {
  2442. return;
  2443. }
  2444. if (ui->action_Fullscreen->isChecked()) {
  2445. ShowFullscreen();
  2446. } else {
  2447. HideFullscreen();
  2448. }
  2449. }
  2450. // We're going to return the screen that the given window has the most pixels on
  2451. static QScreen* GuessCurrentScreen(QWidget* window) {
  2452. const QList<QScreen*> screens = QGuiApplication::screens();
  2453. return *std::max_element(
  2454. screens.cbegin(), screens.cend(), [window](const QScreen* left, const QScreen* right) {
  2455. const QSize left_size = left->geometry().intersected(window->geometry()).size();
  2456. const QSize right_size = right->geometry().intersected(window->geometry()).size();
  2457. return (left_size.height() * left_size.width()) <
  2458. (right_size.height() * right_size.width());
  2459. });
  2460. }
  2461. void GMainWindow::ShowFullscreen() {
  2462. const auto show_fullscreen = [](QWidget* window) {
  2463. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2464. window->showFullScreen();
  2465. return;
  2466. }
  2467. window->hide();
  2468. window->setWindowFlags(window->windowFlags() | Qt::FramelessWindowHint);
  2469. const auto screen_geometry = GuessCurrentScreen(window)->geometry();
  2470. window->setGeometry(screen_geometry.x(), screen_geometry.y(), screen_geometry.width(),
  2471. screen_geometry.height() + 1);
  2472. window->raise();
  2473. window->showNormal();
  2474. };
  2475. if (ui->action_Single_Window_Mode->isChecked()) {
  2476. UISettings::values.geometry = saveGeometry();
  2477. ui->menubar->hide();
  2478. statusBar()->hide();
  2479. show_fullscreen(this);
  2480. } else {
  2481. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2482. show_fullscreen(render_window);
  2483. }
  2484. }
  2485. void GMainWindow::HideFullscreen() {
  2486. if (ui->action_Single_Window_Mode->isChecked()) {
  2487. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2488. showNormal();
  2489. restoreGeometry(UISettings::values.geometry);
  2490. } else {
  2491. hide();
  2492. setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2493. restoreGeometry(UISettings::values.geometry);
  2494. raise();
  2495. show();
  2496. }
  2497. statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
  2498. ui->menubar->show();
  2499. } else {
  2500. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2501. render_window->showNormal();
  2502. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2503. } else {
  2504. render_window->hide();
  2505. render_window->setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2506. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2507. render_window->raise();
  2508. render_window->show();
  2509. }
  2510. }
  2511. }
  2512. void GMainWindow::ToggleWindowMode() {
  2513. if (ui->action_Single_Window_Mode->isChecked()) {
  2514. // Render in the main window...
  2515. render_window->BackupGeometry();
  2516. ui->horizontalLayout->addWidget(render_window);
  2517. render_window->setFocusPolicy(Qt::StrongFocus);
  2518. if (emulation_running) {
  2519. render_window->setVisible(true);
  2520. render_window->setFocus();
  2521. game_list->hide();
  2522. }
  2523. } else {
  2524. // Render in a separate window...
  2525. ui->horizontalLayout->removeWidget(render_window);
  2526. render_window->setParent(nullptr);
  2527. render_window->setFocusPolicy(Qt::NoFocus);
  2528. if (emulation_running) {
  2529. render_window->setVisible(true);
  2530. render_window->RestoreGeometry();
  2531. game_list->show();
  2532. }
  2533. }
  2534. }
  2535. void GMainWindow::ResetWindowSize(u32 width, u32 height) {
  2536. const auto aspect_ratio = Layout::EmulationAspectRatio(
  2537. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  2538. static_cast<float>(height) / width);
  2539. if (!ui->action_Single_Window_Mode->isChecked()) {
  2540. render_window->resize(height / aspect_ratio, height);
  2541. } else {
  2542. const bool show_status_bar = ui->action_Show_Status_Bar->isChecked();
  2543. const auto status_bar_height = show_status_bar ? statusBar()->height() : 0;
  2544. resize(height / aspect_ratio, height + menuBar()->height() + status_bar_height);
  2545. }
  2546. }
  2547. void GMainWindow::ResetWindowSize720() {
  2548. ResetWindowSize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  2549. }
  2550. void GMainWindow::ResetWindowSize900() {
  2551. ResetWindowSize(1600U, 900U);
  2552. }
  2553. void GMainWindow::ResetWindowSize1080() {
  2554. ResetWindowSize(Layout::ScreenDocked::Width, Layout::ScreenDocked::Height);
  2555. }
  2556. void GMainWindow::OnConfigure() {
  2557. const auto old_theme = UISettings::values.theme;
  2558. const bool old_discord_presence = UISettings::values.enable_discord_presence.GetValue();
  2559. Settings::SetConfiguringGlobal(true);
  2560. ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get(), *system,
  2561. !multiplayer_state->IsHostingPublicRoom());
  2562. connect(&configure_dialog, &ConfigureDialog::LanguageChanged, this,
  2563. &GMainWindow::OnLanguageChanged);
  2564. const auto result = configure_dialog.exec();
  2565. if (result != QDialog::Accepted && !UISettings::values.configuration_applied &&
  2566. !UISettings::values.reset_to_defaults) {
  2567. // Runs if the user hit Cancel or closed the window, and did not ever press the Apply button
  2568. // or `Reset to Defaults` button
  2569. return;
  2570. } else if (result == QDialog::Accepted) {
  2571. // Only apply new changes if user hit Okay
  2572. // This is here to avoid applying changes if the user hit Apply, made some changes, then hit
  2573. // Cancel
  2574. configure_dialog.ApplyConfiguration();
  2575. } else if (UISettings::values.reset_to_defaults) {
  2576. LOG_INFO(Frontend, "Resetting all settings to defaults");
  2577. if (!Common::FS::RemoveFile(config->GetConfigFilePath())) {
  2578. LOG_WARNING(Frontend, "Failed to remove configuration file");
  2579. }
  2580. if (!Common::FS::RemoveDirContentsRecursively(
  2581. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom")) {
  2582. LOG_WARNING(Frontend, "Failed to remove custom configuration files");
  2583. }
  2584. if (!Common::FS::RemoveDirRecursively(
  2585. Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) / "game_list")) {
  2586. LOG_WARNING(Frontend, "Failed to remove game metadata cache files");
  2587. }
  2588. // Explicitly save the game directories, since reinitializing config does not explicitly do
  2589. // so.
  2590. QVector<UISettings::GameDir> old_game_dirs = std::move(UISettings::values.game_dirs);
  2591. QVector<u64> old_favorited_ids = std::move(UISettings::values.favorited_ids);
  2592. Settings::values.disabled_addons.clear();
  2593. config = std::make_unique<Config>();
  2594. UISettings::values.reset_to_defaults = false;
  2595. UISettings::values.game_dirs = std::move(old_game_dirs);
  2596. UISettings::values.favorited_ids = std::move(old_favorited_ids);
  2597. InitializeRecentFileMenuActions();
  2598. SetDefaultUIGeometry();
  2599. RestoreUIState();
  2600. ShowTelemetryCallout();
  2601. }
  2602. InitializeHotkeys();
  2603. if (UISettings::values.theme != old_theme) {
  2604. UpdateUITheme();
  2605. }
  2606. if (UISettings::values.enable_discord_presence.GetValue() != old_discord_presence) {
  2607. SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue());
  2608. }
  2609. if (!multiplayer_state->IsHostingPublicRoom()) {
  2610. multiplayer_state->UpdateCredentials();
  2611. }
  2612. emit UpdateThemedIcons();
  2613. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2614. if (reload) {
  2615. game_list->PopulateAsync(UISettings::values.game_dirs);
  2616. }
  2617. UISettings::values.configuration_applied = false;
  2618. config->Save();
  2619. if ((UISettings::values.hide_mouse || Settings::values.mouse_panning) && emulation_running) {
  2620. render_window->installEventFilter(render_window);
  2621. render_window->setAttribute(Qt::WA_Hover, true);
  2622. } else {
  2623. render_window->removeEventFilter(render_window);
  2624. render_window->setAttribute(Qt::WA_Hover, false);
  2625. }
  2626. if (UISettings::values.hide_mouse) {
  2627. mouse_hide_timer.start();
  2628. }
  2629. // Restart camera config
  2630. if (emulation_running) {
  2631. render_window->FinalizeCamera();
  2632. render_window->InitializeCamera();
  2633. }
  2634. if (!UISettings::values.has_broken_vulkan) {
  2635. renderer_status_button->setEnabled(!emulation_running);
  2636. }
  2637. UpdateStatusButtons();
  2638. controller_dialog->refreshConfiguration();
  2639. system->ApplySettings();
  2640. }
  2641. void GMainWindow::OnConfigureTas() {
  2642. ConfigureTasDialog dialog(this);
  2643. const auto result = dialog.exec();
  2644. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  2645. Settings::RestoreGlobalState(system->IsPoweredOn());
  2646. return;
  2647. } else if (result == QDialog::Accepted) {
  2648. dialog.ApplyConfiguration();
  2649. }
  2650. }
  2651. void GMainWindow::OnTasStartStop() {
  2652. if (!emulation_running) {
  2653. return;
  2654. }
  2655. // Disable system buttons to prevent TAS from executing a hotkey
  2656. auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  2657. controller->ResetSystemButtons();
  2658. input_subsystem->GetTas()->StartStop();
  2659. OnTasStateChanged();
  2660. }
  2661. void GMainWindow::OnTasRecord() {
  2662. if (!emulation_running) {
  2663. return;
  2664. }
  2665. if (is_tas_recording_dialog_active) {
  2666. return;
  2667. }
  2668. // Disable system buttons to prevent TAS from recording a hotkey
  2669. auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  2670. controller->ResetSystemButtons();
  2671. const bool is_recording = input_subsystem->GetTas()->Record();
  2672. if (!is_recording) {
  2673. is_tas_recording_dialog_active = true;
  2674. ControllerNavigation* controller_navigation =
  2675. new ControllerNavigation(system->HIDCore(), this);
  2676. // Use QMessageBox instead of question so we can link controller navigation
  2677. QMessageBox* box_dialog = new QMessageBox();
  2678. box_dialog->setWindowTitle(tr("TAS Recording"));
  2679. box_dialog->setText(tr("Overwrite file of player 1?"));
  2680. box_dialog->setStandardButtons(QMessageBox::Yes | QMessageBox::No);
  2681. box_dialog->setDefaultButton(QMessageBox::Yes);
  2682. connect(controller_navigation, &ControllerNavigation::TriggerKeyboardEvent,
  2683. [box_dialog](Qt::Key key) {
  2684. QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier);
  2685. QCoreApplication::postEvent(box_dialog, event);
  2686. });
  2687. int res = box_dialog->exec();
  2688. controller_navigation->UnloadController();
  2689. input_subsystem->GetTas()->SaveRecording(res == QMessageBox::Yes);
  2690. is_tas_recording_dialog_active = false;
  2691. }
  2692. OnTasStateChanged();
  2693. }
  2694. void GMainWindow::OnTasReset() {
  2695. input_subsystem->GetTas()->Reset();
  2696. }
  2697. void GMainWindow::OnToggleDockedMode() {
  2698. const bool is_docked = Settings::values.use_docked_mode.GetValue();
  2699. auto* player_1 = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  2700. auto* handheld = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld);
  2701. if (!is_docked && handheld->IsConnected()) {
  2702. QMessageBox::warning(this, tr("Invalid config detected"),
  2703. tr("Handheld controller can't be used on docked mode. Pro "
  2704. "controller will be selected."));
  2705. handheld->Disconnect();
  2706. player_1->SetNpadStyleIndex(Core::HID::NpadStyleIndex::ProController);
  2707. player_1->Connect();
  2708. controller_dialog->refreshConfiguration();
  2709. }
  2710. Settings::values.use_docked_mode.SetValue(!is_docked);
  2711. UpdateDockedButton();
  2712. OnDockedModeChanged(is_docked, !is_docked, *system);
  2713. }
  2714. void GMainWindow::OnToggleGpuAccuracy() {
  2715. switch (Settings::values.gpu_accuracy.GetValue()) {
  2716. case Settings::GPUAccuracy::High: {
  2717. Settings::values.gpu_accuracy.SetValue(Settings::GPUAccuracy::Normal);
  2718. break;
  2719. }
  2720. case Settings::GPUAccuracy::Normal:
  2721. case Settings::GPUAccuracy::Extreme:
  2722. default: {
  2723. Settings::values.gpu_accuracy.SetValue(Settings::GPUAccuracy::High);
  2724. break;
  2725. }
  2726. }
  2727. system->ApplySettings();
  2728. UpdateGPUAccuracyButton();
  2729. }
  2730. void GMainWindow::OnToggleAdaptingFilter() {
  2731. auto filter = Settings::values.scaling_filter.GetValue();
  2732. if (filter == Settings::ScalingFilter::LastFilter) {
  2733. filter = Settings::ScalingFilter::NearestNeighbor;
  2734. } else {
  2735. filter = static_cast<Settings::ScalingFilter>(static_cast<u32>(filter) + 1);
  2736. }
  2737. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL &&
  2738. filter == Settings::ScalingFilter::Fsr) {
  2739. filter = Settings::ScalingFilter::NearestNeighbor;
  2740. }
  2741. Settings::values.scaling_filter.SetValue(filter);
  2742. filter_status_button->setChecked(true);
  2743. UpdateFilterText();
  2744. }
  2745. void GMainWindow::OnConfigurePerGame() {
  2746. const u64 title_id = system->GetCurrentProcessProgramID();
  2747. OpenPerGameConfiguration(title_id, current_game_path.toStdString());
  2748. }
  2749. void GMainWindow::OpenPerGameConfiguration(u64 title_id, const std::string& file_name) {
  2750. const auto v_file = Core::GetGameFileFromPath(vfs, file_name);
  2751. Settings::SetConfiguringGlobal(false);
  2752. ConfigurePerGame dialog(this, title_id, file_name, *system);
  2753. dialog.LoadFromFile(v_file);
  2754. const auto result = dialog.exec();
  2755. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  2756. Settings::RestoreGlobalState(system->IsPoweredOn());
  2757. return;
  2758. } else if (result == QDialog::Accepted) {
  2759. dialog.ApplyConfiguration();
  2760. }
  2761. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2762. if (reload) {
  2763. game_list->PopulateAsync(UISettings::values.game_dirs);
  2764. }
  2765. // Do not cause the global config to write local settings into the config file
  2766. const bool is_powered_on = system->IsPoweredOn();
  2767. Settings::RestoreGlobalState(is_powered_on);
  2768. UISettings::values.configuration_applied = false;
  2769. if (!is_powered_on) {
  2770. config->Save();
  2771. }
  2772. }
  2773. void GMainWindow::OnLoadAmiibo() {
  2774. if (emu_thread == nullptr || !emu_thread->IsRunning()) {
  2775. return;
  2776. }
  2777. if (is_amiibo_file_select_active) {
  2778. return;
  2779. }
  2780. auto* virtual_amiibo = input_subsystem->GetVirtualAmiibo();
  2781. // Remove amiibo if one is connected
  2782. if (virtual_amiibo->GetCurrentState() == InputCommon::VirtualAmiibo::State::AmiiboIsOpen) {
  2783. virtual_amiibo->CloseAmiibo();
  2784. QMessageBox::warning(this, tr("Amiibo"), tr("The current amiibo has been removed"));
  2785. return;
  2786. }
  2787. if (virtual_amiibo->GetCurrentState() != InputCommon::VirtualAmiibo::State::WaitingForAmiibo) {
  2788. QMessageBox::warning(this, tr("Error"), tr("The current game is not looking for amiibos"));
  2789. return;
  2790. }
  2791. is_amiibo_file_select_active = true;
  2792. const QString extensions{QStringLiteral("*.bin")};
  2793. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  2794. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter);
  2795. is_amiibo_file_select_active = false;
  2796. if (filename.isEmpty()) {
  2797. return;
  2798. }
  2799. LoadAmiibo(filename);
  2800. }
  2801. void GMainWindow::LoadAmiibo(const QString& filename) {
  2802. auto* virtual_amiibo = input_subsystem->GetVirtualAmiibo();
  2803. const QString title = tr("Error loading Amiibo data");
  2804. // Remove amiibo if one is connected
  2805. if (virtual_amiibo->GetCurrentState() == InputCommon::VirtualAmiibo::State::AmiiboIsOpen) {
  2806. virtual_amiibo->CloseAmiibo();
  2807. QMessageBox::warning(this, tr("Amiibo"), tr("The current amiibo has been removed"));
  2808. return;
  2809. }
  2810. switch (virtual_amiibo->LoadAmiibo(filename.toStdString())) {
  2811. case InputCommon::VirtualAmiibo::Info::NotAnAmiibo:
  2812. QMessageBox::warning(this, title, tr("The selected file is not a valid amiibo"));
  2813. break;
  2814. case InputCommon::VirtualAmiibo::Info::UnableToLoad:
  2815. QMessageBox::warning(this, title, tr("The selected file is already on use"));
  2816. break;
  2817. case InputCommon::VirtualAmiibo::Info::WrongDeviceState:
  2818. QMessageBox::warning(this, title, tr("The current game is not looking for amiibos"));
  2819. break;
  2820. case InputCommon::VirtualAmiibo::Info::Unknown:
  2821. QMessageBox::warning(this, title, tr("An unknown error occurred"));
  2822. break;
  2823. default:
  2824. break;
  2825. }
  2826. }
  2827. void GMainWindow::OnOpenYuzuFolder() {
  2828. QDesktopServices::openUrl(QUrl::fromLocalFile(
  2829. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::YuzuDir))));
  2830. }
  2831. void GMainWindow::OnAbout() {
  2832. AboutDialog aboutDialog(this);
  2833. aboutDialog.exec();
  2834. }
  2835. void GMainWindow::OnToggleFilterBar() {
  2836. game_list->SetFilterVisible(ui->action_Show_Filter_Bar->isChecked());
  2837. if (ui->action_Show_Filter_Bar->isChecked()) {
  2838. game_list->SetFilterFocus();
  2839. } else {
  2840. game_list->ClearFilter();
  2841. }
  2842. }
  2843. void GMainWindow::OnToggleStatusBar() {
  2844. statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
  2845. }
  2846. void GMainWindow::OnCaptureScreenshot() {
  2847. if (emu_thread == nullptr || !emu_thread->IsRunning()) {
  2848. return;
  2849. }
  2850. const u64 title_id = system->GetCurrentProcessProgramID();
  2851. const auto screenshot_path =
  2852. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::ScreenshotsDir));
  2853. const auto date =
  2854. QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd_hh-mm-ss-zzz"));
  2855. QString filename = QStringLiteral("%1/%2_%3.png")
  2856. .arg(screenshot_path)
  2857. .arg(title_id, 16, 16, QLatin1Char{'0'})
  2858. .arg(date);
  2859. if (!Common::FS::CreateDir(screenshot_path.toStdString())) {
  2860. return;
  2861. }
  2862. #ifdef _WIN32
  2863. if (UISettings::values.enable_screenshot_save_as) {
  2864. OnPauseGame();
  2865. filename = QFileDialog::getSaveFileName(this, tr("Capture Screenshot"), filename,
  2866. tr("PNG Image (*.png)"));
  2867. OnStartGame();
  2868. if (filename.isEmpty()) {
  2869. return;
  2870. }
  2871. }
  2872. #endif
  2873. render_window->CaptureScreenshot(filename);
  2874. }
  2875. // TODO: Written 2020-10-01: Remove per-game config migration code when it is irrelevant
  2876. void GMainWindow::MigrateConfigFiles() {
  2877. const auto config_dir_fs_path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir);
  2878. const QDir config_dir =
  2879. QDir(QString::fromStdString(Common::FS::PathToUTF8String(config_dir_fs_path)));
  2880. const QStringList config_dir_list = config_dir.entryList(QStringList(QStringLiteral("*.ini")));
  2881. if (!Common::FS::CreateDirs(config_dir_fs_path / "custom")) {
  2882. LOG_ERROR(Frontend, "Failed to create new config file directory");
  2883. }
  2884. for (auto it = config_dir_list.constBegin(); it != config_dir_list.constEnd(); ++it) {
  2885. const auto filename = it->toStdString();
  2886. if (filename.find_first_not_of("0123456789abcdefACBDEF", 0) < 16) {
  2887. continue;
  2888. }
  2889. const auto origin = config_dir_fs_path / filename;
  2890. const auto destination = config_dir_fs_path / "custom" / filename;
  2891. LOG_INFO(Frontend, "Migrating config file from {} to {}", origin.string(),
  2892. destination.string());
  2893. if (!Common::FS::RenameFile(origin, destination)) {
  2894. // Delete the old config file if one already exists in the new location.
  2895. Common::FS::RemoveFile(origin);
  2896. }
  2897. }
  2898. }
  2899. void GMainWindow::UpdateWindowTitle(std::string_view title_name, std::string_view title_version,
  2900. std::string_view gpu_vendor) {
  2901. const auto branch_name = std::string(Common::g_scm_branch);
  2902. const auto description = std::string(Common::g_scm_desc);
  2903. const auto build_id = std::string(Common::g_build_id);
  2904. const auto yuzu_title = fmt::format("yuzu | {}-{}", branch_name, description);
  2905. const auto override_title =
  2906. fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id);
  2907. const auto window_title = override_title.empty() ? yuzu_title : override_title;
  2908. if (title_name.empty()) {
  2909. setWindowTitle(QString::fromStdString(window_title));
  2910. } else {
  2911. const auto run_title = [window_title, title_name, title_version, gpu_vendor]() {
  2912. if (title_version.empty()) {
  2913. return fmt::format("{} | {} | {}", window_title, title_name, gpu_vendor);
  2914. }
  2915. return fmt::format("{} | {} | {} | {}", window_title, title_name, title_version,
  2916. gpu_vendor);
  2917. }();
  2918. setWindowTitle(QString::fromStdString(run_title));
  2919. }
  2920. }
  2921. QString GMainWindow::GetTasStateDescription() const {
  2922. auto [tas_status, current_tas_frame, total_tas_frames] = input_subsystem->GetTas()->GetStatus();
  2923. switch (tas_status) {
  2924. case InputCommon::TasInput::TasState::Running:
  2925. return tr("TAS state: Running %1/%2").arg(current_tas_frame).arg(total_tas_frames);
  2926. case InputCommon::TasInput::TasState::Recording:
  2927. return tr("TAS state: Recording %1").arg(total_tas_frames);
  2928. case InputCommon::TasInput::TasState::Stopped:
  2929. return tr("TAS state: Idle %1/%2").arg(current_tas_frame).arg(total_tas_frames);
  2930. default:
  2931. return tr("TAS State: Invalid");
  2932. }
  2933. }
  2934. void GMainWindow::OnTasStateChanged() {
  2935. bool is_running = false;
  2936. bool is_recording = false;
  2937. if (emulation_running) {
  2938. const InputCommon::TasInput::TasState tas_status =
  2939. std::get<0>(input_subsystem->GetTas()->GetStatus());
  2940. is_running = tas_status == InputCommon::TasInput::TasState::Running;
  2941. is_recording = tas_status == InputCommon::TasInput::TasState::Recording;
  2942. }
  2943. ui->action_TAS_Start->setText(is_running ? tr("&Stop Running") : tr("&Start"));
  2944. ui->action_TAS_Record->setText(is_recording ? tr("Stop R&ecording") : tr("R&ecord"));
  2945. ui->action_TAS_Start->setEnabled(emulation_running);
  2946. ui->action_TAS_Record->setEnabled(emulation_running);
  2947. ui->action_TAS_Reset->setEnabled(emulation_running);
  2948. }
  2949. void GMainWindow::UpdateStatusBar() {
  2950. if (emu_thread == nullptr || !system->IsPoweredOn()) {
  2951. status_bar_update_timer.stop();
  2952. return;
  2953. }
  2954. if (Settings::values.tas_enable) {
  2955. tas_label->setText(GetTasStateDescription());
  2956. } else {
  2957. tas_label->clear();
  2958. }
  2959. auto results = system->GetAndResetPerfStats();
  2960. auto& shader_notify = system->GPU().ShaderNotify();
  2961. const int shaders_building = shader_notify.ShadersBuilding();
  2962. if (shaders_building > 0) {
  2963. shader_building_label->setText(tr("Building: %n shader(s)", "", shaders_building));
  2964. shader_building_label->setVisible(true);
  2965. } else {
  2966. shader_building_label->setVisible(false);
  2967. }
  2968. const auto res_info = Settings::values.resolution_info;
  2969. const auto res_scale = res_info.up_factor;
  2970. res_scale_label->setText(
  2971. tr("Scale: %1x", "%1 is the resolution scaling factor").arg(res_scale));
  2972. if (Settings::values.use_speed_limit.GetValue()) {
  2973. emu_speed_label->setText(tr("Speed: %1% / %2%")
  2974. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  2975. .arg(Settings::values.speed_limit.GetValue()));
  2976. } else {
  2977. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  2978. }
  2979. if (!Settings::values.use_speed_limit) {
  2980. game_fps_label->setText(
  2981. tr("Game: %1 FPS (Unlocked)").arg(std::round(results.average_game_fps), 0, 'f', 0));
  2982. } else {
  2983. game_fps_label->setText(
  2984. tr("Game: %1 FPS").arg(std::round(results.average_game_fps), 0, 'f', 0));
  2985. }
  2986. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  2987. res_scale_label->setVisible(true);
  2988. emu_speed_label->setVisible(!Settings::values.use_multi_core.GetValue());
  2989. game_fps_label->setVisible(true);
  2990. emu_frametime_label->setVisible(true);
  2991. }
  2992. void GMainWindow::UpdateGPUAccuracyButton() {
  2993. switch (Settings::values.gpu_accuracy.GetValue()) {
  2994. case Settings::GPUAccuracy::Normal: {
  2995. gpu_accuracy_button->setText(tr("GPU NORMAL"));
  2996. gpu_accuracy_button->setChecked(false);
  2997. break;
  2998. }
  2999. case Settings::GPUAccuracy::High: {
  3000. gpu_accuracy_button->setText(tr("GPU HIGH"));
  3001. gpu_accuracy_button->setChecked(true);
  3002. break;
  3003. }
  3004. case Settings::GPUAccuracy::Extreme: {
  3005. gpu_accuracy_button->setText(tr("GPU EXTREME"));
  3006. gpu_accuracy_button->setChecked(true);
  3007. break;
  3008. }
  3009. default: {
  3010. gpu_accuracy_button->setText(tr("GPU ERROR"));
  3011. gpu_accuracy_button->setChecked(true);
  3012. break;
  3013. }
  3014. }
  3015. }
  3016. void GMainWindow::UpdateDockedButton() {
  3017. const bool is_docked = Settings::values.use_docked_mode.GetValue();
  3018. dock_status_button->setChecked(is_docked);
  3019. dock_status_button->setText(is_docked ? tr("DOCKED") : tr("HANDHELD"));
  3020. }
  3021. void GMainWindow::UpdateFilterText() {
  3022. const auto filter = Settings::values.scaling_filter.GetValue();
  3023. switch (filter) {
  3024. case Settings::ScalingFilter::NearestNeighbor:
  3025. filter_status_button->setText(tr("NEAREST"));
  3026. break;
  3027. case Settings::ScalingFilter::Bilinear:
  3028. filter_status_button->setText(tr("BILINEAR"));
  3029. break;
  3030. case Settings::ScalingFilter::Bicubic:
  3031. filter_status_button->setText(tr("BICUBIC"));
  3032. break;
  3033. case Settings::ScalingFilter::Gaussian:
  3034. filter_status_button->setText(tr("GAUSSIAN"));
  3035. break;
  3036. case Settings::ScalingFilter::ScaleForce:
  3037. filter_status_button->setText(tr("SCALEFORCE"));
  3038. break;
  3039. case Settings::ScalingFilter::Fsr:
  3040. filter_status_button->setText(tr("FSR"));
  3041. break;
  3042. default:
  3043. filter_status_button->setText(tr("BILINEAR"));
  3044. break;
  3045. }
  3046. }
  3047. void GMainWindow::UpdateAAText() {
  3048. const auto aa_mode = Settings::values.anti_aliasing.GetValue();
  3049. switch (aa_mode) {
  3050. case Settings::AntiAliasing::None:
  3051. aa_status_button->setText(tr("NO AA"));
  3052. break;
  3053. case Settings::AntiAliasing::Fxaa:
  3054. aa_status_button->setText(tr("FXAA"));
  3055. break;
  3056. default:
  3057. aa_status_button->setText(tr("NO AA"));
  3058. break;
  3059. }
  3060. }
  3061. void GMainWindow::UpdateStatusButtons() {
  3062. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  3063. Settings::RendererBackend::Vulkan);
  3064. UpdateGPUAccuracyButton();
  3065. UpdateDockedButton();
  3066. UpdateFilterText();
  3067. UpdateAAText();
  3068. }
  3069. void GMainWindow::UpdateUISettings() {
  3070. if (!ui->action_Fullscreen->isChecked()) {
  3071. UISettings::values.geometry = saveGeometry();
  3072. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  3073. }
  3074. UISettings::values.state = saveState();
  3075. #if MICROPROFILE_ENABLED
  3076. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  3077. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  3078. #endif
  3079. UISettings::values.single_window_mode = ui->action_Single_Window_Mode->isChecked();
  3080. UISettings::values.fullscreen = ui->action_Fullscreen->isChecked();
  3081. UISettings::values.display_titlebar = ui->action_Display_Dock_Widget_Headers->isChecked();
  3082. UISettings::values.show_filter_bar = ui->action_Show_Filter_Bar->isChecked();
  3083. UISettings::values.show_status_bar = ui->action_Show_Status_Bar->isChecked();
  3084. UISettings::values.first_start = false;
  3085. }
  3086. void GMainWindow::HideMouseCursor() {
  3087. if (emu_thread == nullptr && UISettings::values.hide_mouse) {
  3088. mouse_hide_timer.stop();
  3089. ShowMouseCursor();
  3090. return;
  3091. }
  3092. render_window->setCursor(QCursor(Qt::BlankCursor));
  3093. }
  3094. void GMainWindow::ShowMouseCursor() {
  3095. render_window->unsetCursor();
  3096. if (emu_thread != nullptr && UISettings::values.hide_mouse) {
  3097. mouse_hide_timer.start();
  3098. }
  3099. }
  3100. void GMainWindow::CenterMouseCursor() {
  3101. if (emu_thread == nullptr || !Settings::values.mouse_panning) {
  3102. mouse_center_timer.stop();
  3103. return;
  3104. }
  3105. if (!this->isActiveWindow()) {
  3106. mouse_center_timer.stop();
  3107. return;
  3108. }
  3109. const int center_x = render_window->width() / 2;
  3110. const int center_y = render_window->height() / 2;
  3111. QCursor::setPos(mapToGlobal(QPoint{center_x, center_y}));
  3112. }
  3113. void GMainWindow::OnMouseActivity() {
  3114. if (!Settings::values.mouse_panning) {
  3115. ShowMouseCursor();
  3116. }
  3117. mouse_center_timer.stop();
  3118. }
  3119. void GMainWindow::OnCoreError(Core::SystemResultStatus result, std::string details) {
  3120. QMessageBox::StandardButton answer;
  3121. QString status_message;
  3122. const QString common_message =
  3123. tr("The game you are trying to load requires additional files from your Switch to be "
  3124. "dumped "
  3125. "before playing.<br/><br/>For more information on dumping these files, please see the "
  3126. "following wiki page: <a "
  3127. "href='https://yuzu-emu.org/wiki/"
  3128. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  3129. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  3130. "quit "
  3131. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  3132. "data, or other bugs.");
  3133. switch (result) {
  3134. case Core::SystemResultStatus::ErrorSystemFiles: {
  3135. QString message;
  3136. if (details.empty()) {
  3137. message =
  3138. tr("yuzu was unable to locate a Switch system archive. %1").arg(common_message);
  3139. } else {
  3140. message = tr("yuzu was unable to locate a Switch system archive: %1. %2")
  3141. .arg(QString::fromStdString(details), common_message);
  3142. }
  3143. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  3144. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3145. status_message = tr("System Archive Missing");
  3146. break;
  3147. }
  3148. case Core::SystemResultStatus::ErrorSharedFont: {
  3149. const QString message =
  3150. tr("yuzu was unable to locate the Switch shared fonts. %1").arg(common_message);
  3151. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  3152. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3153. status_message = tr("Shared Font Missing");
  3154. break;
  3155. }
  3156. default:
  3157. answer = QMessageBox::question(
  3158. this, tr("Fatal Error"),
  3159. tr("yuzu has encountered a fatal error, please see the log for more details. "
  3160. "For more information on accessing the log, please see the following page: "
  3161. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  3162. "to "
  3163. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  3164. "list? "
  3165. "Continuing emulation may result in crashes, corrupted save data, or other "
  3166. "bugs."),
  3167. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3168. status_message = tr("Fatal Error encountered");
  3169. break;
  3170. }
  3171. if (answer == QMessageBox::Yes) {
  3172. if (emu_thread) {
  3173. ShutdownGame();
  3174. Settings::RestoreGlobalState(system->IsPoweredOn());
  3175. UpdateStatusButtons();
  3176. }
  3177. } else {
  3178. // Only show the message if the game is still running.
  3179. if (emu_thread) {
  3180. emu_thread->SetRunning(true);
  3181. message_label->setText(status_message);
  3182. }
  3183. }
  3184. }
  3185. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  3186. if (behavior == ReinitializeKeyBehavior::Warning) {
  3187. const auto res = QMessageBox::information(
  3188. this, tr("Confirm Key Rederivation"),
  3189. tr("You are about to force rederive all of your keys. \nIf you do not know what "
  3190. "this "
  3191. "means or what you are doing, \nthis is a potentially destructive action. "
  3192. "\nPlease "
  3193. "make sure this is what you want \nand optionally make backups.\n\nThis will "
  3194. "delete "
  3195. "your autogenerated key files and re-run the key derivation module."),
  3196. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  3197. if (res == QMessageBox::Cancel)
  3198. return;
  3199. const auto keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
  3200. Common::FS::RemoveFile(keys_dir / "prod.keys_autogenerated");
  3201. Common::FS::RemoveFile(keys_dir / "console.keys_autogenerated");
  3202. Common::FS::RemoveFile(keys_dir / "title.keys_autogenerated");
  3203. }
  3204. Core::Crypto::KeyManager& keys = Core::Crypto::KeyManager::Instance();
  3205. if (keys.BaseDeriveNecessary()) {
  3206. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory("", FileSys::Mode::Read)};
  3207. const auto function = [this, &keys, &pdm] {
  3208. keys.PopulateFromPartitionData(pdm);
  3209. system->GetFileSystemController().CreateFactories(*vfs);
  3210. keys.DeriveETicket(pdm, system->GetContentProvider());
  3211. };
  3212. QString errors;
  3213. if (!pdm.HasFuses()) {
  3214. errors += tr("Missing fuses");
  3215. }
  3216. if (!pdm.HasBoot0()) {
  3217. errors += tr(" - Missing BOOT0");
  3218. }
  3219. if (!pdm.HasPackage2()) {
  3220. errors += tr(" - Missing BCPKG2-1-Normal-Main");
  3221. }
  3222. if (!pdm.HasProdInfo()) {
  3223. errors += tr(" - Missing PRODINFO");
  3224. }
  3225. if (!errors.isEmpty()) {
  3226. QMessageBox::warning(
  3227. this, tr("Derivation Components Missing"),
  3228. tr("Encryption keys are missing. "
  3229. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  3230. "quickstart guide</a> to get all your keys, firmware and "
  3231. "games.<br><br><small>(%1)</small>")
  3232. .arg(errors));
  3233. }
  3234. QProgressDialog prog(this);
  3235. prog.setRange(0, 0);
  3236. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  3237. "system's performance."));
  3238. prog.setWindowTitle(tr("Deriving Keys"));
  3239. prog.show();
  3240. auto future = QtConcurrent::run(function);
  3241. while (!future.isFinished()) {
  3242. QCoreApplication::processEvents();
  3243. }
  3244. prog.close();
  3245. }
  3246. system->GetFileSystemController().CreateFactories(*vfs);
  3247. if (behavior == ReinitializeKeyBehavior::Warning) {
  3248. game_list->PopulateAsync(UISettings::values.game_dirs);
  3249. }
  3250. }
  3251. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
  3252. u64 program_id) {
  3253. const auto dlc_entries =
  3254. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  3255. std::vector<FileSys::ContentProviderEntry> dlc_match;
  3256. dlc_match.reserve(dlc_entries.size());
  3257. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  3258. [&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
  3259. return FileSys::GetBaseTitleID(entry.title_id) == program_id &&
  3260. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  3261. });
  3262. std::vector<u64> romfs_tids;
  3263. romfs_tids.push_back(program_id);
  3264. for (const auto& entry : dlc_match) {
  3265. romfs_tids.push_back(entry.title_id);
  3266. }
  3267. if (romfs_tids.size() > 1) {
  3268. QStringList list{QStringLiteral("Base")};
  3269. for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
  3270. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  3271. }
  3272. bool ok;
  3273. const auto res = QInputDialog::getItem(
  3274. this, tr("Select RomFS Dump Target"),
  3275. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  3276. if (!ok) {
  3277. return {};
  3278. }
  3279. return romfs_tids[list.indexOf(res)];
  3280. }
  3281. return program_id;
  3282. }
  3283. bool GMainWindow::ConfirmClose() {
  3284. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  3285. return true;
  3286. }
  3287. const auto text = tr("Are you sure you want to close yuzu?");
  3288. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  3289. return answer != QMessageBox::No;
  3290. }
  3291. void GMainWindow::closeEvent(QCloseEvent* event) {
  3292. if (!ConfirmClose()) {
  3293. event->ignore();
  3294. return;
  3295. }
  3296. UpdateUISettings();
  3297. game_list->SaveInterfaceLayout();
  3298. hotkey_registry.SaveHotkeys();
  3299. // Unload controllers early
  3300. controller_dialog->UnloadController();
  3301. game_list->UnloadController();
  3302. system->HIDCore().UnloadInputDevices();
  3303. // Shutdown session if the emu thread is active...
  3304. if (emu_thread != nullptr) {
  3305. ShutdownGame();
  3306. Settings::RestoreGlobalState(system->IsPoweredOn());
  3307. UpdateStatusButtons();
  3308. }
  3309. render_window->close();
  3310. multiplayer_state->Close();
  3311. system->GetRoomNetwork().Shutdown();
  3312. QWidget::closeEvent(event);
  3313. }
  3314. static bool IsSingleFileDropEvent(const QMimeData* mime) {
  3315. return mime->hasUrls() && mime->urls().length() == 1;
  3316. }
  3317. void GMainWindow::AcceptDropEvent(QDropEvent* event) {
  3318. if (IsSingleFileDropEvent(event->mimeData())) {
  3319. event->setDropAction(Qt::DropAction::LinkAction);
  3320. event->accept();
  3321. }
  3322. }
  3323. bool GMainWindow::DropAction(QDropEvent* event) {
  3324. if (!IsSingleFileDropEvent(event->mimeData())) {
  3325. return false;
  3326. }
  3327. const QMimeData* mime_data = event->mimeData();
  3328. const QString& filename = mime_data->urls().at(0).toLocalFile();
  3329. if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
  3330. // Amiibo
  3331. LoadAmiibo(filename);
  3332. } else {
  3333. // Game
  3334. if (ConfirmChangeGame()) {
  3335. BootGame(filename);
  3336. }
  3337. }
  3338. return true;
  3339. }
  3340. void GMainWindow::dropEvent(QDropEvent* event) {
  3341. DropAction(event);
  3342. }
  3343. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  3344. AcceptDropEvent(event);
  3345. }
  3346. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  3347. AcceptDropEvent(event);
  3348. }
  3349. void GMainWindow::leaveEvent(QEvent* event) {
  3350. if (Settings::values.mouse_panning) {
  3351. const QRect& rect = geometry();
  3352. QPoint position = QCursor::pos();
  3353. qint32 x = qBound(rect.left(), position.x(), rect.right());
  3354. qint32 y = qBound(rect.top(), position.y(), rect.bottom());
  3355. // Only start the timer if the mouse has left the window bound.
  3356. // The leave event is also triggered when the window looses focus.
  3357. if (x != position.x() || y != position.y()) {
  3358. mouse_center_timer.start();
  3359. }
  3360. event->accept();
  3361. }
  3362. }
  3363. bool GMainWindow::ConfirmChangeGame() {
  3364. if (emu_thread == nullptr)
  3365. return true;
  3366. const auto answer = QMessageBox::question(
  3367. this, tr("yuzu"),
  3368. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  3369. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3370. return answer != QMessageBox::No;
  3371. }
  3372. bool GMainWindow::ConfirmForceLockedExit() {
  3373. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  3374. return true;
  3375. }
  3376. const auto text = tr("The currently running application has requested yuzu to not exit.\n\n"
  3377. "Would you like to bypass this and exit anyway?");
  3378. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  3379. return answer != QMessageBox::No;
  3380. }
  3381. void GMainWindow::RequestGameExit() {
  3382. auto& sm{system->ServiceManager()};
  3383. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  3384. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  3385. bool has_signalled = false;
  3386. if (applet_oe != nullptr) {
  3387. applet_oe->GetMessageQueue()->RequestExit();
  3388. has_signalled = true;
  3389. }
  3390. if (applet_ae != nullptr && !has_signalled) {
  3391. applet_ae->GetMessageQueue()->RequestExit();
  3392. }
  3393. }
  3394. void GMainWindow::RequestGameResume() {
  3395. auto& sm{system->ServiceManager()};
  3396. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  3397. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  3398. if (applet_oe != nullptr) {
  3399. applet_oe->GetMessageQueue()->RequestResume();
  3400. return;
  3401. }
  3402. if (applet_ae != nullptr) {
  3403. applet_ae->GetMessageQueue()->RequestResume();
  3404. }
  3405. }
  3406. void GMainWindow::filterBarSetChecked(bool state) {
  3407. ui->action_Show_Filter_Bar->setChecked(state);
  3408. emit(OnToggleFilterBar());
  3409. }
  3410. static void AdjustLinkColor() {
  3411. QPalette new_pal(qApp->palette());
  3412. if (UISettings::IsDarkTheme()) {
  3413. new_pal.setColor(QPalette::Link, QColor(0, 190, 255, 255));
  3414. } else {
  3415. new_pal.setColor(QPalette::Link, QColor(0, 140, 200, 255));
  3416. }
  3417. if (qApp->palette().color(QPalette::Link) != new_pal.color(QPalette::Link)) {
  3418. qApp->setPalette(new_pal);
  3419. }
  3420. }
  3421. void GMainWindow::UpdateUITheme() {
  3422. const QString default_theme =
  3423. QString::fromUtf8(UISettings::themes[static_cast<size_t>(Config::default_theme)].second);
  3424. QString current_theme = UISettings::values.theme;
  3425. QStringList theme_paths(default_theme_paths);
  3426. if (current_theme.isEmpty()) {
  3427. current_theme = default_theme;
  3428. }
  3429. #ifdef _WIN32
  3430. QIcon::setThemeName(current_theme);
  3431. AdjustLinkColor();
  3432. #else
  3433. if (current_theme == QStringLiteral("default") || current_theme == QStringLiteral("colorful")) {
  3434. QIcon::setThemeName(current_theme == QStringLiteral("colorful") ? current_theme
  3435. : startup_icon_theme);
  3436. QIcon::setThemeSearchPaths(theme_paths);
  3437. if (CheckDarkMode()) {
  3438. current_theme = QStringLiteral("default_dark");
  3439. }
  3440. } else {
  3441. QIcon::setThemeName(current_theme);
  3442. QIcon::setThemeSearchPaths(QStringList(QStringLiteral(":/icons")));
  3443. AdjustLinkColor();
  3444. }
  3445. #endif
  3446. if (current_theme != default_theme) {
  3447. QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)};
  3448. QFile f(theme_uri);
  3449. if (!f.open(QFile::ReadOnly | QFile::Text)) {
  3450. LOG_ERROR(Frontend, "Unable to open style \"{}\", fallback to the default theme",
  3451. UISettings::values.theme.toStdString());
  3452. current_theme = default_theme;
  3453. }
  3454. }
  3455. QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)};
  3456. QFile f(theme_uri);
  3457. if (f.open(QFile::ReadOnly | QFile::Text)) {
  3458. QTextStream ts(&f);
  3459. qApp->setStyleSheet(ts.readAll());
  3460. setStyleSheet(ts.readAll());
  3461. } else {
  3462. LOG_ERROR(Frontend, "Unable to set style \"{}\", stylesheet file not found",
  3463. UISettings::values.theme.toStdString());
  3464. qApp->setStyleSheet({});
  3465. setStyleSheet({});
  3466. }
  3467. }
  3468. void GMainWindow::LoadTranslation() {
  3469. bool loaded;
  3470. if (UISettings::values.language.isEmpty()) {
  3471. // If the selected language is empty, use system locale
  3472. loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/"));
  3473. } else {
  3474. // Otherwise load from the specified file
  3475. loaded = translator.load(UISettings::values.language, QStringLiteral(":/languages/"));
  3476. }
  3477. if (loaded) {
  3478. qApp->installTranslator(&translator);
  3479. } else {
  3480. UISettings::values.language = QStringLiteral("en");
  3481. }
  3482. }
  3483. void GMainWindow::OnLanguageChanged(const QString& locale) {
  3484. if (UISettings::values.language != QStringLiteral("en")) {
  3485. qApp->removeTranslator(&translator);
  3486. }
  3487. UISettings::values.language = locale;
  3488. LoadTranslation();
  3489. ui->retranslateUi(this);
  3490. multiplayer_state->retranslateUi();
  3491. UpdateWindowTitle();
  3492. }
  3493. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  3494. #ifdef USE_DISCORD_PRESENCE
  3495. if (state) {
  3496. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>(*system);
  3497. } else {
  3498. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  3499. }
  3500. #else
  3501. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  3502. #endif
  3503. discord_rpc->Update();
  3504. }
  3505. void GMainWindow::changeEvent(QEvent* event) {
  3506. #ifdef __unix__
  3507. // PaletteChange event appears to only reach so far into the GUI, explicitly asking to
  3508. // UpdateUITheme is a decent work around
  3509. if (event->type() == QEvent::PaletteChange) {
  3510. const QPalette test_palette(qApp->palette());
  3511. const QString current_theme = UISettings::values.theme;
  3512. // Keeping eye on QPalette::Window to avoid looping. QPalette::Text might be useful too
  3513. static QColor last_window_color;
  3514. const QColor window_color = test_palette.color(QPalette::Active, QPalette::Window);
  3515. if (last_window_color != window_color && (current_theme == QStringLiteral("default") ||
  3516. current_theme == QStringLiteral("colorful"))) {
  3517. UpdateUITheme();
  3518. }
  3519. last_window_color = window_color;
  3520. }
  3521. #endif // __unix__
  3522. QWidget::changeEvent(event);
  3523. }
  3524. #ifdef main
  3525. #undef main
  3526. #endif
  3527. int main(int argc, char* argv[]) {
  3528. std::unique_ptr<Config> config = std::make_unique<Config>();
  3529. bool has_broken_vulkan = false;
  3530. bool is_child = false;
  3531. if (CheckEnvVars(&is_child)) {
  3532. return 0;
  3533. }
  3534. #ifdef YUZU_DBGHELP
  3535. PROCESS_INFORMATION pi;
  3536. if (!is_child && Settings::values.create_crash_dumps.GetValue() &&
  3537. MiniDump::SpawnDebuggee(argv[0], pi)) {
  3538. // Delete the config object so that it doesn't save when the program exits
  3539. config.reset(nullptr);
  3540. MiniDump::DebugDebuggee(pi);
  3541. return 0;
  3542. }
  3543. #endif
  3544. if (StartupChecks(argv[0], &has_broken_vulkan,
  3545. Settings::values.perform_vulkan_check.GetValue())) {
  3546. return 0;
  3547. }
  3548. Common::DetachedTasks detached_tasks;
  3549. MicroProfileOnThreadCreate("Frontend");
  3550. SCOPE_EXIT({ MicroProfileShutdown(); });
  3551. Common::ConfigureNvidiaEnvironmentFlags();
  3552. // Init settings params
  3553. QCoreApplication::setOrganizationName(QStringLiteral("yuzu team"));
  3554. QCoreApplication::setApplicationName(QStringLiteral("yuzu"));
  3555. #ifdef _WIN32
  3556. // Increases the maximum open file limit to 8192
  3557. _setmaxstdio(8192);
  3558. #endif
  3559. #ifdef __APPLE__
  3560. // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/".
  3561. // But since we require the working directory to be the executable path for the location of
  3562. // the user folder in the Qt Frontend, we need to cd into that working directory
  3563. const auto bin_path = Common::FS::GetBundleDirectory() / "..";
  3564. chdir(Common::FS::PathToUTF8String(bin_path).c_str());
  3565. #endif
  3566. #ifdef __linux__
  3567. // Set the DISPLAY variable in order to open web browsers
  3568. // TODO (lat9nq): Find a better solution for AppImages to start external applications
  3569. if (QString::fromLocal8Bit(qgetenv("DISPLAY")).isEmpty()) {
  3570. qputenv("DISPLAY", ":0");
  3571. }
  3572. #endif
  3573. // Enables the core to make the qt created contexts current on std::threads
  3574. QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  3575. QApplication app(argc, argv);
  3576. #ifdef _WIN32
  3577. OverrideWindowsFont();
  3578. #endif
  3579. // Workaround for QTBUG-85409, for Suzhou numerals the number 1 is actually \u3021
  3580. // so we can see if we get \u3008 instead
  3581. // TL;DR all other number formats are consecutive in unicode code points
  3582. // This bug is fixed in Qt6, specifically 6.0.0-alpha1
  3583. const QLocale locale = QLocale::system();
  3584. if (QStringLiteral("\u3008") == locale.toString(1)) {
  3585. QLocale::setDefault(QLocale::system().name());
  3586. }
  3587. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  3588. // generating shaders
  3589. setlocale(LC_ALL, "C");
  3590. GMainWindow main_window{std::move(config), has_broken_vulkan};
  3591. // After settings have been loaded by GMainWindow, apply the filter
  3592. main_window.show();
  3593. QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
  3594. &GMainWindow::OnAppFocusStateChanged);
  3595. int result = app.exec();
  3596. detached_tasks.WaitForAllTasks();
  3597. return result;
  3598. }