main.cpp 193 KB

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