main.cpp 158 KB

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