main.cpp 93 KB

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