main.cpp 174 KB

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