main.cpp 166 KB

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