main.cpp 96 KB

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