main.cpp 165 KB

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