main.cpp 194 KB

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