main.cpp 159 KB

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