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. Core::System::GetInstance().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()
  176. : input_subsystem{std::make_shared<InputCommon::InputSubsystem>()},
  177. config{std::make_unique<Config>()}, vfs{std::make_shared<FileSys::RealVfsFilesystem>()},
  178. provider{std::make_unique<FileSys::ManualContentProvider>()} {
  179. Common::Log::Initialize();
  180. LoadTranslation();
  181. setAcceptDrops(true);
  182. ui.setupUi(this);
  183. statusBar()->hide();
  184. default_theme_paths = QIcon::themeSearchPaths();
  185. UpdateUITheme();
  186. SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue());
  187. discord_rpc->Update();
  188. RegisterMetaTypes();
  189. InitializeWidgets();
  190. InitializeDebugWidgets();
  191. InitializeRecentFileMenuActions();
  192. InitializeHotkeys();
  193. SetDefaultUIGeometry();
  194. RestoreUIState();
  195. ConnectMenuEvents();
  196. ConnectWidgetEvents();
  197. const auto branch_name = std::string(Common::g_scm_branch);
  198. const auto description = std::string(Common::g_scm_desc);
  199. const auto build_id = std::string(Common::g_build_id);
  200. const auto yuzu_build = fmt::format("yuzu Development Build | {}-{}", branch_name, description);
  201. const auto override_build =
  202. fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id);
  203. const auto yuzu_build_version = override_build.empty() ? yuzu_build : override_build;
  204. LOG_INFO(Frontend, "yuzu Version: {}", yuzu_build_version);
  205. #ifdef ARCHITECTURE_x86_64
  206. const auto& caps = Common::GetCPUCaps();
  207. std::string cpu_string = caps.cpu_string;
  208. if (caps.avx || caps.avx2 || caps.avx512) {
  209. cpu_string += " | AVX";
  210. if (caps.avx512) {
  211. cpu_string += "512";
  212. } else if (caps.avx2) {
  213. cpu_string += '2';
  214. }
  215. if (caps.fma || caps.fma4) {
  216. cpu_string += " | FMA";
  217. }
  218. }
  219. LOG_INFO(Frontend, "Host CPU: {}", cpu_string);
  220. #endif
  221. LOG_INFO(Frontend, "Host OS: {}", QSysInfo::prettyProductName().toStdString());
  222. LOG_INFO(Frontend, "Host RAM: {:.2f} GB",
  223. Common::GetMemInfo().TotalPhysicalMemory / 1024.0f / 1024 / 1024);
  224. LOG_INFO(Frontend, "Host Swap: {:.2f} GB",
  225. Common::GetMemInfo().TotalSwapMemory / 1024.0f / 1024 / 1024);
  226. UpdateWindowTitle();
  227. show();
  228. Core::System::GetInstance().SetContentProvider(
  229. std::make_unique<FileSys::ContentProviderUnion>());
  230. Core::System::GetInstance().RegisterContentProvider(
  231. FileSys::ContentProviderUnionSlot::FrontendManual, provider.get());
  232. Core::System::GetInstance().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());
  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. Core::System::GetInstance().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, Core::System::GetInstance(),
  387. is_inline, 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, Core::System::GetInstance(), 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);
  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());
  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);
  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. Core::System::GetInstance().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. Core::System::GetInstance().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(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 (!Core::System::GetInstance().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());
  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. Core::System& system{Core::System::GetInstance()};
  1044. system.SetFilesystem(vfs);
  1045. system.SetAppletFrontendSet({
  1046. std::make_unique<QtControllerSelector>(*this), // Controller Selector
  1047. std::make_unique<QtErrorDisplay>(*this), // Error Display
  1048. nullptr, // Parental Controls
  1049. nullptr, // Photo Viewer
  1050. std::make_unique<QtProfileSelector>(*this), // Profile Selector
  1051. std::make_unique<QtSoftwareKeyboard>(*this), // Software Keyboard
  1052. std::make_unique<QtWebBrowser>(*this), // Web Browser
  1053. });
  1054. const Core::System::ResultStatus result{
  1055. system.Load(*render_window, filename.toStdString(), program_id, program_index)};
  1056. const auto drd_callout = (UISettings::values.callout_flags.GetValue() &
  1057. static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  1058. if (result == Core::System::ResultStatus::Success &&
  1059. system.GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  1060. drd_callout) {
  1061. UISettings::values.callout_flags = UISettings::values.callout_flags.GetValue() |
  1062. static_cast<u32>(CalloutFlag::DRDDeprecation);
  1063. QMessageBox::warning(
  1064. this, tr("Warning Outdated Game Format"),
  1065. tr("You are using the deconstructed ROM directory format for this game, which is an "
  1066. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  1067. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  1068. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  1069. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  1070. "wiki</a>. This message will not be shown again."));
  1071. }
  1072. if (result != Core::System::ResultStatus::Success) {
  1073. switch (result) {
  1074. case Core::System::ResultStatus::ErrorGetLoader:
  1075. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  1076. QMessageBox::critical(this, tr("Error while loading ROM!"),
  1077. tr("The ROM format is not supported."));
  1078. break;
  1079. case Core::System::ResultStatus::ErrorVideoCore:
  1080. QMessageBox::critical(
  1081. this, tr("An error occurred initializing the video core."),
  1082. tr("yuzu has encountered an error while running the video core, please see the "
  1083. "log for more details."
  1084. "For more information on accessing the log, please see the following page: "
  1085. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  1086. "to "
  1087. "Upload the Log File</a>."
  1088. "Ensure that you have the latest graphics drivers for your GPU."));
  1089. break;
  1090. default:
  1091. if (result > Core::System::ResultStatus::ErrorLoader) {
  1092. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  1093. const u16 error_id = static_cast<u16>(result) - loader_id;
  1094. const std::string error_code = fmt::format("({:04X}-{:04X})", loader_id, error_id);
  1095. LOG_CRITICAL(Frontend, "Failed to load ROM! {}", error_code);
  1096. const auto title =
  1097. tr("Error while loading ROM! %1", "%1 signifies a numeric error code.")
  1098. .arg(QString::fromStdString(error_code));
  1099. const auto description =
  1100. tr("%1<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the "
  1101. "yuzu quickstart guide</a> to redump your files.<br>You can refer "
  1102. "to the yuzu wiki</a> or the yuzu Discord</a> for help.",
  1103. "%1 signifies an error string.")
  1104. .arg(QString::fromStdString(
  1105. GetResultStatusString(static_cast<Loader::ResultStatus>(error_id))));
  1106. QMessageBox::critical(this, title, description);
  1107. } else {
  1108. QMessageBox::critical(
  1109. this, tr("Error while loading ROM!"),
  1110. tr("An unknown error occurred. Please see the log for more details."));
  1111. }
  1112. break;
  1113. }
  1114. return false;
  1115. }
  1116. game_path = filename;
  1117. system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "Qt");
  1118. return true;
  1119. }
  1120. void GMainWindow::SelectAndSetCurrentUser() {
  1121. QtProfileSelectionDialog dialog(this);
  1122. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1123. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1124. dialog.setWindowModality(Qt::WindowModal);
  1125. if (dialog.exec() == QDialog::Rejected) {
  1126. return;
  1127. }
  1128. Settings::values.current_user = dialog.GetIndex();
  1129. }
  1130. void GMainWindow::BootGame(const QString& filename, u64 program_id, std::size_t program_index,
  1131. StartGameType type) {
  1132. LOG_INFO(Frontend, "yuzu starting...");
  1133. StoreRecentFile(filename); // Put the filename on top of the list
  1134. u64 title_id{0};
  1135. last_filename_booted = filename;
  1136. auto& system = Core::System::GetInstance();
  1137. const auto v_file = Core::GetGameFileFromPath(vfs, filename.toUtf8().constData());
  1138. const auto loader = Loader::GetLoader(system, v_file, program_id, program_index);
  1139. if (loader != nullptr && loader->ReadProgramId(title_id) == Loader::ResultStatus::Success &&
  1140. type == StartGameType::Normal) {
  1141. // Load per game settings
  1142. const auto file_path = std::filesystem::path{filename.toStdU16String()};
  1143. const auto config_file_name = title_id == 0
  1144. ? Common::FS::PathToUTF8String(file_path.filename())
  1145. : fmt::format("{:016X}", title_id);
  1146. Config per_game_config(config_file_name, Config::ConfigType::PerGameConfig);
  1147. }
  1148. ConfigureVibration::SetAllVibrationDevices();
  1149. // Disable fps limit toggle when booting a new title
  1150. Settings::values.disable_fps_limit.SetValue(false);
  1151. // Save configurations
  1152. UpdateUISettings();
  1153. game_list->SaveInterfaceLayout();
  1154. config->Save();
  1155. Settings::LogSettings();
  1156. if (UISettings::values.select_user_on_boot) {
  1157. SelectAndSetCurrentUser();
  1158. }
  1159. if (!LoadROM(filename, program_id, program_index))
  1160. return;
  1161. // Create and start the emulation thread
  1162. emu_thread = std::make_unique<EmuThread>();
  1163. emit EmulationStarting(emu_thread.get());
  1164. emu_thread->start();
  1165. // Register an ExecuteProgram callback such that Core can execute a sub-program
  1166. system.RegisterExecuteProgramCallback(
  1167. [this](std::size_t program_index) { render_window->ExecuteProgram(program_index); });
  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 = [&system, 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. auto& system = Core::System::GetInstance();
  1311. const auto [user_save_size, device_save_size] = [this, &game_path, &program_id, &system] {
  1312. const FileSys::PatchManager pm{program_id, system.GetFileSystemController(),
  1313. system.GetContentProvider()};
  1314. const auto control = pm.GetControlMetadata().first;
  1315. if (control != nullptr) {
  1316. return std::make_pair(control->GetDefaultNormalSaveSize(),
  1317. control->GetDeviceSaveDataSize());
  1318. } else {
  1319. const auto file = Core::GetGameFileFromPath(vfs, game_path);
  1320. const auto loader = Loader::GetLoader(system, file);
  1321. FileSys::NACP nacp{};
  1322. loader->ReadControlData(nacp);
  1323. return std::make_pair(nacp.GetDefaultNormalSaveSize(), nacp.GetDeviceSaveDataSize());
  1324. }
  1325. }();
  1326. const bool has_user_save{user_save_size > 0};
  1327. const bool has_device_save{device_save_size > 0};
  1328. ASSERT_MSG(has_user_save != has_device_save, "Game uses both user and device savedata?");
  1329. switch (target) {
  1330. case GameListOpenTarget::SaveData: {
  1331. open_target = tr("Save Data");
  1332. const auto nand_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir);
  1333. if (has_user_save) {
  1334. // User save data
  1335. const auto select_profile = [this] {
  1336. QtProfileSelectionDialog dialog(this);
  1337. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1338. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1339. dialog.setWindowModality(Qt::WindowModal);
  1340. if (dialog.exec() == QDialog::Rejected) {
  1341. return -1;
  1342. }
  1343. return dialog.GetIndex();
  1344. };
  1345. const auto index = select_profile();
  1346. if (index == -1) {
  1347. return;
  1348. }
  1349. Service::Account::ProfileManager manager;
  1350. const auto user_id = manager.GetUser(static_cast<std::size_t>(index));
  1351. ASSERT(user_id);
  1352. const auto user_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1353. system, FileSys::SaveDataSpaceId::NandUser, FileSys::SaveDataType::SaveData,
  1354. program_id, user_id->uuid, 0);
  1355. path = Common::FS::ConcatPathSafe(nand_dir, user_save_data_path);
  1356. } else {
  1357. // Device save data
  1358. const auto device_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1359. system, FileSys::SaveDataSpaceId::NandUser, FileSys::SaveDataType::SaveData,
  1360. program_id, {}, 0);
  1361. path = Common::FS::ConcatPathSafe(nand_dir, device_save_data_path);
  1362. }
  1363. if (!Common::FS::CreateDirs(path)) {
  1364. LOG_ERROR(Frontend, "Unable to create the directories for save data");
  1365. }
  1366. break;
  1367. }
  1368. case GameListOpenTarget::ModData: {
  1369. open_target = tr("Mod Data");
  1370. path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::LoadDir) /
  1371. fmt::format("{:016X}", program_id);
  1372. break;
  1373. }
  1374. default:
  1375. UNIMPLEMENTED();
  1376. }
  1377. const QString qpath = QString::fromStdString(Common::FS::PathToUTF8String(path));
  1378. const QDir dir(qpath);
  1379. if (!dir.exists()) {
  1380. QMessageBox::warning(this, tr("Error Opening %1 Folder").arg(open_target),
  1381. tr("Folder does not exist!"));
  1382. return;
  1383. }
  1384. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target.toStdString(),
  1385. program_id);
  1386. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  1387. }
  1388. void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
  1389. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1390. const auto shader_cache_folder_path{shader_cache_dir / fmt::format("{:016x}", program_id)};
  1391. if (!Common::FS::CreateDirs(shader_cache_folder_path)) {
  1392. QMessageBox::warning(this, tr("Error Opening Transferable Shader Cache"),
  1393. tr("Filed to create the shader cache directory for this title."));
  1394. return;
  1395. }
  1396. const auto shader_path_string{Common::FS::PathToUTF8String(shader_cache_folder_path)};
  1397. const auto qt_shader_cache_path = QString::fromStdString(shader_path_string);
  1398. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_shader_cache_path));
  1399. }
  1400. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  1401. std::size_t out = 0;
  1402. for (const auto& subdir : dir->GetSubdirectories()) {
  1403. out += 1 + CalculateRomFSEntrySize(subdir, full);
  1404. }
  1405. return out + (full ? dir->GetFiles().size() : 0);
  1406. }
  1407. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  1408. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  1409. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  1410. return false;
  1411. if (dialog.wasCanceled())
  1412. return false;
  1413. if (full) {
  1414. for (const auto& file : src->GetFiles()) {
  1415. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  1416. if (!FileSys::VfsRawCopy(file, out, block_size))
  1417. return false;
  1418. dialog.setValue(dialog.value() + 1);
  1419. if (dialog.wasCanceled())
  1420. return false;
  1421. }
  1422. }
  1423. for (const auto& dir : src->GetSubdirectories()) {
  1424. const auto out = dest->CreateSubdirectory(dir->GetName());
  1425. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  1426. return false;
  1427. dialog.setValue(dialog.value() + 1);
  1428. if (dialog.wasCanceled())
  1429. return false;
  1430. }
  1431. return true;
  1432. }
  1433. void GMainWindow::OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type) {
  1434. const QString entry_type = [this, type] {
  1435. switch (type) {
  1436. case InstalledEntryType::Game:
  1437. return tr("Contents");
  1438. case InstalledEntryType::Update:
  1439. return tr("Update");
  1440. case InstalledEntryType::AddOnContent:
  1441. return tr("DLC");
  1442. default:
  1443. return QString{};
  1444. }
  1445. }();
  1446. if (QMessageBox::question(
  1447. this, tr("Remove Entry"), tr("Remove Installed Game %1?").arg(entry_type),
  1448. QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
  1449. return;
  1450. }
  1451. switch (type) {
  1452. case InstalledEntryType::Game:
  1453. RemoveBaseContent(program_id, entry_type);
  1454. [[fallthrough]];
  1455. case InstalledEntryType::Update:
  1456. RemoveUpdateContent(program_id, entry_type);
  1457. if (type != InstalledEntryType::Game) {
  1458. break;
  1459. }
  1460. [[fallthrough]];
  1461. case InstalledEntryType::AddOnContent:
  1462. RemoveAddOnContent(program_id, entry_type);
  1463. break;
  1464. }
  1465. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  1466. "game_list");
  1467. game_list->PopulateAsync(UISettings::values.game_dirs);
  1468. }
  1469. void GMainWindow::RemoveBaseContent(u64 program_id, const QString& entry_type) {
  1470. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1471. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(program_id) ||
  1472. fs_controller.GetSDMCContents()->RemoveExistingEntry(program_id);
  1473. if (res) {
  1474. QMessageBox::information(this, tr("Successfully Removed"),
  1475. tr("Successfully removed the installed base game."));
  1476. } else {
  1477. QMessageBox::warning(
  1478. this, tr("Error Removing %1").arg(entry_type),
  1479. tr("The base game is not installed in the NAND and cannot be removed."));
  1480. }
  1481. }
  1482. void GMainWindow::RemoveUpdateContent(u64 program_id, const QString& entry_type) {
  1483. const auto update_id = program_id | 0x800;
  1484. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1485. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(update_id) ||
  1486. fs_controller.GetSDMCContents()->RemoveExistingEntry(update_id);
  1487. if (res) {
  1488. QMessageBox::information(this, tr("Successfully Removed"),
  1489. tr("Successfully removed the installed update."));
  1490. } else {
  1491. QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
  1492. tr("There is no update installed for this title."));
  1493. }
  1494. }
  1495. void GMainWindow::RemoveAddOnContent(u64 program_id, const QString& entry_type) {
  1496. u32 count{};
  1497. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1498. const auto dlc_entries = Core::System::GetInstance().GetContentProvider().ListEntriesFilter(
  1499. FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1500. for (const auto& entry : dlc_entries) {
  1501. if (FileSys::GetBaseTitleID(entry.title_id) == program_id) {
  1502. const auto res =
  1503. fs_controller.GetUserNANDContents()->RemoveExistingEntry(entry.title_id) ||
  1504. fs_controller.GetSDMCContents()->RemoveExistingEntry(entry.title_id);
  1505. if (res) {
  1506. ++count;
  1507. }
  1508. }
  1509. }
  1510. if (count == 0) {
  1511. QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
  1512. tr("There are no DLC installed for this title."));
  1513. return;
  1514. }
  1515. QMessageBox::information(this, tr("Successfully Removed"),
  1516. tr("Successfully removed %1 installed DLC.").arg(count));
  1517. }
  1518. void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target,
  1519. const std::string& game_path) {
  1520. const QString question = [this, target] {
  1521. switch (target) {
  1522. case GameListRemoveTarget::GlShaderCache:
  1523. return tr("Delete OpenGL Transferable Shader Cache?");
  1524. case GameListRemoveTarget::VkShaderCache:
  1525. return tr("Delete Vulkan Transferable Shader Cache?");
  1526. case GameListRemoveTarget::AllShaderCache:
  1527. return tr("Delete All Transferable Shader Caches?");
  1528. case GameListRemoveTarget::CustomConfiguration:
  1529. return tr("Remove Custom Game Configuration?");
  1530. default:
  1531. return QString{};
  1532. }
  1533. }();
  1534. if (QMessageBox::question(this, tr("Remove File"), question, QMessageBox::Yes | QMessageBox::No,
  1535. QMessageBox::No) != QMessageBox::Yes) {
  1536. return;
  1537. }
  1538. switch (target) {
  1539. case GameListRemoveTarget::GlShaderCache:
  1540. case GameListRemoveTarget::VkShaderCache:
  1541. RemoveTransferableShaderCache(program_id, target);
  1542. break;
  1543. case GameListRemoveTarget::AllShaderCache:
  1544. RemoveAllTransferableShaderCaches(program_id);
  1545. break;
  1546. case GameListRemoveTarget::CustomConfiguration:
  1547. RemoveCustomConfiguration(program_id, game_path);
  1548. break;
  1549. }
  1550. }
  1551. void GMainWindow::RemoveTransferableShaderCache(u64 program_id, GameListRemoveTarget target) {
  1552. const auto target_file_name = [target] {
  1553. switch (target) {
  1554. case GameListRemoveTarget::GlShaderCache:
  1555. return "opengl.bin";
  1556. case GameListRemoveTarget::VkShaderCache:
  1557. return "vulkan.bin";
  1558. default:
  1559. return "";
  1560. }
  1561. }();
  1562. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1563. const auto shader_cache_folder_path = shader_cache_dir / fmt::format("{:016x}", program_id);
  1564. const auto target_file = shader_cache_folder_path / target_file_name;
  1565. if (!Common::FS::Exists(target_file)) {
  1566. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1567. tr("A shader cache for this title does not exist."));
  1568. return;
  1569. }
  1570. if (Common::FS::RemoveFile(target_file)) {
  1571. QMessageBox::information(this, tr("Successfully Removed"),
  1572. tr("Successfully removed the transferable shader cache."));
  1573. } else {
  1574. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1575. tr("Failed to remove the transferable shader cache."));
  1576. }
  1577. }
  1578. void GMainWindow::RemoveAllTransferableShaderCaches(u64 program_id) {
  1579. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1580. const auto program_shader_cache_dir = shader_cache_dir / fmt::format("{:016x}", program_id);
  1581. if (!Common::FS::Exists(program_shader_cache_dir)) {
  1582. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  1583. tr("A shader cache for this title does not exist."));
  1584. return;
  1585. }
  1586. if (Common::FS::RemoveDirRecursively(program_shader_cache_dir)) {
  1587. QMessageBox::information(this, tr("Successfully Removed"),
  1588. tr("Successfully removed the transferable shader caches."));
  1589. } else {
  1590. QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"),
  1591. tr("Failed to remove the transferable shader cache directory."));
  1592. }
  1593. }
  1594. void GMainWindow::RemoveCustomConfiguration(u64 program_id, const std::string& game_path) {
  1595. const auto file_path = std::filesystem::path(Common::FS::ToU8String(game_path));
  1596. const auto config_file_name =
  1597. program_id == 0 ? Common::FS::PathToUTF8String(file_path.filename()).append(".ini")
  1598. : fmt::format("{:016X}.ini", program_id);
  1599. const auto custom_config_file_path =
  1600. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom" / config_file_name;
  1601. if (!Common::FS::Exists(custom_config_file_path)) {
  1602. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1603. tr("A custom configuration for this title does not exist."));
  1604. return;
  1605. }
  1606. if (Common::FS::RemoveFile(custom_config_file_path)) {
  1607. QMessageBox::information(this, tr("Successfully Removed"),
  1608. tr("Successfully removed the custom game configuration."));
  1609. } else {
  1610. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1611. tr("Failed to remove the custom game configuration."));
  1612. }
  1613. }
  1614. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path,
  1615. DumpRomFSTarget target) {
  1616. const auto failed = [this] {
  1617. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1618. tr("There was an error copying the RomFS files or the user "
  1619. "cancelled the operation."));
  1620. };
  1621. auto& system = Core::System::GetInstance();
  1622. const auto loader = Loader::GetLoader(system, vfs->OpenFile(game_path, FileSys::Mode::Read));
  1623. if (loader == nullptr) {
  1624. failed();
  1625. return;
  1626. }
  1627. FileSys::VirtualFile file;
  1628. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  1629. failed();
  1630. return;
  1631. }
  1632. const auto& installed = system.GetContentProvider();
  1633. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  1634. if (!romfs_title_id) {
  1635. failed();
  1636. return;
  1637. }
  1638. const auto dump_dir =
  1639. target == DumpRomFSTarget::Normal
  1640. ? Common::FS::GetYuzuPath(Common::FS::YuzuPath::DumpDir)
  1641. : Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "atmosphere" / "contents";
  1642. const auto romfs_dir = fmt::format("{:016X}/romfs", *romfs_title_id);
  1643. const auto path = Common::FS::PathToUTF8String(dump_dir / romfs_dir);
  1644. FileSys::VirtualFile romfs;
  1645. if (*romfs_title_id == program_id) {
  1646. const u64 ivfc_offset = loader->ReadRomFSIVFCOffset();
  1647. const FileSys::PatchManager pm{program_id, system.GetFileSystemController(), installed};
  1648. romfs =
  1649. pm.PatchRomFS(file, ivfc_offset, FileSys::ContentRecordType::Program, nullptr, false);
  1650. } else {
  1651. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  1652. }
  1653. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  1654. if (extracted == nullptr) {
  1655. failed();
  1656. return;
  1657. }
  1658. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  1659. if (out == nullptr) {
  1660. failed();
  1661. vfs->DeleteDirectory(path);
  1662. return;
  1663. }
  1664. bool ok = false;
  1665. const QStringList selections{tr("Full"), tr("Skeleton")};
  1666. const auto res = QInputDialog::getItem(
  1667. this, tr("Select RomFS Dump Mode"),
  1668. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  1669. "files into the new directory while <br>skeleton will only create the directory "
  1670. "structure."),
  1671. selections, 0, false, &ok);
  1672. if (!ok) {
  1673. failed();
  1674. vfs->DeleteDirectory(path);
  1675. return;
  1676. }
  1677. const auto full = res == selections.constFirst();
  1678. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  1679. // The minimum required space is the size of the extracted RomFS + 1 GiB
  1680. const auto minimum_free_space = extracted->GetSize() + 0x40000000;
  1681. if (full && Common::FS::GetFreeSpaceSize(path) < minimum_free_space) {
  1682. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1683. tr("There is not enough free space at %1 to extract the RomFS. Please "
  1684. "free up space or select a different dump directory at "
  1685. "Emulation > Configure > System > Filesystem > Dump Root")
  1686. .arg(QString::fromStdString(path)));
  1687. return;
  1688. }
  1689. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  1690. static_cast<s32>(entry_size), this);
  1691. progress.setWindowModality(Qt::WindowModal);
  1692. progress.setMinimumDuration(100);
  1693. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  1694. progress.close();
  1695. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  1696. tr("The operation completed successfully."));
  1697. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  1698. } else {
  1699. progress.close();
  1700. failed();
  1701. vfs->DeleteDirectory(path);
  1702. }
  1703. }
  1704. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  1705. QClipboard* clipboard = QGuiApplication::clipboard();
  1706. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  1707. }
  1708. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  1709. const CompatibilityList& compatibility_list) {
  1710. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  1711. QString directory;
  1712. if (it != compatibility_list.end()) {
  1713. directory = it->second.second;
  1714. }
  1715. QDesktopServices::openUrl(QUrl(QStringLiteral("https://yuzu-emu.org/game/") + directory));
  1716. }
  1717. void GMainWindow::OnGameListOpenDirectory(const QString& directory) {
  1718. std::filesystem::path fs_path;
  1719. if (directory == QStringLiteral("SDMC")) {
  1720. fs_path =
  1721. Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "Nintendo/Contents/registered";
  1722. } else if (directory == QStringLiteral("UserNAND")) {
  1723. fs_path =
  1724. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "user/Contents/registered";
  1725. } else if (directory == QStringLiteral("SysNAND")) {
  1726. fs_path =
  1727. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "system/Contents/registered";
  1728. } else {
  1729. fs_path = directory.toStdString();
  1730. }
  1731. const auto qt_path = QString::fromStdString(Common::FS::PathToUTF8String(fs_path));
  1732. if (!Common::FS::IsDir(fs_path)) {
  1733. QMessageBox::critical(this, tr("Error Opening %1").arg(qt_path),
  1734. tr("Folder does not exist!"));
  1735. return;
  1736. }
  1737. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_path));
  1738. }
  1739. void GMainWindow::OnGameListAddDirectory() {
  1740. const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1741. if (dir_path.isEmpty()) {
  1742. return;
  1743. }
  1744. UISettings::GameDir game_dir{dir_path, false, true};
  1745. if (!UISettings::values.game_dirs.contains(game_dir)) {
  1746. UISettings::values.game_dirs.append(game_dir);
  1747. game_list->PopulateAsync(UISettings::values.game_dirs);
  1748. } else {
  1749. LOG_WARNING(Frontend, "Selected directory is already in the game list");
  1750. }
  1751. }
  1752. void GMainWindow::OnGameListShowList(bool show) {
  1753. if (emulation_running && ui.action_Single_Window_Mode->isChecked())
  1754. return;
  1755. game_list->setVisible(show);
  1756. game_list_placeholder->setVisible(!show);
  1757. };
  1758. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  1759. u64 title_id{};
  1760. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  1761. const auto loader = Loader::GetLoader(Core::System::GetInstance(), v_file);
  1762. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  1763. QMessageBox::information(this, tr("Properties"),
  1764. tr("The game properties could not be loaded."));
  1765. return;
  1766. }
  1767. OpenPerGameConfiguration(title_id, file);
  1768. }
  1769. void GMainWindow::OnMenuLoadFile() {
  1770. const QString extensions =
  1771. QStringLiteral("*.")
  1772. .append(GameList::supported_file_extensions.join(QStringLiteral(" *.")))
  1773. .append(QStringLiteral(" main"));
  1774. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  1775. "%1 is an identifier for the Switch executable file extensions.")
  1776. .arg(extensions);
  1777. const QString filename = QFileDialog::getOpenFileName(
  1778. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  1779. if (filename.isEmpty()) {
  1780. return;
  1781. }
  1782. UISettings::values.roms_path = QFileInfo(filename).path();
  1783. BootGame(filename);
  1784. }
  1785. void GMainWindow::OnMenuLoadFolder() {
  1786. const QString dir_path =
  1787. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  1788. if (dir_path.isNull()) {
  1789. return;
  1790. }
  1791. const QDir dir{dir_path};
  1792. const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files);
  1793. if (matching_main.size() == 1) {
  1794. BootGame(dir.path() + QDir::separator() + matching_main[0]);
  1795. } else {
  1796. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  1797. tr("The directory you have selected does not contain a 'main' file."));
  1798. }
  1799. }
  1800. void GMainWindow::IncrementInstallProgress() {
  1801. install_progress->setValue(install_progress->value() + 1);
  1802. }
  1803. void GMainWindow::OnMenuInstallToNAND() {
  1804. const QString file_filter =
  1805. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  1806. "(*.nca);;Nintendo Submission Package (*.nsp);;NX Cartridge "
  1807. "Image (*.xci)");
  1808. QStringList filenames = QFileDialog::getOpenFileNames(
  1809. this, tr("Install Files"), UISettings::values.roms_path, file_filter);
  1810. if (filenames.isEmpty()) {
  1811. return;
  1812. }
  1813. InstallDialog installDialog(this, filenames);
  1814. if (installDialog.exec() == QDialog::Rejected) {
  1815. return;
  1816. }
  1817. const QStringList files = installDialog.GetFiles();
  1818. if (files.isEmpty()) {
  1819. return;
  1820. }
  1821. int remaining = filenames.size();
  1822. // This would only overflow above 2^43 bytes (8.796 TB)
  1823. int total_size = 0;
  1824. for (const QString& file : files) {
  1825. total_size += static_cast<int>(QFile(file).size() / 0x1000);
  1826. }
  1827. if (total_size < 0) {
  1828. LOG_CRITICAL(Frontend, "Attempting to install too many files, aborting.");
  1829. return;
  1830. }
  1831. QStringList new_files{}; // Newly installed files that do not yet exist in the NAND
  1832. QStringList overwritten_files{}; // Files that overwrote those existing in the NAND
  1833. QStringList failed_files{}; // Files that failed to install due to errors
  1834. bool detected_base_install{}; // Whether a base game was attempted to be installed
  1835. ui.action_Install_File_NAND->setEnabled(false);
  1836. install_progress = new QProgressDialog(QString{}, tr("Cancel"), 0, total_size, this);
  1837. install_progress->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint &
  1838. ~Qt::WindowMaximizeButtonHint);
  1839. install_progress->setAttribute(Qt::WA_DeleteOnClose, true);
  1840. install_progress->setFixedWidth(installDialog.GetMinimumWidth() + 40);
  1841. install_progress->show();
  1842. for (const QString& file : files) {
  1843. install_progress->setWindowTitle(tr("%n file(s) remaining", "", remaining));
  1844. install_progress->setLabelText(
  1845. tr("Installing file \"%1\"...").arg(QFileInfo(file).fileName()));
  1846. QFuture<InstallResult> future;
  1847. InstallResult result;
  1848. if (file.endsWith(QStringLiteral("xci"), Qt::CaseInsensitive) ||
  1849. file.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1850. future = QtConcurrent::run([this, &file] { return InstallNSPXCI(file); });
  1851. while (!future.isFinished()) {
  1852. QCoreApplication::processEvents();
  1853. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1854. }
  1855. result = future.result();
  1856. } else {
  1857. result = InstallNCA(file);
  1858. }
  1859. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1860. switch (result) {
  1861. case InstallResult::Success:
  1862. new_files.append(QFileInfo(file).fileName());
  1863. break;
  1864. case InstallResult::Overwrite:
  1865. overwritten_files.append(QFileInfo(file).fileName());
  1866. break;
  1867. case InstallResult::Failure:
  1868. failed_files.append(QFileInfo(file).fileName());
  1869. break;
  1870. case InstallResult::BaseInstallAttempted:
  1871. failed_files.append(QFileInfo(file).fileName());
  1872. detected_base_install = true;
  1873. break;
  1874. }
  1875. --remaining;
  1876. }
  1877. install_progress->close();
  1878. if (detected_base_install) {
  1879. QMessageBox::warning(
  1880. this, tr("Install Results"),
  1881. tr("To avoid possible conflicts, we discourage users from installing base games to the "
  1882. "NAND.\nPlease, only use this feature to install updates and DLC."));
  1883. }
  1884. const QString install_results =
  1885. (new_files.isEmpty() ? QString{}
  1886. : tr("%n file(s) were newly installed\n", "", new_files.size())) +
  1887. (overwritten_files.isEmpty()
  1888. ? QString{}
  1889. : tr("%n file(s) were overwritten\n", "", overwritten_files.size())) +
  1890. (failed_files.isEmpty() ? QString{}
  1891. : tr("%n file(s) failed to install\n", "", failed_files.size()));
  1892. QMessageBox::information(this, tr("Install Results"), install_results);
  1893. Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  1894. "game_list");
  1895. game_list->PopulateAsync(UISettings::values.game_dirs);
  1896. ui.action_Install_File_NAND->setEnabled(true);
  1897. }
  1898. InstallResult GMainWindow::InstallNSPXCI(const QString& filename) {
  1899. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1900. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1901. if (src == nullptr || dest == nullptr) {
  1902. return false;
  1903. }
  1904. if (!dest->Resize(src->GetSize())) {
  1905. return false;
  1906. }
  1907. std::array<u8, 0x1000> buffer{};
  1908. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1909. if (install_progress->wasCanceled()) {
  1910. dest->Resize(0);
  1911. return false;
  1912. }
  1913. emit UpdateInstallProgress();
  1914. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1915. dest->Write(buffer.data(), read, i);
  1916. }
  1917. return true;
  1918. };
  1919. std::shared_ptr<FileSys::NSP> nsp;
  1920. if (filename.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1921. nsp = std::make_shared<FileSys::NSP>(
  1922. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1923. if (nsp->IsExtractedType()) {
  1924. return InstallResult::Failure;
  1925. }
  1926. } else {
  1927. const auto xci = std::make_shared<FileSys::XCI>(
  1928. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1929. nsp = xci->GetSecurePartitionNSP();
  1930. }
  1931. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  1932. return InstallResult::Failure;
  1933. }
  1934. const auto res =
  1935. Core::System::GetInstance().GetFileSystemController().GetUserNANDContents()->InstallEntry(
  1936. *nsp, true, qt_raw_copy);
  1937. switch (res) {
  1938. case FileSys::InstallResult::Success:
  1939. return InstallResult::Success;
  1940. case FileSys::InstallResult::OverwriteExisting:
  1941. return InstallResult::Overwrite;
  1942. case FileSys::InstallResult::ErrorBaseInstall:
  1943. return InstallResult::BaseInstallAttempted;
  1944. default:
  1945. return InstallResult::Failure;
  1946. }
  1947. }
  1948. InstallResult GMainWindow::InstallNCA(const QString& filename) {
  1949. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1950. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1951. if (src == nullptr || dest == nullptr) {
  1952. return false;
  1953. }
  1954. if (!dest->Resize(src->GetSize())) {
  1955. return false;
  1956. }
  1957. std::array<u8, 0x1000> buffer{};
  1958. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1959. if (install_progress->wasCanceled()) {
  1960. dest->Resize(0);
  1961. return false;
  1962. }
  1963. emit UpdateInstallProgress();
  1964. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1965. dest->Write(buffer.data(), read, i);
  1966. }
  1967. return true;
  1968. };
  1969. const auto nca =
  1970. std::make_shared<FileSys::NCA>(vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1971. const auto id = nca->GetStatus();
  1972. // Game updates necessary are missing base RomFS
  1973. if (id != Loader::ResultStatus::Success &&
  1974. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  1975. return InstallResult::Failure;
  1976. }
  1977. const QStringList tt_options{tr("System Application"),
  1978. tr("System Archive"),
  1979. tr("System Application Update"),
  1980. tr("Firmware Package (Type A)"),
  1981. tr("Firmware Package (Type B)"),
  1982. tr("Game"),
  1983. tr("Game Update"),
  1984. tr("Game DLC"),
  1985. tr("Delta Title")};
  1986. bool ok;
  1987. const auto item = QInputDialog::getItem(
  1988. this, tr("Select NCA Install Type..."),
  1989. tr("Please select the type of title you would like to install this NCA as:\n(In "
  1990. "most instances, the default 'Game' is fine.)"),
  1991. tt_options, 5, false, &ok);
  1992. auto index = tt_options.indexOf(item);
  1993. if (!ok || index == -1) {
  1994. QMessageBox::warning(this, tr("Failed to Install"),
  1995. tr("The title type you selected for the NCA is invalid."));
  1996. return InstallResult::Failure;
  1997. }
  1998. // If index is equal to or past Game, add the jump in TitleType.
  1999. if (index >= 5) {
  2000. index += static_cast<size_t>(FileSys::TitleType::Application) -
  2001. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  2002. }
  2003. FileSys::InstallResult res;
  2004. if (index >= static_cast<s32>(FileSys::TitleType::Application)) {
  2005. res = Core::System::GetInstance()
  2006. .GetFileSystemController()
  2007. .GetUserNANDContents()
  2008. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  2009. } else {
  2010. res = Core::System::GetInstance()
  2011. .GetFileSystemController()
  2012. .GetSystemNANDContents()
  2013. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  2014. }
  2015. if (res == FileSys::InstallResult::Success) {
  2016. return InstallResult::Success;
  2017. } else if (res == FileSys::InstallResult::OverwriteExisting) {
  2018. return InstallResult::Overwrite;
  2019. } else {
  2020. return InstallResult::Failure;
  2021. }
  2022. }
  2023. void GMainWindow::OnMenuRecentFile() {
  2024. QAction* action = qobject_cast<QAction*>(sender());
  2025. assert(action);
  2026. const QString filename = action->data().toString();
  2027. if (QFileInfo::exists(filename)) {
  2028. BootGame(filename);
  2029. } else {
  2030. // Display an error message and remove the file from the list.
  2031. QMessageBox::information(this, tr("File not found"),
  2032. tr("File \"%1\" not found").arg(filename));
  2033. UISettings::values.recent_files.removeOne(filename);
  2034. UpdateRecentFiles();
  2035. }
  2036. }
  2037. void GMainWindow::OnStartGame() {
  2038. PreventOSSleep();
  2039. emu_thread->SetRunning(true);
  2040. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  2041. ui.action_Start->setEnabled(false);
  2042. ui.action_Start->setText(tr("&Continue"));
  2043. ui.action_Pause->setEnabled(true);
  2044. ui.action_Stop->setEnabled(true);
  2045. ui.action_Restart->setEnabled(true);
  2046. ui.action_Configure_Current_Game->setEnabled(true);
  2047. ui.action_Report_Compatibility->setEnabled(true);
  2048. discord_rpc->Update();
  2049. ui.action_Load_Amiibo->setEnabled(true);
  2050. ui.action_Capture_Screenshot->setEnabled(true);
  2051. }
  2052. void GMainWindow::OnPauseGame() {
  2053. emu_thread->SetRunning(false);
  2054. ui.action_Start->setEnabled(true);
  2055. ui.action_Pause->setEnabled(false);
  2056. ui.action_Stop->setEnabled(true);
  2057. ui.action_Capture_Screenshot->setEnabled(false);
  2058. AllowOSSleep();
  2059. }
  2060. void GMainWindow::OnStopGame() {
  2061. auto& system{Core::System::GetInstance()};
  2062. if (system.GetExitLock() && !ConfirmForceLockedExit()) {
  2063. return;
  2064. }
  2065. ShutdownGame();
  2066. Settings::RestoreGlobalState(system.IsPoweredOn());
  2067. UpdateStatusButtons();
  2068. }
  2069. void GMainWindow::OnLoadComplete() {
  2070. loading_screen->OnLoadComplete();
  2071. }
  2072. void GMainWindow::OnExecuteProgram(std::size_t program_index) {
  2073. ShutdownGame();
  2074. BootGame(last_filename_booted, 0, program_index);
  2075. }
  2076. void GMainWindow::ErrorDisplayDisplayError(QString error_code, QString error_text) {
  2077. OverlayDialog dialog(render_window, Core::System::GetInstance(), error_code, error_text,
  2078. QString{}, tr("OK"), Qt::AlignLeft | Qt::AlignVCenter);
  2079. dialog.exec();
  2080. emit ErrorDisplayFinished();
  2081. }
  2082. void GMainWindow::OnMenuReportCompatibility() {
  2083. if (!Settings::values.yuzu_token.GetValue().empty() &&
  2084. !Settings::values.yuzu_username.GetValue().empty()) {
  2085. CompatDB compatdb{this};
  2086. compatdb.exec();
  2087. } else {
  2088. QMessageBox::critical(
  2089. this, tr("Missing yuzu Account"),
  2090. tr("In order to submit a game compatibility test case, you must link your yuzu "
  2091. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  2092. "&gt; "
  2093. "Web."));
  2094. }
  2095. }
  2096. void GMainWindow::OpenURL(const QUrl& url) {
  2097. const bool open = QDesktopServices::openUrl(url);
  2098. if (!open) {
  2099. QMessageBox::warning(this, tr("Error opening URL"),
  2100. tr("Unable to open the URL \"%1\".").arg(url.toString()));
  2101. }
  2102. }
  2103. void GMainWindow::OnOpenModsPage() {
  2104. OpenURL(QUrl(QStringLiteral("https://github.com/yuzu-emu/yuzu/wiki/Switch-Mods")));
  2105. }
  2106. void GMainWindow::OnOpenQuickstartGuide() {
  2107. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/help/quickstart/")));
  2108. }
  2109. void GMainWindow::OnOpenFAQ() {
  2110. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/wiki/faq/")));
  2111. }
  2112. void GMainWindow::ToggleFullscreen() {
  2113. if (!emulation_running) {
  2114. return;
  2115. }
  2116. if (ui.action_Fullscreen->isChecked()) {
  2117. ShowFullscreen();
  2118. } else {
  2119. HideFullscreen();
  2120. }
  2121. }
  2122. void GMainWindow::ShowFullscreen() {
  2123. if (ui.action_Single_Window_Mode->isChecked()) {
  2124. UISettings::values.geometry = saveGeometry();
  2125. ui.menubar->hide();
  2126. statusBar()->hide();
  2127. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2128. showFullScreen();
  2129. return;
  2130. }
  2131. hide();
  2132. setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
  2133. const auto screen_geometry = QApplication::desktop()->screenGeometry(this);
  2134. setGeometry(screen_geometry.x(), screen_geometry.y(), screen_geometry.width(),
  2135. screen_geometry.height() + 1);
  2136. raise();
  2137. showNormal();
  2138. } else {
  2139. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2140. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2141. render_window->showFullScreen();
  2142. return;
  2143. }
  2144. render_window->hide();
  2145. render_window->setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
  2146. const auto screen_geometry = QApplication::desktop()->screenGeometry(this);
  2147. render_window->setGeometry(screen_geometry.x(), screen_geometry.y(),
  2148. screen_geometry.width(), screen_geometry.height() + 1);
  2149. render_window->raise();
  2150. render_window->showNormal();
  2151. }
  2152. }
  2153. void GMainWindow::HideFullscreen() {
  2154. if (ui.action_Single_Window_Mode->isChecked()) {
  2155. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2156. showNormal();
  2157. restoreGeometry(UISettings::values.geometry);
  2158. } else {
  2159. hide();
  2160. setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2161. restoreGeometry(UISettings::values.geometry);
  2162. raise();
  2163. show();
  2164. }
  2165. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  2166. ui.menubar->show();
  2167. } else {
  2168. if (Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive) {
  2169. render_window->showNormal();
  2170. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2171. } else {
  2172. render_window->hide();
  2173. render_window->setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2174. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2175. render_window->raise();
  2176. render_window->show();
  2177. }
  2178. }
  2179. }
  2180. void GMainWindow::ToggleWindowMode() {
  2181. if (ui.action_Single_Window_Mode->isChecked()) {
  2182. // Render in the main window...
  2183. render_window->BackupGeometry();
  2184. ui.horizontalLayout->addWidget(render_window);
  2185. render_window->setFocusPolicy(Qt::StrongFocus);
  2186. if (emulation_running) {
  2187. render_window->setVisible(true);
  2188. render_window->setFocus();
  2189. game_list->hide();
  2190. }
  2191. } else {
  2192. // Render in a separate window...
  2193. ui.horizontalLayout->removeWidget(render_window);
  2194. render_window->setParent(nullptr);
  2195. render_window->setFocusPolicy(Qt::NoFocus);
  2196. if (emulation_running) {
  2197. render_window->setVisible(true);
  2198. render_window->RestoreGeometry();
  2199. game_list->show();
  2200. }
  2201. }
  2202. }
  2203. void GMainWindow::ResetWindowSize720() {
  2204. const auto aspect_ratio = Layout::EmulationAspectRatio(
  2205. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  2206. static_cast<float>(Layout::ScreenUndocked::Height) / Layout::ScreenUndocked::Width);
  2207. if (!ui.action_Single_Window_Mode->isChecked()) {
  2208. render_window->resize(Layout::ScreenUndocked::Height / aspect_ratio,
  2209. Layout::ScreenUndocked::Height);
  2210. } else {
  2211. resize(Layout::ScreenUndocked::Height / aspect_ratio,
  2212. Layout::ScreenUndocked::Height + menuBar()->height() +
  2213. (ui.action_Show_Status_Bar->isChecked() ? statusBar()->height() : 0));
  2214. }
  2215. }
  2216. void GMainWindow::ResetWindowSize1080() {
  2217. const auto aspect_ratio = Layout::EmulationAspectRatio(
  2218. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  2219. static_cast<float>(Layout::ScreenDocked::Height) / Layout::ScreenDocked::Width);
  2220. if (!ui.action_Single_Window_Mode->isChecked()) {
  2221. render_window->resize(Layout::ScreenDocked::Height / aspect_ratio,
  2222. Layout::ScreenDocked::Height);
  2223. } else {
  2224. resize(Layout::ScreenDocked::Height / aspect_ratio,
  2225. Layout::ScreenDocked::Height + menuBar()->height() +
  2226. (ui.action_Show_Status_Bar->isChecked() ? statusBar()->height() : 0));
  2227. }
  2228. }
  2229. void GMainWindow::OnConfigure() {
  2230. const auto old_theme = UISettings::values.theme;
  2231. const bool old_discord_presence = UISettings::values.enable_discord_presence.GetValue();
  2232. ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get());
  2233. connect(&configure_dialog, &ConfigureDialog::LanguageChanged, this,
  2234. &GMainWindow::OnLanguageChanged);
  2235. const auto result = configure_dialog.exec();
  2236. if (result != QDialog::Accepted && !UISettings::values.configuration_applied &&
  2237. !UISettings::values.reset_to_defaults) {
  2238. // Runs if the user hit Cancel or closed the window, and did not ever press the Apply button
  2239. // or `Reset to Defaults` button
  2240. return;
  2241. } else if (result == QDialog::Accepted) {
  2242. // Only apply new changes if user hit Okay
  2243. // This is here to avoid applying changes if the user hit Apply, made some changes, then hit
  2244. // Cancel
  2245. configure_dialog.ApplyConfiguration();
  2246. } else if (UISettings::values.reset_to_defaults) {
  2247. LOG_INFO(Frontend, "Resetting all settings to defaults");
  2248. if (!Common::FS::RemoveFile(config->GetConfigFilePath())) {
  2249. LOG_WARNING(Frontend, "Failed to remove configuration file");
  2250. }
  2251. if (!Common::FS::RemoveDirContentsRecursively(
  2252. Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) / "custom")) {
  2253. LOG_WARNING(Frontend, "Failed to remove custom configuration files");
  2254. }
  2255. if (!Common::FS::RemoveDirRecursively(
  2256. Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) / "game_list")) {
  2257. LOG_WARNING(Frontend, "Failed to remove game metadata cache files");
  2258. }
  2259. // Explicitly save the game directories, since reinitializing config does not explicitly do
  2260. // so.
  2261. QVector<UISettings::GameDir> old_game_dirs = std::move(UISettings::values.game_dirs);
  2262. QVector<u64> old_favorited_ids = std::move(UISettings::values.favorited_ids);
  2263. Settings::values.disabled_addons.clear();
  2264. config = std::make_unique<Config>();
  2265. UISettings::values.reset_to_defaults = false;
  2266. UISettings::values.game_dirs = std::move(old_game_dirs);
  2267. UISettings::values.favorited_ids = std::move(old_favorited_ids);
  2268. InitializeRecentFileMenuActions();
  2269. SetDefaultUIGeometry();
  2270. RestoreUIState();
  2271. ShowTelemetryCallout();
  2272. }
  2273. controller_dialog->refreshConfiguration();
  2274. InitializeHotkeys();
  2275. if (UISettings::values.theme != old_theme) {
  2276. UpdateUITheme();
  2277. }
  2278. if (UISettings::values.enable_discord_presence.GetValue() != old_discord_presence) {
  2279. SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue());
  2280. }
  2281. emit UpdateThemedIcons();
  2282. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2283. if (reload) {
  2284. game_list->PopulateAsync(UISettings::values.game_dirs);
  2285. }
  2286. UISettings::values.configuration_applied = false;
  2287. config->Save();
  2288. if ((UISettings::values.hide_mouse || Settings::values.mouse_panning) && emulation_running) {
  2289. render_window->installEventFilter(render_window);
  2290. render_window->setAttribute(Qt::WA_Hover, true);
  2291. } else {
  2292. render_window->removeEventFilter(render_window);
  2293. render_window->setAttribute(Qt::WA_Hover, false);
  2294. }
  2295. if (UISettings::values.hide_mouse) {
  2296. mouse_hide_timer.start();
  2297. }
  2298. UpdateStatusButtons();
  2299. }
  2300. void GMainWindow::OnConfigureTas() {
  2301. const auto& system = Core::System::GetInstance();
  2302. ConfigureTasDialog dialog(this);
  2303. const auto result = dialog.exec();
  2304. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  2305. Settings::RestoreGlobalState(system.IsPoweredOn());
  2306. return;
  2307. } else if (result == QDialog::Accepted) {
  2308. dialog.ApplyConfiguration();
  2309. }
  2310. }
  2311. void GMainWindow::OnConfigurePerGame() {
  2312. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  2313. OpenPerGameConfiguration(title_id, game_path.toStdString());
  2314. }
  2315. void GMainWindow::OpenPerGameConfiguration(u64 title_id, const std::string& file_name) {
  2316. const auto v_file = Core::GetGameFileFromPath(vfs, file_name);
  2317. const auto& system = Core::System::GetInstance();
  2318. ConfigurePerGame dialog(this, title_id, file_name);
  2319. dialog.LoadFromFile(v_file);
  2320. const auto result = dialog.exec();
  2321. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  2322. Settings::RestoreGlobalState(system.IsPoweredOn());
  2323. return;
  2324. } else if (result == QDialog::Accepted) {
  2325. dialog.ApplyConfiguration();
  2326. }
  2327. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2328. if (reload) {
  2329. game_list->PopulateAsync(UISettings::values.game_dirs);
  2330. }
  2331. // Do not cause the global config to write local settings into the config file
  2332. const bool is_powered_on = system.IsPoweredOn();
  2333. Settings::RestoreGlobalState(is_powered_on);
  2334. UISettings::values.configuration_applied = false;
  2335. if (!is_powered_on) {
  2336. config->Save();
  2337. }
  2338. }
  2339. void GMainWindow::OnLoadAmiibo() {
  2340. const QString extensions{QStringLiteral("*.bin")};
  2341. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  2342. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter);
  2343. if (filename.isEmpty()) {
  2344. return;
  2345. }
  2346. LoadAmiibo(filename);
  2347. }
  2348. void GMainWindow::LoadAmiibo(const QString& filename) {
  2349. Core::System& system{Core::System::GetInstance()};
  2350. Service::SM::ServiceManager& sm = system.ServiceManager();
  2351. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  2352. if (nfc == nullptr) {
  2353. return;
  2354. }
  2355. QFile nfc_file{filename};
  2356. if (!nfc_file.open(QIODevice::ReadOnly)) {
  2357. QMessageBox::warning(this, tr("Error opening Amiibo data file"),
  2358. tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
  2359. return;
  2360. }
  2361. const u64 nfc_file_size = nfc_file.size();
  2362. std::vector<u8> buffer(nfc_file_size);
  2363. const u64 read_size = nfc_file.read(reinterpret_cast<char*>(buffer.data()), nfc_file_size);
  2364. if (nfc_file_size != read_size) {
  2365. QMessageBox::warning(this, tr("Error reading Amiibo data file"),
  2366. tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
  2367. "was only able to read %2 bytes.")
  2368. .arg(nfc_file_size)
  2369. .arg(read_size));
  2370. return;
  2371. }
  2372. if (!nfc->LoadAmiibo(buffer)) {
  2373. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  2374. tr("Unable to load Amiibo data."));
  2375. }
  2376. }
  2377. void GMainWindow::OnOpenYuzuFolder() {
  2378. QDesktopServices::openUrl(QUrl::fromLocalFile(
  2379. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::YuzuDir))));
  2380. }
  2381. void GMainWindow::OnAbout() {
  2382. AboutDialog aboutDialog(this);
  2383. aboutDialog.exec();
  2384. }
  2385. void GMainWindow::OnToggleFilterBar() {
  2386. game_list->SetFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  2387. if (ui.action_Show_Filter_Bar->isChecked()) {
  2388. game_list->SetFilterFocus();
  2389. } else {
  2390. game_list->ClearFilter();
  2391. }
  2392. }
  2393. void GMainWindow::OnCaptureScreenshot() {
  2394. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  2395. const auto screenshot_path =
  2396. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::ScreenshotsDir));
  2397. const auto date =
  2398. QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd_hh-mm-ss-zzz"));
  2399. QString filename = QStringLiteral("%1/%2_%3.png")
  2400. .arg(screenshot_path)
  2401. .arg(title_id, 16, 16, QLatin1Char{'0'})
  2402. .arg(date);
  2403. if (!Common::FS::CreateDir(screenshot_path.toStdString())) {
  2404. return;
  2405. }
  2406. #ifdef _WIN32
  2407. if (UISettings::values.enable_screenshot_save_as) {
  2408. OnPauseGame();
  2409. filename = QFileDialog::getSaveFileName(this, tr("Capture Screenshot"), filename,
  2410. tr("PNG Image (*.png)"));
  2411. OnStartGame();
  2412. if (filename.isEmpty()) {
  2413. return;
  2414. }
  2415. }
  2416. #endif
  2417. render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor.GetValue(),
  2418. filename);
  2419. }
  2420. // TODO: Written 2020-10-01: Remove per-game config migration code when it is irrelevant
  2421. void GMainWindow::MigrateConfigFiles() {
  2422. const auto config_dir_fs_path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir);
  2423. const QDir config_dir =
  2424. QDir(QString::fromStdString(Common::FS::PathToUTF8String(config_dir_fs_path)));
  2425. const QStringList config_dir_list = config_dir.entryList(QStringList(QStringLiteral("*.ini")));
  2426. if (!Common::FS::CreateDirs(config_dir_fs_path / "custom")) {
  2427. LOG_ERROR(Frontend, "Failed to create new config file directory");
  2428. }
  2429. for (auto it = config_dir_list.constBegin(); it != config_dir_list.constEnd(); ++it) {
  2430. const auto filename = it->toStdString();
  2431. if (filename.find_first_not_of("0123456789abcdefACBDEF", 0) < 16) {
  2432. continue;
  2433. }
  2434. const auto origin = config_dir_fs_path / filename;
  2435. const auto destination = config_dir_fs_path / "custom" / filename;
  2436. LOG_INFO(Frontend, "Migrating config file from {} to {}", origin, destination);
  2437. if (!Common::FS::RenameFile(origin, destination)) {
  2438. // Delete the old config file if one already exists in the new location.
  2439. Common::FS::RemoveFile(origin);
  2440. }
  2441. }
  2442. }
  2443. void GMainWindow::UpdateWindowTitle(std::string_view title_name, std::string_view title_version,
  2444. std::string_view gpu_vendor) {
  2445. const auto branch_name = std::string(Common::g_scm_branch);
  2446. const auto description = std::string(Common::g_scm_desc);
  2447. const auto build_id = std::string(Common::g_build_id);
  2448. const auto yuzu_title = fmt::format("yuzu | {}-{}", branch_name, description);
  2449. const auto override_title =
  2450. fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id);
  2451. const auto window_title = override_title.empty() ? yuzu_title : override_title;
  2452. if (title_name.empty()) {
  2453. setWindowTitle(QString::fromStdString(window_title));
  2454. } else {
  2455. const auto run_title =
  2456. fmt::format("{} | {} | {} | {}", window_title, title_name, title_version, gpu_vendor);
  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& system = Core::System::GetInstance();
  2484. auto results = system.GetAndResetPerfStats();
  2485. auto& shader_notify = system.GPU().ShaderNotify();
  2486. const int shaders_building = shader_notify.ShadersBuilding();
  2487. if (shaders_building > 0) {
  2488. shader_building_label->setText(tr("Building: %n shader(s)", "", shaders_building));
  2489. shader_building_label->setVisible(true);
  2490. } else {
  2491. shader_building_label->setVisible(false);
  2492. }
  2493. if (Settings::values.use_speed_limit.GetValue()) {
  2494. emu_speed_label->setText(tr("Speed: %1% / %2%")
  2495. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  2496. .arg(Settings::values.speed_limit.GetValue()));
  2497. } else {
  2498. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  2499. }
  2500. if (Settings::values.disable_fps_limit) {
  2501. game_fps_label->setText(
  2502. tr("Game: %1 FPS (Unlocked)").arg(results.average_game_fps, 0, 'f', 0));
  2503. } else {
  2504. game_fps_label->setText(tr("Game: %1 FPS").arg(results.average_game_fps, 0, 'f', 0));
  2505. }
  2506. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  2507. emu_speed_label->setVisible(!Settings::values.use_multi_core.GetValue());
  2508. game_fps_label->setVisible(true);
  2509. emu_frametime_label->setVisible(true);
  2510. }
  2511. void GMainWindow::UpdateGPUAccuracyButton() {
  2512. switch (Settings::values.gpu_accuracy.GetValue()) {
  2513. case Settings::GPUAccuracy::Normal: {
  2514. gpu_accuracy_button->setText(tr("GPU NORMAL"));
  2515. gpu_accuracy_button->setChecked(false);
  2516. break;
  2517. }
  2518. case Settings::GPUAccuracy::High: {
  2519. gpu_accuracy_button->setText(tr("GPU HIGH"));
  2520. gpu_accuracy_button->setChecked(true);
  2521. break;
  2522. }
  2523. case Settings::GPUAccuracy::Extreme: {
  2524. gpu_accuracy_button->setText(tr("GPU EXTREME"));
  2525. gpu_accuracy_button->setChecked(true);
  2526. break;
  2527. }
  2528. default: {
  2529. gpu_accuracy_button->setText(tr("GPU ERROR"));
  2530. gpu_accuracy_button->setChecked(true);
  2531. }
  2532. }
  2533. }
  2534. void GMainWindow::UpdateStatusButtons() {
  2535. dock_status_button->setChecked(Settings::values.use_docked_mode.GetValue());
  2536. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  2537. Settings::RendererBackend::Vulkan);
  2538. UpdateGPUAccuracyButton();
  2539. }
  2540. void GMainWindow::UpdateUISettings() {
  2541. if (!ui.action_Fullscreen->isChecked()) {
  2542. UISettings::values.geometry = saveGeometry();
  2543. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2544. }
  2545. UISettings::values.state = saveState();
  2546. #if MICROPROFILE_ENABLED
  2547. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  2548. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  2549. #endif
  2550. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  2551. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  2552. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  2553. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  2554. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  2555. UISettings::values.first_start = false;
  2556. }
  2557. void GMainWindow::HideMouseCursor() {
  2558. if (emu_thread == nullptr && UISettings::values.hide_mouse) {
  2559. mouse_hide_timer.stop();
  2560. ShowMouseCursor();
  2561. return;
  2562. }
  2563. render_window->setCursor(QCursor(Qt::BlankCursor));
  2564. }
  2565. void GMainWindow::ShowMouseCursor() {
  2566. render_window->unsetCursor();
  2567. if (emu_thread != nullptr && UISettings::values.hide_mouse) {
  2568. mouse_hide_timer.start();
  2569. }
  2570. }
  2571. void GMainWindow::OnMouseActivity() {
  2572. if (!Settings::values.mouse_panning) {
  2573. ShowMouseCursor();
  2574. }
  2575. }
  2576. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  2577. QMessageBox::StandardButton answer;
  2578. QString status_message;
  2579. const QString common_message =
  2580. tr("The game you are trying to load requires additional files from your Switch to be "
  2581. "dumped "
  2582. "before playing.<br/><br/>For more information on dumping these files, please see the "
  2583. "following wiki page: <a "
  2584. "href='https://yuzu-emu.org/wiki/"
  2585. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  2586. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  2587. "quit "
  2588. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  2589. "data, or other bugs.");
  2590. switch (result) {
  2591. case Core::System::ResultStatus::ErrorSystemFiles: {
  2592. QString message;
  2593. if (details.empty()) {
  2594. message =
  2595. tr("yuzu was unable to locate a Switch system archive. %1").arg(common_message);
  2596. } else {
  2597. message = tr("yuzu was unable to locate a Switch system archive: %1. %2")
  2598. .arg(QString::fromStdString(details), common_message);
  2599. }
  2600. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  2601. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2602. status_message = tr("System Archive Missing");
  2603. break;
  2604. }
  2605. case Core::System::ResultStatus::ErrorSharedFont: {
  2606. const QString message =
  2607. tr("yuzu was unable to locate the Switch shared fonts. %1").arg(common_message);
  2608. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  2609. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2610. status_message = tr("Shared Font Missing");
  2611. break;
  2612. }
  2613. default:
  2614. answer = QMessageBox::question(
  2615. this, tr("Fatal Error"),
  2616. tr("yuzu has encountered a fatal error, please see the log for more details. "
  2617. "For more information on accessing the log, please see the following page: "
  2618. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  2619. "to "
  2620. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  2621. "list? "
  2622. "Continuing emulation may result in crashes, corrupted save data, or other "
  2623. "bugs."),
  2624. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2625. status_message = tr("Fatal Error encountered");
  2626. break;
  2627. }
  2628. if (answer == QMessageBox::Yes) {
  2629. if (emu_thread) {
  2630. ShutdownGame();
  2631. Settings::RestoreGlobalState(Core::System::GetInstance().IsPoweredOn());
  2632. UpdateStatusButtons();
  2633. }
  2634. } else {
  2635. // Only show the message if the game is still running.
  2636. if (emu_thread) {
  2637. emu_thread->SetRunning(true);
  2638. message_label->setText(status_message);
  2639. }
  2640. }
  2641. }
  2642. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  2643. if (behavior == ReinitializeKeyBehavior::Warning) {
  2644. const auto res = QMessageBox::information(
  2645. this, tr("Confirm Key Rederivation"),
  2646. tr("You are about to force rederive all of your keys. \nIf you do not know what "
  2647. "this "
  2648. "means or what you are doing, \nthis is a potentially destructive action. "
  2649. "\nPlease "
  2650. "make sure this is what you want \nand optionally make backups.\n\nThis will "
  2651. "delete "
  2652. "your autogenerated key files and re-run the key derivation module."),
  2653. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  2654. if (res == QMessageBox::Cancel)
  2655. return;
  2656. const auto keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
  2657. Common::FS::RemoveFile(keys_dir / "prod.keys_autogenerated");
  2658. Common::FS::RemoveFile(keys_dir / "console.keys_autogenerated");
  2659. Common::FS::RemoveFile(keys_dir / "title.keys_autogenerated");
  2660. }
  2661. Core::Crypto::KeyManager& keys = Core::Crypto::KeyManager::Instance();
  2662. if (keys.BaseDeriveNecessary()) {
  2663. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory("", FileSys::Mode::Read)};
  2664. const auto function = [this, &keys, &pdm] {
  2665. keys.PopulateFromPartitionData(pdm);
  2666. auto& system = Core::System::GetInstance();
  2667. system.GetFileSystemController().CreateFactories(*vfs);
  2668. keys.DeriveETicket(pdm, system.GetContentProvider());
  2669. };
  2670. QString errors;
  2671. if (!pdm.HasFuses()) {
  2672. errors += tr("Missing fuses");
  2673. }
  2674. if (!pdm.HasBoot0()) {
  2675. errors += tr(" - Missing BOOT0");
  2676. }
  2677. if (!pdm.HasPackage2()) {
  2678. errors += tr(" - Missing BCPKG2-1-Normal-Main");
  2679. }
  2680. if (!pdm.HasProdInfo()) {
  2681. errors += tr(" - Missing PRODINFO");
  2682. }
  2683. if (!errors.isEmpty()) {
  2684. QMessageBox::warning(
  2685. this, tr("Derivation Components Missing"),
  2686. tr("Components are missing that may hinder key derivation from completing. "
  2687. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  2688. "quickstart guide</a> to get all your keys and "
  2689. "games.<br><br><small>(%1)</small>")
  2690. .arg(errors));
  2691. }
  2692. QProgressDialog prog(this);
  2693. prog.setRange(0, 0);
  2694. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  2695. "system's performance."));
  2696. prog.setWindowTitle(tr("Deriving Keys"));
  2697. prog.show();
  2698. auto future = QtConcurrent::run(function);
  2699. while (!future.isFinished()) {
  2700. QCoreApplication::processEvents();
  2701. }
  2702. prog.close();
  2703. }
  2704. Core::System::GetInstance().GetFileSystemController().CreateFactories(*vfs);
  2705. if (behavior == ReinitializeKeyBehavior::Warning) {
  2706. game_list->PopulateAsync(UISettings::values.game_dirs);
  2707. }
  2708. }
  2709. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
  2710. u64 program_id) {
  2711. const auto dlc_entries =
  2712. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  2713. std::vector<FileSys::ContentProviderEntry> dlc_match;
  2714. dlc_match.reserve(dlc_entries.size());
  2715. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  2716. [&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
  2717. return FileSys::GetBaseTitleID(entry.title_id) == program_id &&
  2718. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  2719. });
  2720. std::vector<u64> romfs_tids;
  2721. romfs_tids.push_back(program_id);
  2722. for (const auto& entry : dlc_match) {
  2723. romfs_tids.push_back(entry.title_id);
  2724. }
  2725. if (romfs_tids.size() > 1) {
  2726. QStringList list{QStringLiteral("Base")};
  2727. for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
  2728. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  2729. }
  2730. bool ok;
  2731. const auto res = QInputDialog::getItem(
  2732. this, tr("Select RomFS Dump Target"),
  2733. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  2734. if (!ok) {
  2735. return {};
  2736. }
  2737. return romfs_tids[list.indexOf(res)];
  2738. }
  2739. return program_id;
  2740. }
  2741. bool GMainWindow::ConfirmClose() {
  2742. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  2743. return true;
  2744. }
  2745. const auto text = tr("Are you sure you want to close yuzu?");
  2746. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  2747. return answer != QMessageBox::No;
  2748. }
  2749. void GMainWindow::closeEvent(QCloseEvent* event) {
  2750. if (!ConfirmClose()) {
  2751. event->ignore();
  2752. return;
  2753. }
  2754. UpdateUISettings();
  2755. game_list->SaveInterfaceLayout();
  2756. hotkey_registry.SaveHotkeys();
  2757. // Shutdown session if the emu thread is active...
  2758. if (emu_thread != nullptr) {
  2759. ShutdownGame();
  2760. Settings::RestoreGlobalState(Core::System::GetInstance().IsPoweredOn());
  2761. UpdateStatusButtons();
  2762. }
  2763. render_window->close();
  2764. QWidget::closeEvent(event);
  2765. }
  2766. static bool IsSingleFileDropEvent(const QMimeData* mime) {
  2767. return mime->hasUrls() && mime->urls().length() == 1;
  2768. }
  2769. void GMainWindow::AcceptDropEvent(QDropEvent* event) {
  2770. if (IsSingleFileDropEvent(event->mimeData())) {
  2771. event->setDropAction(Qt::DropAction::LinkAction);
  2772. event->accept();
  2773. }
  2774. }
  2775. bool GMainWindow::DropAction(QDropEvent* event) {
  2776. if (!IsSingleFileDropEvent(event->mimeData())) {
  2777. return false;
  2778. }
  2779. const QMimeData* mime_data = event->mimeData();
  2780. const QString& filename = mime_data->urls().at(0).toLocalFile();
  2781. if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
  2782. // Amiibo
  2783. LoadAmiibo(filename);
  2784. } else {
  2785. // Game
  2786. if (ConfirmChangeGame()) {
  2787. BootGame(filename);
  2788. }
  2789. }
  2790. return true;
  2791. }
  2792. void GMainWindow::dropEvent(QDropEvent* event) {
  2793. DropAction(event);
  2794. }
  2795. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  2796. AcceptDropEvent(event);
  2797. }
  2798. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  2799. AcceptDropEvent(event);
  2800. }
  2801. bool GMainWindow::ConfirmChangeGame() {
  2802. if (emu_thread == nullptr)
  2803. return true;
  2804. const auto answer = QMessageBox::question(
  2805. this, tr("yuzu"),
  2806. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  2807. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2808. return answer != QMessageBox::No;
  2809. }
  2810. bool GMainWindow::ConfirmForceLockedExit() {
  2811. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) {
  2812. return true;
  2813. }
  2814. const auto text = tr("The currently running application has requested yuzu to not exit.\n\n"
  2815. "Would you like to bypass this and exit anyway?");
  2816. const auto answer = QMessageBox::question(this, tr("yuzu"), text);
  2817. return answer != QMessageBox::No;
  2818. }
  2819. void GMainWindow::RequestGameExit() {
  2820. auto& sm{Core::System::GetInstance().ServiceManager()};
  2821. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  2822. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  2823. bool has_signalled = false;
  2824. if (applet_oe != nullptr) {
  2825. applet_oe->GetMessageQueue()->RequestExit();
  2826. has_signalled = true;
  2827. }
  2828. if (applet_ae != nullptr && !has_signalled) {
  2829. applet_ae->GetMessageQueue()->RequestExit();
  2830. }
  2831. }
  2832. void GMainWindow::filterBarSetChecked(bool state) {
  2833. ui.action_Show_Filter_Bar->setChecked(state);
  2834. emit(OnToggleFilterBar());
  2835. }
  2836. void GMainWindow::UpdateUITheme() {
  2837. const QString default_icons = QStringLiteral("default");
  2838. const QString& current_theme = UISettings::values.theme;
  2839. const bool is_default_theme = current_theme == QString::fromUtf8(UISettings::themes[0].second);
  2840. QStringList theme_paths(default_theme_paths);
  2841. if (is_default_theme || current_theme.isEmpty()) {
  2842. const QString theme_uri(QStringLiteral(":default/style.qss"));
  2843. QFile f(theme_uri);
  2844. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2845. QTextStream ts(&f);
  2846. qApp->setStyleSheet(ts.readAll());
  2847. setStyleSheet(ts.readAll());
  2848. } else {
  2849. qApp->setStyleSheet({});
  2850. setStyleSheet({});
  2851. }
  2852. QIcon::setThemeName(default_icons);
  2853. } else {
  2854. const QString theme_uri(QLatin1Char{':'} + current_theme + QStringLiteral("/style.qss"));
  2855. QFile f(theme_uri);
  2856. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2857. QTextStream ts(&f);
  2858. qApp->setStyleSheet(ts.readAll());
  2859. setStyleSheet(ts.readAll());
  2860. } else {
  2861. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  2862. }
  2863. QIcon::setThemeName(current_theme);
  2864. }
  2865. QIcon::setThemeSearchPaths(theme_paths);
  2866. }
  2867. void GMainWindow::LoadTranslation() {
  2868. // If the selected language is English, no need to install any translation
  2869. if (UISettings::values.language == QStringLiteral("en")) {
  2870. return;
  2871. }
  2872. bool loaded;
  2873. if (UISettings::values.language.isEmpty()) {
  2874. // If the selected language is empty, use system locale
  2875. loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/"));
  2876. } else {
  2877. // Otherwise load from the specified file
  2878. loaded = translator.load(UISettings::values.language, QStringLiteral(":/languages/"));
  2879. }
  2880. if (loaded) {
  2881. qApp->installTranslator(&translator);
  2882. } else {
  2883. UISettings::values.language = QStringLiteral("en");
  2884. }
  2885. }
  2886. void GMainWindow::OnLanguageChanged(const QString& locale) {
  2887. if (UISettings::values.language != QStringLiteral("en")) {
  2888. qApp->removeTranslator(&translator);
  2889. }
  2890. UISettings::values.language = locale;
  2891. LoadTranslation();
  2892. ui.retranslateUi(this);
  2893. UpdateWindowTitle();
  2894. if (emulation_running)
  2895. ui.action_Start->setText(tr("&Continue"));
  2896. }
  2897. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  2898. #ifdef USE_DISCORD_PRESENCE
  2899. if (state) {
  2900. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  2901. } else {
  2902. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2903. }
  2904. #else
  2905. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2906. #endif
  2907. discord_rpc->Update();
  2908. }
  2909. #ifdef main
  2910. #undef main
  2911. #endif
  2912. int main(int argc, char* argv[]) {
  2913. Common::DetachedTasks detached_tasks;
  2914. MicroProfileOnThreadCreate("Frontend");
  2915. SCOPE_EXIT({ MicroProfileShutdown(); });
  2916. Common::ConfigureNvidiaEnvironmentFlags();
  2917. // Init settings params
  2918. QCoreApplication::setOrganizationName(QStringLiteral("yuzu team"));
  2919. QCoreApplication::setApplicationName(QStringLiteral("yuzu"));
  2920. #ifdef _WIN32
  2921. // Increases the maximum open file limit to 4096
  2922. _setmaxstdio(4096);
  2923. #endif
  2924. #ifdef __APPLE__
  2925. // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/".
  2926. // But since we require the working directory to be the executable path for the location of
  2927. // the user folder in the Qt Frontend, we need to cd into that working directory
  2928. const auto bin_path = Common::FS::GetBundleDirectory() / "..";
  2929. chdir(Common::FS::PathToUTF8String(bin_path).c_str());
  2930. #endif
  2931. #ifdef __linux__
  2932. // Set the DISPLAY variable in order to open web browsers
  2933. // TODO (lat9nq): Find a better solution for AppImages to start external applications
  2934. if (QString::fromLocal8Bit(qgetenv("DISPLAY")).isEmpty()) {
  2935. qputenv("DISPLAY", ":0");
  2936. }
  2937. #endif
  2938. // Enables the core to make the qt created contexts current on std::threads
  2939. QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  2940. QApplication app(argc, argv);
  2941. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  2942. // generating shaders
  2943. setlocale(LC_ALL, "C");
  2944. Core::System::InitializeGlobalInstance();
  2945. GMainWindow main_window;
  2946. // After settings have been loaded by GMainWindow, apply the filter
  2947. main_window.show();
  2948. QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
  2949. &GMainWindow::OnAppFocusStateChanged);
  2950. int result = app.exec();
  2951. detached_tasks.WaitForAllTasks();
  2952. return result;
  2953. }