main.cpp 153 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129
  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. if (!nfc->LoadAmiibo(filename.toStdString())) {
  2747. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  2748. tr("Unable to load Amiibo data."));
  2749. }
  2750. }
  2751. void GMainWindow::OnOpenYuzuFolder() {
  2752. QDesktopServices::openUrl(QUrl::fromLocalFile(
  2753. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::YuzuDir))));
  2754. }
  2755. void GMainWindow::OnAbout() {
  2756. AboutDialog aboutDialog(this);
  2757. aboutDialog.exec();
  2758. }
  2759. void GMainWindow::OnToggleFilterBar() {
  2760. game_list->SetFilterVisible(ui->action_Show_Filter_Bar->isChecked());
  2761. if (ui->action_Show_Filter_Bar->isChecked()) {
  2762. game_list->SetFilterFocus();
  2763. } else {
  2764. game_list->ClearFilter();
  2765. }
  2766. }
  2767. void GMainWindow::OnToggleStatusBar() {
  2768. statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked());
  2769. }
  2770. void GMainWindow::OnCaptureScreenshot() {
  2771. if (emu_thread == nullptr || !emu_thread->IsRunning()) {
  2772. return;
  2773. }
  2774. const u64 title_id = system->GetCurrentProcessProgramID();
  2775. const auto screenshot_path =
  2776. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::ScreenshotsDir));
  2777. const auto date =
  2778. QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd_hh-mm-ss-zzz"));
  2779. QString filename = QStringLiteral("%1/%2_%3.png")
  2780. .arg(screenshot_path)
  2781. .arg(title_id, 16, 16, QLatin1Char{'0'})
  2782. .arg(date);
  2783. if (!Common::FS::CreateDir(screenshot_path.toStdString())) {
  2784. return;
  2785. }
  2786. #ifdef _WIN32
  2787. if (UISettings::values.enable_screenshot_save_as) {
  2788. OnPauseGame();
  2789. filename = QFileDialog::getSaveFileName(this, tr("Capture Screenshot"), filename,
  2790. tr("PNG Image (*.png)"));
  2791. OnStartGame();
  2792. if (filename.isEmpty()) {
  2793. return;
  2794. }
  2795. }
  2796. #endif
  2797. render_window->CaptureScreenshot(filename);
  2798. }
  2799. // TODO: Written 2020-10-01: Remove per-game config migration code when it is irrelevant
  2800. void GMainWindow::MigrateConfigFiles() {
  2801. const auto config_dir_fs_path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir);
  2802. const QDir config_dir =
  2803. QDir(QString::fromStdString(Common::FS::PathToUTF8String(config_dir_fs_path)));
  2804. const QStringList config_dir_list = config_dir.entryList(QStringList(QStringLiteral("*.ini")));
  2805. if (!Common::FS::CreateDirs(config_dir_fs_path / "custom")) {
  2806. LOG_ERROR(Frontend, "Failed to create new config file directory");
  2807. }
  2808. for (auto it = config_dir_list.constBegin(); it != config_dir_list.constEnd(); ++it) {
  2809. const auto filename = it->toStdString();
  2810. if (filename.find_first_not_of("0123456789abcdefACBDEF", 0) < 16) {
  2811. continue;
  2812. }
  2813. const auto origin = config_dir_fs_path / filename;
  2814. const auto destination = config_dir_fs_path / "custom" / filename;
  2815. LOG_INFO(Frontend, "Migrating config file from {} to {}", origin.string(),
  2816. destination.string());
  2817. if (!Common::FS::RenameFile(origin, destination)) {
  2818. // Delete the old config file if one already exists in the new location.
  2819. Common::FS::RemoveFile(origin);
  2820. }
  2821. }
  2822. }
  2823. void GMainWindow::UpdateWindowTitle(std::string_view title_name, std::string_view title_version,
  2824. std::string_view gpu_vendor) {
  2825. const auto branch_name = std::string(Common::g_scm_branch);
  2826. const auto description = std::string(Common::g_scm_desc);
  2827. const auto build_id = std::string(Common::g_build_id);
  2828. const auto yuzu_title = fmt::format("yuzu | {}-{}", branch_name, description);
  2829. const auto override_title =
  2830. fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id);
  2831. const auto window_title = override_title.empty() ? yuzu_title : override_title;
  2832. if (title_name.empty()) {
  2833. setWindowTitle(QString::fromStdString(window_title));
  2834. } else {
  2835. const auto run_title = [window_title, title_name, title_version, gpu_vendor]() {
  2836. if (title_version.empty()) {
  2837. return fmt::format("{} | {} | {}", window_title, title_name, gpu_vendor);
  2838. }
  2839. return fmt::format("{} | {} | {} | {}", window_title, title_name, title_version,
  2840. gpu_vendor);
  2841. }();
  2842. setWindowTitle(QString::fromStdString(run_title));
  2843. }
  2844. }
  2845. QString GMainWindow::GetTasStateDescription() const {
  2846. auto [tas_status, current_tas_frame, total_tas_frames] = input_subsystem->GetTas()->GetStatus();
  2847. switch (tas_status) {
  2848. case InputCommon::TasInput::TasState::Running:
  2849. return tr("TAS state: Running %1/%2").arg(current_tas_frame).arg(total_tas_frames);
  2850. case InputCommon::TasInput::TasState::Recording:
  2851. return tr("TAS state: Recording %1").arg(total_tas_frames);
  2852. case InputCommon::TasInput::TasState::Stopped:
  2853. return tr("TAS state: Idle %1/%2").arg(current_tas_frame).arg(total_tas_frames);
  2854. default:
  2855. return tr("TAS State: Invalid");
  2856. }
  2857. }
  2858. void GMainWindow::OnTasStateChanged() {
  2859. bool is_running = false;
  2860. bool is_recording = false;
  2861. if (emulation_running) {
  2862. const InputCommon::TasInput::TasState tas_status =
  2863. std::get<0>(input_subsystem->GetTas()->GetStatus());
  2864. is_running = tas_status == InputCommon::TasInput::TasState::Running;
  2865. is_recording = tas_status == InputCommon::TasInput::TasState::Recording;
  2866. }
  2867. ui->action_TAS_Start->setText(is_running ? tr("&Stop Running") : tr("&Start"));
  2868. ui->action_TAS_Record->setText(is_recording ? tr("Stop R&ecording") : tr("R&ecord"));
  2869. ui->action_TAS_Start->setEnabled(emulation_running);
  2870. ui->action_TAS_Record->setEnabled(emulation_running);
  2871. ui->action_TAS_Reset->setEnabled(emulation_running);
  2872. }
  2873. void GMainWindow::UpdateStatusBar() {
  2874. if (emu_thread == nullptr || !system->IsPoweredOn()) {
  2875. status_bar_update_timer.stop();
  2876. return;
  2877. }
  2878. if (Settings::values.tas_enable) {
  2879. tas_label->setText(GetTasStateDescription());
  2880. } else {
  2881. tas_label->clear();
  2882. }
  2883. auto results = system->GetAndResetPerfStats();
  2884. auto& shader_notify = system->GPU().ShaderNotify();
  2885. const int shaders_building = shader_notify.ShadersBuilding();
  2886. if (shaders_building > 0) {
  2887. shader_building_label->setText(tr("Building: %n shader(s)", "", shaders_building));
  2888. shader_building_label->setVisible(true);
  2889. } else {
  2890. shader_building_label->setVisible(false);
  2891. }
  2892. const auto res_info = Settings::values.resolution_info;
  2893. const auto res_scale = res_info.up_factor;
  2894. res_scale_label->setText(
  2895. tr("Scale: %1x", "%1 is the resolution scaling factor").arg(res_scale));
  2896. if (Settings::values.use_speed_limit.GetValue()) {
  2897. emu_speed_label->setText(tr("Speed: %1% / %2%")
  2898. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  2899. .arg(Settings::values.speed_limit.GetValue()));
  2900. } else {
  2901. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  2902. }
  2903. if (!Settings::values.use_speed_limit) {
  2904. game_fps_label->setText(
  2905. tr("Game: %1 FPS (Unlocked)").arg(results.average_game_fps, 0, 'f', 0));
  2906. } else {
  2907. game_fps_label->setText(tr("Game: %1 FPS").arg(results.average_game_fps, 0, 'f', 0));
  2908. }
  2909. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  2910. res_scale_label->setVisible(true);
  2911. emu_speed_label->setVisible(!Settings::values.use_multi_core.GetValue());
  2912. game_fps_label->setVisible(true);
  2913. emu_frametime_label->setVisible(true);
  2914. }
  2915. void GMainWindow::UpdateGPUAccuracyButton() {
  2916. switch (Settings::values.gpu_accuracy.GetValue()) {
  2917. case Settings::GPUAccuracy::Normal: {
  2918. gpu_accuracy_button->setText(tr("GPU NORMAL"));
  2919. gpu_accuracy_button->setChecked(false);
  2920. break;
  2921. }
  2922. case Settings::GPUAccuracy::High: {
  2923. gpu_accuracy_button->setText(tr("GPU HIGH"));
  2924. gpu_accuracy_button->setChecked(true);
  2925. break;
  2926. }
  2927. case Settings::GPUAccuracy::Extreme: {
  2928. gpu_accuracy_button->setText(tr("GPU EXTREME"));
  2929. gpu_accuracy_button->setChecked(true);
  2930. break;
  2931. }
  2932. default: {
  2933. gpu_accuracy_button->setText(tr("GPU ERROR"));
  2934. gpu_accuracy_button->setChecked(true);
  2935. }
  2936. }
  2937. }
  2938. void GMainWindow::UpdateDockedButton() {
  2939. const bool is_docked = Settings::values.use_docked_mode.GetValue();
  2940. dock_status_button->setChecked(is_docked);
  2941. dock_status_button->setText(is_docked ? tr("DOCKED") : tr("HANDHELD"));
  2942. }
  2943. void GMainWindow::UpdateFilterText() {
  2944. const auto filter = Settings::values.scaling_filter.GetValue();
  2945. switch (filter) {
  2946. case Settings::ScalingFilter::NearestNeighbor:
  2947. filter_status_button->setText(tr("NEAREST"));
  2948. break;
  2949. case Settings::ScalingFilter::Bilinear:
  2950. filter_status_button->setText(tr("BILINEAR"));
  2951. break;
  2952. case Settings::ScalingFilter::Bicubic:
  2953. filter_status_button->setText(tr("BICUBIC"));
  2954. break;
  2955. case Settings::ScalingFilter::Gaussian:
  2956. filter_status_button->setText(tr("GAUSSIAN"));
  2957. break;
  2958. case Settings::ScalingFilter::ScaleForce:
  2959. filter_status_button->setText(tr("SCALEFORCE"));
  2960. break;
  2961. case Settings::ScalingFilter::Fsr:
  2962. filter_status_button->setText(tr("FSR"));
  2963. break;
  2964. default:
  2965. filter_status_button->setText(tr("BILINEAR"));
  2966. break;
  2967. }
  2968. }
  2969. void GMainWindow::UpdateAAText() {
  2970. const auto aa_mode = Settings::values.anti_aliasing.GetValue();
  2971. switch (aa_mode) {
  2972. case Settings::AntiAliasing::None:
  2973. aa_status_button->setText(tr("NO AA"));
  2974. break;
  2975. case Settings::AntiAliasing::Fxaa:
  2976. aa_status_button->setText(tr("FXAA"));
  2977. break;
  2978. default:
  2979. aa_status_button->setText(tr("NO AA"));
  2980. break;
  2981. }
  2982. }
  2983. void GMainWindow::UpdateStatusButtons() {
  2984. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  2985. Settings::RendererBackend::Vulkan);
  2986. UpdateGPUAccuracyButton();
  2987. UpdateDockedButton();
  2988. UpdateFilterText();
  2989. UpdateAAText();
  2990. }
  2991. void GMainWindow::UpdateUISettings() {
  2992. if (!ui->action_Fullscreen->isChecked()) {
  2993. UISettings::values.geometry = saveGeometry();
  2994. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2995. }
  2996. UISettings::values.state = saveState();
  2997. #if MICROPROFILE_ENABLED
  2998. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  2999. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  3000. #endif
  3001. UISettings::values.single_window_mode = ui->action_Single_Window_Mode->isChecked();
  3002. UISettings::values.fullscreen = ui->action_Fullscreen->isChecked();
  3003. UISettings::values.display_titlebar = ui->action_Display_Dock_Widget_Headers->isChecked();
  3004. UISettings::values.show_filter_bar = ui->action_Show_Filter_Bar->isChecked();
  3005. UISettings::values.show_status_bar = ui->action_Show_Status_Bar->isChecked();
  3006. UISettings::values.first_start = false;
  3007. }
  3008. void GMainWindow::HideMouseCursor() {
  3009. if (emu_thread == nullptr && UISettings::values.hide_mouse) {
  3010. mouse_hide_timer.stop();
  3011. ShowMouseCursor();
  3012. return;
  3013. }
  3014. render_window->setCursor(QCursor(Qt::BlankCursor));
  3015. }
  3016. void GMainWindow::ShowMouseCursor() {
  3017. render_window->unsetCursor();
  3018. if (emu_thread != nullptr && UISettings::values.hide_mouse) {
  3019. mouse_hide_timer.start();
  3020. }
  3021. }
  3022. void GMainWindow::CenterMouseCursor() {
  3023. if (emu_thread == nullptr || !Settings::values.mouse_panning) {
  3024. mouse_center_timer.stop();
  3025. return;
  3026. }
  3027. if (!this->isActiveWindow()) {
  3028. mouse_center_timer.stop();
  3029. return;
  3030. }
  3031. const int center_x = render_window->width() / 2;
  3032. const int center_y = render_window->height() / 2;
  3033. QCursor::setPos(mapToGlobal(QPoint{center_x, center_y}));
  3034. }
  3035. void GMainWindow::OnMouseActivity() {
  3036. if (!Settings::values.mouse_panning) {
  3037. ShowMouseCursor();
  3038. }
  3039. mouse_center_timer.stop();
  3040. }
  3041. void GMainWindow::OnCoreError(Core::SystemResultStatus result, std::string details) {
  3042. QMessageBox::StandardButton answer;
  3043. QString status_message;
  3044. const QString common_message =
  3045. tr("The game you are trying to load requires additional files from your Switch to be "
  3046. "dumped "
  3047. "before playing.<br/><br/>For more information on dumping these files, please see the "
  3048. "following wiki page: <a "
  3049. "href='https://yuzu-emu.org/wiki/"
  3050. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  3051. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  3052. "quit "
  3053. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  3054. "data, or other bugs.");
  3055. switch (result) {
  3056. case Core::SystemResultStatus::ErrorSystemFiles: {
  3057. QString message;
  3058. if (details.empty()) {
  3059. message =
  3060. tr("yuzu was unable to locate a Switch system archive. %1").arg(common_message);
  3061. } else {
  3062. message = tr("yuzu was unable to locate a Switch system archive: %1. %2")
  3063. .arg(QString::fromStdString(details), common_message);
  3064. }
  3065. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  3066. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3067. status_message = tr("System Archive Missing");
  3068. break;
  3069. }
  3070. case Core::SystemResultStatus::ErrorSharedFont: {
  3071. const QString message =
  3072. tr("yuzu was unable to locate the Switch shared fonts. %1").arg(common_message);
  3073. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  3074. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3075. status_message = tr("Shared Font Missing");
  3076. break;
  3077. }
  3078. default:
  3079. answer = QMessageBox::question(
  3080. this, tr("Fatal Error"),
  3081. tr("yuzu has encountered a fatal error, please see the log for more details. "
  3082. "For more information on accessing the log, please see the following page: "
  3083. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  3084. "to "
  3085. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  3086. "list? "
  3087. "Continuing emulation may result in crashes, corrupted save data, or other "
  3088. "bugs."),
  3089. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3090. status_message = tr("Fatal Error encountered");
  3091. break;
  3092. }
  3093. if (answer == QMessageBox::Yes) {
  3094. if (emu_thread) {
  3095. ShutdownGame();
  3096. Settings::RestoreGlobalState(system->IsPoweredOn());
  3097. UpdateStatusButtons();
  3098. }
  3099. } else {
  3100. // Only show the message if the game is still running.
  3101. if (emu_thread) {
  3102. emu_thread->SetRunning(true);
  3103. message_label->setText(status_message);
  3104. }
  3105. }
  3106. }
  3107. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  3108. if (behavior == ReinitializeKeyBehavior::Warning) {
  3109. const auto res = QMessageBox::information(
  3110. this, tr("Confirm Key Rederivation"),
  3111. tr("You are about to force rederive all of your keys. \nIf you do not know what "
  3112. "this "
  3113. "means or what you are doing, \nthis is a potentially destructive action. "
  3114. "\nPlease "
  3115. "make sure this is what you want \nand optionally make backups.\n\nThis will "
  3116. "delete "
  3117. "your autogenerated key files and re-run the key derivation module."),
  3118. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  3119. if (res == QMessageBox::Cancel)
  3120. return;
  3121. const auto keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
  3122. Common::FS::RemoveFile(keys_dir / "prod.keys_autogenerated");
  3123. Common::FS::RemoveFile(keys_dir / "console.keys_autogenerated");
  3124. Common::FS::RemoveFile(keys_dir / "title.keys_autogenerated");
  3125. }
  3126. Core::Crypto::KeyManager& keys = Core::Crypto::KeyManager::Instance();
  3127. if (keys.BaseDeriveNecessary()) {
  3128. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory("", FileSys::Mode::Read)};
  3129. const auto function = [this, &keys, &pdm] {
  3130. keys.PopulateFromPartitionData(pdm);
  3131. system->GetFileSystemController().CreateFactories(*vfs);
  3132. keys.DeriveETicket(pdm, system->GetContentProvider());
  3133. };
  3134. QString errors;
  3135. if (!pdm.HasFuses()) {
  3136. errors += tr("Missing fuses");
  3137. }
  3138. if (!pdm.HasBoot0()) {
  3139. errors += tr(" - Missing BOOT0");
  3140. }
  3141. if (!pdm.HasPackage2()) {
  3142. errors += tr(" - Missing BCPKG2-1-Normal-Main");
  3143. }
  3144. if (!pdm.HasProdInfo()) {
  3145. errors += tr(" - Missing PRODINFO");
  3146. }
  3147. if (!errors.isEmpty()) {
  3148. QMessageBox::warning(
  3149. this, tr("Derivation Components Missing"),
  3150. tr("Encryption keys are missing. "
  3151. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  3152. "quickstart guide</a> to get all your keys, firmware and "
  3153. "games.<br><br><small>(%1)</small>")
  3154. .arg(errors));
  3155. }
  3156. QProgressDialog prog(this);
  3157. prog.setRange(0, 0);
  3158. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  3159. "system's performance."));
  3160. prog.setWindowTitle(tr("Deriving Keys"));
  3161. prog.show();
  3162. auto future = QtConcurrent::run(function);
  3163. while (!future.isFinished()) {
  3164. QCoreApplication::processEvents();
  3165. }
  3166. prog.close();
  3167. }
  3168. system->GetFileSystemController().CreateFactories(*vfs);
  3169. if (behavior == ReinitializeKeyBehavior::Warning) {
  3170. game_list->PopulateAsync(UISettings::values.game_dirs);
  3171. }
  3172. }
  3173. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
  3174. u64 program_id) {
  3175. const auto dlc_entries =
  3176. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  3177. std::vector<FileSys::ContentProviderEntry> dlc_match;
  3178. dlc_match.reserve(dlc_entries.size());
  3179. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  3180. [&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
  3181. return FileSys::GetBaseTitleID(entry.title_id) == program_id &&
  3182. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  3183. });
  3184. std::vector<u64> romfs_tids;
  3185. romfs_tids.push_back(program_id);
  3186. for (const auto& entry : dlc_match) {
  3187. romfs_tids.push_back(entry.title_id);
  3188. }
  3189. if (romfs_tids.size() > 1) {
  3190. QStringList list{QStringLiteral("Base")};
  3191. for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
  3192. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  3193. }
  3194. bool ok;
  3195. const auto res = QInputDialog::getItem(
  3196. this, tr("Select RomFS Dump Target"),
  3197. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  3198. if (!ok) {
  3199. return {};
  3200. }
  3201. return romfs_tids[list.indexOf(res)];
  3202. }
  3203. return program_id;
  3204. }
  3205. bool GMainWindow::ConfirmClose() {
  3206. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  3207. return true;
  3208. }
  3209. const auto text = tr("Are you sure you want to close yuzu?");
  3210. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  3211. return answer != QMessageBox::No;
  3212. }
  3213. void GMainWindow::closeEvent(QCloseEvent* event) {
  3214. if (!ConfirmClose()) {
  3215. event->ignore();
  3216. return;
  3217. }
  3218. UpdateUISettings();
  3219. game_list->SaveInterfaceLayout();
  3220. hotkey_registry.SaveHotkeys();
  3221. // Unload controllers early
  3222. controller_dialog->UnloadController();
  3223. game_list->UnloadController();
  3224. system->HIDCore().UnloadInputDevices();
  3225. // Shutdown session if the emu thread is active...
  3226. if (emu_thread != nullptr) {
  3227. ShutdownGame();
  3228. Settings::RestoreGlobalState(system->IsPoweredOn());
  3229. UpdateStatusButtons();
  3230. }
  3231. render_window->close();
  3232. multiplayer_state->Close();
  3233. system->GetRoomNetwork().Shutdown();
  3234. QWidget::closeEvent(event);
  3235. }
  3236. static bool IsSingleFileDropEvent(const QMimeData* mime) {
  3237. return mime->hasUrls() && mime->urls().length() == 1;
  3238. }
  3239. void GMainWindow::AcceptDropEvent(QDropEvent* event) {
  3240. if (IsSingleFileDropEvent(event->mimeData())) {
  3241. event->setDropAction(Qt::DropAction::LinkAction);
  3242. event->accept();
  3243. }
  3244. }
  3245. bool GMainWindow::DropAction(QDropEvent* event) {
  3246. if (!IsSingleFileDropEvent(event->mimeData())) {
  3247. return false;
  3248. }
  3249. const QMimeData* mime_data = event->mimeData();
  3250. const QString& filename = mime_data->urls().at(0).toLocalFile();
  3251. if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
  3252. // Amiibo
  3253. LoadAmiibo(filename);
  3254. } else {
  3255. // Game
  3256. if (ConfirmChangeGame()) {
  3257. BootGame(filename);
  3258. }
  3259. }
  3260. return true;
  3261. }
  3262. void GMainWindow::dropEvent(QDropEvent* event) {
  3263. DropAction(event);
  3264. }
  3265. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  3266. AcceptDropEvent(event);
  3267. }
  3268. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  3269. AcceptDropEvent(event);
  3270. }
  3271. void GMainWindow::leaveEvent(QEvent* event) {
  3272. if (Settings::values.mouse_panning) {
  3273. const QRect& rect = geometry();
  3274. QPoint position = QCursor::pos();
  3275. qint32 x = qBound(rect.left(), position.x(), rect.right());
  3276. qint32 y = qBound(rect.top(), position.y(), rect.bottom());
  3277. // Only start the timer if the mouse has left the window bound.
  3278. // The leave event is also triggered when the window looses focus.
  3279. if (x != position.x() || y != position.y()) {
  3280. mouse_center_timer.start();
  3281. }
  3282. event->accept();
  3283. }
  3284. }
  3285. bool GMainWindow::ConfirmChangeGame() {
  3286. if (emu_thread == nullptr)
  3287. return true;
  3288. const auto answer = QMessageBox::question(
  3289. this, tr("yuzu"),
  3290. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  3291. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  3292. return answer != QMessageBox::No;
  3293. }
  3294. bool GMainWindow::ConfirmForceLockedExit() {
  3295. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  3296. return true;
  3297. }
  3298. const auto text = tr("The currently running application has requested yuzu to not exit.\n\n"
  3299. "Would you like to bypass this and exit anyway?");
  3300. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  3301. return answer != QMessageBox::No;
  3302. }
  3303. void GMainWindow::RequestGameExit() {
  3304. auto& sm{system->ServiceManager()};
  3305. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  3306. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  3307. bool has_signalled = false;
  3308. if (applet_oe != nullptr) {
  3309. applet_oe->GetMessageQueue()->RequestExit();
  3310. has_signalled = true;
  3311. }
  3312. if (applet_ae != nullptr && !has_signalled) {
  3313. applet_ae->GetMessageQueue()->RequestExit();
  3314. }
  3315. }
  3316. void GMainWindow::RequestGameResume() {
  3317. auto& sm{system->ServiceManager()};
  3318. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  3319. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  3320. if (applet_oe != nullptr) {
  3321. applet_oe->GetMessageQueue()->RequestResume();
  3322. return;
  3323. }
  3324. if (applet_ae != nullptr) {
  3325. applet_ae->GetMessageQueue()->RequestResume();
  3326. }
  3327. }
  3328. void GMainWindow::filterBarSetChecked(bool state) {
  3329. ui->action_Show_Filter_Bar->setChecked(state);
  3330. emit(OnToggleFilterBar());
  3331. }
  3332. static void AdjustLinkColor() {
  3333. QPalette new_pal(qApp->palette());
  3334. if (UISettings::IsDarkTheme()) {
  3335. new_pal.setColor(QPalette::Link, QColor(0, 190, 255, 255));
  3336. } else {
  3337. new_pal.setColor(QPalette::Link, QColor(0, 140, 200, 255));
  3338. }
  3339. if (qApp->palette().color(QPalette::Link) != new_pal.color(QPalette::Link)) {
  3340. qApp->setPalette(new_pal);
  3341. }
  3342. }
  3343. void GMainWindow::UpdateUITheme() {
  3344. const QString default_theme =
  3345. QString::fromUtf8(UISettings::themes[static_cast<size_t>(Config::default_theme)].second);
  3346. QString current_theme = UISettings::values.theme;
  3347. QStringList theme_paths(default_theme_paths);
  3348. if (current_theme.isEmpty()) {
  3349. current_theme = default_theme;
  3350. }
  3351. #ifdef _WIN32
  3352. QIcon::setThemeName(current_theme);
  3353. AdjustLinkColor();
  3354. #else
  3355. if (current_theme == QStringLiteral("default") || current_theme == QStringLiteral("colorful")) {
  3356. QIcon::setThemeName(current_theme == QStringLiteral("colorful") ? current_theme
  3357. : startup_icon_theme);
  3358. QIcon::setThemeSearchPaths(theme_paths);
  3359. if (CheckDarkMode()) {
  3360. current_theme = QStringLiteral("default_dark");
  3361. }
  3362. } else {
  3363. QIcon::setThemeName(current_theme);
  3364. QIcon::setThemeSearchPaths(QStringList(QStringLiteral(":/icons")));
  3365. AdjustLinkColor();
  3366. }
  3367. #endif
  3368. if (current_theme != default_theme) {
  3369. QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)};
  3370. QFile f(theme_uri);
  3371. if (!f.open(QFile::ReadOnly | QFile::Text)) {
  3372. LOG_ERROR(Frontend, "Unable to open style \"{}\", fallback to the default theme",
  3373. UISettings::values.theme.toStdString());
  3374. current_theme = default_theme;
  3375. }
  3376. }
  3377. QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)};
  3378. QFile f(theme_uri);
  3379. if (f.open(QFile::ReadOnly | QFile::Text)) {
  3380. QTextStream ts(&f);
  3381. qApp->setStyleSheet(ts.readAll());
  3382. setStyleSheet(ts.readAll());
  3383. } else {
  3384. LOG_ERROR(Frontend, "Unable to set style \"{}\", stylesheet file not found",
  3385. UISettings::values.theme.toStdString());
  3386. qApp->setStyleSheet({});
  3387. setStyleSheet({});
  3388. }
  3389. }
  3390. void GMainWindow::LoadTranslation() {
  3391. bool loaded;
  3392. if (UISettings::values.language.isEmpty()) {
  3393. // If the selected language is empty, use system locale
  3394. loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/"));
  3395. } else {
  3396. // Otherwise load from the specified file
  3397. loaded = translator.load(UISettings::values.language, QStringLiteral(":/languages/"));
  3398. }
  3399. if (loaded) {
  3400. qApp->installTranslator(&translator);
  3401. } else {
  3402. UISettings::values.language = QStringLiteral("en");
  3403. }
  3404. }
  3405. void GMainWindow::OnLanguageChanged(const QString& locale) {
  3406. if (UISettings::values.language != QStringLiteral("en")) {
  3407. qApp->removeTranslator(&translator);
  3408. }
  3409. UISettings::values.language = locale;
  3410. LoadTranslation();
  3411. ui->retranslateUi(this);
  3412. multiplayer_state->retranslateUi();
  3413. UpdateWindowTitle();
  3414. }
  3415. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  3416. #ifdef USE_DISCORD_PRESENCE
  3417. if (state) {
  3418. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>(*system);
  3419. } else {
  3420. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  3421. }
  3422. #else
  3423. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  3424. #endif
  3425. discord_rpc->Update();
  3426. }
  3427. void GMainWindow::changeEvent(QEvent* event) {
  3428. #ifdef __linux__
  3429. // PaletteChange event appears to only reach so far into the GUI, explicitly asking to
  3430. // UpdateUITheme is a decent work around
  3431. if (event->type() == QEvent::PaletteChange) {
  3432. const QPalette test_palette(qApp->palette());
  3433. const QString current_theme = UISettings::values.theme;
  3434. // Keeping eye on QPalette::Window to avoid looping. QPalette::Text might be useful too
  3435. static QColor last_window_color;
  3436. const QColor window_color = test_palette.color(QPalette::Active, QPalette::Window);
  3437. if (last_window_color != window_color && (current_theme == QStringLiteral("default") ||
  3438. current_theme == QStringLiteral("colorful"))) {
  3439. UpdateUITheme();
  3440. }
  3441. last_window_color = window_color;
  3442. }
  3443. #endif // __linux__
  3444. QWidget::changeEvent(event);
  3445. }
  3446. #ifdef main
  3447. #undef main
  3448. #endif
  3449. int main(int argc, char* argv[]) {
  3450. bool has_broken_vulkan = false;
  3451. if (StartupChecks(argv[0], &has_broken_vulkan)) {
  3452. return 0;
  3453. }
  3454. Common::DetachedTasks detached_tasks;
  3455. MicroProfileOnThreadCreate("Frontend");
  3456. SCOPE_EXIT({ MicroProfileShutdown(); });
  3457. Common::ConfigureNvidiaEnvironmentFlags();
  3458. // Init settings params
  3459. QCoreApplication::setOrganizationName(QStringLiteral("yuzu team"));
  3460. QCoreApplication::setApplicationName(QStringLiteral("yuzu"));
  3461. #ifdef _WIN32
  3462. // Increases the maximum open file limit to 8192
  3463. _setmaxstdio(8192);
  3464. #endif
  3465. #ifdef __APPLE__
  3466. // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/".
  3467. // But since we require the working directory to be the executable path for the location of
  3468. // the user folder in the Qt Frontend, we need to cd into that working directory
  3469. const auto bin_path = Common::FS::GetBundleDirectory() / "..";
  3470. chdir(Common::FS::PathToUTF8String(bin_path).c_str());
  3471. #endif
  3472. #ifdef __linux__
  3473. // Set the DISPLAY variable in order to open web browsers
  3474. // TODO (lat9nq): Find a better solution for AppImages to start external applications
  3475. if (QString::fromLocal8Bit(qgetenv("DISPLAY")).isEmpty()) {
  3476. qputenv("DISPLAY", ":0");
  3477. }
  3478. #endif
  3479. // Enables the core to make the qt created contexts current on std::threads
  3480. QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  3481. QApplication app(argc, argv);
  3482. // Workaround for QTBUG-85409, for Suzhou numerals the number 1 is actually \u3021
  3483. // so we can see if we get \u3008 instead
  3484. // TL;DR all other number formats are consecutive in unicode code points
  3485. // This bug is fixed in Qt6, specifically 6.0.0-alpha1
  3486. const QLocale locale = QLocale::system();
  3487. if (QStringLiteral("\u3008") == locale.toString(1)) {
  3488. QLocale::setDefault(QLocale::system().name());
  3489. }
  3490. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  3491. // generating shaders
  3492. setlocale(LC_ALL, "C");
  3493. GMainWindow main_window{has_broken_vulkan};
  3494. // After settings have been loaded by GMainWindow, apply the filter
  3495. main_window.show();
  3496. QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
  3497. &GMainWindow::OnAppFocusStateChanged);
  3498. int result = app.exec();
  3499. detached_tasks.WaitForAllTasks();
  3500. return result;
  3501. }