main.cpp 156 KB

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