main.cpp 147 KB

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