main.cpp 79 KB

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