main.cpp 171 KB

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