main.cpp 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779
  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. // Create and start the emulation thread
  1623. emu_thread = std::make_unique<EmuThread>(*system);
  1624. emit EmulationStarting(emu_thread.get());
  1625. emu_thread->start();
  1626. // Register an ExecuteProgram callback such that Core can execute a sub-program
  1627. system->RegisterExecuteProgramCallback(
  1628. [this](std::size_t program_index_) { render_window->ExecuteProgram(program_index_); });
  1629. system->RegisterExitCallback([this] {
  1630. emu_thread->ForceStop();
  1631. render_window->Exit();
  1632. });
  1633. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1634. connect(render_window, &GRenderWindow::MouseActivity, this, &GMainWindow::OnMouseActivity);
  1635. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  1636. // before the CPU continues
  1637. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  1638. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  1639. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  1640. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  1641. connect(emu_thread.get(), &EmuThread::LoadProgress, loading_screen,
  1642. &LoadingScreen::OnLoadProgress, Qt::QueuedConnection);
  1643. // Update the GUI
  1644. UpdateStatusButtons();
  1645. if (ui->action_Single_Window_Mode->isChecked()) {
  1646. game_list->hide();
  1647. game_list_placeholder->hide();
  1648. }
  1649. status_bar_update_timer.start(500);
  1650. renderer_status_button->setDisabled(true);
  1651. if (UISettings::values.hide_mouse || Settings::values.mouse_panning) {
  1652. render_window->installEventFilter(render_window);
  1653. render_window->setAttribute(Qt::WA_Hover, true);
  1654. }
  1655. if (UISettings::values.hide_mouse) {
  1656. mouse_hide_timer.start();
  1657. }
  1658. render_window->InitializeCamera();
  1659. std::string title_name;
  1660. std::string title_version;
  1661. const auto res = system->GetGameName(title_name);
  1662. const auto metadata = [this, title_id] {
  1663. const FileSys::PatchManager pm(title_id, system->GetFileSystemController(),
  1664. system->GetContentProvider());
  1665. return pm.GetControlMetadata();
  1666. }();
  1667. if (metadata.first != nullptr) {
  1668. title_version = metadata.first->GetVersionString();
  1669. title_name = metadata.first->GetApplicationName();
  1670. }
  1671. if (res != Loader::ResultStatus::Success || title_name.empty()) {
  1672. title_name = Common::FS::PathToUTF8String(
  1673. std::filesystem::path{Common::U16StringFromBuffer(filename.utf16(), filename.size())}
  1674. .filename());
  1675. }
  1676. const bool is_64bit = system->Kernel().ApplicationProcess()->Is64BitProcess();
  1677. const auto instruction_set_suffix = is_64bit ? tr("(64-bit)") : tr("(32-bit)");
  1678. title_name = tr("%1 %2", "%1 is the title name. %2 indicates if the title is 64-bit or 32-bit")
  1679. .arg(QString::fromStdString(title_name), instruction_set_suffix)
  1680. .toStdString();
  1681. LOG_INFO(Frontend, "Booting game: {:016X} | {} | {}", title_id, title_name, title_version);
  1682. const auto gpu_vendor = system->GPU().Renderer().GetDeviceVendor();
  1683. UpdateWindowTitle(title_name, title_version, gpu_vendor);
  1684. loading_screen->Prepare(system->GetAppLoader());
  1685. loading_screen->show();
  1686. emulation_running = true;
  1687. if (ui->action_Fullscreen->isChecked()) {
  1688. ShowFullscreen();
  1689. }
  1690. OnStartGame();
  1691. }
  1692. bool GMainWindow::OnShutdownBegin() {
  1693. if (!emulation_running) {
  1694. return false;
  1695. }
  1696. if (ui->action_Fullscreen->isChecked()) {
  1697. HideFullscreen();
  1698. }
  1699. AllowOSSleep();
  1700. // Disable unlimited frame rate
  1701. Settings::values.use_speed_limit.SetValue(true);
  1702. if (system->IsShuttingDown()) {
  1703. return false;
  1704. }
  1705. system->SetShuttingDown(true);
  1706. discord_rpc->Pause();
  1707. RequestGameExit();
  1708. emu_thread->disconnect();
  1709. emu_thread->SetRunning(true);
  1710. emit EmulationStopping();
  1711. shutdown_timer.setSingleShot(true);
  1712. shutdown_timer.start(system->DebuggerEnabled() ? 0 : 5000);
  1713. connect(&shutdown_timer, &QTimer::timeout, this, &GMainWindow::OnEmulationStopTimeExpired);
  1714. connect(emu_thread.get(), &QThread::finished, this, &GMainWindow::OnEmulationStopped);
  1715. // Disable everything to prevent anything from being triggered here
  1716. ui->action_Pause->setEnabled(false);
  1717. ui->action_Restart->setEnabled(false);
  1718. ui->action_Stop->setEnabled(false);
  1719. return true;
  1720. }
  1721. void GMainWindow::OnShutdownBeginDialog() {
  1722. shutdown_dialog = new OverlayDialog(this, *system, QString{}, tr("Closing software..."),
  1723. QString{}, QString{}, Qt::AlignHCenter | Qt::AlignVCenter);
  1724. shutdown_dialog->open();
  1725. }
  1726. void GMainWindow::OnEmulationStopTimeExpired() {
  1727. if (emu_thread) {
  1728. emu_thread->ForceStop();
  1729. }
  1730. }
  1731. void GMainWindow::OnEmulationStopped() {
  1732. shutdown_timer.stop();
  1733. if (emu_thread) {
  1734. emu_thread->disconnect();
  1735. emu_thread->wait();
  1736. emu_thread.reset();
  1737. }
  1738. if (shutdown_dialog) {
  1739. shutdown_dialog->deleteLater();
  1740. shutdown_dialog = nullptr;
  1741. }
  1742. emulation_running = false;
  1743. discord_rpc->Update();
  1744. // The emulation is stopped, so closing the window or not does not matter anymore
  1745. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1746. // Update the GUI
  1747. UpdateMenuState();
  1748. render_window->hide();
  1749. loading_screen->hide();
  1750. loading_screen->Clear();
  1751. if (game_list->IsEmpty()) {
  1752. game_list_placeholder->show();
  1753. } else {
  1754. game_list->show();
  1755. }
  1756. game_list->SetFilterFocus();
  1757. tas_label->clear();
  1758. input_subsystem->GetTas()->Stop();
  1759. OnTasStateChanged();
  1760. render_window->FinalizeCamera();
  1761. // Enable all controllers
  1762. system->HIDCore().SetSupportedStyleTag({Core::HID::NpadStyleSet::All});
  1763. render_window->removeEventFilter(render_window);
  1764. render_window->setAttribute(Qt::WA_Hover, false);
  1765. UpdateWindowTitle();
  1766. // Disable status bar updates
  1767. status_bar_update_timer.stop();
  1768. shader_building_label->setVisible(false);
  1769. res_scale_label->setVisible(false);
  1770. emu_speed_label->setVisible(false);
  1771. game_fps_label->setVisible(false);
  1772. emu_frametime_label->setVisible(false);
  1773. renderer_status_button->setEnabled(!UISettings::values.has_broken_vulkan);
  1774. current_game_path.clear();
  1775. // When closing the game, destroy the GLWindow to clear the context after the game is closed
  1776. render_window->ReleaseRenderTarget();
  1777. Settings::RestoreGlobalState(system->IsPoweredOn());
  1778. system->HIDCore().ReloadInputDevices();
  1779. UpdateStatusButtons();
  1780. }
  1781. void GMainWindow::ShutdownGame() {
  1782. if (!emulation_running) {
  1783. return;
  1784. }
  1785. OnShutdownBegin();
  1786. OnEmulationStopTimeExpired();
  1787. OnEmulationStopped();
  1788. }
  1789. void GMainWindow::StoreRecentFile(const QString& filename) {
  1790. UISettings::values.recent_files.prepend(filename);
  1791. UISettings::values.recent_files.removeDuplicates();
  1792. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  1793. UISettings::values.recent_files.removeLast();
  1794. }
  1795. UpdateRecentFiles();
  1796. }
  1797. void GMainWindow::UpdateRecentFiles() {
  1798. const int num_recent_files =
  1799. std::min(static_cast<int>(UISettings::values.recent_files.size()), max_recent_files_item);
  1800. for (int i = 0; i < num_recent_files; i++) {
  1801. const QString text = QStringLiteral("&%1. %2").arg(i + 1).arg(
  1802. QFileInfo(UISettings::values.recent_files[i]).fileName());
  1803. actions_recent_files[i]->setText(text);
  1804. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  1805. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  1806. actions_recent_files[i]->setVisible(true);
  1807. }
  1808. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  1809. actions_recent_files[j]->setVisible(false);
  1810. }
  1811. // Enable the recent files menu if the list isn't empty
  1812. ui->menu_recent_files->setEnabled(num_recent_files != 0);
  1813. }
  1814. void GMainWindow::OnGameListLoadFile(QString game_path, u64 program_id) {
  1815. BootGame(game_path, program_id);
  1816. }
  1817. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target,
  1818. const std::string& game_path) {
  1819. std::filesystem::path path;
  1820. QString open_target;
  1821. const auto [user_save_size, device_save_size] = [this, &game_path, &program_id] {
  1822. const FileSys::PatchManager pm{program_id, system->GetFileSystemController(),
  1823. system->GetContentProvider()};
  1824. const auto control = pm.GetControlMetadata().first;
  1825. if (control != nullptr) {
  1826. return std::make_pair(control->GetDefaultNormalSaveSize(),
  1827. control->GetDeviceSaveDataSize());
  1828. } else {
  1829. const auto file = Core::GetGameFileFromPath(vfs, game_path);
  1830. const auto loader = Loader::GetLoader(*system, file);
  1831. FileSys::NACP nacp{};
  1832. loader->ReadControlData(nacp);
  1833. return std::make_pair(nacp.GetDefaultNormalSaveSize(), nacp.GetDeviceSaveDataSize());
  1834. }
  1835. }();
  1836. const bool has_user_save{user_save_size > 0};
  1837. const bool has_device_save{device_save_size > 0};
  1838. ASSERT_MSG(has_user_save != has_device_save, "Game uses both user and device savedata?");
  1839. switch (target) {
  1840. case GameListOpenTarget::SaveData: {
  1841. open_target = tr("Save Data");
  1842. const auto nand_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir);
  1843. auto vfs_nand_dir =
  1844. vfs->OpenDirectory(Common::FS::PathToUTF8String(nand_dir), FileSys::Mode::Read);
  1845. if (has_user_save) {
  1846. // User save data
  1847. const auto select_profile = [this] {
  1848. const Core::Frontend::ProfileSelectParameters parameters{
  1849. .mode = Service::AM::Applets::UiMode::UserSelector,
  1850. .invalid_uid_list = {},
  1851. .display_options = {},
  1852. .purpose = Service::AM::Applets::UserSelectionPurpose::General,
  1853. };
  1854. QtProfileSelectionDialog dialog(system->HIDCore(), this, parameters);
  1855. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1856. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1857. dialog.setWindowModality(Qt::WindowModal);
  1858. if (dialog.exec() == QDialog::Rejected) {
  1859. return -1;
  1860. }
  1861. return dialog.GetIndex();
  1862. };
  1863. const auto index = select_profile();
  1864. if (index == -1) {
  1865. return;
  1866. }
  1867. Service::Account::ProfileManager manager;
  1868. const auto user_id = manager.GetUser(static_cast<std::size_t>(index));
  1869. ASSERT(user_id);
  1870. const auto user_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1871. *system, vfs_nand_dir, FileSys::SaveDataSpaceId::NandUser,
  1872. FileSys::SaveDataType::SaveData, program_id, user_id->AsU128(), 0);
  1873. path = Common::FS::ConcatPathSafe(nand_dir, user_save_data_path);
  1874. } else {
  1875. // Device save data
  1876. const auto device_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1877. *system, vfs_nand_dir, FileSys::SaveDataSpaceId::NandUser,
  1878. FileSys::SaveDataType::SaveData, program_id, {}, 0);
  1879. path = Common::FS::ConcatPathSafe(nand_dir, device_save_data_path);
  1880. }
  1881. if (!Common::FS::CreateDirs(path)) {
  1882. LOG_ERROR(Frontend, "Unable to create the directories for save data");
  1883. }
  1884. break;
  1885. }
  1886. case GameListOpenTarget::ModData: {
  1887. open_target = tr("Mod Data");
  1888. path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::LoadDir) /
  1889. fmt::format("{:016X}", program_id);
  1890. break;
  1891. }
  1892. default:
  1893. UNIMPLEMENTED();
  1894. break;
  1895. }
  1896. const QString qpath = QString::fromStdString(Common::FS::PathToUTF8String(path));
  1897. const QDir dir(qpath);
  1898. if (!dir.exists()) {
  1899. QMessageBox::warning(this, tr("Error Opening %1 Folder").arg(open_target),
  1900. tr("Folder does not exist!"));
  1901. return;
  1902. }
  1903. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target.toStdString(),
  1904. program_id);
  1905. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  1906. }
  1907. void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
  1908. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1909. const auto shader_cache_folder_path{shader_cache_dir / fmt::format("{:016x}", program_id)};
  1910. if (!Common::FS::CreateDirs(shader_cache_folder_path)) {
  1911. QMessageBox::warning(this, tr("Error Opening Transferable Shader Cache"),
  1912. tr("Failed to create the shader cache directory for this title."));
  1913. return;
  1914. }
  1915. const auto shader_path_string{Common::FS::PathToUTF8String(shader_cache_folder_path)};
  1916. const auto qt_shader_cache_path = QString::fromStdString(shader_path_string);
  1917. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_shader_cache_path));
  1918. }
  1919. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  1920. std::size_t out = 0;
  1921. for (const auto& subdir : dir->GetSubdirectories()) {
  1922. out += 1 + CalculateRomFSEntrySize(subdir, full);
  1923. }
  1924. return out + (full ? dir->GetFiles().size() : 0);
  1925. }
  1926. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  1927. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  1928. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  1929. return false;
  1930. if (dialog.wasCanceled())
  1931. return false;
  1932. if (full) {
  1933. for (const auto& file : src->GetFiles()) {
  1934. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  1935. if (!FileSys::VfsRawCopy(file, out, block_size))
  1936. return false;
  1937. dialog.setValue(dialog.value() + 1);
  1938. if (dialog.wasCanceled())
  1939. return false;
  1940. }
  1941. }
  1942. for (const auto& dir : src->GetSubdirectories()) {
  1943. const auto out = dest->CreateSubdirectory(dir->GetName());
  1944. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  1945. return false;
  1946. dialog.setValue(dialog.value() + 1);
  1947. if (dialog.wasCanceled())
  1948. return false;
  1949. }
  1950. return true;
  1951. }
  1952. QString GMainWindow::GetGameListErrorRemoving(InstalledEntryType type) const {
  1953. switch (type) {
  1954. case InstalledEntryType::Game:
  1955. return tr("Error Removing Contents");
  1956. case InstalledEntryType::Update:
  1957. return tr("Error Removing Update");
  1958. case InstalledEntryType::AddOnContent:
  1959. return tr("Error Removing DLC");
  1960. default:
  1961. return QStringLiteral("Error Removing <Invalid Type>");
  1962. }
  1963. }
  1964. void GMainWindow::OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type) {
  1965. const QString entry_question = [type] {
  1966. switch (type) {
  1967. case InstalledEntryType::Game:
  1968. return tr("Remove Installed Game Contents?");
  1969. case InstalledEntryType::Update:
  1970. return tr("Remove Installed Game Update?");
  1971. case InstalledEntryType::AddOnContent:
  1972. return tr("Remove Installed Game DLC?");
  1973. default:
  1974. return QStringLiteral("Remove Installed Game <Invalid Type>?");
  1975. }
  1976. }();
  1977. if (QMessageBox::question(this, tr("Remove Entry"), entry_question,
  1978. QMessageBox::Yes | QMessageBox::No,
  1979. QMessageBox::No) != QMessageBox::Yes) {
  1980. return;
  1981. }
  1982. switch (type) {
  1983. case InstalledEntryType::Game:
  1984. RemoveBaseContent(program_id, type);
  1985. [[fallthrough]];
  1986. case InstalledEntryType::Update:
  1987. RemoveUpdateContent(program_id, type);
  1988. if (type != InstalledEntryType::Game) {
  1989. break;
  1990. }
  1991. [[fallthrough]];
  1992. case InstalledEntryType::AddOnContent:
  1993. RemoveAddOnContent(program_id, type);
  1994. break;
  1995. }
  1996. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  1997. "game_list");
  1998. game_list->PopulateAsync(UISettings::values.game_dirs);
  1999. }
  2000. void GMainWindow::RemoveBaseContent(u64 program_id, InstalledEntryType type) {
  2001. const auto& fs_controller = system->GetFileSystemController();
  2002. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(program_id) ||
  2003. fs_controller.GetSDMCContents()->RemoveExistingEntry(program_id);
  2004. if (res) {
  2005. QMessageBox::information(this, tr("Successfully Removed"),
  2006. tr("Successfully removed the installed base game."));
  2007. } else {
  2008. QMessageBox::warning(
  2009. this, GetGameListErrorRemoving(type),
  2010. tr("The base game is not installed in the NAND and cannot be removed."));
  2011. }
  2012. }
  2013. void GMainWindow::RemoveUpdateContent(u64 program_id, InstalledEntryType type) {
  2014. const auto update_id = program_id | 0x800;
  2015. const auto& fs_controller = system->GetFileSystemController();
  2016. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(update_id) ||
  2017. fs_controller.GetSDMCContents()->RemoveExistingEntry(update_id);
  2018. if (res) {
  2019. QMessageBox::information(this, tr("Successfully Removed"),
  2020. tr("Successfully removed the installed update."));
  2021. } else {
  2022. QMessageBox::warning(this, GetGameListErrorRemoving(type),
  2023. tr("There is no update installed for this title."));
  2024. }
  2025. }
  2026. void GMainWindow::RemoveAddOnContent(u64 program_id, InstalledEntryType type) {
  2027. u32 count{};
  2028. const auto& fs_controller = system->GetFileSystemController();
  2029. const auto dlc_entries = system->GetContentProvider().ListEntriesFilter(
  2030. FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  2031. for (const auto& entry : dlc_entries) {
  2032. if (FileSys::GetBaseTitleID(entry.title_id) == program_id) {
  2033. const auto res =
  2034. fs_controller.GetUserNANDContents()->RemoveExistingEntry(entry.title_id) ||
  2035. fs_controller.GetSDMCContents()->RemoveExistingEntry(entry.title_id);
  2036. if (res) {
  2037. ++count;
  2038. }
  2039. }
  2040. }
  2041. if (count == 0) {
  2042. QMessageBox::warning(this, GetGameListErrorRemoving(type),
  2043. tr("There are no DLC installed for this title."));
  2044. return;
  2045. }
  2046. QMessageBox::information(this, tr("Successfully Removed"),
  2047. tr("Successfully removed %1 installed DLC.").arg(count));
  2048. }
  2049. void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target,
  2050. const std::string& game_path) {
  2051. const QString question = [target] {
  2052. switch (target) {
  2053. case GameListRemoveTarget::GlShaderCache:
  2054. return tr("Delete OpenGL Transferable Shader Cache?");
  2055. case GameListRemoveTarget::VkShaderCache:
  2056. return tr("Delete Vulkan Transferable Shader Cache?");
  2057. case GameListRemoveTarget::AllShaderCache:
  2058. return tr("Delete All Transferable Shader Caches?");
  2059. case GameListRemoveTarget::CustomConfiguration:
  2060. return tr("Remove Custom Game Configuration?");
  2061. default:
  2062. return QString{};
  2063. }
  2064. }();
  2065. if (QMessageBox::question(this, tr("Remove File"), question, QMessageBox::Yes | QMessageBox::No,
  2066. QMessageBox::No) != QMessageBox::Yes) {
  2067. return;
  2068. }
  2069. switch (target) {
  2070. case GameListRemoveTarget::VkShaderCache:
  2071. RemoveVulkanDriverPipelineCache(program_id);
  2072. [[fallthrough]];
  2073. case GameListRemoveTarget::GlShaderCache:
  2074. RemoveTransferableShaderCache(program_id, target);
  2075. break;
  2076. case GameListRemoveTarget::AllShaderCache:
  2077. RemoveAllTransferableShaderCaches(program_id);
  2078. break;
  2079. case GameListRemoveTarget::CustomConfiguration:
  2080. RemoveCustomConfiguration(program_id, game_path);
  2081. break;
  2082. }
  2083. }
  2084. void GMainWindow::RemoveTransferableShaderCache(u64 program_id, GameListRemoveTarget target) {
  2085. const auto target_file_name = [target] {
  2086. switch (target) {
  2087. case GameListRemoveTarget::GlShaderCache:
  2088. return "opengl.bin";
  2089. case GameListRemoveTarget::VkShaderCache:
  2090. return "vulkan.bin";
  2091. default:
  2092. return "";
  2093. }
  2094. }();
  2095. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  2096. const auto shader_cache_folder_path = shader_cache_dir / fmt::format("{:016x}", program_id);
  2097. const auto target_file = shader_cache_folder_path / target_file_name;
  2098. if (!Common::FS::Exists(target_file)) {
  2099. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  2100. tr("A shader cache for this title does not exist."));
  2101. return;
  2102. }
  2103. if (Common::FS::RemoveFile(target_file)) {
  2104. QMessageBox::information(this, tr("Successfully Removed"),
  2105. tr("Successfully removed the transferable shader cache."));
  2106. } else {
  2107. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  2108. tr("Failed to remove the transferable shader cache."));
  2109. }
  2110. }
  2111. void GMainWindow::RemoveVulkanDriverPipelineCache(u64 program_id) {
  2112. static constexpr std::string_view target_file_name = "vulkan_pipelines.bin";
  2113. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  2114. const auto shader_cache_folder_path = shader_cache_dir / fmt::format("{:016x}", program_id);
  2115. const auto target_file = shader_cache_folder_path / target_file_name;
  2116. if (!Common::FS::Exists(target_file)) {
  2117. return;
  2118. }
  2119. if (!Common::FS::RemoveFile(target_file)) {
  2120. QMessageBox::warning(this, tr("Error Removing Vulkan Driver Pipeline Cache"),
  2121. tr("Failed to remove the driver pipeline cache."));
  2122. }
  2123. }
  2124. void GMainWindow::RemoveAllTransferableShaderCaches(u64 program_id) {
  2125. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  2126. const auto program_shader_cache_dir = shader_cache_dir / fmt::format("{:016x}", program_id);
  2127. if (!Common::FS::Exists(program_shader_cache_dir)) {
  2128. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  2129. tr("A shader cache for this title does not exist."));
  2130. return;
  2131. }
  2132. if (Common::FS::RemoveDirRecursively(program_shader_cache_dir)) {
  2133. QMessageBox::information(this, tr("Successfully Removed"),
  2134. tr("Successfully removed the transferable shader caches."));
  2135. } else {
  2136. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  2137. tr("Failed to remove the transferable shader cache directory."));
  2138. }
  2139. }
  2140. void GMainWindow::RemoveCustomConfiguration(u64 program_id, const std::string& game_path) {
  2141. const auto file_path = std::filesystem::path(Common::FS::ToU8String(game_path));
  2142. const auto config_file_name =
  2143. program_id == 0 ? Common::FS::PathToUTF8String(file_path.filename()).append(".ini")
  2144. : fmt::format("{:016X}.ini", program_id);
  2145. const auto custom_config_file_path =
  2146. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom" / config_file_name;
  2147. if (!Common::FS::Exists(custom_config_file_path)) {
  2148. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  2149. tr("A custom configuration for this title does not exist."));
  2150. return;
  2151. }
  2152. if (Common::FS::RemoveFile(custom_config_file_path)) {
  2153. QMessageBox::information(this, tr("Successfully Removed"),
  2154. tr("Successfully removed the custom game configuration."));
  2155. } else {
  2156. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  2157. tr("Failed to remove the custom game configuration."));
  2158. }
  2159. }
  2160. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path,
  2161. DumpRomFSTarget target) {
  2162. const auto failed = [this] {
  2163. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  2164. tr("There was an error copying the RomFS files or the user "
  2165. "cancelled the operation."));
  2166. };
  2167. const auto loader = Loader::GetLoader(*system, vfs->OpenFile(game_path, FileSys::Mode::Read));
  2168. if (loader == nullptr) {
  2169. failed();
  2170. return;
  2171. }
  2172. FileSys::VirtualFile file;
  2173. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  2174. failed();
  2175. return;
  2176. }
  2177. const auto& installed = system->GetContentProvider();
  2178. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  2179. if (!romfs_title_id) {
  2180. failed();
  2181. return;
  2182. }
  2183. const auto dump_dir =
  2184. target == DumpRomFSTarget::Normal
  2185. ? Common::FS::GetYuzuPath(Common::FS::YuzuPath::DumpDir)
  2186. : Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "atmosphere" / "contents";
  2187. const auto romfs_dir = fmt::format("{:016X}/romfs", *romfs_title_id);
  2188. const auto path = Common::FS::PathToUTF8String(dump_dir / romfs_dir);
  2189. FileSys::VirtualFile romfs;
  2190. if (*romfs_title_id == program_id) {
  2191. const u64 ivfc_offset = loader->ReadRomFSIVFCOffset();
  2192. const FileSys::PatchManager pm{program_id, system->GetFileSystemController(), installed};
  2193. romfs =
  2194. pm.PatchRomFS(file, ivfc_offset, FileSys::ContentRecordType::Program, nullptr, false);
  2195. } else {
  2196. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  2197. }
  2198. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  2199. if (extracted == nullptr) {
  2200. failed();
  2201. return;
  2202. }
  2203. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  2204. if (out == nullptr) {
  2205. failed();
  2206. vfs->DeleteDirectory(path);
  2207. return;
  2208. }
  2209. bool ok = false;
  2210. const QStringList selections{tr("Full"), tr("Skeleton")};
  2211. const auto res = QInputDialog::getItem(
  2212. this, tr("Select RomFS Dump Mode"),
  2213. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  2214. "files into the new directory while <br>skeleton will only create the directory "
  2215. "structure."),
  2216. selections, 0, false, &ok);
  2217. if (!ok) {
  2218. failed();
  2219. vfs->DeleteDirectory(path);
  2220. return;
  2221. }
  2222. const auto full = res == selections.constFirst();
  2223. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  2224. // The minimum required space is the size of the extracted RomFS + 1 GiB
  2225. const auto minimum_free_space = extracted->GetSize() + 0x40000000;
  2226. if (full && Common::FS::GetFreeSpaceSize(path) < minimum_free_space) {
  2227. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  2228. tr("There is not enough free space at %1 to extract the RomFS. Please "
  2229. "free up space or select a different dump directory at "
  2230. "Emulation > Configure > System > Filesystem > Dump Root")
  2231. .arg(QString::fromStdString(path)));
  2232. return;
  2233. }
  2234. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  2235. static_cast<s32>(entry_size), this);
  2236. progress.setWindowModality(Qt::WindowModal);
  2237. progress.setMinimumDuration(100);
  2238. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  2239. progress.close();
  2240. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  2241. tr("The operation completed successfully."));
  2242. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  2243. } else {
  2244. progress.close();
  2245. failed();
  2246. vfs->DeleteDirectory(path);
  2247. }
  2248. }
  2249. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  2250. QClipboard* clipboard = QGuiApplication::clipboard();
  2251. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  2252. }
  2253. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  2254. const CompatibilityList& compatibility_list) {
  2255. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  2256. QString directory;
  2257. if (it != compatibility_list.end()) {
  2258. directory = it->second.second;
  2259. }
  2260. QDesktopServices::openUrl(QUrl(QStringLiteral("https://yuzu-emu.org/game/") + directory));
  2261. }
  2262. void GMainWindow::OnGameListCreateShortcut(u64 program_id, const std::string& game_path,
  2263. GameListShortcutTarget target) {
  2264. // Get path to yuzu executable
  2265. const QStringList args = QApplication::arguments();
  2266. std::filesystem::path yuzu_command = args[0].toStdString();
  2267. #if defined(__linux__) || defined(__FreeBSD__)
  2268. // If relative path, make it an absolute path
  2269. if (yuzu_command.c_str()[0] == '.') {
  2270. yuzu_command = Common::FS::GetCurrentDir() / yuzu_command;
  2271. }
  2272. #if defined(__linux__)
  2273. // Warn once if we are making a shortcut to a volatile AppImage
  2274. const std::string appimage_ending =
  2275. std::string(Common::g_scm_rev).substr(0, 9).append(".AppImage");
  2276. if (yuzu_command.string().ends_with(appimage_ending) &&
  2277. !UISettings::values.shortcut_already_warned) {
  2278. if (QMessageBox::warning(this, tr("Create Shortcut"),
  2279. tr("This will create a shortcut to the current AppImage. This may "
  2280. "not work well if you update. Continue?"),
  2281. QMessageBox::StandardButton::Ok |
  2282. QMessageBox::StandardButton::Cancel) ==
  2283. QMessageBox::StandardButton::Cancel) {
  2284. return;
  2285. }
  2286. UISettings::values.shortcut_already_warned = true;
  2287. }
  2288. #endif // __linux__
  2289. #endif // __linux__ || __FreeBSD__
  2290. std::filesystem::path target_directory{};
  2291. // Determine target directory for shortcut
  2292. #if defined(__linux__) || defined(__FreeBSD__)
  2293. const char* home = std::getenv("HOME");
  2294. const std::filesystem::path home_path = (home == nullptr ? "~" : home);
  2295. const char* xdg_data_home = std::getenv("XDG_DATA_HOME");
  2296. if (target == GameListShortcutTarget::Desktop) {
  2297. target_directory = home_path / "Desktop";
  2298. if (!Common::FS::IsDir(target_directory)) {
  2299. QMessageBox::critical(
  2300. this, tr("Create Shortcut"),
  2301. tr("Cannot create shortcut on desktop. Path \"%1\" does not exist.")
  2302. .arg(QString::fromStdString(target_directory)),
  2303. QMessageBox::StandardButton::Ok);
  2304. return;
  2305. }
  2306. } else if (target == GameListShortcutTarget::Applications) {
  2307. target_directory = (xdg_data_home == nullptr ? home_path / ".local/share" : xdg_data_home) /
  2308. "applications";
  2309. if (!Common::FS::CreateDirs(target_directory)) {
  2310. QMessageBox::critical(this, tr("Create Shortcut"),
  2311. tr("Cannot create shortcut in applications menu. Path \"%1\" "
  2312. "does not exist and cannot be created.")
  2313. .arg(QString::fromStdString(target_directory)),
  2314. QMessageBox::StandardButton::Ok);
  2315. return;
  2316. }
  2317. }
  2318. #endif
  2319. const std::string game_file_name = std::filesystem::path(game_path).filename().string();
  2320. // Determine full paths for icon and shortcut
  2321. #if defined(__linux__) || defined(__FreeBSD__)
  2322. std::filesystem::path system_icons_path =
  2323. (xdg_data_home == nullptr ? home_path / ".local/share/" : xdg_data_home) /
  2324. "icons/hicolor/256x256";
  2325. if (!Common::FS::CreateDirs(system_icons_path)) {
  2326. QMessageBox::critical(
  2327. this, tr("Create Icon"),
  2328. tr("Cannot create icon file. Path \"%1\" does not exist and cannot be created.")
  2329. .arg(QString::fromStdString(system_icons_path)),
  2330. QMessageBox::StandardButton::Ok);
  2331. return;
  2332. }
  2333. std::filesystem::path icon_path =
  2334. system_icons_path / (program_id == 0 ? fmt::format("yuzu-{}.png", game_file_name)
  2335. : fmt::format("yuzu-{:016X}.png", program_id));
  2336. const std::filesystem::path shortcut_path =
  2337. target_directory / (program_id == 0 ? fmt::format("yuzu-{}.desktop", game_file_name)
  2338. : fmt::format("yuzu-{:016X}.desktop", program_id));
  2339. #else
  2340. const std::filesystem::path icon_path{};
  2341. const std::filesystem::path shortcut_path{};
  2342. #endif
  2343. // Get title from game file
  2344. const FileSys::PatchManager pm{program_id, system->GetFileSystemController(),
  2345. system->GetContentProvider()};
  2346. const auto control = pm.GetControlMetadata();
  2347. const auto loader = Loader::GetLoader(*system, vfs->OpenFile(game_path, FileSys::Mode::Read));
  2348. std::string title{fmt::format("{:016X}", program_id)};
  2349. if (control.first != nullptr) {
  2350. title = control.first->GetApplicationName();
  2351. } else {
  2352. loader->ReadTitle(title);
  2353. }
  2354. // Get icon from game file
  2355. std::vector<u8> icon_image_file{};
  2356. if (control.second != nullptr) {
  2357. icon_image_file = control.second->ReadAllBytes();
  2358. } else if (loader->ReadIcon(icon_image_file) != Loader::ResultStatus::Success) {
  2359. LOG_WARNING(Frontend, "Could not read icon from {:s}", game_path);
  2360. }
  2361. QImage icon_jpeg =
  2362. QImage::fromData(icon_image_file.data(), static_cast<int>(icon_image_file.size()));
  2363. #if defined(__linux__) || defined(__FreeBSD__)
  2364. // Convert and write the icon as a PNG
  2365. if (!icon_jpeg.save(QString::fromStdString(icon_path.string()))) {
  2366. LOG_ERROR(Frontend, "Could not write icon as PNG to file");
  2367. } else {
  2368. LOG_INFO(Frontend, "Wrote an icon to {}", icon_path.string());
  2369. }
  2370. #endif // __linux__
  2371. #if defined(__linux__) || defined(__FreeBSD__)
  2372. const std::string comment =
  2373. tr("Start %1 with the yuzu Emulator").arg(QString::fromStdString(title)).toStdString();
  2374. const std::string arguments = fmt::format("-g \"{:s}\"", game_path);
  2375. const std::string categories = "Game;Emulator;Qt;";
  2376. const std::string keywords = "Switch;Nintendo;";
  2377. #else
  2378. const std::string comment{};
  2379. const std::string arguments{};
  2380. const std::string categories{};
  2381. const std::string keywords{};
  2382. #endif
  2383. if (!CreateShortcut(shortcut_path.string(), title, comment, icon_path.string(),
  2384. yuzu_command.string(), arguments, categories, keywords)) {
  2385. QMessageBox::critical(this, tr("Create Shortcut"),
  2386. tr("Failed to create a shortcut at %1")
  2387. .arg(QString::fromStdString(shortcut_path.string())));
  2388. return;
  2389. }
  2390. LOG_INFO(Frontend, "Wrote a shortcut to {}", shortcut_path.string());
  2391. QMessageBox::information(
  2392. this, tr("Create Shortcut"),
  2393. tr("Successfully created a shortcut to %1").arg(QString::fromStdString(title)));
  2394. }
  2395. void GMainWindow::OnGameListOpenDirectory(const QString& directory) {
  2396. std::filesystem::path fs_path;
  2397. if (directory == QStringLiteral("SDMC")) {
  2398. fs_path =
  2399. Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "Nintendo/Contents/registered";
  2400. } else if (directory == QStringLiteral("UserNAND")) {
  2401. fs_path =
  2402. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "user/Contents/registered";
  2403. } else if (directory == QStringLiteral("SysNAND")) {
  2404. fs_path =
  2405. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "system/Contents/registered";
  2406. } else {
  2407. fs_path = directory.toStdString();
  2408. }
  2409. const auto qt_path = QString::fromStdString(Common::FS::PathToUTF8String(fs_path));
  2410. if (!Common::FS::IsDir(fs_path)) {
  2411. QMessageBox::critical(this, tr("Error Opening %1").arg(qt_path),
  2412. tr("Folder does not exist!"));
  2413. return;
  2414. }
  2415. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_path));
  2416. }
  2417. void GMainWindow::OnGameListAddDirectory() {
  2418. const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  2419. if (dir_path.isEmpty()) {
  2420. return;
  2421. }
  2422. UISettings::GameDir game_dir{dir_path, false, true};
  2423. if (!UISettings::values.game_dirs.contains(game_dir)) {
  2424. UISettings::values.game_dirs.append(game_dir);
  2425. game_list->PopulateAsync(UISettings::values.game_dirs);
  2426. } else {
  2427. LOG_WARNING(Frontend, "Selected directory is already in the game list");
  2428. }
  2429. OnSaveConfig();
  2430. }
  2431. void GMainWindow::OnGameListShowList(bool show) {
  2432. if (emulation_running && ui->action_Single_Window_Mode->isChecked())
  2433. return;
  2434. game_list->setVisible(show);
  2435. game_list_placeholder->setVisible(!show);
  2436. };
  2437. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  2438. u64 title_id{};
  2439. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  2440. const auto loader = Loader::GetLoader(*system, v_file);
  2441. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  2442. QMessageBox::information(this, tr("Properties"),
  2443. tr("The game properties could not be loaded."));
  2444. return;
  2445. }
  2446. OpenPerGameConfiguration(title_id, file);
  2447. }
  2448. void GMainWindow::OnMenuLoadFile() {
  2449. if (is_load_file_select_active) {
  2450. return;
  2451. }
  2452. is_load_file_select_active = true;
  2453. const QString extensions =
  2454. QStringLiteral("*.")
  2455. .append(GameList::supported_file_extensions.join(QStringLiteral(" *.")))
  2456. .append(QStringLiteral(" main"));
  2457. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  2458. "%1 is an identifier for the Switch executable file extensions.")
  2459. .arg(extensions);
  2460. const QString filename = QFileDialog::getOpenFileName(
  2461. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  2462. is_load_file_select_active = false;
  2463. if (filename.isEmpty()) {
  2464. return;
  2465. }
  2466. UISettings::values.roms_path = QFileInfo(filename).path();
  2467. BootGame(filename);
  2468. }
  2469. void GMainWindow::OnMenuLoadFolder() {
  2470. const QString dir_path =
  2471. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  2472. if (dir_path.isNull()) {
  2473. return;
  2474. }
  2475. const QDir dir{dir_path};
  2476. const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files);
  2477. if (matching_main.size() == 1) {
  2478. BootGame(dir.path() + QDir::separator() + matching_main[0]);
  2479. } else {
  2480. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  2481. tr("The directory you have selected does not contain a 'main' file."));
  2482. }
  2483. }
  2484. void GMainWindow::IncrementInstallProgress() {
  2485. install_progress->setValue(install_progress->value() + 1);
  2486. }
  2487. void GMainWindow::OnMenuInstallToNAND() {
  2488. const QString file_filter =
  2489. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  2490. "(*.nca);;Nintendo Submission Package (*.nsp);;NX Cartridge "
  2491. "Image (*.xci)");
  2492. QStringList filenames = QFileDialog::getOpenFileNames(
  2493. this, tr("Install Files"), UISettings::values.roms_path, file_filter);
  2494. if (filenames.isEmpty()) {
  2495. return;
  2496. }
  2497. InstallDialog installDialog(this, filenames);
  2498. if (installDialog.exec() == QDialog::Rejected) {
  2499. return;
  2500. }
  2501. const QStringList files = installDialog.GetFiles();
  2502. if (files.isEmpty()) {
  2503. return;
  2504. }
  2505. // Save folder location of the first selected file
  2506. UISettings::values.roms_path = QFileInfo(filenames[0]).path();
  2507. int remaining = filenames.size();
  2508. // This would only overflow above 2^43 bytes (8.796 TB)
  2509. int total_size = 0;
  2510. for (const QString& file : files) {
  2511. total_size += static_cast<int>(QFile(file).size() / 0x1000);
  2512. }
  2513. if (total_size < 0) {
  2514. LOG_CRITICAL(Frontend, "Attempting to install too many files, aborting.");
  2515. return;
  2516. }
  2517. QStringList new_files{}; // Newly installed files that do not yet exist in the NAND
  2518. QStringList overwritten_files{}; // Files that overwrote those existing in the NAND
  2519. QStringList failed_files{}; // Files that failed to install due to errors
  2520. bool detected_base_install{}; // Whether a base game was attempted to be installed
  2521. ui->action_Install_File_NAND->setEnabled(false);
  2522. install_progress = new QProgressDialog(QString{}, tr("Cancel"), 0, total_size, this);
  2523. install_progress->setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint);
  2524. install_progress->setAttribute(Qt::WA_DeleteOnClose, true);
  2525. install_progress->setFixedWidth(installDialog.GetMinimumWidth() + 40);
  2526. install_progress->show();
  2527. for (const QString& file : files) {
  2528. install_progress->setWindowTitle(tr("%n file(s) remaining", "", remaining));
  2529. install_progress->setLabelText(
  2530. tr("Installing file \"%1\"...").arg(QFileInfo(file).fileName()));
  2531. QFuture<InstallResult> future;
  2532. InstallResult result;
  2533. if (file.endsWith(QStringLiteral("xci"), Qt::CaseInsensitive) ||
  2534. file.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  2535. future = QtConcurrent::run([this, &file] { return InstallNSPXCI(file); });
  2536. while (!future.isFinished()) {
  2537. QCoreApplication::processEvents();
  2538. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2539. }
  2540. result = future.result();
  2541. } else {
  2542. result = InstallNCA(file);
  2543. }
  2544. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2545. switch (result) {
  2546. case InstallResult::Success:
  2547. new_files.append(QFileInfo(file).fileName());
  2548. break;
  2549. case InstallResult::Overwrite:
  2550. overwritten_files.append(QFileInfo(file).fileName());
  2551. break;
  2552. case InstallResult::Failure:
  2553. failed_files.append(QFileInfo(file).fileName());
  2554. break;
  2555. case InstallResult::BaseInstallAttempted:
  2556. failed_files.append(QFileInfo(file).fileName());
  2557. detected_base_install = true;
  2558. break;
  2559. }
  2560. --remaining;
  2561. }
  2562. install_progress->close();
  2563. if (detected_base_install) {
  2564. QMessageBox::warning(
  2565. this, tr("Install Results"),
  2566. tr("To avoid possible conflicts, we discourage users from installing base games to the "
  2567. "NAND.\nPlease, only use this feature to install updates and DLC."));
  2568. }
  2569. const QString install_results =
  2570. (new_files.isEmpty() ? QString{}
  2571. : tr("%n file(s) were newly installed\n", "", new_files.size())) +
  2572. (overwritten_files.isEmpty()
  2573. ? QString{}
  2574. : tr("%n file(s) were overwritten\n", "", overwritten_files.size())) +
  2575. (failed_files.isEmpty() ? QString{}
  2576. : tr("%n file(s) failed to install\n", "", failed_files.size()));
  2577. QMessageBox::information(this, tr("Install Results"), install_results);
  2578. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  2579. "game_list");
  2580. game_list->PopulateAsync(UISettings::values.game_dirs);
  2581. ui->action_Install_File_NAND->setEnabled(true);
  2582. }
  2583. InstallResult GMainWindow::InstallNSPXCI(const QString& filename) {
  2584. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  2585. const FileSys::VirtualFile& dest, std::size_t block_size) {
  2586. if (src == nullptr || dest == nullptr) {
  2587. return false;
  2588. }
  2589. if (!dest->Resize(src->GetSize())) {
  2590. return false;
  2591. }
  2592. std::array<u8, 0x1000> buffer{};
  2593. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  2594. if (install_progress->wasCanceled()) {
  2595. dest->Resize(0);
  2596. return false;
  2597. }
  2598. emit UpdateInstallProgress();
  2599. const auto read = src->Read(buffer.data(), buffer.size(), i);
  2600. dest->Write(buffer.data(), read, i);
  2601. }
  2602. return true;
  2603. };
  2604. std::shared_ptr<FileSys::NSP> nsp;
  2605. if (filename.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  2606. nsp = std::make_shared<FileSys::NSP>(
  2607. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  2608. if (nsp->IsExtractedType()) {
  2609. return InstallResult::Failure;
  2610. }
  2611. } else {
  2612. const auto xci = std::make_shared<FileSys::XCI>(
  2613. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  2614. nsp = xci->GetSecurePartitionNSP();
  2615. }
  2616. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  2617. return InstallResult::Failure;
  2618. }
  2619. const auto res = system->GetFileSystemController().GetUserNANDContents()->InstallEntry(
  2620. *nsp, true, qt_raw_copy);
  2621. switch (res) {
  2622. case FileSys::InstallResult::Success:
  2623. return InstallResult::Success;
  2624. case FileSys::InstallResult::OverwriteExisting:
  2625. return InstallResult::Overwrite;
  2626. case FileSys::InstallResult::ErrorBaseInstall:
  2627. return InstallResult::BaseInstallAttempted;
  2628. default:
  2629. return InstallResult::Failure;
  2630. }
  2631. }
  2632. InstallResult GMainWindow::InstallNCA(const QString& filename) {
  2633. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  2634. const FileSys::VirtualFile& dest, std::size_t block_size) {
  2635. if (src == nullptr || dest == nullptr) {
  2636. return false;
  2637. }
  2638. if (!dest->Resize(src->GetSize())) {
  2639. return false;
  2640. }
  2641. std::array<u8, 0x1000> buffer{};
  2642. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  2643. if (install_progress->wasCanceled()) {
  2644. dest->Resize(0);
  2645. return false;
  2646. }
  2647. emit UpdateInstallProgress();
  2648. const auto read = src->Read(buffer.data(), buffer.size(), i);
  2649. dest->Write(buffer.data(), read, i);
  2650. }
  2651. return true;
  2652. };
  2653. const auto nca =
  2654. std::make_shared<FileSys::NCA>(vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  2655. const auto id = nca->GetStatus();
  2656. // Game updates necessary are missing base RomFS
  2657. if (id != Loader::ResultStatus::Success &&
  2658. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  2659. return InstallResult::Failure;
  2660. }
  2661. const QStringList tt_options{tr("System Application"),
  2662. tr("System Archive"),
  2663. tr("System Application Update"),
  2664. tr("Firmware Package (Type A)"),
  2665. tr("Firmware Package (Type B)"),
  2666. tr("Game"),
  2667. tr("Game Update"),
  2668. tr("Game DLC"),
  2669. tr("Delta Title")};
  2670. bool ok;
  2671. const auto item = QInputDialog::getItem(
  2672. this, tr("Select NCA Install Type..."),
  2673. tr("Please select the type of title you would like to install this NCA as:\n(In "
  2674. "most instances, the default 'Game' is fine.)"),
  2675. tt_options, 5, false, &ok);
  2676. auto index = tt_options.indexOf(item);
  2677. if (!ok || index == -1) {
  2678. QMessageBox::warning(this, tr("Failed to Install"),
  2679. tr("The title type you selected for the NCA is invalid."));
  2680. return InstallResult::Failure;
  2681. }
  2682. // If index is equal to or past Game, add the jump in TitleType.
  2683. if (index >= 5) {
  2684. index += static_cast<size_t>(FileSys::TitleType::Application) -
  2685. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  2686. }
  2687. const bool is_application = index >= static_cast<s32>(FileSys::TitleType::Application);
  2688. const auto& fs_controller = system->GetFileSystemController();
  2689. auto* registered_cache = is_application ? fs_controller.GetUserNANDContents()
  2690. : fs_controller.GetSystemNANDContents();
  2691. const auto res = registered_cache->InstallEntry(*nca, static_cast<FileSys::TitleType>(index),
  2692. true, qt_raw_copy);
  2693. if (res == FileSys::InstallResult::Success) {
  2694. return InstallResult::Success;
  2695. } else if (res == FileSys::InstallResult::OverwriteExisting) {
  2696. return InstallResult::Overwrite;
  2697. } else {
  2698. return InstallResult::Failure;
  2699. }
  2700. }
  2701. void GMainWindow::OnMenuRecentFile() {
  2702. QAction* action = qobject_cast<QAction*>(sender());
  2703. assert(action);
  2704. const QString filename = action->data().toString();
  2705. if (QFileInfo::exists(filename)) {
  2706. BootGame(filename);
  2707. } else {
  2708. // Display an error message and remove the file from the list.
  2709. QMessageBox::information(this, tr("File not found"),
  2710. tr("File \"%1\" not found").arg(filename));
  2711. UISettings::values.recent_files.removeOne(filename);
  2712. UpdateRecentFiles();
  2713. }
  2714. }
  2715. void GMainWindow::OnStartGame() {
  2716. PreventOSSleep();
  2717. emu_thread->SetRunning(true);
  2718. UpdateMenuState();
  2719. OnTasStateChanged();
  2720. discord_rpc->Update();
  2721. }
  2722. void GMainWindow::OnRestartGame() {
  2723. if (!system->IsPoweredOn()) {
  2724. return;
  2725. }
  2726. // Make a copy since ShutdownGame edits game_path
  2727. const auto current_game = QString(current_game_path);
  2728. ShutdownGame();
  2729. BootGame(current_game);
  2730. }
  2731. void GMainWindow::OnPauseGame() {
  2732. emu_thread->SetRunning(false);
  2733. UpdateMenuState();
  2734. AllowOSSleep();
  2735. }
  2736. void GMainWindow::OnPauseContinueGame() {
  2737. if (emulation_running) {
  2738. if (emu_thread->IsRunning()) {
  2739. OnPauseGame();
  2740. } else {
  2741. RequestGameResume();
  2742. OnStartGame();
  2743. }
  2744. }
  2745. }
  2746. void GMainWindow::OnStopGame() {
  2747. if (system->GetExitLock() && !ConfirmForceLockedExit()) {
  2748. return;
  2749. }
  2750. if (OnShutdownBegin()) {
  2751. OnShutdownBeginDialog();
  2752. } else {
  2753. OnEmulationStopped();
  2754. }
  2755. }
  2756. void GMainWindow::OnLoadComplete() {
  2757. loading_screen->OnLoadComplete();
  2758. }
  2759. void GMainWindow::OnExecuteProgram(std::size_t program_index) {
  2760. ShutdownGame();
  2761. BootGame(last_filename_booted, 0, program_index);
  2762. }
  2763. void GMainWindow::OnExit() {
  2764. OnStopGame();
  2765. }
  2766. void GMainWindow::OnSaveConfig() {
  2767. system->ApplySettings();
  2768. config->Save();
  2769. }
  2770. void GMainWindow::ErrorDisplayDisplayError(QString error_code, QString error_text) {
  2771. error_applet = new OverlayDialog(render_window, *system, error_code, error_text, QString{},
  2772. tr("OK"), Qt::AlignLeft | Qt::AlignVCenter);
  2773. SCOPE_EXIT({
  2774. error_applet->deleteLater();
  2775. error_applet = nullptr;
  2776. });
  2777. error_applet->exec();
  2778. emit ErrorDisplayFinished();
  2779. }
  2780. void GMainWindow::ErrorDisplayRequestExit() {
  2781. if (error_applet) {
  2782. error_applet->reject();
  2783. }
  2784. }
  2785. void GMainWindow::OnMenuReportCompatibility() {
  2786. #if defined(ARCHITECTURE_x86_64) && !defined(__APPLE__)
  2787. const auto& caps = Common::GetCPUCaps();
  2788. const bool has_fma = caps.fma || caps.fma4;
  2789. const auto processor_count = std::thread::hardware_concurrency();
  2790. const bool has_4threads = processor_count == 0 || processor_count >= 4;
  2791. const bool has_8gb_ram = Common::GetMemInfo().TotalPhysicalMemory >= 8_GiB;
  2792. const bool has_broken_vulkan = UISettings::values.has_broken_vulkan;
  2793. if (!has_fma || !has_4threads || !has_8gb_ram || has_broken_vulkan) {
  2794. QMessageBox::critical(this, tr("Hardware requirements not met"),
  2795. tr("Your system does not meet the recommended hardware requirements. "
  2796. "Compatibility reporting has been disabled."));
  2797. return;
  2798. }
  2799. if (!Settings::values.yuzu_token.GetValue().empty() &&
  2800. !Settings::values.yuzu_username.GetValue().empty()) {
  2801. CompatDB compatdb{system->TelemetrySession(), this};
  2802. compatdb.exec();
  2803. } else {
  2804. QMessageBox::critical(
  2805. this, tr("Missing yuzu Account"),
  2806. tr("In order to submit a game compatibility test case, you must link your yuzu "
  2807. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  2808. "&gt; "
  2809. "Web."));
  2810. }
  2811. #else
  2812. QMessageBox::critical(this, tr("Hardware requirements not met"),
  2813. tr("Your system does not meet the recommended hardware requirements. "
  2814. "Compatibility reporting has been disabled."));
  2815. #endif
  2816. }
  2817. void GMainWindow::OpenURL(const QUrl& url) {
  2818. const bool open = QDesktopServices::openUrl(url);
  2819. if (!open) {
  2820. QMessageBox::warning(this, tr("Error opening URL"),
  2821. tr("Unable to open the URL \"%1\".").arg(url.toString()));
  2822. }
  2823. }
  2824. void GMainWindow::OnOpenModsPage() {
  2825. OpenURL(QUrl(QStringLiteral("https://github.com/yuzu-emu/yuzu/wiki/Switch-Mods")));
  2826. }
  2827. void GMainWindow::OnOpenQuickstartGuide() {
  2828. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/help/quickstart/")));
  2829. }
  2830. void GMainWindow::OnOpenFAQ() {
  2831. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/wiki/faq/")));
  2832. }
  2833. void GMainWindow::ToggleFullscreen() {
  2834. if (!emulation_running) {
  2835. return;
  2836. }
  2837. if (ui->action_Fullscreen->isChecked()) {
  2838. ShowFullscreen();
  2839. } else {
  2840. HideFullscreen();
  2841. }
  2842. }
  2843. // We're going to return the screen that the given window has the most pixels on
  2844. static QScreen* GuessCurrentScreen(QWidget* window) {
  2845. const QList<QScreen*> screens = QGuiApplication::screens();
  2846. return *std::max_element(
  2847. screens.cbegin(), screens.cend(), [window](const QScreen* left, const QScreen* right) {
  2848. const QSize left_size = left->geometry().intersected(window->geometry()).size();
  2849. const QSize right_size = right->geometry().intersected(window->geometry()).size();
  2850. return (left_size.height() * left_size.width()) <
  2851. (right_size.height() * right_size.width());
  2852. });
  2853. }
  2854. bool GMainWindow::UsingExclusiveFullscreen() {
  2855. return Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive ||
  2856. QGuiApplication::platformName() == QStringLiteral("wayland") ||
  2857. QGuiApplication::platformName() == QStringLiteral("wayland-egl");
  2858. }
  2859. void GMainWindow::ShowFullscreen() {
  2860. const auto show_fullscreen = [this](QWidget* window) {
  2861. if (UsingExclusiveFullscreen()) {
  2862. window->showFullScreen();
  2863. return;
  2864. }
  2865. window->hide();
  2866. window->setWindowFlags(window->windowFlags() | Qt::FramelessWindowHint);
  2867. const auto screen_geometry = GuessCurrentScreen(window)->geometry();
  2868. window->setGeometry(screen_geometry.x(), screen_geometry.y(), screen_geometry.width(),
  2869. screen_geometry.height() + 1);
  2870. window->raise();
  2871. window->showNormal();
  2872. };
  2873. if (ui->action_Single_Window_Mode->isChecked()) {
  2874. UISettings::values.geometry = saveGeometry();
  2875. ui->menubar->hide();
  2876. statusBar()->hide();
  2877. show_fullscreen(this);
  2878. } else {
  2879. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2880. show_fullscreen(render_window);
  2881. }
  2882. }
  2883. void GMainWindow::HideFullscreen() {
  2884. if (ui->action_Single_Window_Mode->isChecked()) {
  2885. if (UsingExclusiveFullscreen()) {
  2886. showNormal();
  2887. restoreGeometry(UISettings::values.geometry);
  2888. } else {
  2889. hide();
  2890. setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2891. restoreGeometry(UISettings::values.geometry);
  2892. raise();
  2893. show();
  2894. }
  2895. statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
  2896. ui->menubar->show();
  2897. } else {
  2898. if (UsingExclusiveFullscreen()) {
  2899. render_window->showNormal();
  2900. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2901. } else {
  2902. render_window->hide();
  2903. render_window->setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2904. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2905. render_window->raise();
  2906. render_window->show();
  2907. }
  2908. }
  2909. }
  2910. void GMainWindow::ToggleWindowMode() {
  2911. if (ui->action_Single_Window_Mode->isChecked()) {
  2912. // Render in the main window...
  2913. render_window->BackupGeometry();
  2914. ui->horizontalLayout->addWidget(render_window);
  2915. render_window->setFocusPolicy(Qt::StrongFocus);
  2916. if (emulation_running) {
  2917. render_window->setVisible(true);
  2918. render_window->setFocus();
  2919. game_list->hide();
  2920. }
  2921. } else {
  2922. // Render in a separate window...
  2923. ui->horizontalLayout->removeWidget(render_window);
  2924. render_window->setParent(nullptr);
  2925. render_window->setFocusPolicy(Qt::NoFocus);
  2926. if (emulation_running) {
  2927. render_window->setVisible(true);
  2928. render_window->RestoreGeometry();
  2929. game_list->show();
  2930. }
  2931. }
  2932. }
  2933. void GMainWindow::ResetWindowSize(u32 width, u32 height) {
  2934. const auto aspect_ratio = Layout::EmulationAspectRatio(
  2935. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  2936. static_cast<float>(height) / width);
  2937. if (!ui->action_Single_Window_Mode->isChecked()) {
  2938. render_window->resize(height / aspect_ratio, height);
  2939. } else {
  2940. const bool show_status_bar = ui->action_Show_Status_Bar->isChecked();
  2941. const auto status_bar_height = show_status_bar ? statusBar()->height() : 0;
  2942. resize(height / aspect_ratio, height + menuBar()->height() + status_bar_height);
  2943. }
  2944. }
  2945. void GMainWindow::ResetWindowSize720() {
  2946. ResetWindowSize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  2947. }
  2948. void GMainWindow::ResetWindowSize900() {
  2949. ResetWindowSize(1600U, 900U);
  2950. }
  2951. void GMainWindow::ResetWindowSize1080() {
  2952. ResetWindowSize(Layout::ScreenDocked::Width, Layout::ScreenDocked::Height);
  2953. }
  2954. void GMainWindow::OnConfigure() {
  2955. const auto old_theme = UISettings::values.theme;
  2956. const bool old_discord_presence = UISettings::values.enable_discord_presence.GetValue();
  2957. Settings::SetConfiguringGlobal(true);
  2958. ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get(), *system,
  2959. !multiplayer_state->IsHostingPublicRoom());
  2960. connect(&configure_dialog, &ConfigureDialog::LanguageChanged, this,
  2961. &GMainWindow::OnLanguageChanged);
  2962. const auto result = configure_dialog.exec();
  2963. if (result != QDialog::Accepted && !UISettings::values.configuration_applied &&
  2964. !UISettings::values.reset_to_defaults) {
  2965. // Runs if the user hit Cancel or closed the window, and did not ever press the Apply button
  2966. // or `Reset to Defaults` button
  2967. return;
  2968. } else if (result == QDialog::Accepted) {
  2969. // Only apply new changes if user hit Okay
  2970. // This is here to avoid applying changes if the user hit Apply, made some changes, then hit
  2971. // Cancel
  2972. configure_dialog.ApplyConfiguration();
  2973. } else if (UISettings::values.reset_to_defaults) {
  2974. LOG_INFO(Frontend, "Resetting all settings to defaults");
  2975. if (!Common::FS::RemoveFile(config->GetConfigFilePath())) {
  2976. LOG_WARNING(Frontend, "Failed to remove configuration file");
  2977. }
  2978. if (!Common::FS::RemoveDirContentsRecursively(
  2979. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom")) {
  2980. LOG_WARNING(Frontend, "Failed to remove custom configuration files");
  2981. }
  2982. if (!Common::FS::RemoveDirRecursively(
  2983. Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) / "game_list")) {
  2984. LOG_WARNING(Frontend, "Failed to remove game metadata cache files");
  2985. }
  2986. // Explicitly save the game directories, since reinitializing config does not explicitly do
  2987. // so.
  2988. QVector<UISettings::GameDir> old_game_dirs = std::move(UISettings::values.game_dirs);
  2989. QVector<u64> old_favorited_ids = std::move(UISettings::values.favorited_ids);
  2990. Settings::values.disabled_addons.clear();
  2991. config = std::make_unique<Config>();
  2992. UISettings::values.reset_to_defaults = false;
  2993. UISettings::values.game_dirs = std::move(old_game_dirs);
  2994. UISettings::values.favorited_ids = std::move(old_favorited_ids);
  2995. InitializeRecentFileMenuActions();
  2996. SetDefaultUIGeometry();
  2997. RestoreUIState();
  2998. ShowTelemetryCallout();
  2999. }
  3000. InitializeHotkeys();
  3001. if (UISettings::values.theme != old_theme) {
  3002. UpdateUITheme();
  3003. }
  3004. if (UISettings::values.enable_discord_presence.GetValue() != old_discord_presence) {
  3005. SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue());
  3006. }
  3007. if (!multiplayer_state->IsHostingPublicRoom()) {
  3008. multiplayer_state->UpdateCredentials();
  3009. }
  3010. emit UpdateThemedIcons();
  3011. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  3012. if (reload) {
  3013. game_list->PopulateAsync(UISettings::values.game_dirs);
  3014. }
  3015. UISettings::values.configuration_applied = false;
  3016. config->Save();
  3017. if ((UISettings::values.hide_mouse || Settings::values.mouse_panning) && emulation_running) {
  3018. render_window->installEventFilter(render_window);
  3019. render_window->setAttribute(Qt::WA_Hover, true);
  3020. } else {
  3021. render_window->removeEventFilter(render_window);
  3022. render_window->setAttribute(Qt::WA_Hover, false);
  3023. }
  3024. if (UISettings::values.hide_mouse) {
  3025. mouse_hide_timer.start();
  3026. }
  3027. // Restart camera config
  3028. if (emulation_running) {
  3029. render_window->FinalizeCamera();
  3030. render_window->InitializeCamera();
  3031. }
  3032. if (!UISettings::values.has_broken_vulkan) {
  3033. renderer_status_button->setEnabled(!emulation_running);
  3034. }
  3035. UpdateStatusButtons();
  3036. controller_dialog->refreshConfiguration();
  3037. system->ApplySettings();
  3038. }
  3039. void GMainWindow::OnConfigureTas() {
  3040. ConfigureTasDialog dialog(this);
  3041. const auto result = dialog.exec();
  3042. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  3043. Settings::RestoreGlobalState(system->IsPoweredOn());
  3044. return;
  3045. } else if (result == QDialog::Accepted) {
  3046. dialog.ApplyConfiguration();
  3047. OnSaveConfig();
  3048. }
  3049. }
  3050. void GMainWindow::OnTasStartStop() {
  3051. if (!emulation_running) {
  3052. return;
  3053. }
  3054. // Disable system buttons to prevent TAS from executing a hotkey
  3055. auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  3056. controller->ResetSystemButtons();
  3057. input_subsystem->GetTas()->StartStop();
  3058. OnTasStateChanged();
  3059. }
  3060. void GMainWindow::OnTasRecord() {
  3061. if (!emulation_running) {
  3062. return;
  3063. }
  3064. if (is_tas_recording_dialog_active) {
  3065. return;
  3066. }
  3067. // Disable system buttons to prevent TAS from recording a hotkey
  3068. auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  3069. controller->ResetSystemButtons();
  3070. const bool is_recording = input_subsystem->GetTas()->Record();
  3071. if (!is_recording) {
  3072. is_tas_recording_dialog_active = true;
  3073. ControllerNavigation* controller_navigation =
  3074. new ControllerNavigation(system->HIDCore(), this);
  3075. // Use QMessageBox instead of question so we can link controller navigation
  3076. QMessageBox* box_dialog = new QMessageBox();
  3077. box_dialog->setWindowTitle(tr("TAS Recording"));
  3078. box_dialog->setText(tr("Overwrite file of player 1?"));
  3079. box_dialog->setStandardButtons(QMessageBox::Yes | QMessageBox::No);
  3080. box_dialog->setDefaultButton(QMessageBox::Yes);
  3081. connect(controller_navigation, &ControllerNavigation::TriggerKeyboardEvent,
  3082. [box_dialog](Qt::Key key) {
  3083. QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier);
  3084. QCoreApplication::postEvent(box_dialog, event);
  3085. });
  3086. int res = box_dialog->exec();
  3087. controller_navigation->UnloadController();
  3088. input_subsystem->GetTas()->SaveRecording(res == QMessageBox::Yes);
  3089. is_tas_recording_dialog_active = false;
  3090. }
  3091. OnTasStateChanged();
  3092. }
  3093. void GMainWindow::OnTasReset() {
  3094. input_subsystem->GetTas()->Reset();
  3095. }
  3096. void GMainWindow::OnToggleDockedMode() {
  3097. const bool is_docked = Settings::values.use_docked_mode.GetValue();
  3098. auto* player_1 = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  3099. auto* handheld = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld);
  3100. if (!is_docked && handheld->IsConnected()) {
  3101. QMessageBox::warning(this, tr("Invalid config detected"),
  3102. tr("Handheld controller can't be used on docked mode. Pro "
  3103. "controller will be selected."));
  3104. handheld->Disconnect();
  3105. player_1->SetNpadStyleIndex(Core::HID::NpadStyleIndex::ProController);
  3106. player_1->Connect();
  3107. controller_dialog->refreshConfiguration();
  3108. }
  3109. Settings::values.use_docked_mode.SetValue(!is_docked);
  3110. UpdateDockedButton();
  3111. OnDockedModeChanged(is_docked, !is_docked, *system);
  3112. }
  3113. void GMainWindow::OnToggleGpuAccuracy() {
  3114. switch (Settings::values.gpu_accuracy.GetValue()) {
  3115. case Settings::GPUAccuracy::High: {
  3116. Settings::values.gpu_accuracy.SetValue(Settings::GPUAccuracy::Normal);
  3117. break;
  3118. }
  3119. case Settings::GPUAccuracy::Normal:
  3120. case Settings::GPUAccuracy::Extreme:
  3121. default: {
  3122. Settings::values.gpu_accuracy.SetValue(Settings::GPUAccuracy::High);
  3123. break;
  3124. }
  3125. }
  3126. system->ApplySettings();
  3127. UpdateGPUAccuracyButton();
  3128. }
  3129. void GMainWindow::OnMute() {
  3130. Settings::values.audio_muted = !Settings::values.audio_muted;
  3131. UpdateVolumeUI();
  3132. }
  3133. void GMainWindow::OnDecreaseVolume() {
  3134. Settings::values.audio_muted = false;
  3135. const auto current_volume = static_cast<s32>(Settings::values.volume.GetValue());
  3136. int step = 5;
  3137. if (current_volume <= 30) {
  3138. step = 2;
  3139. }
  3140. if (current_volume <= 6) {
  3141. step = 1;
  3142. }
  3143. Settings::values.volume.SetValue(std::max(current_volume - step, 0));
  3144. UpdateVolumeUI();
  3145. }
  3146. void GMainWindow::OnIncreaseVolume() {
  3147. Settings::values.audio_muted = false;
  3148. const auto current_volume = static_cast<s32>(Settings::values.volume.GetValue());
  3149. int step = 5;
  3150. if (current_volume < 30) {
  3151. step = 2;
  3152. }
  3153. if (current_volume < 6) {
  3154. step = 1;
  3155. }
  3156. Settings::values.volume.SetValue(current_volume + step);
  3157. UpdateVolumeUI();
  3158. }
  3159. void GMainWindow::OnToggleAdaptingFilter() {
  3160. auto filter = Settings::values.scaling_filter.GetValue();
  3161. if (filter == Settings::ScalingFilter::LastFilter) {
  3162. filter = Settings::ScalingFilter::NearestNeighbor;
  3163. } else {
  3164. filter = static_cast<Settings::ScalingFilter>(static_cast<u32>(filter) + 1);
  3165. }
  3166. Settings::values.scaling_filter.SetValue(filter);
  3167. filter_status_button->setChecked(true);
  3168. UpdateFilterText();
  3169. }
  3170. void GMainWindow::OnToggleGraphicsAPI() {
  3171. auto api = Settings::values.renderer_backend.GetValue();
  3172. if (api == Settings::RendererBackend::OpenGL) {
  3173. api = Settings::RendererBackend::Vulkan;
  3174. } else {
  3175. api = Settings::RendererBackend::OpenGL;
  3176. }
  3177. Settings::values.renderer_backend.SetValue(api);
  3178. renderer_status_button->setChecked(api == Settings::RendererBackend::Vulkan);
  3179. UpdateAPIText();
  3180. }
  3181. void GMainWindow::OnConfigurePerGame() {
  3182. const u64 title_id = system->GetApplicationProcessProgramID();
  3183. OpenPerGameConfiguration(title_id, current_game_path.toStdString());
  3184. }
  3185. void GMainWindow::OpenPerGameConfiguration(u64 title_id, const std::string& file_name) {
  3186. const auto v_file = Core::GetGameFileFromPath(vfs, file_name);
  3187. Settings::SetConfiguringGlobal(false);
  3188. ConfigurePerGame dialog(this, title_id, file_name, *system);
  3189. dialog.LoadFromFile(v_file);
  3190. const auto result = dialog.exec();
  3191. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  3192. Settings::RestoreGlobalState(system->IsPoweredOn());
  3193. return;
  3194. } else if (result == QDialog::Accepted) {
  3195. dialog.ApplyConfiguration();
  3196. }
  3197. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  3198. if (reload) {
  3199. game_list->PopulateAsync(UISettings::values.game_dirs);
  3200. }
  3201. // Do not cause the global config to write local settings into the config file
  3202. const bool is_powered_on = system->IsPoweredOn();
  3203. Settings::RestoreGlobalState(is_powered_on);
  3204. system->HIDCore().ReloadInputDevices();
  3205. UISettings::values.configuration_applied = false;
  3206. if (!is_powered_on) {
  3207. config->Save();
  3208. }
  3209. }
  3210. bool GMainWindow::CreateShortcut(const std::string& shortcut_path, const std::string& title,
  3211. const std::string& comment, const std::string& icon_path,
  3212. const std::string& command, const std::string& arguments,
  3213. const std::string& categories, const std::string& keywords) {
  3214. #if defined(__linux__) || defined(__FreeBSD__)
  3215. // This desktop file template was writing referencing
  3216. // https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.0.html
  3217. std::string shortcut_contents{};
  3218. shortcut_contents.append("[Desktop Entry]\n");
  3219. shortcut_contents.append("Type=Application\n");
  3220. shortcut_contents.append("Version=1.0\n");
  3221. shortcut_contents.append(fmt::format("Name={:s}\n", title));
  3222. shortcut_contents.append(fmt::format("Comment={:s}\n", comment));
  3223. shortcut_contents.append(fmt::format("Icon={:s}\n", icon_path));
  3224. shortcut_contents.append(fmt::format("TryExec={:s}\n", command));
  3225. shortcut_contents.append(fmt::format("Exec={:s} {:s}\n", command, arguments));
  3226. shortcut_contents.append(fmt::format("Categories={:s}\n", categories));
  3227. shortcut_contents.append(fmt::format("Keywords={:s}\n", keywords));
  3228. std::ofstream shortcut_stream(shortcut_path);
  3229. if (!shortcut_stream.is_open()) {
  3230. LOG_WARNING(Common, "Failed to create file {:s}", shortcut_path);
  3231. return false;
  3232. }
  3233. shortcut_stream << shortcut_contents;
  3234. shortcut_stream.close();
  3235. return true;
  3236. #endif
  3237. return false;
  3238. }
  3239. void GMainWindow::OnLoadAmiibo() {
  3240. if (emu_thread == nullptr || !emu_thread->IsRunning()) {
  3241. return;
  3242. }
  3243. if (is_amiibo_file_select_active) {
  3244. return;
  3245. }
  3246. auto* virtual_amiibo = input_subsystem->GetVirtualAmiibo();
  3247. // Remove amiibo if one is connected
  3248. if (virtual_amiibo->GetCurrentState() == InputCommon::VirtualAmiibo::State::AmiiboIsOpen) {
  3249. virtual_amiibo->CloseAmiibo();
  3250. QMessageBox::warning(this, tr("Amiibo"), tr("The current amiibo has been removed"));
  3251. return;
  3252. }
  3253. if (virtual_amiibo->GetCurrentState() != InputCommon::VirtualAmiibo::State::WaitingForAmiibo) {
  3254. QMessageBox::warning(this, tr("Error"), tr("The current game is not looking for amiibos"));
  3255. return;
  3256. }
  3257. is_amiibo_file_select_active = true;
  3258. const QString extensions{QStringLiteral("*.bin")};
  3259. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  3260. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter);
  3261. is_amiibo_file_select_active = false;
  3262. if (filename.isEmpty()) {
  3263. return;
  3264. }
  3265. LoadAmiibo(filename);
  3266. }
  3267. void GMainWindow::LoadAmiibo(const QString& filename) {
  3268. auto* virtual_amiibo = input_subsystem->GetVirtualAmiibo();
  3269. const QString title = tr("Error loading Amiibo data");
  3270. // Remove amiibo if one is connected
  3271. if (virtual_amiibo->GetCurrentState() == InputCommon::VirtualAmiibo::State::AmiiboIsOpen) {
  3272. virtual_amiibo->CloseAmiibo();
  3273. QMessageBox::warning(this, tr("Amiibo"), tr("The current amiibo has been removed"));
  3274. return;
  3275. }
  3276. switch (virtual_amiibo->LoadAmiibo(filename.toStdString())) {
  3277. case InputCommon::VirtualAmiibo::Info::NotAnAmiibo:
  3278. QMessageBox::warning(this, title, tr("The selected file is not a valid amiibo"));
  3279. break;
  3280. case InputCommon::VirtualAmiibo::Info::UnableToLoad:
  3281. QMessageBox::warning(this, title, tr("The selected file is already on use"));
  3282. break;
  3283. case InputCommon::VirtualAmiibo::Info::WrongDeviceState:
  3284. QMessageBox::warning(this, title, tr("The current game is not looking for amiibos"));
  3285. break;
  3286. case InputCommon::VirtualAmiibo::Info::Unknown:
  3287. QMessageBox::warning(this, title, tr("An unknown error occurred"));
  3288. break;
  3289. default:
  3290. break;
  3291. }
  3292. }
  3293. void GMainWindow::OnOpenYuzuFolder() {
  3294. QDesktopServices::openUrl(QUrl::fromLocalFile(
  3295. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::YuzuDir))));
  3296. }
  3297. void GMainWindow::OnAbout() {
  3298. AboutDialog aboutDialog(this);
  3299. aboutDialog.exec();
  3300. }
  3301. void GMainWindow::OnToggleFilterBar() {
  3302. game_list->SetFilterVisible(ui->action_Show_Filter_Bar->isChecked());
  3303. if (ui->action_Show_Filter_Bar->isChecked()) {
  3304. game_list->SetFilterFocus();
  3305. } else {
  3306. game_list->ClearFilter();
  3307. }
  3308. }
  3309. void GMainWindow::OnToggleStatusBar() {
  3310. statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
  3311. }
  3312. void GMainWindow::OnCaptureScreenshot() {
  3313. if (emu_thread == nullptr || !emu_thread->IsRunning()) {
  3314. return;
  3315. }
  3316. const u64 title_id = system->GetApplicationProcessProgramID();
  3317. const auto screenshot_path =
  3318. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::ScreenshotsDir));
  3319. const auto date =
  3320. QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd_hh-mm-ss-zzz"));
  3321. QString filename = QStringLiteral("%1/%2_%3.png")
  3322. .arg(screenshot_path)
  3323. .arg(title_id, 16, 16, QLatin1Char{'0'})
  3324. .arg(date);
  3325. if (!Common::FS::CreateDir(screenshot_path.toStdString())) {
  3326. return;
  3327. }
  3328. #ifdef _WIN32
  3329. if (UISettings::values.enable_screenshot_save_as) {
  3330. OnPauseGame();
  3331. filename = QFileDialog::getSaveFileName(this, tr("Capture Screenshot"), filename,
  3332. tr("PNG Image (*.png)"));
  3333. OnStartGame();
  3334. if (filename.isEmpty()) {
  3335. return;
  3336. }
  3337. }
  3338. #endif
  3339. render_window->CaptureScreenshot(filename);
  3340. }
  3341. // TODO: Written 2020-10-01: Remove per-game config migration code when it is irrelevant
  3342. void GMainWindow::MigrateConfigFiles() {
  3343. const auto config_dir_fs_path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir);
  3344. const QDir config_dir =
  3345. QDir(QString::fromStdString(Common::FS::PathToUTF8String(config_dir_fs_path)));
  3346. const QStringList config_dir_list = config_dir.entryList(QStringList(QStringLiteral("*.ini")));
  3347. if (!Common::FS::CreateDirs(config_dir_fs_path / "custom")) {
  3348. LOG_ERROR(Frontend, "Failed to create new config file directory");
  3349. }
  3350. for (auto it = config_dir_list.constBegin(); it != config_dir_list.constEnd(); ++it) {
  3351. const auto filename = it->toStdString();
  3352. if (filename.find_first_not_of("0123456789abcdefACBDEF", 0) < 16) {
  3353. continue;
  3354. }
  3355. const auto origin = config_dir_fs_path / filename;
  3356. const auto destination = config_dir_fs_path / "custom" / filename;
  3357. LOG_INFO(Frontend, "Migrating config file from {} to {}", origin.string(),
  3358. destination.string());
  3359. if (!Common::FS::RenameFile(origin, destination)) {
  3360. // Delete the old config file if one already exists in the new location.
  3361. Common::FS::RemoveFile(origin);
  3362. }
  3363. }
  3364. }
  3365. void GMainWindow::UpdateWindowTitle(std::string_view title_name, std::string_view title_version,
  3366. std::string_view gpu_vendor) {
  3367. const auto branch_name = std::string(Common::g_scm_branch);
  3368. const auto description = std::string(Common::g_scm_desc);
  3369. const auto build_id = std::string(Common::g_build_id);
  3370. const auto yuzu_title = fmt::format("yuzu | {}-{}", branch_name, description);
  3371. const auto override_title =
  3372. fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id);
  3373. const auto window_title = override_title.empty() ? yuzu_title : override_title;
  3374. if (title_name.empty()) {
  3375. setWindowTitle(QString::fromStdString(window_title));
  3376. } else {
  3377. const auto run_title = [window_title, title_name, title_version, gpu_vendor]() {
  3378. if (title_version.empty()) {
  3379. return fmt::format("{} | {} | {}", window_title, title_name, gpu_vendor);
  3380. }
  3381. return fmt::format("{} | {} | {} | {}", window_title, title_name, title_version,
  3382. gpu_vendor);
  3383. }();
  3384. setWindowTitle(QString::fromStdString(run_title));
  3385. }
  3386. }
  3387. std::string GMainWindow::CreateTASFramesString(
  3388. std::array<size_t, InputCommon::TasInput::PLAYER_NUMBER> frames) const {
  3389. std::string string = "";
  3390. size_t maxPlayerIndex = 0;
  3391. for (size_t i = 0; i < frames.size(); i++) {
  3392. if (frames[i] != 0) {
  3393. if (maxPlayerIndex != 0)
  3394. string += ", ";
  3395. while (maxPlayerIndex++ != i)
  3396. string += "0, ";
  3397. string += std::to_string(frames[i]);
  3398. }
  3399. }
  3400. return string;
  3401. }
  3402. QString GMainWindow::GetTasStateDescription() const {
  3403. auto [tas_status, current_tas_frame, total_tas_frames] = input_subsystem->GetTas()->GetStatus();
  3404. std::string tas_frames_string = CreateTASFramesString(total_tas_frames);
  3405. switch (tas_status) {
  3406. case InputCommon::TasInput::TasState::Running:
  3407. return tr("TAS state: Running %1/%2")
  3408. .arg(current_tas_frame)
  3409. .arg(QString::fromStdString(tas_frames_string));
  3410. case InputCommon::TasInput::TasState::Recording:
  3411. return tr("TAS state: Recording %1").arg(total_tas_frames[0]);
  3412. case InputCommon::TasInput::TasState::Stopped:
  3413. return tr("TAS state: Idle %1/%2")
  3414. .arg(current_tas_frame)
  3415. .arg(QString::fromStdString(tas_frames_string));
  3416. default:
  3417. return tr("TAS State: Invalid");
  3418. }
  3419. }
  3420. void GMainWindow::OnTasStateChanged() {
  3421. bool is_running = false;
  3422. bool is_recording = false;
  3423. if (emulation_running) {
  3424. const InputCommon::TasInput::TasState tas_status =
  3425. std::get<0>(input_subsystem->GetTas()->GetStatus());
  3426. is_running = tas_status == InputCommon::TasInput::TasState::Running;
  3427. is_recording = tas_status == InputCommon::TasInput::TasState::Recording;
  3428. }
  3429. ui->action_TAS_Start->setText(is_running ? tr("&Stop Running") : tr("&Start"));
  3430. ui->action_TAS_Record->setText(is_recording ? tr("Stop R&ecording") : tr("R&ecord"));
  3431. ui->action_TAS_Start->setEnabled(emulation_running);
  3432. ui->action_TAS_Record->setEnabled(emulation_running);
  3433. ui->action_TAS_Reset->setEnabled(emulation_running);
  3434. }
  3435. void GMainWindow::UpdateStatusBar() {
  3436. if (emu_thread == nullptr || !system->IsPoweredOn()) {
  3437. status_bar_update_timer.stop();
  3438. return;
  3439. }
  3440. if (Settings::values.tas_enable) {
  3441. tas_label->setText(GetTasStateDescription());
  3442. } else {
  3443. tas_label->clear();
  3444. }
  3445. auto results = system->GetAndResetPerfStats();
  3446. auto& shader_notify = system->GPU().ShaderNotify();
  3447. const int shaders_building = shader_notify.ShadersBuilding();
  3448. if (shaders_building > 0) {
  3449. shader_building_label->setText(tr("Building: %n shader(s)", "", shaders_building));
  3450. shader_building_label->setVisible(true);
  3451. } else {
  3452. shader_building_label->setVisible(false);
  3453. }
  3454. const auto res_info = Settings::values.resolution_info;
  3455. const auto res_scale = res_info.up_factor;
  3456. res_scale_label->setText(
  3457. tr("Scale: %1x", "%1 is the resolution scaling factor").arg(res_scale));
  3458. if (Settings::values.use_speed_limit.GetValue()) {
  3459. emu_speed_label->setText(tr("Speed: %1% / %2%")
  3460. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  3461. .arg(Settings::values.speed_limit.GetValue()));
  3462. } else {
  3463. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  3464. }
  3465. if (!Settings::values.use_speed_limit) {
  3466. game_fps_label->setText(
  3467. tr("Game: %1 FPS (Unlocked)").arg(std::round(results.average_game_fps), 0, 'f', 0));
  3468. } else {
  3469. game_fps_label->setText(
  3470. tr("Game: %1 FPS").arg(std::round(results.average_game_fps), 0, 'f', 0));
  3471. }
  3472. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  3473. res_scale_label->setVisible(true);
  3474. emu_speed_label->setVisible(!Settings::values.use_multi_core.GetValue());
  3475. game_fps_label->setVisible(true);
  3476. emu_frametime_label->setVisible(true);
  3477. }
  3478. void GMainWindow::UpdateGPUAccuracyButton() {
  3479. const auto gpu_accuracy = Settings::values.gpu_accuracy.GetValue();
  3480. const auto gpu_accuracy_text = Config::gpu_accuracy_texts_map.find(gpu_accuracy)->second;
  3481. gpu_accuracy_button->setText(gpu_accuracy_text.toUpper());
  3482. gpu_accuracy_button->setChecked(gpu_accuracy != Settings::GPUAccuracy::Normal);
  3483. }
  3484. void GMainWindow::UpdateDockedButton() {
  3485. const bool is_docked = Settings::values.use_docked_mode.GetValue();
  3486. dock_status_button->setChecked(is_docked);
  3487. dock_status_button->setText(
  3488. Config::use_docked_mode_texts_map.find(is_docked)->second.toUpper());
  3489. }
  3490. void GMainWindow::UpdateAPIText() {
  3491. const auto api = Settings::values.renderer_backend.GetValue();
  3492. const auto renderer_status_text = Config::renderer_backend_texts_map.find(api)->second;
  3493. renderer_status_button->setText(renderer_status_text.toUpper());
  3494. }
  3495. void GMainWindow::UpdateFilterText() {
  3496. const auto filter = Settings::values.scaling_filter.GetValue();
  3497. const auto filter_text = Config::scaling_filter_texts_map.find(filter)->second;
  3498. filter_status_button->setText(filter == Settings::ScalingFilter::Fsr ? tr("FSR")
  3499. : filter_text.toUpper());
  3500. }
  3501. void GMainWindow::UpdateAAText() {
  3502. const auto aa_mode = Settings::values.anti_aliasing.GetValue();
  3503. const auto aa_text = Config::anti_aliasing_texts_map.find(aa_mode)->second;
  3504. aa_status_button->setText(aa_mode == Settings::AntiAliasing::None
  3505. ? QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "NO AA"))
  3506. : aa_text.toUpper());
  3507. }
  3508. void GMainWindow::UpdateVolumeUI() {
  3509. const auto volume_value = static_cast<int>(Settings::values.volume.GetValue());
  3510. volume_slider->setValue(volume_value);
  3511. if (Settings::values.audio_muted) {
  3512. volume_button->setChecked(false);
  3513. volume_button->setText(tr("VOLUME: MUTE"));
  3514. } else {
  3515. volume_button->setChecked(true);
  3516. volume_button->setText(tr("VOLUME: %1%", "Volume percentage (e.g. 50%)").arg(volume_value));
  3517. }
  3518. }
  3519. void GMainWindow::UpdateStatusButtons() {
  3520. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  3521. Settings::RendererBackend::Vulkan);
  3522. UpdateAPIText();
  3523. UpdateGPUAccuracyButton();
  3524. UpdateDockedButton();
  3525. UpdateFilterText();
  3526. UpdateAAText();
  3527. UpdateVolumeUI();
  3528. }
  3529. void GMainWindow::UpdateUISettings() {
  3530. if (!ui->action_Fullscreen->isChecked()) {
  3531. UISettings::values.geometry = saveGeometry();
  3532. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  3533. }
  3534. UISettings::values.state = saveState();
  3535. #if MICROPROFILE_ENABLED
  3536. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  3537. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  3538. #endif
  3539. UISettings::values.single_window_mode = ui->action_Single_Window_Mode->isChecked();
  3540. UISettings::values.fullscreen = ui->action_Fullscreen->isChecked();
  3541. UISettings::values.display_titlebar = ui->action_Display_Dock_Widget_Headers->isChecked();
  3542. UISettings::values.show_filter_bar = ui->action_Show_Filter_Bar->isChecked();
  3543. UISettings::values.show_status_bar = ui->action_Show_Status_Bar->isChecked();
  3544. UISettings::values.first_start = false;
  3545. }
  3546. void GMainWindow::UpdateInputDrivers() {
  3547. if (!input_subsystem) {
  3548. return;
  3549. }
  3550. input_subsystem->PumpEvents();
  3551. }
  3552. void GMainWindow::HideMouseCursor() {
  3553. if (emu_thread == nullptr && UISettings::values.hide_mouse) {
  3554. mouse_hide_timer.stop();
  3555. ShowMouseCursor();
  3556. return;
  3557. }
  3558. render_window->setCursor(QCursor(Qt::BlankCursor));
  3559. }
  3560. void GMainWindow::ShowMouseCursor() {
  3561. render_window->unsetCursor();
  3562. if (emu_thread != nullptr && UISettings::values.hide_mouse) {
  3563. mouse_hide_timer.start();
  3564. }
  3565. }
  3566. void GMainWindow::CenterMouseCursor() {
  3567. if (emu_thread == nullptr || !Settings::values.mouse_panning) {
  3568. mouse_center_timer.stop();
  3569. return;
  3570. }
  3571. if (!this->isActiveWindow()) {
  3572. mouse_center_timer.stop();
  3573. return;
  3574. }
  3575. const int center_x = render_window->width() / 2;
  3576. const int center_y = render_window->height() / 2;
  3577. QCursor::setPos(mapToGlobal(QPoint{center_x, center_y}));
  3578. }
  3579. void GMainWindow::OnMouseActivity() {
  3580. if (!Settings::values.mouse_panning) {
  3581. ShowMouseCursor();
  3582. }
  3583. mouse_center_timer.stop();
  3584. }
  3585. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  3586. if (behavior == ReinitializeKeyBehavior::Warning) {
  3587. const auto res = QMessageBox::information(
  3588. this, tr("Confirm Key Rederivation"),
  3589. tr("You are about to force rederive all of your keys. \nIf you do not know what "
  3590. "this "
  3591. "means or what you are doing, \nthis is a potentially destructive action. "
  3592. "\nPlease "
  3593. "make sure this is what you want \nand optionally make backups.\n\nThis will "
  3594. "delete "
  3595. "your autogenerated key files and re-run the key derivation module."),
  3596. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  3597. if (res == QMessageBox::Cancel)
  3598. return;
  3599. const auto keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
  3600. Common::FS::RemoveFile(keys_dir / "prod.keys_autogenerated");
  3601. Common::FS::RemoveFile(keys_dir / "console.keys_autogenerated");
  3602. Common::FS::RemoveFile(keys_dir / "title.keys_autogenerated");
  3603. }
  3604. Core::Crypto::KeyManager& keys = Core::Crypto::KeyManager::Instance();
  3605. bool all_keys_present{true};
  3606. if (keys.BaseDeriveNecessary()) {
  3607. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory("", FileSys::Mode::Read)};
  3608. const auto function = [this, &keys, &pdm] {
  3609. keys.PopulateFromPartitionData(pdm);
  3610. system->GetFileSystemController().CreateFactories(*vfs);
  3611. keys.DeriveETicket(pdm, system->GetContentProvider());
  3612. };
  3613. QString errors;
  3614. if (!pdm.HasFuses()) {
  3615. errors += tr("Missing fuses");
  3616. }
  3617. if (!pdm.HasBoot0()) {
  3618. errors += tr(" - Missing BOOT0");
  3619. }
  3620. if (!pdm.HasPackage2()) {
  3621. errors += tr(" - Missing BCPKG2-1-Normal-Main");
  3622. }
  3623. if (!pdm.HasProdInfo()) {
  3624. errors += tr(" - Missing PRODINFO");
  3625. }
  3626. if (!errors.isEmpty()) {
  3627. all_keys_present = false;
  3628. QMessageBox::warning(
  3629. this, tr("Derivation Components Missing"),
  3630. tr("Encryption keys are missing. "
  3631. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  3632. "quickstart guide</a> to get all your keys, firmware and "
  3633. "games.<br><br><small>(%1)</small>")
  3634. .arg(errors));
  3635. }
  3636. QProgressDialog prog(this);
  3637. prog.setRange(0, 0);
  3638. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  3639. "system's performance."));
  3640. prog.setWindowTitle(tr("Deriving Keys"));
  3641. prog.show();
  3642. auto future = QtConcurrent::run(function);
  3643. while (!future.isFinished()) {
  3644. QCoreApplication::processEvents();
  3645. }
  3646. prog.close();
  3647. }
  3648. system->GetFileSystemController().CreateFactories(*vfs);
  3649. if (all_keys_present && !this->CheckSystemArchiveDecryption()) {
  3650. LOG_WARNING(Frontend, "Mii model decryption failed");
  3651. QMessageBox::warning(
  3652. this, tr("System Archive Decryption Failed"),
  3653. tr("Encryption keys failed to decrypt firmware. "
  3654. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  3655. "quickstart guide</a> to get all your keys, firmware and "
  3656. "games."));
  3657. }
  3658. if (behavior == ReinitializeKeyBehavior::Warning) {
  3659. game_list->PopulateAsync(UISettings::values.game_dirs);
  3660. }
  3661. }
  3662. bool GMainWindow::CheckSystemArchiveDecryption() {
  3663. constexpr u64 MiiModelId = 0x0100000000000802;
  3664. auto bis_system = system->GetFileSystemController().GetSystemNANDContents();
  3665. if (!bis_system) {
  3666. // Not having system BIS files is not an error.
  3667. return true;
  3668. }
  3669. auto mii_nca = bis_system->GetEntry(MiiModelId, FileSys::ContentRecordType::Data);
  3670. if (!mii_nca) {
  3671. // Not having the Mii model is not an error.
  3672. return true;
  3673. }
  3674. // Return whether we are able to decrypt the RomFS of the Mii model.
  3675. return mii_nca->GetRomFS().get() != nullptr;
  3676. }
  3677. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
  3678. u64 program_id) {
  3679. const auto dlc_entries =
  3680. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  3681. std::vector<FileSys::ContentProviderEntry> dlc_match;
  3682. dlc_match.reserve(dlc_entries.size());
  3683. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  3684. [&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
  3685. return FileSys::GetBaseTitleID(entry.title_id) == program_id &&
  3686. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  3687. });
  3688. std::vector<u64> romfs_tids;
  3689. romfs_tids.push_back(program_id);
  3690. for (const auto& entry : dlc_match) {
  3691. romfs_tids.push_back(entry.title_id);
  3692. }
  3693. if (romfs_tids.size() > 1) {
  3694. QStringList list{QStringLiteral("Base")};
  3695. for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
  3696. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  3697. }
  3698. bool ok;
  3699. const auto res = QInputDialog::getItem(
  3700. this, tr("Select RomFS Dump Target"),
  3701. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  3702. if (!ok) {
  3703. return {};
  3704. }
  3705. return romfs_tids[list.indexOf(res)];
  3706. }
  3707. return program_id;
  3708. }
  3709. bool GMainWindow::ConfirmClose() {
  3710. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  3711. return true;
  3712. }
  3713. const auto text = tr("Are you sure you want to close yuzu?");
  3714. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  3715. return answer != QMessageBox::No;
  3716. }
  3717. void GMainWindow::closeEvent(QCloseEvent* event) {
  3718. if (!ConfirmClose()) {
  3719. event->ignore();
  3720. return;
  3721. }
  3722. UpdateUISettings();
  3723. game_list->SaveInterfaceLayout();
  3724. hotkey_registry.SaveHotkeys();
  3725. // Unload controllers early
  3726. controller_dialog->UnloadController();
  3727. game_list->UnloadController();
  3728. // Shutdown session if the emu thread is active...
  3729. if (emu_thread != nullptr) {
  3730. ShutdownGame();
  3731. }
  3732. render_window->close();
  3733. multiplayer_state->Close();
  3734. system->HIDCore().UnloadInputDevices();
  3735. system->GetRoomNetwork().Shutdown();
  3736. QWidget::closeEvent(event);
  3737. }
  3738. static bool IsSingleFileDropEvent(const QMimeData* mime) {
  3739. return mime->hasUrls() && mime->urls().length() == 1;
  3740. }
  3741. void GMainWindow::AcceptDropEvent(QDropEvent* event) {
  3742. if (IsSingleFileDropEvent(event->mimeData())) {
  3743. event->setDropAction(Qt::DropAction::LinkAction);
  3744. event->accept();
  3745. }
  3746. }
  3747. bool GMainWindow::DropAction(QDropEvent* event) {
  3748. if (!IsSingleFileDropEvent(event->mimeData())) {
  3749. return false;
  3750. }
  3751. const QMimeData* mime_data = event->mimeData();
  3752. const QString& filename = mime_data->urls().at(0).toLocalFile();
  3753. if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
  3754. // Amiibo
  3755. LoadAmiibo(filename);
  3756. } else {
  3757. // Game
  3758. if (ConfirmChangeGame()) {
  3759. BootGame(filename);
  3760. }
  3761. }
  3762. return true;
  3763. }
  3764. void GMainWindow::dropEvent(QDropEvent* event) {
  3765. DropAction(event);
  3766. }
  3767. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  3768. AcceptDropEvent(event);
  3769. }
  3770. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  3771. AcceptDropEvent(event);
  3772. }
  3773. void GMainWindow::leaveEvent(QEvent* event) {
  3774. if (Settings::values.mouse_panning) {
  3775. const QRect& rect = geometry();
  3776. QPoint position = QCursor::pos();
  3777. qint32 x = qBound(rect.left(), position.x(), rect.right());
  3778. qint32 y = qBound(rect.top(), position.y(), rect.bottom());
  3779. // Only start the timer if the mouse has left the window bound.
  3780. // The leave event is also triggered when the window looses focus.
  3781. if (x != position.x() || y != position.y()) {
  3782. mouse_center_timer.start();
  3783. }
  3784. event->accept();
  3785. }
  3786. }
  3787. bool GMainWindow::ConfirmChangeGame() {
  3788. if (emu_thread == nullptr)
  3789. return true;
  3790. const auto answer = QMessageBox::question(
  3791. this, tr("yuzu"),
  3792. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  3793. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3794. return answer != QMessageBox::No;
  3795. }
  3796. bool GMainWindow::ConfirmForceLockedExit() {
  3797. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  3798. return true;
  3799. }
  3800. const auto text = tr("The currently running application has requested yuzu to not exit.\n\n"
  3801. "Would you like to bypass this and exit anyway?");
  3802. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  3803. return answer != QMessageBox::No;
  3804. }
  3805. void GMainWindow::RequestGameExit() {
  3806. if (!system->IsPoweredOn()) {
  3807. return;
  3808. }
  3809. auto& sm{system->ServiceManager()};
  3810. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  3811. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  3812. bool has_signalled = false;
  3813. if (applet_oe != nullptr) {
  3814. applet_oe->GetMessageQueue()->RequestExit();
  3815. has_signalled = true;
  3816. }
  3817. if (applet_ae != nullptr && !has_signalled) {
  3818. applet_ae->GetMessageQueue()->RequestExit();
  3819. }
  3820. }
  3821. void GMainWindow::RequestGameResume() {
  3822. auto& sm{system->ServiceManager()};
  3823. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  3824. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  3825. if (applet_oe != nullptr) {
  3826. applet_oe->GetMessageQueue()->RequestResume();
  3827. return;
  3828. }
  3829. if (applet_ae != nullptr) {
  3830. applet_ae->GetMessageQueue()->RequestResume();
  3831. }
  3832. }
  3833. void GMainWindow::filterBarSetChecked(bool state) {
  3834. ui->action_Show_Filter_Bar->setChecked(state);
  3835. emit(OnToggleFilterBar());
  3836. }
  3837. static void AdjustLinkColor() {
  3838. QPalette new_pal(qApp->palette());
  3839. if (UISettings::IsDarkTheme()) {
  3840. new_pal.setColor(QPalette::Link, QColor(0, 190, 255, 255));
  3841. } else {
  3842. new_pal.setColor(QPalette::Link, QColor(0, 140, 200, 255));
  3843. }
  3844. if (qApp->palette().color(QPalette::Link) != new_pal.color(QPalette::Link)) {
  3845. qApp->setPalette(new_pal);
  3846. }
  3847. }
  3848. void GMainWindow::UpdateUITheme() {
  3849. const QString default_theme =
  3850. QString::fromUtf8(UISettings::themes[static_cast<size_t>(Config::default_theme)].second);
  3851. QString current_theme = UISettings::values.theme;
  3852. if (current_theme.isEmpty()) {
  3853. current_theme = default_theme;
  3854. }
  3855. #ifdef _WIN32
  3856. QIcon::setThemeName(current_theme);
  3857. AdjustLinkColor();
  3858. #else
  3859. if (current_theme == QStringLiteral("default") || current_theme == QStringLiteral("colorful")) {
  3860. QIcon::setThemeName(current_theme == QStringLiteral("colorful") ? current_theme
  3861. : startup_icon_theme);
  3862. QIcon::setThemeSearchPaths(QStringList(default_theme_paths));
  3863. if (CheckDarkMode()) {
  3864. current_theme = QStringLiteral("default_dark");
  3865. }
  3866. } else {
  3867. QIcon::setThemeName(current_theme);
  3868. QIcon::setThemeSearchPaths(QStringList(QStringLiteral(":/icons")));
  3869. AdjustLinkColor();
  3870. }
  3871. #endif
  3872. if (current_theme != default_theme) {
  3873. QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)};
  3874. QFile f(theme_uri);
  3875. if (!f.open(QFile::ReadOnly | QFile::Text)) {
  3876. LOG_ERROR(Frontend, "Unable to open style \"{}\", fallback to the default theme",
  3877. UISettings::values.theme.toStdString());
  3878. current_theme = default_theme;
  3879. }
  3880. }
  3881. QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)};
  3882. QFile f(theme_uri);
  3883. if (f.open(QFile::ReadOnly | QFile::Text)) {
  3884. QTextStream ts(&f);
  3885. qApp->setStyleSheet(ts.readAll());
  3886. setStyleSheet(ts.readAll());
  3887. } else {
  3888. LOG_ERROR(Frontend, "Unable to set style \"{}\", stylesheet file not found",
  3889. UISettings::values.theme.toStdString());
  3890. qApp->setStyleSheet({});
  3891. setStyleSheet({});
  3892. }
  3893. }
  3894. void GMainWindow::LoadTranslation() {
  3895. bool loaded;
  3896. if (UISettings::values.language.isEmpty()) {
  3897. // If the selected language is empty, use system locale
  3898. loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/"));
  3899. } else {
  3900. // Otherwise load from the specified file
  3901. loaded = translator.load(UISettings::values.language, QStringLiteral(":/languages/"));
  3902. }
  3903. if (loaded) {
  3904. qApp->installTranslator(&translator);
  3905. } else {
  3906. UISettings::values.language = QStringLiteral("en");
  3907. }
  3908. }
  3909. void GMainWindow::OnLanguageChanged(const QString& locale) {
  3910. if (UISettings::values.language != QStringLiteral("en")) {
  3911. qApp->removeTranslator(&translator);
  3912. }
  3913. UISettings::values.language = locale;
  3914. LoadTranslation();
  3915. ui->retranslateUi(this);
  3916. multiplayer_state->retranslateUi();
  3917. UpdateWindowTitle();
  3918. }
  3919. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  3920. #ifdef USE_DISCORD_PRESENCE
  3921. if (state) {
  3922. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>(*system);
  3923. } else {
  3924. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  3925. }
  3926. #else
  3927. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  3928. #endif
  3929. discord_rpc->Update();
  3930. }
  3931. void GMainWindow::changeEvent(QEvent* event) {
  3932. #ifdef __unix__
  3933. // PaletteChange event appears to only reach so far into the GUI, explicitly asking to
  3934. // UpdateUITheme is a decent work around
  3935. if (event->type() == QEvent::PaletteChange) {
  3936. const QPalette test_palette(qApp->palette());
  3937. const QString current_theme = UISettings::values.theme;
  3938. // Keeping eye on QPalette::Window to avoid looping. QPalette::Text might be useful too
  3939. static QColor last_window_color;
  3940. const QColor window_color = test_palette.color(QPalette::Active, QPalette::Window);
  3941. if (last_window_color != window_color && (current_theme == QStringLiteral("default") ||
  3942. current_theme == QStringLiteral("colorful"))) {
  3943. UpdateUITheme();
  3944. }
  3945. last_window_color = window_color;
  3946. }
  3947. #endif // __unix__
  3948. QWidget::changeEvent(event);
  3949. }
  3950. #ifdef main
  3951. #undef main
  3952. #endif
  3953. static void SetHighDPIAttributes() {
  3954. #ifdef _WIN32
  3955. // For Windows, we want to avoid scaling artifacts on fractional scaling ratios.
  3956. // This is done by setting the optimal scaling policy for the primary screen.
  3957. // Create a temporary QApplication.
  3958. int temp_argc = 0;
  3959. char** temp_argv = nullptr;
  3960. QApplication temp{temp_argc, temp_argv};
  3961. // Get the current screen geometry.
  3962. const QScreen* primary_screen = QGuiApplication::primaryScreen();
  3963. if (primary_screen == nullptr) {
  3964. return;
  3965. }
  3966. const QRect screen_rect = primary_screen->geometry();
  3967. const int real_width = screen_rect.width();
  3968. const int real_height = screen_rect.height();
  3969. const float real_ratio = primary_screen->logicalDotsPerInch() / 96.0f;
  3970. // Recommended minimum width and height for proper window fit.
  3971. // Any screen with a lower resolution than this will still have a scale of 1.
  3972. constexpr float minimum_width = 1350.0f;
  3973. constexpr float minimum_height = 900.0f;
  3974. const float width_ratio = std::max(1.0f, real_width / minimum_width);
  3975. const float height_ratio = std::max(1.0f, real_height / minimum_height);
  3976. // Get the lower of the 2 ratios and truncate, this is the maximum integer scale.
  3977. const float max_ratio = std::trunc(std::min(width_ratio, height_ratio));
  3978. if (max_ratio > real_ratio) {
  3979. QApplication::setHighDpiScaleFactorRoundingPolicy(
  3980. Qt::HighDpiScaleFactorRoundingPolicy::Round);
  3981. } else {
  3982. QApplication::setHighDpiScaleFactorRoundingPolicy(
  3983. Qt::HighDpiScaleFactorRoundingPolicy::Floor);
  3984. }
  3985. #else
  3986. // Other OSes should be better than Windows at fractional scaling.
  3987. QApplication::setHighDpiScaleFactorRoundingPolicy(
  3988. Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  3989. #endif
  3990. QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  3991. QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
  3992. }
  3993. int main(int argc, char* argv[]) {
  3994. std::unique_ptr<Config> config = std::make_unique<Config>();
  3995. bool has_broken_vulkan = false;
  3996. bool is_child = false;
  3997. if (CheckEnvVars(&is_child)) {
  3998. return 0;
  3999. }
  4000. #ifdef YUZU_DBGHELP
  4001. PROCESS_INFORMATION pi;
  4002. if (!is_child && Settings::values.create_crash_dumps.GetValue() &&
  4003. MiniDump::SpawnDebuggee(argv[0], pi)) {
  4004. // Delete the config object so that it doesn't save when the program exits
  4005. config.reset(nullptr);
  4006. MiniDump::DebugDebuggee(pi);
  4007. return 0;
  4008. }
  4009. #endif
  4010. if (StartupChecks(argv[0], &has_broken_vulkan,
  4011. Settings::values.perform_vulkan_check.GetValue())) {
  4012. return 0;
  4013. }
  4014. Common::DetachedTasks detached_tasks;
  4015. MicroProfileOnThreadCreate("Frontend");
  4016. SCOPE_EXIT({ MicroProfileShutdown(); });
  4017. Common::ConfigureNvidiaEnvironmentFlags();
  4018. // Init settings params
  4019. QCoreApplication::setOrganizationName(QStringLiteral("yuzu team"));
  4020. QCoreApplication::setApplicationName(QStringLiteral("yuzu"));
  4021. #ifdef _WIN32
  4022. // Increases the maximum open file limit to 8192
  4023. _setmaxstdio(8192);
  4024. #endif
  4025. #ifdef __APPLE__
  4026. // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/".
  4027. // But since we require the working directory to be the executable path for the location of
  4028. // the user folder in the Qt Frontend, we need to cd into that working directory
  4029. const auto bin_path = Common::FS::GetBundleDirectory() / "..";
  4030. chdir(Common::FS::PathToUTF8String(bin_path).c_str());
  4031. #endif
  4032. #ifdef __linux__
  4033. // Set the DISPLAY variable in order to open web browsers
  4034. // TODO (lat9nq): Find a better solution for AppImages to start external applications
  4035. if (QString::fromLocal8Bit(qgetenv("DISPLAY")).isEmpty()) {
  4036. qputenv("DISPLAY", ":0");
  4037. }
  4038. #endif
  4039. SetHighDPIAttributes();
  4040. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  4041. // Disables the "?" button on all dialogs. Disabled by default on Qt6.
  4042. QCoreApplication::setAttribute(Qt::AA_DisableWindowContextHelpButton);
  4043. #endif
  4044. // Enables the core to make the qt created contexts current on std::threads
  4045. QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  4046. QApplication app(argc, argv);
  4047. #ifdef _WIN32
  4048. OverrideWindowsFont();
  4049. #endif
  4050. // Workaround for QTBUG-85409, for Suzhou numerals the number 1 is actually \u3021
  4051. // so we can see if we get \u3008 instead
  4052. // TL;DR all other number formats are consecutive in unicode code points
  4053. // This bug is fixed in Qt6, specifically 6.0.0-alpha1
  4054. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  4055. const QLocale locale = QLocale::system();
  4056. if (QStringLiteral("\u3008") == locale.toString(1)) {
  4057. QLocale::setDefault(QLocale::system().name());
  4058. }
  4059. #endif
  4060. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  4061. // generating shaders
  4062. setlocale(LC_ALL, "C");
  4063. GMainWindow main_window{std::move(config), has_broken_vulkan};
  4064. // After settings have been loaded by GMainWindow, apply the filter
  4065. main_window.show();
  4066. QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
  4067. &GMainWindow::OnAppFocusStateChanged);
  4068. int result = app.exec();
  4069. detached_tasks.WaitForAllTasks();
  4070. return result;
  4071. }