main.cpp 134 KB

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