main.cpp 182 KB

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