main.cpp 168 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472
  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. if (!render_window->InitRenderTarget()) {
  1320. return false;
  1321. }
  1322. system->SetFilesystem(vfs);
  1323. system->SetAppletFrontendSet({
  1324. std::make_unique<QtAmiiboSettings>(*this), // Amiibo Settings
  1325. std::make_unique<QtControllerSelector>(*this), // Controller Selector
  1326. std::make_unique<QtErrorDisplay>(*this), // Error Display
  1327. nullptr, // Mii Editor
  1328. nullptr, // Parental Controls
  1329. nullptr, // Photo Viewer
  1330. std::make_unique<QtProfileSelector>(*this), // Profile Selector
  1331. std::make_unique<QtSoftwareKeyboard>(*this), // Software Keyboard
  1332. std::make_unique<QtWebBrowser>(*this), // Web Browser
  1333. });
  1334. const Core::SystemResultStatus result{
  1335. system->Load(*render_window, filename.toStdString(), program_id, program_index)};
  1336. const auto drd_callout = (UISettings::values.callout_flags.GetValue() &
  1337. static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  1338. if (result == Core::SystemResultStatus::Success &&
  1339. system->GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  1340. drd_callout) {
  1341. UISettings::values.callout_flags = UISettings::values.callout_flags.GetValue() |
  1342. static_cast<u32>(CalloutFlag::DRDDeprecation);
  1343. QMessageBox::warning(
  1344. this, tr("Warning Outdated Game Format"),
  1345. tr("You are using the deconstructed ROM directory format for this game, which is an "
  1346. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  1347. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  1348. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  1349. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  1350. "wiki</a>. This message will not be shown again."));
  1351. }
  1352. if (result != Core::SystemResultStatus::Success) {
  1353. switch (result) {
  1354. case Core::SystemResultStatus::ErrorGetLoader:
  1355. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  1356. QMessageBox::critical(this, tr("Error while loading ROM!"),
  1357. tr("The ROM format is not supported."));
  1358. break;
  1359. case Core::SystemResultStatus::ErrorVideoCore:
  1360. QMessageBox::critical(
  1361. this, tr("An error occurred initializing the video core."),
  1362. tr("yuzu has encountered an error while running the video core. "
  1363. "This is usually caused by outdated GPU drivers, including integrated ones. "
  1364. "Please see the log for more details. "
  1365. "For more information on accessing the log, please see the following page: "
  1366. "<a href='https://yuzu-emu.org/help/reference/log-files/'>"
  1367. "How to Upload the Log File</a>. "));
  1368. break;
  1369. default:
  1370. if (result > Core::SystemResultStatus::ErrorLoader) {
  1371. const u16 loader_id = static_cast<u16>(Core::SystemResultStatus::ErrorLoader);
  1372. const u16 error_id = static_cast<u16>(result) - loader_id;
  1373. const std::string error_code = fmt::format("({:04X}-{:04X})", loader_id, error_id);
  1374. LOG_CRITICAL(Frontend, "Failed to load ROM! {}", error_code);
  1375. const auto title =
  1376. tr("Error while loading ROM! %1", "%1 signifies a numeric error code.")
  1377. .arg(QString::fromStdString(error_code));
  1378. const auto description =
  1379. tr("%1<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the "
  1380. "yuzu quickstart guide</a> to redump your files.<br>You can refer "
  1381. "to the yuzu wiki</a> or the yuzu Discord</a> for help.",
  1382. "%1 signifies an error string.")
  1383. .arg(QString::fromStdString(
  1384. GetResultStatusString(static_cast<Loader::ResultStatus>(error_id))));
  1385. QMessageBox::critical(this, title, description);
  1386. } else {
  1387. QMessageBox::critical(
  1388. this, tr("Error while loading ROM!"),
  1389. tr("An unknown error occurred. Please see the log for more details."));
  1390. }
  1391. break;
  1392. }
  1393. return false;
  1394. }
  1395. current_game_path = filename;
  1396. system->TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "Qt");
  1397. return true;
  1398. }
  1399. bool GMainWindow::SelectAndSetCurrentUser() {
  1400. QtProfileSelectionDialog dialog(system->HIDCore(), this);
  1401. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1402. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1403. dialog.setWindowModality(Qt::WindowModal);
  1404. if (dialog.exec() == QDialog::Rejected) {
  1405. return false;
  1406. }
  1407. Settings::values.current_user = dialog.GetIndex();
  1408. return true;
  1409. }
  1410. void GMainWindow::BootGame(const QString& filename, u64 program_id, std::size_t program_index,
  1411. StartGameType type) {
  1412. LOG_INFO(Frontend, "yuzu starting...");
  1413. StoreRecentFile(filename); // Put the filename on top of the list
  1414. // Save configurations
  1415. UpdateUISettings();
  1416. game_list->SaveInterfaceLayout();
  1417. config->Save();
  1418. u64 title_id{0};
  1419. last_filename_booted = filename;
  1420. const auto v_file = Core::GetGameFileFromPath(vfs, filename.toUtf8().constData());
  1421. const auto loader = Loader::GetLoader(*system, v_file, program_id, program_index);
  1422. if (loader != nullptr && loader->ReadProgramId(title_id) == Loader::ResultStatus::Success &&
  1423. type == StartGameType::Normal) {
  1424. // Load per game settings
  1425. const auto file_path =
  1426. std::filesystem::path{Common::U16StringFromBuffer(filename.utf16(), filename.size())};
  1427. const auto config_file_name = title_id == 0
  1428. ? Common::FS::PathToUTF8String(file_path.filename())
  1429. : fmt::format("{:016X}", title_id);
  1430. Config per_game_config(config_file_name, Config::ConfigType::PerGameConfig);
  1431. system->HIDCore().ReloadInputDevices();
  1432. system->ApplySettings();
  1433. }
  1434. Settings::LogSettings();
  1435. if (UISettings::values.select_user_on_boot) {
  1436. if (SelectAndSetCurrentUser() == false) {
  1437. return;
  1438. }
  1439. }
  1440. if (!LoadROM(filename, program_id, program_index)) {
  1441. return;
  1442. }
  1443. system->SetShuttingDown(false);
  1444. // Create and start the emulation thread
  1445. emu_thread = std::make_unique<EmuThread>(*system);
  1446. emit EmulationStarting(emu_thread.get());
  1447. emu_thread->start();
  1448. // Register an ExecuteProgram callback such that Core can execute a sub-program
  1449. system->RegisterExecuteProgramCallback(
  1450. [this](std::size_t program_index_) { render_window->ExecuteProgram(program_index_); });
  1451. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1452. connect(render_window, &GRenderWindow::MouseActivity, this, &GMainWindow::OnMouseActivity);
  1453. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  1454. // before the CPU continues
  1455. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  1456. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  1457. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  1458. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  1459. connect(emu_thread.get(), &EmuThread::LoadProgress, loading_screen,
  1460. &LoadingScreen::OnLoadProgress, Qt::QueuedConnection);
  1461. // Update the GUI
  1462. UpdateStatusButtons();
  1463. if (ui->action_Single_Window_Mode->isChecked()) {
  1464. game_list->hide();
  1465. game_list_placeholder->hide();
  1466. }
  1467. status_bar_update_timer.start(500);
  1468. renderer_status_button->setDisabled(true);
  1469. if (UISettings::values.hide_mouse || Settings::values.mouse_panning) {
  1470. render_window->installEventFilter(render_window);
  1471. render_window->setAttribute(Qt::WA_Hover, true);
  1472. }
  1473. if (UISettings::values.hide_mouse) {
  1474. mouse_hide_timer.start();
  1475. }
  1476. render_window->InitializeCamera();
  1477. std::string title_name;
  1478. std::string title_version;
  1479. const auto res = system->GetGameName(title_name);
  1480. const auto metadata = [this, title_id] {
  1481. const FileSys::PatchManager pm(title_id, system->GetFileSystemController(),
  1482. system->GetContentProvider());
  1483. return pm.GetControlMetadata();
  1484. }();
  1485. if (metadata.first != nullptr) {
  1486. title_version = metadata.first->GetVersionString();
  1487. title_name = metadata.first->GetApplicationName();
  1488. }
  1489. if (res != Loader::ResultStatus::Success || title_name.empty()) {
  1490. title_name = Common::FS::PathToUTF8String(
  1491. std::filesystem::path{Common::U16StringFromBuffer(filename.utf16(), filename.size())}
  1492. .filename());
  1493. }
  1494. const bool is_64bit = system->Kernel().CurrentProcess()->Is64BitProcess();
  1495. const auto instruction_set_suffix = is_64bit ? tr("(64-bit)") : tr("(32-bit)");
  1496. title_name = tr("%1 %2", "%1 is the title name. %2 indicates if the title is 64-bit or 32-bit")
  1497. .arg(QString::fromStdString(title_name), instruction_set_suffix)
  1498. .toStdString();
  1499. LOG_INFO(Frontend, "Booting game: {:016X} | {} | {}", title_id, title_name, title_version);
  1500. const auto gpu_vendor = system->GPU().Renderer().GetDeviceVendor();
  1501. UpdateWindowTitle(title_name, title_version, gpu_vendor);
  1502. loading_screen->Prepare(system->GetAppLoader());
  1503. loading_screen->show();
  1504. emulation_running = true;
  1505. if (ui->action_Fullscreen->isChecked()) {
  1506. ShowFullscreen();
  1507. }
  1508. OnStartGame();
  1509. }
  1510. void GMainWindow::ShutdownGame() {
  1511. if (!emulation_running) {
  1512. return;
  1513. }
  1514. if (ui->action_Fullscreen->isChecked()) {
  1515. HideFullscreen();
  1516. }
  1517. AllowOSSleep();
  1518. // Disable unlimited frame rate
  1519. Settings::values.use_speed_limit.SetValue(true);
  1520. system->SetShuttingDown(true);
  1521. system->DetachDebugger();
  1522. discord_rpc->Pause();
  1523. RequestGameExit();
  1524. emit EmulationStopping();
  1525. // Wait for emulation thread to complete and delete it
  1526. if (!emu_thread->wait(5000)) {
  1527. emu_thread->ForceStop();
  1528. emu_thread->wait();
  1529. }
  1530. emu_thread = nullptr;
  1531. emulation_running = false;
  1532. discord_rpc->Update();
  1533. // The emulation is stopped, so closing the window or not does not matter anymore
  1534. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1535. // Update the GUI
  1536. UpdateMenuState();
  1537. render_window->hide();
  1538. loading_screen->hide();
  1539. loading_screen->Clear();
  1540. if (game_list->IsEmpty()) {
  1541. game_list_placeholder->show();
  1542. } else {
  1543. game_list->show();
  1544. }
  1545. game_list->SetFilterFocus();
  1546. tas_label->clear();
  1547. input_subsystem->GetTas()->Stop();
  1548. OnTasStateChanged();
  1549. render_window->FinalizeCamera();
  1550. // Enable all controllers
  1551. system->HIDCore().SetSupportedStyleTag({Core::HID::NpadStyleSet::All});
  1552. render_window->removeEventFilter(render_window);
  1553. render_window->setAttribute(Qt::WA_Hover, false);
  1554. UpdateWindowTitle();
  1555. // Disable status bar updates
  1556. status_bar_update_timer.stop();
  1557. shader_building_label->setVisible(false);
  1558. res_scale_label->setVisible(false);
  1559. emu_speed_label->setVisible(false);
  1560. game_fps_label->setVisible(false);
  1561. emu_frametime_label->setVisible(false);
  1562. renderer_status_button->setEnabled(!UISettings::values.has_broken_vulkan);
  1563. current_game_path.clear();
  1564. // When closing the game, destroy the GLWindow to clear the context after the game is closed
  1565. render_window->ReleaseRenderTarget();
  1566. }
  1567. void GMainWindow::StoreRecentFile(const QString& filename) {
  1568. UISettings::values.recent_files.prepend(filename);
  1569. UISettings::values.recent_files.removeDuplicates();
  1570. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  1571. UISettings::values.recent_files.removeLast();
  1572. }
  1573. UpdateRecentFiles();
  1574. }
  1575. void GMainWindow::UpdateRecentFiles() {
  1576. const int num_recent_files =
  1577. std::min(static_cast<int>(UISettings::values.recent_files.size()), max_recent_files_item);
  1578. for (int i = 0; i < num_recent_files; i++) {
  1579. const QString text = QStringLiteral("&%1. %2").arg(i + 1).arg(
  1580. QFileInfo(UISettings::values.recent_files[i]).fileName());
  1581. actions_recent_files[i]->setText(text);
  1582. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  1583. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  1584. actions_recent_files[i]->setVisible(true);
  1585. }
  1586. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  1587. actions_recent_files[j]->setVisible(false);
  1588. }
  1589. // Enable the recent files menu if the list isn't empty
  1590. ui->menu_recent_files->setEnabled(num_recent_files != 0);
  1591. }
  1592. void GMainWindow::OnGameListLoadFile(QString game_path, u64 program_id) {
  1593. BootGame(game_path, program_id);
  1594. }
  1595. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target,
  1596. const std::string& game_path) {
  1597. std::filesystem::path path;
  1598. QString open_target;
  1599. const auto [user_save_size, device_save_size] = [this, &game_path, &program_id] {
  1600. const FileSys::PatchManager pm{program_id, system->GetFileSystemController(),
  1601. system->GetContentProvider()};
  1602. const auto control = pm.GetControlMetadata().first;
  1603. if (control != nullptr) {
  1604. return std::make_pair(control->GetDefaultNormalSaveSize(),
  1605. control->GetDeviceSaveDataSize());
  1606. } else {
  1607. const auto file = Core::GetGameFileFromPath(vfs, game_path);
  1608. const auto loader = Loader::GetLoader(*system, file);
  1609. FileSys::NACP nacp{};
  1610. loader->ReadControlData(nacp);
  1611. return std::make_pair(nacp.GetDefaultNormalSaveSize(), nacp.GetDeviceSaveDataSize());
  1612. }
  1613. }();
  1614. const bool has_user_save{user_save_size > 0};
  1615. const bool has_device_save{device_save_size > 0};
  1616. ASSERT_MSG(has_user_save != has_device_save, "Game uses both user and device savedata?");
  1617. switch (target) {
  1618. case GameListOpenTarget::SaveData: {
  1619. open_target = tr("Save Data");
  1620. const auto nand_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir);
  1621. auto vfs_nand_dir =
  1622. vfs->OpenDirectory(Common::FS::PathToUTF8String(nand_dir), FileSys::Mode::Read);
  1623. if (has_user_save) {
  1624. // User save data
  1625. const auto select_profile = [this] {
  1626. QtProfileSelectionDialog dialog(system->HIDCore(), this);
  1627. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1628. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1629. dialog.setWindowModality(Qt::WindowModal);
  1630. if (dialog.exec() == QDialog::Rejected) {
  1631. return -1;
  1632. }
  1633. return dialog.GetIndex();
  1634. };
  1635. const auto index = select_profile();
  1636. if (index == -1) {
  1637. return;
  1638. }
  1639. Service::Account::ProfileManager manager;
  1640. const auto user_id = manager.GetUser(static_cast<std::size_t>(index));
  1641. ASSERT(user_id);
  1642. const auto user_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1643. *system, vfs_nand_dir, FileSys::SaveDataSpaceId::NandUser,
  1644. FileSys::SaveDataType::SaveData, program_id, user_id->AsU128(), 0);
  1645. path = Common::FS::ConcatPathSafe(nand_dir, user_save_data_path);
  1646. } else {
  1647. // Device save data
  1648. const auto device_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1649. *system, vfs_nand_dir, FileSys::SaveDataSpaceId::NandUser,
  1650. FileSys::SaveDataType::SaveData, program_id, {}, 0);
  1651. path = Common::FS::ConcatPathSafe(nand_dir, device_save_data_path);
  1652. }
  1653. if (!Common::FS::CreateDirs(path)) {
  1654. LOG_ERROR(Frontend, "Unable to create the directories for save data");
  1655. }
  1656. break;
  1657. }
  1658. case GameListOpenTarget::ModData: {
  1659. open_target = tr("Mod Data");
  1660. path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::LoadDir) /
  1661. fmt::format("{:016X}", program_id);
  1662. break;
  1663. }
  1664. default:
  1665. UNIMPLEMENTED();
  1666. break;
  1667. }
  1668. const QString qpath = QString::fromStdString(Common::FS::PathToUTF8String(path));
  1669. const QDir dir(qpath);
  1670. if (!dir.exists()) {
  1671. QMessageBox::warning(this, tr("Error Opening %1 Folder").arg(open_target),
  1672. tr("Folder does not exist!"));
  1673. return;
  1674. }
  1675. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target.toStdString(),
  1676. program_id);
  1677. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  1678. }
  1679. void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
  1680. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1681. const auto shader_cache_folder_path{shader_cache_dir / fmt::format("{:016x}", program_id)};
  1682. if (!Common::FS::CreateDirs(shader_cache_folder_path)) {
  1683. QMessageBox::warning(this, tr("Error Opening Transferable Shader Cache"),
  1684. tr("Failed to create the shader cache directory for this title."));
  1685. return;
  1686. }
  1687. const auto shader_path_string{Common::FS::PathToUTF8String(shader_cache_folder_path)};
  1688. const auto qt_shader_cache_path = QString::fromStdString(shader_path_string);
  1689. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_shader_cache_path));
  1690. }
  1691. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  1692. std::size_t out = 0;
  1693. for (const auto& subdir : dir->GetSubdirectories()) {
  1694. out += 1 + CalculateRomFSEntrySize(subdir, full);
  1695. }
  1696. return out + (full ? dir->GetFiles().size() : 0);
  1697. }
  1698. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  1699. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  1700. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  1701. return false;
  1702. if (dialog.wasCanceled())
  1703. return false;
  1704. if (full) {
  1705. for (const auto& file : src->GetFiles()) {
  1706. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  1707. if (!FileSys::VfsRawCopy(file, out, block_size))
  1708. return false;
  1709. dialog.setValue(dialog.value() + 1);
  1710. if (dialog.wasCanceled())
  1711. return false;
  1712. }
  1713. }
  1714. for (const auto& dir : src->GetSubdirectories()) {
  1715. const auto out = dest->CreateSubdirectory(dir->GetName());
  1716. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  1717. return false;
  1718. dialog.setValue(dialog.value() + 1);
  1719. if (dialog.wasCanceled())
  1720. return false;
  1721. }
  1722. return true;
  1723. }
  1724. QString GMainWindow::GetGameListErrorRemoving(InstalledEntryType type) const {
  1725. switch (type) {
  1726. case InstalledEntryType::Game:
  1727. return tr("Error Removing Contents");
  1728. case InstalledEntryType::Update:
  1729. return tr("Error Removing Update");
  1730. case InstalledEntryType::AddOnContent:
  1731. return tr("Error Removing DLC");
  1732. default:
  1733. return QStringLiteral("Error Removing <Invalid Type>");
  1734. }
  1735. }
  1736. void GMainWindow::OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type) {
  1737. const QString entry_question = [type] {
  1738. switch (type) {
  1739. case InstalledEntryType::Game:
  1740. return tr("Remove Installed Game Contents?");
  1741. case InstalledEntryType::Update:
  1742. return tr("Remove Installed Game Update?");
  1743. case InstalledEntryType::AddOnContent:
  1744. return tr("Remove Installed Game DLC?");
  1745. default:
  1746. return QStringLiteral("Remove Installed Game <Invalid Type>?");
  1747. }
  1748. }();
  1749. if (QMessageBox::question(this, tr("Remove Entry"), entry_question,
  1750. QMessageBox::Yes | QMessageBox::No,
  1751. QMessageBox::No) != QMessageBox::Yes) {
  1752. return;
  1753. }
  1754. switch (type) {
  1755. case InstalledEntryType::Game:
  1756. RemoveBaseContent(program_id, type);
  1757. [[fallthrough]];
  1758. case InstalledEntryType::Update:
  1759. RemoveUpdateContent(program_id, type);
  1760. if (type != InstalledEntryType::Game) {
  1761. break;
  1762. }
  1763. [[fallthrough]];
  1764. case InstalledEntryType::AddOnContent:
  1765. RemoveAddOnContent(program_id, type);
  1766. break;
  1767. }
  1768. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  1769. "game_list");
  1770. game_list->PopulateAsync(UISettings::values.game_dirs);
  1771. }
  1772. void GMainWindow::RemoveBaseContent(u64 program_id, InstalledEntryType type) {
  1773. const auto& fs_controller = system->GetFileSystemController();
  1774. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(program_id) ||
  1775. fs_controller.GetSDMCContents()->RemoveExistingEntry(program_id);
  1776. if (res) {
  1777. QMessageBox::information(this, tr("Successfully Removed"),
  1778. tr("Successfully removed the installed base game."));
  1779. } else {
  1780. QMessageBox::warning(
  1781. this, GetGameListErrorRemoving(type),
  1782. tr("The base game is not installed in the NAND and cannot be removed."));
  1783. }
  1784. }
  1785. void GMainWindow::RemoveUpdateContent(u64 program_id, InstalledEntryType type) {
  1786. const auto update_id = program_id | 0x800;
  1787. const auto& fs_controller = system->GetFileSystemController();
  1788. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(update_id) ||
  1789. fs_controller.GetSDMCContents()->RemoveExistingEntry(update_id);
  1790. if (res) {
  1791. QMessageBox::information(this, tr("Successfully Removed"),
  1792. tr("Successfully removed the installed update."));
  1793. } else {
  1794. QMessageBox::warning(this, GetGameListErrorRemoving(type),
  1795. tr("There is no update installed for this title."));
  1796. }
  1797. }
  1798. void GMainWindow::RemoveAddOnContent(u64 program_id, InstalledEntryType type) {
  1799. u32 count{};
  1800. const auto& fs_controller = system->GetFileSystemController();
  1801. const auto dlc_entries = system->GetContentProvider().ListEntriesFilter(
  1802. FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1803. for (const auto& entry : dlc_entries) {
  1804. if (FileSys::GetBaseTitleID(entry.title_id) == program_id) {
  1805. const auto res =
  1806. fs_controller.GetUserNANDContents()->RemoveExistingEntry(entry.title_id) ||
  1807. fs_controller.GetSDMCContents()->RemoveExistingEntry(entry.title_id);
  1808. if (res) {
  1809. ++count;
  1810. }
  1811. }
  1812. }
  1813. if (count == 0) {
  1814. QMessageBox::warning(this, GetGameListErrorRemoving(type),
  1815. tr("There are no DLC installed for this title."));
  1816. return;
  1817. }
  1818. QMessageBox::information(this, tr("Successfully Removed"),
  1819. tr("Successfully removed %1 installed DLC.").arg(count));
  1820. }
  1821. void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target,
  1822. const std::string& game_path) {
  1823. const QString question = [target] {
  1824. switch (target) {
  1825. case GameListRemoveTarget::GlShaderCache:
  1826. return tr("Delete OpenGL Transferable Shader Cache?");
  1827. case GameListRemoveTarget::VkShaderCache:
  1828. return tr("Delete Vulkan Transferable Shader Cache?");
  1829. case GameListRemoveTarget::AllShaderCache:
  1830. return tr("Delete All Transferable Shader Caches?");
  1831. case GameListRemoveTarget::CustomConfiguration:
  1832. return tr("Remove Custom Game Configuration?");
  1833. default:
  1834. return QString{};
  1835. }
  1836. }();
  1837. if (QMessageBox::question(this, tr("Remove File"), question, QMessageBox::Yes | QMessageBox::No,
  1838. QMessageBox::No) != QMessageBox::Yes) {
  1839. return;
  1840. }
  1841. switch (target) {
  1842. case GameListRemoveTarget::GlShaderCache:
  1843. case GameListRemoveTarget::VkShaderCache:
  1844. RemoveTransferableShaderCache(program_id, target);
  1845. break;
  1846. case GameListRemoveTarget::AllShaderCache:
  1847. RemoveAllTransferableShaderCaches(program_id);
  1848. break;
  1849. case GameListRemoveTarget::CustomConfiguration:
  1850. RemoveCustomConfiguration(program_id, game_path);
  1851. break;
  1852. }
  1853. }
  1854. void GMainWindow::RemoveTransferableShaderCache(u64 program_id, GameListRemoveTarget target) {
  1855. const auto target_file_name = [target] {
  1856. switch (target) {
  1857. case GameListRemoveTarget::GlShaderCache:
  1858. return "opengl.bin";
  1859. case GameListRemoveTarget::VkShaderCache:
  1860. return "vulkan.bin";
  1861. default:
  1862. return "";
  1863. }
  1864. }();
  1865. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1866. const auto shader_cache_folder_path = shader_cache_dir / fmt::format("{:016x}", program_id);
  1867. const auto target_file = shader_cache_folder_path / target_file_name;
  1868. if (!Common::FS::Exists(target_file)) {
  1869. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1870. tr("A shader cache for this title does not exist."));
  1871. return;
  1872. }
  1873. if (Common::FS::RemoveFile(target_file)) {
  1874. QMessageBox::information(this, tr("Successfully Removed"),
  1875. tr("Successfully removed the transferable shader cache."));
  1876. } else {
  1877. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1878. tr("Failed to remove the transferable shader cache."));
  1879. }
  1880. }
  1881. void GMainWindow::RemoveAllTransferableShaderCaches(u64 program_id) {
  1882. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1883. const auto program_shader_cache_dir = shader_cache_dir / fmt::format("{:016x}", program_id);
  1884. if (!Common::FS::Exists(program_shader_cache_dir)) {
  1885. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  1886. tr("A shader cache for this title does not exist."));
  1887. return;
  1888. }
  1889. if (Common::FS::RemoveDirRecursively(program_shader_cache_dir)) {
  1890. QMessageBox::information(this, tr("Successfully Removed"),
  1891. tr("Successfully removed the transferable shader caches."));
  1892. } else {
  1893. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  1894. tr("Failed to remove the transferable shader cache directory."));
  1895. }
  1896. }
  1897. void GMainWindow::RemoveCustomConfiguration(u64 program_id, const std::string& game_path) {
  1898. const auto file_path = std::filesystem::path(Common::FS::ToU8String(game_path));
  1899. const auto config_file_name =
  1900. program_id == 0 ? Common::FS::PathToUTF8String(file_path.filename()).append(".ini")
  1901. : fmt::format("{:016X}.ini", program_id);
  1902. const auto custom_config_file_path =
  1903. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom" / config_file_name;
  1904. if (!Common::FS::Exists(custom_config_file_path)) {
  1905. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1906. tr("A custom configuration for this title does not exist."));
  1907. return;
  1908. }
  1909. if (Common::FS::RemoveFile(custom_config_file_path)) {
  1910. QMessageBox::information(this, tr("Successfully Removed"),
  1911. tr("Successfully removed the custom game configuration."));
  1912. } else {
  1913. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1914. tr("Failed to remove the custom game configuration."));
  1915. }
  1916. }
  1917. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path,
  1918. DumpRomFSTarget target) {
  1919. const auto failed = [this] {
  1920. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1921. tr("There was an error copying the RomFS files or the user "
  1922. "cancelled the operation."));
  1923. };
  1924. const auto loader = Loader::GetLoader(*system, vfs->OpenFile(game_path, FileSys::Mode::Read));
  1925. if (loader == nullptr) {
  1926. failed();
  1927. return;
  1928. }
  1929. FileSys::VirtualFile file;
  1930. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  1931. failed();
  1932. return;
  1933. }
  1934. const auto& installed = system->GetContentProvider();
  1935. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  1936. if (!romfs_title_id) {
  1937. failed();
  1938. return;
  1939. }
  1940. const auto dump_dir =
  1941. target == DumpRomFSTarget::Normal
  1942. ? Common::FS::GetYuzuPath(Common::FS::YuzuPath::DumpDir)
  1943. : Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "atmosphere" / "contents";
  1944. const auto romfs_dir = fmt::format("{:016X}/romfs", *romfs_title_id);
  1945. const auto path = Common::FS::PathToUTF8String(dump_dir / romfs_dir);
  1946. FileSys::VirtualFile romfs;
  1947. if (*romfs_title_id == program_id) {
  1948. const u64 ivfc_offset = loader->ReadRomFSIVFCOffset();
  1949. const FileSys::PatchManager pm{program_id, system->GetFileSystemController(), installed};
  1950. romfs =
  1951. pm.PatchRomFS(file, ivfc_offset, FileSys::ContentRecordType::Program, nullptr, false);
  1952. } else {
  1953. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  1954. }
  1955. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  1956. if (extracted == nullptr) {
  1957. failed();
  1958. return;
  1959. }
  1960. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  1961. if (out == nullptr) {
  1962. failed();
  1963. vfs->DeleteDirectory(path);
  1964. return;
  1965. }
  1966. bool ok = false;
  1967. const QStringList selections{tr("Full"), tr("Skeleton")};
  1968. const auto res = QInputDialog::getItem(
  1969. this, tr("Select RomFS Dump Mode"),
  1970. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  1971. "files into the new directory while <br>skeleton will only create the directory "
  1972. "structure."),
  1973. selections, 0, false, &ok);
  1974. if (!ok) {
  1975. failed();
  1976. vfs->DeleteDirectory(path);
  1977. return;
  1978. }
  1979. const auto full = res == selections.constFirst();
  1980. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  1981. // The minimum required space is the size of the extracted RomFS + 1 GiB
  1982. const auto minimum_free_space = extracted->GetSize() + 0x40000000;
  1983. if (full && Common::FS::GetFreeSpaceSize(path) < minimum_free_space) {
  1984. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1985. tr("There is not enough free space at %1 to extract the RomFS. Please "
  1986. "free up space or select a different dump directory at "
  1987. "Emulation > Configure > System > Filesystem > Dump Root")
  1988. .arg(QString::fromStdString(path)));
  1989. return;
  1990. }
  1991. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  1992. static_cast<s32>(entry_size), this);
  1993. progress.setWindowModality(Qt::WindowModal);
  1994. progress.setMinimumDuration(100);
  1995. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  1996. progress.close();
  1997. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  1998. tr("The operation completed successfully."));
  1999. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  2000. } else {
  2001. progress.close();
  2002. failed();
  2003. vfs->DeleteDirectory(path);
  2004. }
  2005. }
  2006. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  2007. QClipboard* clipboard = QGuiApplication::clipboard();
  2008. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  2009. }
  2010. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  2011. const CompatibilityList& compatibility_list) {
  2012. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  2013. QString directory;
  2014. if (it != compatibility_list.end()) {
  2015. directory = it->second.second;
  2016. }
  2017. QDesktopServices::openUrl(QUrl(QStringLiteral("https://yuzu-emu.org/game/") + directory));
  2018. }
  2019. void GMainWindow::OnGameListCreateShortcut(u64 program_id, const std::string& game_path,
  2020. GameListShortcutTarget target) {
  2021. // Get path to yuzu executable
  2022. const QStringList args = QApplication::arguments();
  2023. std::filesystem::path yuzu_command = args[0].toStdString();
  2024. #if defined(__linux__) || defined(__FreeBSD__)
  2025. // If relative path, make it an absolute path
  2026. if (yuzu_command.c_str()[0] == '.') {
  2027. yuzu_command = Common::FS::GetCurrentDir() / yuzu_command;
  2028. }
  2029. #if defined(__linux__)
  2030. // Warn once if we are making a shortcut to a volatile AppImage
  2031. const std::string appimage_ending =
  2032. std::string(Common::g_scm_rev).substr(0, 9).append(".AppImage");
  2033. if (yuzu_command.string().ends_with(appimage_ending) &&
  2034. !UISettings::values.shortcut_already_warned) {
  2035. if (QMessageBox::warning(this, tr("Create Shortcut"),
  2036. tr("This will create a shortcut to the current AppImage. This may "
  2037. "not work well if you update. Continue?"),
  2038. QMessageBox::StandardButton::Ok |
  2039. QMessageBox::StandardButton::Cancel) ==
  2040. QMessageBox::StandardButton::Cancel) {
  2041. return;
  2042. }
  2043. UISettings::values.shortcut_already_warned = true;
  2044. }
  2045. #endif // __linux__
  2046. #endif // __linux__ || __FreeBSD__
  2047. std::filesystem::path target_directory{};
  2048. // Determine target directory for shortcut
  2049. #if defined(__linux__) || defined(__FreeBSD__)
  2050. const char* home = std::getenv("HOME");
  2051. const std::filesystem::path home_path = (home == nullptr ? "~" : home);
  2052. const char* xdg_data_home = std::getenv("XDG_DATA_HOME");
  2053. if (target == GameListShortcutTarget::Desktop) {
  2054. target_directory = home_path / "Desktop";
  2055. if (!Common::FS::IsDir(target_directory)) {
  2056. QMessageBox::critical(
  2057. this, tr("Create Shortcut"),
  2058. tr("Cannot create shortcut on desktop. Path \"%1\" does not exist.")
  2059. .arg(QString::fromStdString(target_directory)),
  2060. QMessageBox::StandardButton::Ok);
  2061. return;
  2062. }
  2063. } else if (target == GameListShortcutTarget::Applications) {
  2064. target_directory = (xdg_data_home == nullptr ? home_path / ".local/share" : xdg_data_home) /
  2065. "applications";
  2066. if (!Common::FS::CreateDirs(target_directory)) {
  2067. QMessageBox::critical(this, tr("Create Shortcut"),
  2068. tr("Cannot create shortcut in applications menu. Path \"%1\" "
  2069. "does not exist and cannot be created.")
  2070. .arg(QString::fromStdString(target_directory)),
  2071. QMessageBox::StandardButton::Ok);
  2072. return;
  2073. }
  2074. }
  2075. #endif
  2076. const std::string game_file_name = std::filesystem::path(game_path).filename().string();
  2077. // Determine full paths for icon and shortcut
  2078. #if defined(__linux__) || defined(__FreeBSD__)
  2079. std::filesystem::path system_icons_path =
  2080. (xdg_data_home == nullptr ? home_path / ".local/share/" : xdg_data_home) /
  2081. "icons/hicolor/256x256";
  2082. if (!Common::FS::CreateDirs(system_icons_path)) {
  2083. QMessageBox::critical(
  2084. this, tr("Create Icon"),
  2085. tr("Cannot create icon file. Path \"%1\" does not exist and cannot be created.")
  2086. .arg(QString::fromStdString(system_icons_path)),
  2087. QMessageBox::StandardButton::Ok);
  2088. return;
  2089. }
  2090. std::filesystem::path icon_path =
  2091. system_icons_path / (program_id == 0 ? fmt::format("yuzu-{}.png", game_file_name)
  2092. : fmt::format("yuzu-{:016X}.png", program_id));
  2093. const std::filesystem::path shortcut_path =
  2094. target_directory / (program_id == 0 ? fmt::format("yuzu-{}.desktop", game_file_name)
  2095. : fmt::format("yuzu-{:016X}.desktop", program_id));
  2096. #else
  2097. const std::filesystem::path icon_path{};
  2098. const std::filesystem::path shortcut_path{};
  2099. #endif
  2100. // Get title from game file
  2101. const FileSys::PatchManager pm{program_id, system->GetFileSystemController(),
  2102. system->GetContentProvider()};
  2103. const auto control = pm.GetControlMetadata();
  2104. const auto loader = Loader::GetLoader(*system, vfs->OpenFile(game_path, FileSys::Mode::Read));
  2105. std::string title{fmt::format("{:016X}", program_id)};
  2106. if (control.first != nullptr) {
  2107. title = control.first->GetApplicationName();
  2108. } else {
  2109. loader->ReadTitle(title);
  2110. }
  2111. // Get icon from game file
  2112. std::vector<u8> icon_image_file{};
  2113. if (control.second != nullptr) {
  2114. icon_image_file = control.second->ReadAllBytes();
  2115. } else if (loader->ReadIcon(icon_image_file) != Loader::ResultStatus::Success) {
  2116. LOG_WARNING(Frontend, "Could not read icon from {:s}", game_path);
  2117. }
  2118. QImage icon_jpeg =
  2119. QImage::fromData(icon_image_file.data(), static_cast<int>(icon_image_file.size()));
  2120. #if defined(__linux__) || defined(__FreeBSD__)
  2121. // Convert and write the icon as a PNG
  2122. if (!icon_jpeg.save(QString::fromStdString(icon_path.string()))) {
  2123. LOG_ERROR(Frontend, "Could not write icon as PNG to file");
  2124. } else {
  2125. LOG_INFO(Frontend, "Wrote an icon to {}", icon_path.string());
  2126. }
  2127. #endif // __linux__
  2128. #if defined(__linux__) || defined(__FreeBSD__)
  2129. const std::string comment =
  2130. tr("Start %1 with the yuzu Emulator").arg(QString::fromStdString(title)).toStdString();
  2131. const std::string arguments = fmt::format("-g \"{:s}\"", game_path);
  2132. const std::string categories = "Game;Emulator;Qt;";
  2133. const std::string keywords = "Switch;Nintendo;";
  2134. #else
  2135. const std::string comment{};
  2136. const std::string arguments{};
  2137. const std::string categories{};
  2138. const std::string keywords{};
  2139. #endif
  2140. if (!CreateShortcut(shortcut_path.string(), title, comment, icon_path.string(),
  2141. yuzu_command.string(), arguments, categories, keywords)) {
  2142. QMessageBox::critical(this, tr("Create Shortcut"),
  2143. tr("Failed to create a shortcut at %1")
  2144. .arg(QString::fromStdString(shortcut_path.string())));
  2145. return;
  2146. }
  2147. LOG_INFO(Frontend, "Wrote a shortcut to {}", shortcut_path.string());
  2148. QMessageBox::information(
  2149. this, tr("Create Shortcut"),
  2150. tr("Successfully created a shortcut to %1").arg(QString::fromStdString(title)));
  2151. }
  2152. void GMainWindow::OnGameListOpenDirectory(const QString& directory) {
  2153. std::filesystem::path fs_path;
  2154. if (directory == QStringLiteral("SDMC")) {
  2155. fs_path =
  2156. Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "Nintendo/Contents/registered";
  2157. } else if (directory == QStringLiteral("UserNAND")) {
  2158. fs_path =
  2159. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "user/Contents/registered";
  2160. } else if (directory == QStringLiteral("SysNAND")) {
  2161. fs_path =
  2162. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "system/Contents/registered";
  2163. } else {
  2164. fs_path = directory.toStdString();
  2165. }
  2166. const auto qt_path = QString::fromStdString(Common::FS::PathToUTF8String(fs_path));
  2167. if (!Common::FS::IsDir(fs_path)) {
  2168. QMessageBox::critical(this, tr("Error Opening %1").arg(qt_path),
  2169. tr("Folder does not exist!"));
  2170. return;
  2171. }
  2172. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_path));
  2173. }
  2174. void GMainWindow::OnGameListAddDirectory() {
  2175. const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  2176. if (dir_path.isEmpty()) {
  2177. return;
  2178. }
  2179. UISettings::GameDir game_dir{dir_path, false, true};
  2180. if (!UISettings::values.game_dirs.contains(game_dir)) {
  2181. UISettings::values.game_dirs.append(game_dir);
  2182. game_list->PopulateAsync(UISettings::values.game_dirs);
  2183. } else {
  2184. LOG_WARNING(Frontend, "Selected directory is already in the game list");
  2185. }
  2186. }
  2187. void GMainWindow::OnGameListShowList(bool show) {
  2188. if (emulation_running && ui->action_Single_Window_Mode->isChecked())
  2189. return;
  2190. game_list->setVisible(show);
  2191. game_list_placeholder->setVisible(!show);
  2192. };
  2193. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  2194. u64 title_id{};
  2195. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  2196. const auto loader = Loader::GetLoader(*system, v_file);
  2197. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  2198. QMessageBox::information(this, tr("Properties"),
  2199. tr("The game properties could not be loaded."));
  2200. return;
  2201. }
  2202. OpenPerGameConfiguration(title_id, file);
  2203. }
  2204. void GMainWindow::OnMenuLoadFile() {
  2205. if (is_load_file_select_active) {
  2206. return;
  2207. }
  2208. is_load_file_select_active = true;
  2209. const QString extensions =
  2210. QStringLiteral("*.")
  2211. .append(GameList::supported_file_extensions.join(QStringLiteral(" *.")))
  2212. .append(QStringLiteral(" main"));
  2213. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  2214. "%1 is an identifier for the Switch executable file extensions.")
  2215. .arg(extensions);
  2216. const QString filename = QFileDialog::getOpenFileName(
  2217. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  2218. is_load_file_select_active = false;
  2219. if (filename.isEmpty()) {
  2220. return;
  2221. }
  2222. UISettings::values.roms_path = QFileInfo(filename).path();
  2223. BootGame(filename);
  2224. }
  2225. void GMainWindow::OnMenuLoadFolder() {
  2226. const QString dir_path =
  2227. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  2228. if (dir_path.isNull()) {
  2229. return;
  2230. }
  2231. const QDir dir{dir_path};
  2232. const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files);
  2233. if (matching_main.size() == 1) {
  2234. BootGame(dir.path() + QDir::separator() + matching_main[0]);
  2235. } else {
  2236. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  2237. tr("The directory you have selected does not contain a 'main' file."));
  2238. }
  2239. }
  2240. void GMainWindow::IncrementInstallProgress() {
  2241. install_progress->setValue(install_progress->value() + 1);
  2242. }
  2243. void GMainWindow::OnMenuInstallToNAND() {
  2244. const QString file_filter =
  2245. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  2246. "(*.nca);;Nintendo Submission Package (*.nsp);;NX Cartridge "
  2247. "Image (*.xci)");
  2248. QStringList filenames = QFileDialog::getOpenFileNames(
  2249. this, tr("Install Files"), UISettings::values.roms_path, file_filter);
  2250. if (filenames.isEmpty()) {
  2251. return;
  2252. }
  2253. InstallDialog installDialog(this, filenames);
  2254. if (installDialog.exec() == QDialog::Rejected) {
  2255. return;
  2256. }
  2257. const QStringList files = installDialog.GetFiles();
  2258. if (files.isEmpty()) {
  2259. return;
  2260. }
  2261. // Save folder location of the first selected file
  2262. UISettings::values.roms_path = QFileInfo(filenames[0]).path();
  2263. int remaining = filenames.size();
  2264. // This would only overflow above 2^43 bytes (8.796 TB)
  2265. int total_size = 0;
  2266. for (const QString& file : files) {
  2267. total_size += static_cast<int>(QFile(file).size() / 0x1000);
  2268. }
  2269. if (total_size < 0) {
  2270. LOG_CRITICAL(Frontend, "Attempting to install too many files, aborting.");
  2271. return;
  2272. }
  2273. QStringList new_files{}; // Newly installed files that do not yet exist in the NAND
  2274. QStringList overwritten_files{}; // Files that overwrote those existing in the NAND
  2275. QStringList failed_files{}; // Files that failed to install due to errors
  2276. bool detected_base_install{}; // Whether a base game was attempted to be installed
  2277. ui->action_Install_File_NAND->setEnabled(false);
  2278. install_progress = new QProgressDialog(QString{}, tr("Cancel"), 0, total_size, this);
  2279. install_progress->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint &
  2280. ~Qt::WindowMaximizeButtonHint);
  2281. install_progress->setAttribute(Qt::WA_DeleteOnClose, true);
  2282. install_progress->setFixedWidth(installDialog.GetMinimumWidth() + 40);
  2283. install_progress->show();
  2284. for (const QString& file : files) {
  2285. install_progress->setWindowTitle(tr("%n file(s) remaining", "", remaining));
  2286. install_progress->setLabelText(
  2287. tr("Installing file \"%1\"...").arg(QFileInfo(file).fileName()));
  2288. QFuture<InstallResult> future;
  2289. InstallResult result;
  2290. if (file.endsWith(QStringLiteral("xci"), Qt::CaseInsensitive) ||
  2291. file.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  2292. future = QtConcurrent::run([this, &file] { return InstallNSPXCI(file); });
  2293. while (!future.isFinished()) {
  2294. QCoreApplication::processEvents();
  2295. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2296. }
  2297. result = future.result();
  2298. } else {
  2299. result = InstallNCA(file);
  2300. }
  2301. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2302. switch (result) {
  2303. case InstallResult::Success:
  2304. new_files.append(QFileInfo(file).fileName());
  2305. break;
  2306. case InstallResult::Overwrite:
  2307. overwritten_files.append(QFileInfo(file).fileName());
  2308. break;
  2309. case InstallResult::Failure:
  2310. failed_files.append(QFileInfo(file).fileName());
  2311. break;
  2312. case InstallResult::BaseInstallAttempted:
  2313. failed_files.append(QFileInfo(file).fileName());
  2314. detected_base_install = true;
  2315. break;
  2316. }
  2317. --remaining;
  2318. }
  2319. install_progress->close();
  2320. if (detected_base_install) {
  2321. QMessageBox::warning(
  2322. this, tr("Install Results"),
  2323. tr("To avoid possible conflicts, we discourage users from installing base games to the "
  2324. "NAND.\nPlease, only use this feature to install updates and DLC."));
  2325. }
  2326. const QString install_results =
  2327. (new_files.isEmpty() ? QString{}
  2328. : tr("%n file(s) were newly installed\n", "", new_files.size())) +
  2329. (overwritten_files.isEmpty()
  2330. ? QString{}
  2331. : tr("%n file(s) were overwritten\n", "", overwritten_files.size())) +
  2332. (failed_files.isEmpty() ? QString{}
  2333. : tr("%n file(s) failed to install\n", "", failed_files.size()));
  2334. QMessageBox::information(this, tr("Install Results"), install_results);
  2335. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  2336. "game_list");
  2337. game_list->PopulateAsync(UISettings::values.game_dirs);
  2338. ui->action_Install_File_NAND->setEnabled(true);
  2339. }
  2340. InstallResult GMainWindow::InstallNSPXCI(const QString& filename) {
  2341. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  2342. const FileSys::VirtualFile& dest, std::size_t block_size) {
  2343. if (src == nullptr || dest == nullptr) {
  2344. return false;
  2345. }
  2346. if (!dest->Resize(src->GetSize())) {
  2347. return false;
  2348. }
  2349. std::array<u8, 0x1000> buffer{};
  2350. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  2351. if (install_progress->wasCanceled()) {
  2352. dest->Resize(0);
  2353. return false;
  2354. }
  2355. emit UpdateInstallProgress();
  2356. const auto read = src->Read(buffer.data(), buffer.size(), i);
  2357. dest->Write(buffer.data(), read, i);
  2358. }
  2359. return true;
  2360. };
  2361. std::shared_ptr<FileSys::NSP> nsp;
  2362. if (filename.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  2363. nsp = std::make_shared<FileSys::NSP>(
  2364. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  2365. if (nsp->IsExtractedType()) {
  2366. return InstallResult::Failure;
  2367. }
  2368. } else {
  2369. const auto xci = std::make_shared<FileSys::XCI>(
  2370. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  2371. nsp = xci->GetSecurePartitionNSP();
  2372. }
  2373. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  2374. return InstallResult::Failure;
  2375. }
  2376. const auto res = system->GetFileSystemController().GetUserNANDContents()->InstallEntry(
  2377. *nsp, true, qt_raw_copy);
  2378. switch (res) {
  2379. case FileSys::InstallResult::Success:
  2380. return InstallResult::Success;
  2381. case FileSys::InstallResult::OverwriteExisting:
  2382. return InstallResult::Overwrite;
  2383. case FileSys::InstallResult::ErrorBaseInstall:
  2384. return InstallResult::BaseInstallAttempted;
  2385. default:
  2386. return InstallResult::Failure;
  2387. }
  2388. }
  2389. InstallResult GMainWindow::InstallNCA(const QString& filename) {
  2390. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  2391. const FileSys::VirtualFile& dest, std::size_t block_size) {
  2392. if (src == nullptr || dest == nullptr) {
  2393. return false;
  2394. }
  2395. if (!dest->Resize(src->GetSize())) {
  2396. return false;
  2397. }
  2398. std::array<u8, 0x1000> buffer{};
  2399. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  2400. if (install_progress->wasCanceled()) {
  2401. dest->Resize(0);
  2402. return false;
  2403. }
  2404. emit UpdateInstallProgress();
  2405. const auto read = src->Read(buffer.data(), buffer.size(), i);
  2406. dest->Write(buffer.data(), read, i);
  2407. }
  2408. return true;
  2409. };
  2410. const auto nca =
  2411. std::make_shared<FileSys::NCA>(vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  2412. const auto id = nca->GetStatus();
  2413. // Game updates necessary are missing base RomFS
  2414. if (id != Loader::ResultStatus::Success &&
  2415. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  2416. return InstallResult::Failure;
  2417. }
  2418. const QStringList tt_options{tr("System Application"),
  2419. tr("System Archive"),
  2420. tr("System Application Update"),
  2421. tr("Firmware Package (Type A)"),
  2422. tr("Firmware Package (Type B)"),
  2423. tr("Game"),
  2424. tr("Game Update"),
  2425. tr("Game DLC"),
  2426. tr("Delta Title")};
  2427. bool ok;
  2428. const auto item = QInputDialog::getItem(
  2429. this, tr("Select NCA Install Type..."),
  2430. tr("Please select the type of title you would like to install this NCA as:\n(In "
  2431. "most instances, the default 'Game' is fine.)"),
  2432. tt_options, 5, false, &ok);
  2433. auto index = tt_options.indexOf(item);
  2434. if (!ok || index == -1) {
  2435. QMessageBox::warning(this, tr("Failed to Install"),
  2436. tr("The title type you selected for the NCA is invalid."));
  2437. return InstallResult::Failure;
  2438. }
  2439. // If index is equal to or past Game, add the jump in TitleType.
  2440. if (index >= 5) {
  2441. index += static_cast<size_t>(FileSys::TitleType::Application) -
  2442. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  2443. }
  2444. const bool is_application = index >= static_cast<s32>(FileSys::TitleType::Application);
  2445. const auto& fs_controller = system->GetFileSystemController();
  2446. auto* registered_cache = is_application ? fs_controller.GetUserNANDContents()
  2447. : fs_controller.GetSystemNANDContents();
  2448. const auto res = registered_cache->InstallEntry(*nca, static_cast<FileSys::TitleType>(index),
  2449. true, qt_raw_copy);
  2450. if (res == FileSys::InstallResult::Success) {
  2451. return InstallResult::Success;
  2452. } else if (res == FileSys::InstallResult::OverwriteExisting) {
  2453. return InstallResult::Overwrite;
  2454. } else {
  2455. return InstallResult::Failure;
  2456. }
  2457. }
  2458. void GMainWindow::OnMenuRecentFile() {
  2459. QAction* action = qobject_cast<QAction*>(sender());
  2460. assert(action);
  2461. const QString filename = action->data().toString();
  2462. if (QFileInfo::exists(filename)) {
  2463. BootGame(filename);
  2464. } else {
  2465. // Display an error message and remove the file from the list.
  2466. QMessageBox::information(this, tr("File not found"),
  2467. tr("File \"%1\" not found").arg(filename));
  2468. UISettings::values.recent_files.removeOne(filename);
  2469. UpdateRecentFiles();
  2470. }
  2471. }
  2472. void GMainWindow::OnStartGame() {
  2473. PreventOSSleep();
  2474. emu_thread->SetRunning(true);
  2475. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  2476. UpdateMenuState();
  2477. OnTasStateChanged();
  2478. discord_rpc->Update();
  2479. }
  2480. void GMainWindow::OnRestartGame() {
  2481. if (!system->IsPoweredOn()) {
  2482. return;
  2483. }
  2484. // Make a copy since BootGame edits game_path
  2485. BootGame(QString(current_game_path));
  2486. }
  2487. void GMainWindow::OnPauseGame() {
  2488. emu_thread->SetRunning(false);
  2489. UpdateMenuState();
  2490. AllowOSSleep();
  2491. }
  2492. void GMainWindow::OnPauseContinueGame() {
  2493. if (emulation_running) {
  2494. if (emu_thread->IsRunning()) {
  2495. OnPauseGame();
  2496. } else {
  2497. RequestGameResume();
  2498. OnStartGame();
  2499. }
  2500. }
  2501. }
  2502. void GMainWindow::OnStopGame() {
  2503. if (system->GetExitLock() && !ConfirmForceLockedExit()) {
  2504. return;
  2505. }
  2506. ShutdownGame();
  2507. Settings::RestoreGlobalState(system->IsPoweredOn());
  2508. system->HIDCore().ReloadInputDevices();
  2509. UpdateStatusButtons();
  2510. }
  2511. void GMainWindow::OnLoadComplete() {
  2512. loading_screen->OnLoadComplete();
  2513. }
  2514. void GMainWindow::OnExecuteProgram(std::size_t program_index) {
  2515. ShutdownGame();
  2516. BootGame(last_filename_booted, 0, program_index);
  2517. }
  2518. void GMainWindow::OnExit() {
  2519. OnStopGame();
  2520. }
  2521. void GMainWindow::OnSaveConfig() {
  2522. system->ApplySettings();
  2523. config->Save();
  2524. }
  2525. void GMainWindow::ErrorDisplayDisplayError(QString error_code, QString error_text) {
  2526. OverlayDialog dialog(render_window, *system, error_code, error_text, QString{}, tr("OK"),
  2527. Qt::AlignLeft | Qt::AlignVCenter);
  2528. dialog.exec();
  2529. emit ErrorDisplayFinished();
  2530. }
  2531. void GMainWindow::OnMenuReportCompatibility() {
  2532. #if defined(ARCHITECTURE_x86_64) && !defined(__APPLE__)
  2533. const auto& caps = Common::GetCPUCaps();
  2534. const bool has_fma = caps.fma || caps.fma4;
  2535. const auto processor_count = std::thread::hardware_concurrency();
  2536. const bool has_4threads = processor_count == 0 || processor_count >= 4;
  2537. const bool has_8gb_ram = Common::GetMemInfo().TotalPhysicalMemory >= 8_GiB;
  2538. const bool has_broken_vulkan = UISettings::values.has_broken_vulkan;
  2539. if (!has_fma || !has_4threads || !has_8gb_ram || has_broken_vulkan) {
  2540. QMessageBox::critical(this, tr("Hardware requirements not met"),
  2541. tr("Your system does not meet the recommended hardware requirements. "
  2542. "Compatibility reporting has been disabled."));
  2543. return;
  2544. }
  2545. if (!Settings::values.yuzu_token.GetValue().empty() &&
  2546. !Settings::values.yuzu_username.GetValue().empty()) {
  2547. CompatDB compatdb{system->TelemetrySession(), this};
  2548. compatdb.exec();
  2549. } else {
  2550. QMessageBox::critical(
  2551. this, tr("Missing yuzu Account"),
  2552. tr("In order to submit a game compatibility test case, you must link your yuzu "
  2553. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  2554. "&gt; "
  2555. "Web."));
  2556. }
  2557. #else
  2558. QMessageBox::critical(this, tr("Hardware requirements not met"),
  2559. tr("Your system does not meet the recommended hardware requirements. "
  2560. "Compatibility reporting has been disabled."));
  2561. #endif
  2562. }
  2563. void GMainWindow::OpenURL(const QUrl& url) {
  2564. const bool open = QDesktopServices::openUrl(url);
  2565. if (!open) {
  2566. QMessageBox::warning(this, tr("Error opening URL"),
  2567. tr("Unable to open the URL \"%1\".").arg(url.toString()));
  2568. }
  2569. }
  2570. void GMainWindow::OnOpenModsPage() {
  2571. OpenURL(QUrl(QStringLiteral("https://github.com/yuzu-emu/yuzu/wiki/Switch-Mods")));
  2572. }
  2573. void GMainWindow::OnOpenQuickstartGuide() {
  2574. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/help/quickstart/")));
  2575. }
  2576. void GMainWindow::OnOpenFAQ() {
  2577. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/wiki/faq/")));
  2578. }
  2579. void GMainWindow::ToggleFullscreen() {
  2580. if (!emulation_running) {
  2581. return;
  2582. }
  2583. if (ui->action_Fullscreen->isChecked()) {
  2584. ShowFullscreen();
  2585. } else {
  2586. HideFullscreen();
  2587. }
  2588. }
  2589. // We're going to return the screen that the given window has the most pixels on
  2590. static QScreen* GuessCurrentScreen(QWidget* window) {
  2591. const QList<QScreen*> screens = QGuiApplication::screens();
  2592. return *std::max_element(
  2593. screens.cbegin(), screens.cend(), [window](const QScreen* left, const QScreen* right) {
  2594. const QSize left_size = left->geometry().intersected(window->geometry()).size();
  2595. const QSize right_size = right->geometry().intersected(window->geometry()).size();
  2596. return (left_size.height() * left_size.width()) <
  2597. (right_size.height() * right_size.width());
  2598. });
  2599. }
  2600. bool GMainWindow::UsingExclusiveFullscreen() {
  2601. return Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive ||
  2602. QGuiApplication::platformName() == QStringLiteral("wayland") ||
  2603. QGuiApplication::platformName() == QStringLiteral("wayland-egl");
  2604. }
  2605. void GMainWindow::ShowFullscreen() {
  2606. const auto show_fullscreen = [this](QWidget* window) {
  2607. if (UsingExclusiveFullscreen()) {
  2608. window->showFullScreen();
  2609. return;
  2610. }
  2611. window->hide();
  2612. window->setWindowFlags(window->windowFlags() | Qt::FramelessWindowHint);
  2613. const auto screen_geometry = GuessCurrentScreen(window)->geometry();
  2614. window->setGeometry(screen_geometry.x(), screen_geometry.y(), screen_geometry.width(),
  2615. screen_geometry.height() + 1);
  2616. window->raise();
  2617. window->showNormal();
  2618. };
  2619. if (ui->action_Single_Window_Mode->isChecked()) {
  2620. UISettings::values.geometry = saveGeometry();
  2621. ui->menubar->hide();
  2622. statusBar()->hide();
  2623. show_fullscreen(this);
  2624. } else {
  2625. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2626. show_fullscreen(render_window);
  2627. }
  2628. }
  2629. void GMainWindow::HideFullscreen() {
  2630. if (ui->action_Single_Window_Mode->isChecked()) {
  2631. if (UsingExclusiveFullscreen()) {
  2632. showNormal();
  2633. restoreGeometry(UISettings::values.geometry);
  2634. } else {
  2635. hide();
  2636. setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2637. restoreGeometry(UISettings::values.geometry);
  2638. raise();
  2639. show();
  2640. }
  2641. statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
  2642. ui->menubar->show();
  2643. } else {
  2644. if (UsingExclusiveFullscreen()) {
  2645. render_window->showNormal();
  2646. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2647. } else {
  2648. render_window->hide();
  2649. render_window->setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2650. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2651. render_window->raise();
  2652. render_window->show();
  2653. }
  2654. }
  2655. }
  2656. void GMainWindow::ToggleWindowMode() {
  2657. if (ui->action_Single_Window_Mode->isChecked()) {
  2658. // Render in the main window...
  2659. render_window->BackupGeometry();
  2660. ui->horizontalLayout->addWidget(render_window);
  2661. render_window->setFocusPolicy(Qt::StrongFocus);
  2662. if (emulation_running) {
  2663. render_window->setVisible(true);
  2664. render_window->setFocus();
  2665. game_list->hide();
  2666. }
  2667. } else {
  2668. // Render in a separate window...
  2669. ui->horizontalLayout->removeWidget(render_window);
  2670. render_window->setParent(nullptr);
  2671. render_window->setFocusPolicy(Qt::NoFocus);
  2672. if (emulation_running) {
  2673. render_window->setVisible(true);
  2674. render_window->RestoreGeometry();
  2675. game_list->show();
  2676. }
  2677. }
  2678. }
  2679. void GMainWindow::ResetWindowSize(u32 width, u32 height) {
  2680. const auto aspect_ratio = Layout::EmulationAspectRatio(
  2681. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  2682. static_cast<float>(height) / width);
  2683. if (!ui->action_Single_Window_Mode->isChecked()) {
  2684. render_window->resize(height / aspect_ratio, height);
  2685. } else {
  2686. const bool show_status_bar = ui->action_Show_Status_Bar->isChecked();
  2687. const auto status_bar_height = show_status_bar ? statusBar()->height() : 0;
  2688. resize(height / aspect_ratio, height + menuBar()->height() + status_bar_height);
  2689. }
  2690. }
  2691. void GMainWindow::ResetWindowSize720() {
  2692. ResetWindowSize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height);
  2693. }
  2694. void GMainWindow::ResetWindowSize900() {
  2695. ResetWindowSize(1600U, 900U);
  2696. }
  2697. void GMainWindow::ResetWindowSize1080() {
  2698. ResetWindowSize(Layout::ScreenDocked::Width, Layout::ScreenDocked::Height);
  2699. }
  2700. void GMainWindow::OnConfigure() {
  2701. const auto old_theme = UISettings::values.theme;
  2702. const bool old_discord_presence = UISettings::values.enable_discord_presence.GetValue();
  2703. Settings::SetConfiguringGlobal(true);
  2704. ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get(), *system,
  2705. !multiplayer_state->IsHostingPublicRoom());
  2706. connect(&configure_dialog, &ConfigureDialog::LanguageChanged, this,
  2707. &GMainWindow::OnLanguageChanged);
  2708. const auto result = configure_dialog.exec();
  2709. if (result != QDialog::Accepted && !UISettings::values.configuration_applied &&
  2710. !UISettings::values.reset_to_defaults) {
  2711. // Runs if the user hit Cancel or closed the window, and did not ever press the Apply button
  2712. // or `Reset to Defaults` button
  2713. return;
  2714. } else if (result == QDialog::Accepted) {
  2715. // Only apply new changes if user hit Okay
  2716. // This is here to avoid applying changes if the user hit Apply, made some changes, then hit
  2717. // Cancel
  2718. configure_dialog.ApplyConfiguration();
  2719. } else if (UISettings::values.reset_to_defaults) {
  2720. LOG_INFO(Frontend, "Resetting all settings to defaults");
  2721. if (!Common::FS::RemoveFile(config->GetConfigFilePath())) {
  2722. LOG_WARNING(Frontend, "Failed to remove configuration file");
  2723. }
  2724. if (!Common::FS::RemoveDirContentsRecursively(
  2725. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom")) {
  2726. LOG_WARNING(Frontend, "Failed to remove custom configuration files");
  2727. }
  2728. if (!Common::FS::RemoveDirRecursively(
  2729. Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) / "game_list")) {
  2730. LOG_WARNING(Frontend, "Failed to remove game metadata cache files");
  2731. }
  2732. // Explicitly save the game directories, since reinitializing config does not explicitly do
  2733. // so.
  2734. QVector<UISettings::GameDir> old_game_dirs = std::move(UISettings::values.game_dirs);
  2735. QVector<u64> old_favorited_ids = std::move(UISettings::values.favorited_ids);
  2736. Settings::values.disabled_addons.clear();
  2737. config = std::make_unique<Config>();
  2738. UISettings::values.reset_to_defaults = false;
  2739. UISettings::values.game_dirs = std::move(old_game_dirs);
  2740. UISettings::values.favorited_ids = std::move(old_favorited_ids);
  2741. InitializeRecentFileMenuActions();
  2742. SetDefaultUIGeometry();
  2743. RestoreUIState();
  2744. ShowTelemetryCallout();
  2745. }
  2746. InitializeHotkeys();
  2747. if (UISettings::values.theme != old_theme) {
  2748. UpdateUITheme();
  2749. }
  2750. if (UISettings::values.enable_discord_presence.GetValue() != old_discord_presence) {
  2751. SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue());
  2752. }
  2753. if (!multiplayer_state->IsHostingPublicRoom()) {
  2754. multiplayer_state->UpdateCredentials();
  2755. }
  2756. emit UpdateThemedIcons();
  2757. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2758. if (reload) {
  2759. game_list->PopulateAsync(UISettings::values.game_dirs);
  2760. }
  2761. UISettings::values.configuration_applied = false;
  2762. config->Save();
  2763. if ((UISettings::values.hide_mouse || Settings::values.mouse_panning) && emulation_running) {
  2764. render_window->installEventFilter(render_window);
  2765. render_window->setAttribute(Qt::WA_Hover, true);
  2766. } else {
  2767. render_window->removeEventFilter(render_window);
  2768. render_window->setAttribute(Qt::WA_Hover, false);
  2769. }
  2770. if (UISettings::values.hide_mouse) {
  2771. mouse_hide_timer.start();
  2772. }
  2773. // Restart camera config
  2774. if (emulation_running) {
  2775. render_window->FinalizeCamera();
  2776. render_window->InitializeCamera();
  2777. }
  2778. if (!UISettings::values.has_broken_vulkan) {
  2779. renderer_status_button->setEnabled(!emulation_running);
  2780. }
  2781. UpdateStatusButtons();
  2782. controller_dialog->refreshConfiguration();
  2783. system->ApplySettings();
  2784. }
  2785. void GMainWindow::OnConfigureTas() {
  2786. ConfigureTasDialog dialog(this);
  2787. const auto result = dialog.exec();
  2788. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  2789. Settings::RestoreGlobalState(system->IsPoweredOn());
  2790. return;
  2791. } else if (result == QDialog::Accepted) {
  2792. dialog.ApplyConfiguration();
  2793. }
  2794. }
  2795. void GMainWindow::OnTasStartStop() {
  2796. if (!emulation_running) {
  2797. return;
  2798. }
  2799. // Disable system buttons to prevent TAS from executing a hotkey
  2800. auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  2801. controller->ResetSystemButtons();
  2802. input_subsystem->GetTas()->StartStop();
  2803. OnTasStateChanged();
  2804. }
  2805. void GMainWindow::OnTasRecord() {
  2806. if (!emulation_running) {
  2807. return;
  2808. }
  2809. if (is_tas_recording_dialog_active) {
  2810. return;
  2811. }
  2812. // Disable system buttons to prevent TAS from recording a hotkey
  2813. auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  2814. controller->ResetSystemButtons();
  2815. const bool is_recording = input_subsystem->GetTas()->Record();
  2816. if (!is_recording) {
  2817. is_tas_recording_dialog_active = true;
  2818. ControllerNavigation* controller_navigation =
  2819. new ControllerNavigation(system->HIDCore(), this);
  2820. // Use QMessageBox instead of question so we can link controller navigation
  2821. QMessageBox* box_dialog = new QMessageBox();
  2822. box_dialog->setWindowTitle(tr("TAS Recording"));
  2823. box_dialog->setText(tr("Overwrite file of player 1?"));
  2824. box_dialog->setStandardButtons(QMessageBox::Yes | QMessageBox::No);
  2825. box_dialog->setDefaultButton(QMessageBox::Yes);
  2826. connect(controller_navigation, &ControllerNavigation::TriggerKeyboardEvent,
  2827. [box_dialog](Qt::Key key) {
  2828. QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier);
  2829. QCoreApplication::postEvent(box_dialog, event);
  2830. });
  2831. int res = box_dialog->exec();
  2832. controller_navigation->UnloadController();
  2833. input_subsystem->GetTas()->SaveRecording(res == QMessageBox::Yes);
  2834. is_tas_recording_dialog_active = false;
  2835. }
  2836. OnTasStateChanged();
  2837. }
  2838. void GMainWindow::OnTasReset() {
  2839. input_subsystem->GetTas()->Reset();
  2840. }
  2841. void GMainWindow::OnToggleDockedMode() {
  2842. const bool is_docked = Settings::values.use_docked_mode.GetValue();
  2843. auto* player_1 = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1);
  2844. auto* handheld = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld);
  2845. if (!is_docked && handheld->IsConnected()) {
  2846. QMessageBox::warning(this, tr("Invalid config detected"),
  2847. tr("Handheld controller can't be used on docked mode. Pro "
  2848. "controller will be selected."));
  2849. handheld->Disconnect();
  2850. player_1->SetNpadStyleIndex(Core::HID::NpadStyleIndex::ProController);
  2851. player_1->Connect();
  2852. controller_dialog->refreshConfiguration();
  2853. }
  2854. Settings::values.use_docked_mode.SetValue(!is_docked);
  2855. UpdateDockedButton();
  2856. OnDockedModeChanged(is_docked, !is_docked, *system);
  2857. }
  2858. void GMainWindow::OnToggleGpuAccuracy() {
  2859. switch (Settings::values.gpu_accuracy.GetValue()) {
  2860. case Settings::GPUAccuracy::High: {
  2861. Settings::values.gpu_accuracy.SetValue(Settings::GPUAccuracy::Normal);
  2862. break;
  2863. }
  2864. case Settings::GPUAccuracy::Normal:
  2865. case Settings::GPUAccuracy::Extreme:
  2866. default: {
  2867. Settings::values.gpu_accuracy.SetValue(Settings::GPUAccuracy::High);
  2868. break;
  2869. }
  2870. }
  2871. system->ApplySettings();
  2872. UpdateGPUAccuracyButton();
  2873. }
  2874. void GMainWindow::OnToggleAdaptingFilter() {
  2875. auto filter = Settings::values.scaling_filter.GetValue();
  2876. if (filter == Settings::ScalingFilter::LastFilter) {
  2877. filter = Settings::ScalingFilter::NearestNeighbor;
  2878. } else {
  2879. filter = static_cast<Settings::ScalingFilter>(static_cast<u32>(filter) + 1);
  2880. }
  2881. if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL &&
  2882. filter == Settings::ScalingFilter::Fsr) {
  2883. filter = Settings::ScalingFilter::NearestNeighbor;
  2884. }
  2885. Settings::values.scaling_filter.SetValue(filter);
  2886. filter_status_button->setChecked(true);
  2887. UpdateFilterText();
  2888. }
  2889. void GMainWindow::OnToggleGraphicsAPI() {
  2890. auto api = Settings::values.renderer_backend.GetValue();
  2891. if (api == Settings::RendererBackend::OpenGL) {
  2892. api = Settings::RendererBackend::Vulkan;
  2893. } else {
  2894. api = Settings::RendererBackend::OpenGL;
  2895. }
  2896. Settings::values.renderer_backend.SetValue(api);
  2897. renderer_status_button->setChecked(api == Settings::RendererBackend::Vulkan);
  2898. UpdateAPIText();
  2899. }
  2900. void GMainWindow::OnConfigurePerGame() {
  2901. const u64 title_id = system->GetCurrentProcessProgramID();
  2902. OpenPerGameConfiguration(title_id, current_game_path.toStdString());
  2903. }
  2904. void GMainWindow::OpenPerGameConfiguration(u64 title_id, const std::string& file_name) {
  2905. const auto v_file = Core::GetGameFileFromPath(vfs, file_name);
  2906. Settings::SetConfiguringGlobal(false);
  2907. ConfigurePerGame dialog(this, title_id, file_name, *system);
  2908. dialog.LoadFromFile(v_file);
  2909. const auto result = dialog.exec();
  2910. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  2911. Settings::RestoreGlobalState(system->IsPoweredOn());
  2912. return;
  2913. } else if (result == QDialog::Accepted) {
  2914. dialog.ApplyConfiguration();
  2915. }
  2916. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2917. if (reload) {
  2918. game_list->PopulateAsync(UISettings::values.game_dirs);
  2919. }
  2920. // Do not cause the global config to write local settings into the config file
  2921. const bool is_powered_on = system->IsPoweredOn();
  2922. Settings::RestoreGlobalState(is_powered_on);
  2923. system->HIDCore().ReloadInputDevices();
  2924. UISettings::values.configuration_applied = false;
  2925. if (!is_powered_on) {
  2926. config->Save();
  2927. }
  2928. }
  2929. bool GMainWindow::CreateShortcut(const std::string& shortcut_path, const std::string& title,
  2930. const std::string& comment, const std::string& icon_path,
  2931. const std::string& command, const std::string& arguments,
  2932. const std::string& categories, const std::string& keywords) {
  2933. #if defined(__linux__) || defined(__FreeBSD__)
  2934. // This desktop file template was writting referencing
  2935. // https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.0.html
  2936. std::string shortcut_contents{};
  2937. shortcut_contents.append("[Desktop Entry]\n");
  2938. shortcut_contents.append("Type=Application\n");
  2939. shortcut_contents.append("Version=1.0\n");
  2940. shortcut_contents.append(fmt::format("Name={:s}\n", title));
  2941. shortcut_contents.append(fmt::format("Comment={:s}\n", comment));
  2942. shortcut_contents.append(fmt::format("Icon={:s}\n", icon_path));
  2943. shortcut_contents.append(fmt::format("TryExec={:s}\n", command));
  2944. shortcut_contents.append(fmt::format("Exec={:s} {:s}\n", command, arguments));
  2945. shortcut_contents.append(fmt::format("Categories={:s}\n", categories));
  2946. shortcut_contents.append(fmt::format("Keywords={:s}\n", keywords));
  2947. std::ofstream shortcut_stream(shortcut_path);
  2948. if (!shortcut_stream.is_open()) {
  2949. LOG_WARNING(Common, "Failed to create file {:s}", shortcut_path);
  2950. return false;
  2951. }
  2952. shortcut_stream << shortcut_contents;
  2953. shortcut_stream.close();
  2954. return true;
  2955. #endif
  2956. return false;
  2957. }
  2958. void GMainWindow::OnLoadAmiibo() {
  2959. if (emu_thread == nullptr || !emu_thread->IsRunning()) {
  2960. return;
  2961. }
  2962. if (is_amiibo_file_select_active) {
  2963. return;
  2964. }
  2965. auto* virtual_amiibo = input_subsystem->GetVirtualAmiibo();
  2966. // Remove amiibo if one is connected
  2967. if (virtual_amiibo->GetCurrentState() == InputCommon::VirtualAmiibo::State::AmiiboIsOpen) {
  2968. virtual_amiibo->CloseAmiibo();
  2969. QMessageBox::warning(this, tr("Amiibo"), tr("The current amiibo has been removed"));
  2970. return;
  2971. }
  2972. if (virtual_amiibo->GetCurrentState() != InputCommon::VirtualAmiibo::State::WaitingForAmiibo) {
  2973. QMessageBox::warning(this, tr("Error"), tr("The current game is not looking for amiibos"));
  2974. return;
  2975. }
  2976. is_amiibo_file_select_active = true;
  2977. const QString extensions{QStringLiteral("*.bin")};
  2978. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  2979. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter);
  2980. is_amiibo_file_select_active = false;
  2981. if (filename.isEmpty()) {
  2982. return;
  2983. }
  2984. LoadAmiibo(filename);
  2985. }
  2986. void GMainWindow::LoadAmiibo(const QString& filename) {
  2987. auto* virtual_amiibo = input_subsystem->GetVirtualAmiibo();
  2988. const QString title = tr("Error loading Amiibo data");
  2989. // Remove amiibo if one is connected
  2990. if (virtual_amiibo->GetCurrentState() == InputCommon::VirtualAmiibo::State::AmiiboIsOpen) {
  2991. virtual_amiibo->CloseAmiibo();
  2992. QMessageBox::warning(this, tr("Amiibo"), tr("The current amiibo has been removed"));
  2993. return;
  2994. }
  2995. switch (virtual_amiibo->LoadAmiibo(filename.toStdString())) {
  2996. case InputCommon::VirtualAmiibo::Info::NotAnAmiibo:
  2997. QMessageBox::warning(this, title, tr("The selected file is not a valid amiibo"));
  2998. break;
  2999. case InputCommon::VirtualAmiibo::Info::UnableToLoad:
  3000. QMessageBox::warning(this, title, tr("The selected file is already on use"));
  3001. break;
  3002. case InputCommon::VirtualAmiibo::Info::WrongDeviceState:
  3003. QMessageBox::warning(this, title, tr("The current game is not looking for amiibos"));
  3004. break;
  3005. case InputCommon::VirtualAmiibo::Info::Unknown:
  3006. QMessageBox::warning(this, title, tr("An unknown error occurred"));
  3007. break;
  3008. default:
  3009. break;
  3010. }
  3011. }
  3012. void GMainWindow::OnOpenYuzuFolder() {
  3013. QDesktopServices::openUrl(QUrl::fromLocalFile(
  3014. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::YuzuDir))));
  3015. }
  3016. void GMainWindow::OnAbout() {
  3017. AboutDialog aboutDialog(this);
  3018. aboutDialog.exec();
  3019. }
  3020. void GMainWindow::OnToggleFilterBar() {
  3021. game_list->SetFilterVisible(ui->action_Show_Filter_Bar->isChecked());
  3022. if (ui->action_Show_Filter_Bar->isChecked()) {
  3023. game_list->SetFilterFocus();
  3024. } else {
  3025. game_list->ClearFilter();
  3026. }
  3027. }
  3028. void GMainWindow::OnToggleStatusBar() {
  3029. statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
  3030. }
  3031. void GMainWindow::OnCaptureScreenshot() {
  3032. if (emu_thread == nullptr || !emu_thread->IsRunning()) {
  3033. return;
  3034. }
  3035. const u64 title_id = system->GetCurrentProcessProgramID();
  3036. const auto screenshot_path =
  3037. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::ScreenshotsDir));
  3038. const auto date =
  3039. QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd_hh-mm-ss-zzz"));
  3040. QString filename = QStringLiteral("%1/%2_%3.png")
  3041. .arg(screenshot_path)
  3042. .arg(title_id, 16, 16, QLatin1Char{'0'})
  3043. .arg(date);
  3044. if (!Common::FS::CreateDir(screenshot_path.toStdString())) {
  3045. return;
  3046. }
  3047. #ifdef _WIN32
  3048. if (UISettings::values.enable_screenshot_save_as) {
  3049. OnPauseGame();
  3050. filename = QFileDialog::getSaveFileName(this, tr("Capture Screenshot"), filename,
  3051. tr("PNG Image (*.png)"));
  3052. OnStartGame();
  3053. if (filename.isEmpty()) {
  3054. return;
  3055. }
  3056. }
  3057. #endif
  3058. render_window->CaptureScreenshot(filename);
  3059. }
  3060. // TODO: Written 2020-10-01: Remove per-game config migration code when it is irrelevant
  3061. void GMainWindow::MigrateConfigFiles() {
  3062. const auto config_dir_fs_path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir);
  3063. const QDir config_dir =
  3064. QDir(QString::fromStdString(Common::FS::PathToUTF8String(config_dir_fs_path)));
  3065. const QStringList config_dir_list = config_dir.entryList(QStringList(QStringLiteral("*.ini")));
  3066. if (!Common::FS::CreateDirs(config_dir_fs_path / "custom")) {
  3067. LOG_ERROR(Frontend, "Failed to create new config file directory");
  3068. }
  3069. for (auto it = config_dir_list.constBegin(); it != config_dir_list.constEnd(); ++it) {
  3070. const auto filename = it->toStdString();
  3071. if (filename.find_first_not_of("0123456789abcdefACBDEF", 0) < 16) {
  3072. continue;
  3073. }
  3074. const auto origin = config_dir_fs_path / filename;
  3075. const auto destination = config_dir_fs_path / "custom" / filename;
  3076. LOG_INFO(Frontend, "Migrating config file from {} to {}", origin.string(),
  3077. destination.string());
  3078. if (!Common::FS::RenameFile(origin, destination)) {
  3079. // Delete the old config file if one already exists in the new location.
  3080. Common::FS::RemoveFile(origin);
  3081. }
  3082. }
  3083. }
  3084. void GMainWindow::UpdateWindowTitle(std::string_view title_name, std::string_view title_version,
  3085. std::string_view gpu_vendor) {
  3086. const auto branch_name = std::string(Common::g_scm_branch);
  3087. const auto description = std::string(Common::g_scm_desc);
  3088. const auto build_id = std::string(Common::g_build_id);
  3089. const auto yuzu_title = fmt::format("yuzu | {}-{}", branch_name, description);
  3090. const auto override_title =
  3091. fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id);
  3092. const auto window_title = override_title.empty() ? yuzu_title : override_title;
  3093. if (title_name.empty()) {
  3094. setWindowTitle(QString::fromStdString(window_title));
  3095. } else {
  3096. const auto run_title = [window_title, title_name, title_version, gpu_vendor]() {
  3097. if (title_version.empty()) {
  3098. return fmt::format("{} | {} | {}", window_title, title_name, gpu_vendor);
  3099. }
  3100. return fmt::format("{} | {} | {} | {}", window_title, title_name, title_version,
  3101. gpu_vendor);
  3102. }();
  3103. setWindowTitle(QString::fromStdString(run_title));
  3104. }
  3105. }
  3106. QString GMainWindow::GetTasStateDescription() const {
  3107. auto [tas_status, current_tas_frame, total_tas_frames] = input_subsystem->GetTas()->GetStatus();
  3108. switch (tas_status) {
  3109. case InputCommon::TasInput::TasState::Running:
  3110. return tr("TAS state: Running %1/%2").arg(current_tas_frame).arg(total_tas_frames);
  3111. case InputCommon::TasInput::TasState::Recording:
  3112. return tr("TAS state: Recording %1").arg(total_tas_frames);
  3113. case InputCommon::TasInput::TasState::Stopped:
  3114. return tr("TAS state: Idle %1/%2").arg(current_tas_frame).arg(total_tas_frames);
  3115. default:
  3116. return tr("TAS State: Invalid");
  3117. }
  3118. }
  3119. void GMainWindow::OnTasStateChanged() {
  3120. bool is_running = false;
  3121. bool is_recording = false;
  3122. if (emulation_running) {
  3123. const InputCommon::TasInput::TasState tas_status =
  3124. std::get<0>(input_subsystem->GetTas()->GetStatus());
  3125. is_running = tas_status == InputCommon::TasInput::TasState::Running;
  3126. is_recording = tas_status == InputCommon::TasInput::TasState::Recording;
  3127. }
  3128. ui->action_TAS_Start->setText(is_running ? tr("&Stop Running") : tr("&Start"));
  3129. ui->action_TAS_Record->setText(is_recording ? tr("Stop R&ecording") : tr("R&ecord"));
  3130. ui->action_TAS_Start->setEnabled(emulation_running);
  3131. ui->action_TAS_Record->setEnabled(emulation_running);
  3132. ui->action_TAS_Reset->setEnabled(emulation_running);
  3133. }
  3134. void GMainWindow::UpdateStatusBar() {
  3135. if (emu_thread == nullptr || !system->IsPoweredOn()) {
  3136. status_bar_update_timer.stop();
  3137. return;
  3138. }
  3139. if (Settings::values.tas_enable) {
  3140. tas_label->setText(GetTasStateDescription());
  3141. } else {
  3142. tas_label->clear();
  3143. }
  3144. auto results = system->GetAndResetPerfStats();
  3145. auto& shader_notify = system->GPU().ShaderNotify();
  3146. const int shaders_building = shader_notify.ShadersBuilding();
  3147. if (shaders_building > 0) {
  3148. shader_building_label->setText(tr("Building: %n shader(s)", "", shaders_building));
  3149. shader_building_label->setVisible(true);
  3150. } else {
  3151. shader_building_label->setVisible(false);
  3152. }
  3153. const auto res_info = Settings::values.resolution_info;
  3154. const auto res_scale = res_info.up_factor;
  3155. res_scale_label->setText(
  3156. tr("Scale: %1x", "%1 is the resolution scaling factor").arg(res_scale));
  3157. if (Settings::values.use_speed_limit.GetValue()) {
  3158. emu_speed_label->setText(tr("Speed: %1% / %2%")
  3159. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  3160. .arg(Settings::values.speed_limit.GetValue()));
  3161. } else {
  3162. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  3163. }
  3164. if (!Settings::values.use_speed_limit) {
  3165. game_fps_label->setText(
  3166. tr("Game: %1 FPS (Unlocked)").arg(std::round(results.average_game_fps), 0, 'f', 0));
  3167. } else {
  3168. game_fps_label->setText(
  3169. tr("Game: %1 FPS").arg(std::round(results.average_game_fps), 0, 'f', 0));
  3170. }
  3171. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  3172. res_scale_label->setVisible(true);
  3173. emu_speed_label->setVisible(!Settings::values.use_multi_core.GetValue());
  3174. game_fps_label->setVisible(true);
  3175. emu_frametime_label->setVisible(true);
  3176. }
  3177. void GMainWindow::UpdateGPUAccuracyButton() {
  3178. switch (Settings::values.gpu_accuracy.GetValue()) {
  3179. case Settings::GPUAccuracy::Normal: {
  3180. gpu_accuracy_button->setText(tr("GPU NORMAL"));
  3181. gpu_accuracy_button->setChecked(false);
  3182. break;
  3183. }
  3184. case Settings::GPUAccuracy::High: {
  3185. gpu_accuracy_button->setText(tr("GPU HIGH"));
  3186. gpu_accuracy_button->setChecked(true);
  3187. break;
  3188. }
  3189. case Settings::GPUAccuracy::Extreme: {
  3190. gpu_accuracy_button->setText(tr("GPU EXTREME"));
  3191. gpu_accuracy_button->setChecked(true);
  3192. break;
  3193. }
  3194. default: {
  3195. gpu_accuracy_button->setText(tr("GPU ERROR"));
  3196. gpu_accuracy_button->setChecked(true);
  3197. break;
  3198. }
  3199. }
  3200. }
  3201. void GMainWindow::UpdateDockedButton() {
  3202. const bool is_docked = Settings::values.use_docked_mode.GetValue();
  3203. dock_status_button->setChecked(is_docked);
  3204. dock_status_button->setText(is_docked ? tr("DOCKED") : tr("HANDHELD"));
  3205. }
  3206. void GMainWindow::UpdateAPIText() {
  3207. const auto api = Settings::values.renderer_backend.GetValue();
  3208. switch (api) {
  3209. case Settings::RendererBackend::OpenGL:
  3210. renderer_status_button->setText(tr("OPENGL"));
  3211. break;
  3212. case Settings::RendererBackend::Vulkan:
  3213. renderer_status_button->setText(tr("VULKAN"));
  3214. break;
  3215. case Settings::RendererBackend::Null:
  3216. renderer_status_button->setText(tr("NULL"));
  3217. break;
  3218. }
  3219. }
  3220. void GMainWindow::UpdateFilterText() {
  3221. const auto filter = Settings::values.scaling_filter.GetValue();
  3222. switch (filter) {
  3223. case Settings::ScalingFilter::NearestNeighbor:
  3224. filter_status_button->setText(tr("NEAREST"));
  3225. break;
  3226. case Settings::ScalingFilter::Bilinear:
  3227. filter_status_button->setText(tr("BILINEAR"));
  3228. break;
  3229. case Settings::ScalingFilter::Bicubic:
  3230. filter_status_button->setText(tr("BICUBIC"));
  3231. break;
  3232. case Settings::ScalingFilter::Gaussian:
  3233. filter_status_button->setText(tr("GAUSSIAN"));
  3234. break;
  3235. case Settings::ScalingFilter::ScaleForce:
  3236. filter_status_button->setText(tr("SCALEFORCE"));
  3237. break;
  3238. case Settings::ScalingFilter::Fsr:
  3239. filter_status_button->setText(tr("FSR"));
  3240. break;
  3241. default:
  3242. filter_status_button->setText(tr("BILINEAR"));
  3243. break;
  3244. }
  3245. }
  3246. void GMainWindow::UpdateAAText() {
  3247. const auto aa_mode = Settings::values.anti_aliasing.GetValue();
  3248. switch (aa_mode) {
  3249. case Settings::AntiAliasing::None:
  3250. aa_status_button->setText(tr("NO AA"));
  3251. break;
  3252. case Settings::AntiAliasing::Fxaa:
  3253. aa_status_button->setText(tr("FXAA"));
  3254. break;
  3255. case Settings::AntiAliasing::Smaa:
  3256. aa_status_button->setText(tr("SMAA"));
  3257. break;
  3258. default:
  3259. aa_status_button->setText(tr("NO AA"));
  3260. break;
  3261. }
  3262. }
  3263. void GMainWindow::UpdateStatusButtons() {
  3264. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  3265. Settings::RendererBackend::Vulkan);
  3266. UpdateAPIText();
  3267. UpdateGPUAccuracyButton();
  3268. UpdateDockedButton();
  3269. UpdateFilterText();
  3270. UpdateAAText();
  3271. }
  3272. void GMainWindow::UpdateUISettings() {
  3273. if (!ui->action_Fullscreen->isChecked()) {
  3274. UISettings::values.geometry = saveGeometry();
  3275. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  3276. }
  3277. UISettings::values.state = saveState();
  3278. #if MICROPROFILE_ENABLED
  3279. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  3280. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  3281. #endif
  3282. UISettings::values.single_window_mode = ui->action_Single_Window_Mode->isChecked();
  3283. UISettings::values.fullscreen = ui->action_Fullscreen->isChecked();
  3284. UISettings::values.display_titlebar = ui->action_Display_Dock_Widget_Headers->isChecked();
  3285. UISettings::values.show_filter_bar = ui->action_Show_Filter_Bar->isChecked();
  3286. UISettings::values.show_status_bar = ui->action_Show_Status_Bar->isChecked();
  3287. UISettings::values.first_start = false;
  3288. }
  3289. void GMainWindow::UpdateInputDrivers() {
  3290. if (!input_subsystem) {
  3291. return;
  3292. }
  3293. input_subsystem->PumpEvents();
  3294. }
  3295. void GMainWindow::HideMouseCursor() {
  3296. if (emu_thread == nullptr && UISettings::values.hide_mouse) {
  3297. mouse_hide_timer.stop();
  3298. ShowMouseCursor();
  3299. return;
  3300. }
  3301. render_window->setCursor(QCursor(Qt::BlankCursor));
  3302. }
  3303. void GMainWindow::ShowMouseCursor() {
  3304. render_window->unsetCursor();
  3305. if (emu_thread != nullptr && UISettings::values.hide_mouse) {
  3306. mouse_hide_timer.start();
  3307. }
  3308. }
  3309. void GMainWindow::CenterMouseCursor() {
  3310. if (emu_thread == nullptr || !Settings::values.mouse_panning) {
  3311. mouse_center_timer.stop();
  3312. return;
  3313. }
  3314. if (!this->isActiveWindow()) {
  3315. mouse_center_timer.stop();
  3316. return;
  3317. }
  3318. const int center_x = render_window->width() / 2;
  3319. const int center_y = render_window->height() / 2;
  3320. QCursor::setPos(mapToGlobal(QPoint{center_x, center_y}));
  3321. }
  3322. void GMainWindow::OnMouseActivity() {
  3323. if (!Settings::values.mouse_panning) {
  3324. ShowMouseCursor();
  3325. }
  3326. mouse_center_timer.stop();
  3327. }
  3328. void GMainWindow::OnCoreError(Core::SystemResultStatus result, std::string details) {
  3329. QMessageBox::StandardButton answer;
  3330. QString status_message;
  3331. const QString common_message =
  3332. tr("The game you are trying to load requires additional files from your Switch to be "
  3333. "dumped "
  3334. "before playing.<br/><br/>For more information on dumping these files, please see the "
  3335. "following wiki page: <a "
  3336. "href='https://yuzu-emu.org/wiki/"
  3337. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  3338. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  3339. "quit "
  3340. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  3341. "data, or other bugs.");
  3342. switch (result) {
  3343. case Core::SystemResultStatus::ErrorSystemFiles: {
  3344. QString message;
  3345. if (details.empty()) {
  3346. message =
  3347. tr("yuzu was unable to locate a Switch system archive. %1").arg(common_message);
  3348. } else {
  3349. message = tr("yuzu was unable to locate a Switch system archive: %1. %2")
  3350. .arg(QString::fromStdString(details), common_message);
  3351. }
  3352. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  3353. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3354. status_message = tr("System Archive Missing");
  3355. break;
  3356. }
  3357. case Core::SystemResultStatus::ErrorSharedFont: {
  3358. const QString message =
  3359. tr("yuzu was unable to locate the Switch shared fonts. %1").arg(common_message);
  3360. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  3361. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3362. status_message = tr("Shared Font Missing");
  3363. break;
  3364. }
  3365. default:
  3366. answer = QMessageBox::question(
  3367. this, tr("Fatal Error"),
  3368. tr("yuzu has encountered a fatal error, please see the log for more details. "
  3369. "For more information on accessing the log, please see the following page: "
  3370. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  3371. "to "
  3372. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  3373. "list? "
  3374. "Continuing emulation may result in crashes, corrupted save data, or other "
  3375. "bugs."),
  3376. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3377. status_message = tr("Fatal Error encountered");
  3378. break;
  3379. }
  3380. if (answer == QMessageBox::Yes) {
  3381. if (emu_thread) {
  3382. ShutdownGame();
  3383. Settings::RestoreGlobalState(system->IsPoweredOn());
  3384. system->HIDCore().ReloadInputDevices();
  3385. UpdateStatusButtons();
  3386. }
  3387. } else {
  3388. // Only show the message if the game is still running.
  3389. if (emu_thread) {
  3390. emu_thread->SetRunning(true);
  3391. message_label->setText(status_message);
  3392. }
  3393. }
  3394. }
  3395. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  3396. if (behavior == ReinitializeKeyBehavior::Warning) {
  3397. const auto res = QMessageBox::information(
  3398. this, tr("Confirm Key Rederivation"),
  3399. tr("You are about to force rederive all of your keys. \nIf you do not know what "
  3400. "this "
  3401. "means or what you are doing, \nthis is a potentially destructive action. "
  3402. "\nPlease "
  3403. "make sure this is what you want \nand optionally make backups.\n\nThis will "
  3404. "delete "
  3405. "your autogenerated key files and re-run the key derivation module."),
  3406. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  3407. if (res == QMessageBox::Cancel)
  3408. return;
  3409. const auto keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
  3410. Common::FS::RemoveFile(keys_dir / "prod.keys_autogenerated");
  3411. Common::FS::RemoveFile(keys_dir / "console.keys_autogenerated");
  3412. Common::FS::RemoveFile(keys_dir / "title.keys_autogenerated");
  3413. }
  3414. Core::Crypto::KeyManager& keys = Core::Crypto::KeyManager::Instance();
  3415. if (keys.BaseDeriveNecessary()) {
  3416. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory("", FileSys::Mode::Read)};
  3417. const auto function = [this, &keys, &pdm] {
  3418. keys.PopulateFromPartitionData(pdm);
  3419. system->GetFileSystemController().CreateFactories(*vfs);
  3420. keys.DeriveETicket(pdm, system->GetContentProvider());
  3421. };
  3422. QString errors;
  3423. if (!pdm.HasFuses()) {
  3424. errors += tr("Missing fuses");
  3425. }
  3426. if (!pdm.HasBoot0()) {
  3427. errors += tr(" - Missing BOOT0");
  3428. }
  3429. if (!pdm.HasPackage2()) {
  3430. errors += tr(" - Missing BCPKG2-1-Normal-Main");
  3431. }
  3432. if (!pdm.HasProdInfo()) {
  3433. errors += tr(" - Missing PRODINFO");
  3434. }
  3435. if (!errors.isEmpty()) {
  3436. QMessageBox::warning(
  3437. this, tr("Derivation Components Missing"),
  3438. tr("Encryption keys are missing. "
  3439. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  3440. "quickstart guide</a> to get all your keys, firmware and "
  3441. "games.<br><br><small>(%1)</small>")
  3442. .arg(errors));
  3443. }
  3444. QProgressDialog prog(this);
  3445. prog.setRange(0, 0);
  3446. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  3447. "system's performance."));
  3448. prog.setWindowTitle(tr("Deriving Keys"));
  3449. prog.show();
  3450. auto future = QtConcurrent::run(function);
  3451. while (!future.isFinished()) {
  3452. QCoreApplication::processEvents();
  3453. }
  3454. prog.close();
  3455. }
  3456. system->GetFileSystemController().CreateFactories(*vfs);
  3457. if (behavior == ReinitializeKeyBehavior::Warning) {
  3458. game_list->PopulateAsync(UISettings::values.game_dirs);
  3459. }
  3460. }
  3461. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
  3462. u64 program_id) {
  3463. const auto dlc_entries =
  3464. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  3465. std::vector<FileSys::ContentProviderEntry> dlc_match;
  3466. dlc_match.reserve(dlc_entries.size());
  3467. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  3468. [&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
  3469. return FileSys::GetBaseTitleID(entry.title_id) == program_id &&
  3470. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  3471. });
  3472. std::vector<u64> romfs_tids;
  3473. romfs_tids.push_back(program_id);
  3474. for (const auto& entry : dlc_match) {
  3475. romfs_tids.push_back(entry.title_id);
  3476. }
  3477. if (romfs_tids.size() > 1) {
  3478. QStringList list{QStringLiteral("Base")};
  3479. for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
  3480. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  3481. }
  3482. bool ok;
  3483. const auto res = QInputDialog::getItem(
  3484. this, tr("Select RomFS Dump Target"),
  3485. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  3486. if (!ok) {
  3487. return {};
  3488. }
  3489. return romfs_tids[list.indexOf(res)];
  3490. }
  3491. return program_id;
  3492. }
  3493. bool GMainWindow::ConfirmClose() {
  3494. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  3495. return true;
  3496. }
  3497. const auto text = tr("Are you sure you want to close yuzu?");
  3498. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  3499. return answer != QMessageBox::No;
  3500. }
  3501. void GMainWindow::closeEvent(QCloseEvent* event) {
  3502. if (!ConfirmClose()) {
  3503. event->ignore();
  3504. return;
  3505. }
  3506. UpdateUISettings();
  3507. game_list->SaveInterfaceLayout();
  3508. hotkey_registry.SaveHotkeys();
  3509. // Unload controllers early
  3510. controller_dialog->UnloadController();
  3511. game_list->UnloadController();
  3512. // Shutdown session if the emu thread is active...
  3513. if (emu_thread != nullptr) {
  3514. ShutdownGame();
  3515. Settings::RestoreGlobalState(system->IsPoweredOn());
  3516. system->HIDCore().ReloadInputDevices();
  3517. UpdateStatusButtons();
  3518. }
  3519. render_window->close();
  3520. multiplayer_state->Close();
  3521. system->HIDCore().UnloadInputDevices();
  3522. system->GetRoomNetwork().Shutdown();
  3523. QWidget::closeEvent(event);
  3524. }
  3525. static bool IsSingleFileDropEvent(const QMimeData* mime) {
  3526. return mime->hasUrls() && mime->urls().length() == 1;
  3527. }
  3528. void GMainWindow::AcceptDropEvent(QDropEvent* event) {
  3529. if (IsSingleFileDropEvent(event->mimeData())) {
  3530. event->setDropAction(Qt::DropAction::LinkAction);
  3531. event->accept();
  3532. }
  3533. }
  3534. bool GMainWindow::DropAction(QDropEvent* event) {
  3535. if (!IsSingleFileDropEvent(event->mimeData())) {
  3536. return false;
  3537. }
  3538. const QMimeData* mime_data = event->mimeData();
  3539. const QString& filename = mime_data->urls().at(0).toLocalFile();
  3540. if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
  3541. // Amiibo
  3542. LoadAmiibo(filename);
  3543. } else {
  3544. // Game
  3545. if (ConfirmChangeGame()) {
  3546. BootGame(filename);
  3547. }
  3548. }
  3549. return true;
  3550. }
  3551. void GMainWindow::dropEvent(QDropEvent* event) {
  3552. DropAction(event);
  3553. }
  3554. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  3555. AcceptDropEvent(event);
  3556. }
  3557. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  3558. AcceptDropEvent(event);
  3559. }
  3560. void GMainWindow::leaveEvent(QEvent* event) {
  3561. if (Settings::values.mouse_panning) {
  3562. const QRect& rect = geometry();
  3563. QPoint position = QCursor::pos();
  3564. qint32 x = qBound(rect.left(), position.x(), rect.right());
  3565. qint32 y = qBound(rect.top(), position.y(), rect.bottom());
  3566. // Only start the timer if the mouse has left the window bound.
  3567. // The leave event is also triggered when the window looses focus.
  3568. if (x != position.x() || y != position.y()) {
  3569. mouse_center_timer.start();
  3570. }
  3571. event->accept();
  3572. }
  3573. }
  3574. bool GMainWindow::ConfirmChangeGame() {
  3575. if (emu_thread == nullptr)
  3576. return true;
  3577. const auto answer = QMessageBox::question(
  3578. this, tr("yuzu"),
  3579. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  3580. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3581. return answer != QMessageBox::No;
  3582. }
  3583. bool GMainWindow::ConfirmForceLockedExit() {
  3584. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  3585. return true;
  3586. }
  3587. const auto text = tr("The currently running application has requested yuzu to not exit.\n\n"
  3588. "Would you like to bypass this and exit anyway?");
  3589. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  3590. return answer != QMessageBox::No;
  3591. }
  3592. void GMainWindow::RequestGameExit() {
  3593. auto& sm{system->ServiceManager()};
  3594. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  3595. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  3596. bool has_signalled = false;
  3597. if (applet_oe != nullptr) {
  3598. applet_oe->GetMessageQueue()->RequestExit();
  3599. has_signalled = true;
  3600. }
  3601. if (applet_ae != nullptr && !has_signalled) {
  3602. applet_ae->GetMessageQueue()->RequestExit();
  3603. }
  3604. }
  3605. void GMainWindow::RequestGameResume() {
  3606. auto& sm{system->ServiceManager()};
  3607. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  3608. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  3609. if (applet_oe != nullptr) {
  3610. applet_oe->GetMessageQueue()->RequestResume();
  3611. return;
  3612. }
  3613. if (applet_ae != nullptr) {
  3614. applet_ae->GetMessageQueue()->RequestResume();
  3615. }
  3616. }
  3617. void GMainWindow::filterBarSetChecked(bool state) {
  3618. ui->action_Show_Filter_Bar->setChecked(state);
  3619. emit(OnToggleFilterBar());
  3620. }
  3621. static void AdjustLinkColor() {
  3622. QPalette new_pal(qApp->palette());
  3623. if (UISettings::IsDarkTheme()) {
  3624. new_pal.setColor(QPalette::Link, QColor(0, 190, 255, 255));
  3625. } else {
  3626. new_pal.setColor(QPalette::Link, QColor(0, 140, 200, 255));
  3627. }
  3628. if (qApp->palette().color(QPalette::Link) != new_pal.color(QPalette::Link)) {
  3629. qApp->setPalette(new_pal);
  3630. }
  3631. }
  3632. void GMainWindow::UpdateUITheme() {
  3633. const QString default_theme =
  3634. QString::fromUtf8(UISettings::themes[static_cast<size_t>(Config::default_theme)].second);
  3635. QString current_theme = UISettings::values.theme;
  3636. if (current_theme.isEmpty()) {
  3637. current_theme = default_theme;
  3638. }
  3639. #ifdef _WIN32
  3640. QIcon::setThemeName(current_theme);
  3641. AdjustLinkColor();
  3642. #else
  3643. if (current_theme == QStringLiteral("default") || current_theme == QStringLiteral("colorful")) {
  3644. QIcon::setThemeName(current_theme == QStringLiteral("colorful") ? current_theme
  3645. : startup_icon_theme);
  3646. QIcon::setThemeSearchPaths(QStringList(default_theme_paths));
  3647. if (CheckDarkMode()) {
  3648. current_theme = QStringLiteral("default_dark");
  3649. }
  3650. } else {
  3651. QIcon::setThemeName(current_theme);
  3652. QIcon::setThemeSearchPaths(QStringList(QStringLiteral(":/icons")));
  3653. AdjustLinkColor();
  3654. }
  3655. #endif
  3656. if (current_theme != default_theme) {
  3657. QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)};
  3658. QFile f(theme_uri);
  3659. if (!f.open(QFile::ReadOnly | QFile::Text)) {
  3660. LOG_ERROR(Frontend, "Unable to open style \"{}\", fallback to the default theme",
  3661. UISettings::values.theme.toStdString());
  3662. current_theme = default_theme;
  3663. }
  3664. }
  3665. QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)};
  3666. QFile f(theme_uri);
  3667. if (f.open(QFile::ReadOnly | QFile::Text)) {
  3668. QTextStream ts(&f);
  3669. qApp->setStyleSheet(ts.readAll());
  3670. setStyleSheet(ts.readAll());
  3671. } else {
  3672. LOG_ERROR(Frontend, "Unable to set style \"{}\", stylesheet file not found",
  3673. UISettings::values.theme.toStdString());
  3674. qApp->setStyleSheet({});
  3675. setStyleSheet({});
  3676. }
  3677. }
  3678. void GMainWindow::LoadTranslation() {
  3679. bool loaded;
  3680. if (UISettings::values.language.isEmpty()) {
  3681. // If the selected language is empty, use system locale
  3682. loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/"));
  3683. } else {
  3684. // Otherwise load from the specified file
  3685. loaded = translator.load(UISettings::values.language, QStringLiteral(":/languages/"));
  3686. }
  3687. if (loaded) {
  3688. qApp->installTranslator(&translator);
  3689. } else {
  3690. UISettings::values.language = QStringLiteral("en");
  3691. }
  3692. }
  3693. void GMainWindow::OnLanguageChanged(const QString& locale) {
  3694. if (UISettings::values.language != QStringLiteral("en")) {
  3695. qApp->removeTranslator(&translator);
  3696. }
  3697. UISettings::values.language = locale;
  3698. LoadTranslation();
  3699. ui->retranslateUi(this);
  3700. multiplayer_state->retranslateUi();
  3701. UpdateWindowTitle();
  3702. }
  3703. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  3704. #ifdef USE_DISCORD_PRESENCE
  3705. if (state) {
  3706. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>(*system);
  3707. } else {
  3708. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  3709. }
  3710. #else
  3711. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  3712. #endif
  3713. discord_rpc->Update();
  3714. }
  3715. void GMainWindow::changeEvent(QEvent* event) {
  3716. #ifdef __unix__
  3717. // PaletteChange event appears to only reach so far into the GUI, explicitly asking to
  3718. // UpdateUITheme is a decent work around
  3719. if (event->type() == QEvent::PaletteChange) {
  3720. const QPalette test_palette(qApp->palette());
  3721. const QString current_theme = UISettings::values.theme;
  3722. // Keeping eye on QPalette::Window to avoid looping. QPalette::Text might be useful too
  3723. static QColor last_window_color;
  3724. const QColor window_color = test_palette.color(QPalette::Active, QPalette::Window);
  3725. if (last_window_color != window_color && (current_theme == QStringLiteral("default") ||
  3726. current_theme == QStringLiteral("colorful"))) {
  3727. UpdateUITheme();
  3728. }
  3729. last_window_color = window_color;
  3730. }
  3731. #endif // __unix__
  3732. QWidget::changeEvent(event);
  3733. }
  3734. #ifdef main
  3735. #undef main
  3736. #endif
  3737. int main(int argc, char* argv[]) {
  3738. std::unique_ptr<Config> config = std::make_unique<Config>();
  3739. bool has_broken_vulkan = false;
  3740. bool is_child = false;
  3741. if (CheckEnvVars(&is_child)) {
  3742. return 0;
  3743. }
  3744. #ifdef YUZU_DBGHELP
  3745. PROCESS_INFORMATION pi;
  3746. if (!is_child && Settings::values.create_crash_dumps.GetValue() &&
  3747. MiniDump::SpawnDebuggee(argv[0], pi)) {
  3748. // Delete the config object so that it doesn't save when the program exits
  3749. config.reset(nullptr);
  3750. MiniDump::DebugDebuggee(pi);
  3751. return 0;
  3752. }
  3753. #endif
  3754. if (StartupChecks(argv[0], &has_broken_vulkan,
  3755. Settings::values.perform_vulkan_check.GetValue())) {
  3756. return 0;
  3757. }
  3758. Common::DetachedTasks detached_tasks;
  3759. MicroProfileOnThreadCreate("Frontend");
  3760. SCOPE_EXIT({ MicroProfileShutdown(); });
  3761. Common::ConfigureNvidiaEnvironmentFlags();
  3762. // Init settings params
  3763. QCoreApplication::setOrganizationName(QStringLiteral("yuzu team"));
  3764. QCoreApplication::setApplicationName(QStringLiteral("yuzu"));
  3765. #ifdef _WIN32
  3766. // Increases the maximum open file limit to 8192
  3767. _setmaxstdio(8192);
  3768. #endif
  3769. #ifdef __APPLE__
  3770. // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/".
  3771. // But since we require the working directory to be the executable path for the location of
  3772. // the user folder in the Qt Frontend, we need to cd into that working directory
  3773. const auto bin_path = Common::FS::GetBundleDirectory() / "..";
  3774. chdir(Common::FS::PathToUTF8String(bin_path).c_str());
  3775. #endif
  3776. #ifdef __linux__
  3777. // Set the DISPLAY variable in order to open web browsers
  3778. // TODO (lat9nq): Find a better solution for AppImages to start external applications
  3779. if (QString::fromLocal8Bit(qgetenv("DISPLAY")).isEmpty()) {
  3780. qputenv("DISPLAY", ":0");
  3781. }
  3782. #endif
  3783. // Enables the core to make the qt created contexts current on std::threads
  3784. QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  3785. QApplication app(argc, argv);
  3786. #ifdef _WIN32
  3787. OverrideWindowsFont();
  3788. #endif
  3789. // Workaround for QTBUG-85409, for Suzhou numerals the number 1 is actually \u3021
  3790. // so we can see if we get \u3008 instead
  3791. // TL;DR all other number formats are consecutive in unicode code points
  3792. // This bug is fixed in Qt6, specifically 6.0.0-alpha1
  3793. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  3794. const QLocale locale = QLocale::system();
  3795. if (QStringLiteral("\u3008") == locale.toString(1)) {
  3796. QLocale::setDefault(QLocale::system().name());
  3797. }
  3798. #endif
  3799. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  3800. // generating shaders
  3801. setlocale(LC_ALL, "C");
  3802. GMainWindow main_window{std::move(config), has_broken_vulkan};
  3803. // After settings have been loaded by GMainWindow, apply the filter
  3804. main_window.show();
  3805. QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
  3806. &GMainWindow::OnAppFocusStateChanged);
  3807. int result = app.exec();
  3808. detached_tasks.WaitForAllTasks();
  3809. return result;
  3810. }