main.cpp 174 KB

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