main.cpp 181 KB

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