main.cpp 197 KB

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