main.cpp 111 KB

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