main.cpp 159 KB

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