main.cpp 94 KB

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