main.cpp 94 KB

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