main.cpp 157 KB

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