main.cpp 154 KB

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