main.cpp 185 KB

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