main.cpp 181 KB

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