main.cpp 181 KB

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