main.cpp 156 KB

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