main.cpp 133 KB

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