main.cpp 113 KB

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