main.cpp 113 KB

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