main.cpp 182 KB

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