main.cpp 154 KB

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