main.cpp 157 KB

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