main.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056
  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. constexpr u16 SPEED_LIMIT_STEP = 5;
  480. connect(hotkey_registry.GetHotkey("Main Window", "Increase Speed Limit", this),
  481. &QShortcut::activated, this, [&] {
  482. if (Settings::values.frame_limit < 9999 - SPEED_LIMIT_STEP) {
  483. Settings::values.frame_limit += SPEED_LIMIT_STEP;
  484. UpdateStatusBar();
  485. }
  486. });
  487. connect(hotkey_registry.GetHotkey("Main Window", "Decrease Speed Limit", this),
  488. &QShortcut::activated, this, [&] {
  489. if (Settings::values.frame_limit > SPEED_LIMIT_STEP) {
  490. Settings::values.frame_limit -= SPEED_LIMIT_STEP;
  491. UpdateStatusBar();
  492. }
  493. });
  494. connect(hotkey_registry.GetHotkey("Main Window", "Load Amiibo", this), &QShortcut::activated,
  495. this, [&] {
  496. if (ui.action_Load_Amiibo->isEnabled()) {
  497. OnLoadAmiibo();
  498. }
  499. });
  500. connect(hotkey_registry.GetHotkey("Main Window", "Capture Screenshot", this),
  501. &QShortcut::activated, this, [&] {
  502. if (emu_thread->IsRunning()) {
  503. OnCaptureScreenshot();
  504. }
  505. });
  506. }
  507. void GMainWindow::SetDefaultUIGeometry() {
  508. // geometry: 55% of the window contents are in the upper screen half, 45% in the lower half
  509. const QRect screenRect = QApplication::desktop()->screenGeometry(this);
  510. const int w = screenRect.width() * 2 / 3;
  511. const int h = screenRect.height() / 2;
  512. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  513. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 55 / 100;
  514. setGeometry(x, y, w, h);
  515. }
  516. void GMainWindow::RestoreUIState() {
  517. restoreGeometry(UISettings::values.geometry);
  518. restoreState(UISettings::values.state);
  519. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  520. #if MICROPROFILE_ENABLED
  521. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  522. microProfileDialog->setVisible(UISettings::values.microprofile_visible);
  523. #endif
  524. game_list->LoadInterfaceLayout();
  525. ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode);
  526. ToggleWindowMode();
  527. ui.action_Fullscreen->setChecked(UISettings::values.fullscreen);
  528. ui.action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);
  529. OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked());
  530. ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar);
  531. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  532. ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);
  533. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  534. Debugger::ToggleConsole();
  535. }
  536. void GMainWindow::ConnectWidgetEvents() {
  537. connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
  538. connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
  539. connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS);
  540. connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID);
  541. connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
  542. &GMainWindow::OnGameListNavigateToGamedbEntry);
  543. connect(game_list, &GameList::OpenPerGameGeneralRequested, this,
  544. &GMainWindow::OnGameListOpenPerGameProperties);
  545. connect(this, &GMainWindow::EmulationStarting, render_window,
  546. &GRenderWindow::OnEmulationStarting);
  547. connect(this, &GMainWindow::EmulationStopping, render_window,
  548. &GRenderWindow::OnEmulationStopping);
  549. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  550. }
  551. void GMainWindow::ConnectMenuEvents() {
  552. // File
  553. connect(ui.action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
  554. connect(ui.action_Load_Folder, &QAction::triggered, this, &GMainWindow::OnMenuLoadFolder);
  555. connect(ui.action_Install_File_NAND, &QAction::triggered, this,
  556. &GMainWindow::OnMenuInstallToNAND);
  557. connect(ui.action_Select_Game_List_Root, &QAction::triggered, this,
  558. &GMainWindow::OnMenuSelectGameListRoot);
  559. connect(ui.action_Select_NAND_Directory, &QAction::triggered, this,
  560. [this] { OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget::NAND); });
  561. connect(ui.action_Select_SDMC_Directory, &QAction::triggered, this,
  562. [this] { OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget::SDMC); });
  563. connect(ui.action_Exit, &QAction::triggered, this, &QMainWindow::close);
  564. connect(ui.action_Load_Amiibo, &QAction::triggered, this, &GMainWindow::OnLoadAmiibo);
  565. // Emulation
  566. connect(ui.action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
  567. connect(ui.action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
  568. connect(ui.action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
  569. connect(ui.action_Report_Compatibility, &QAction::triggered, this,
  570. &GMainWindow::OnMenuReportCompatibility);
  571. connect(ui.action_Restart, &QAction::triggered, this, [this] { BootGame(QString(game_path)); });
  572. connect(ui.action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
  573. // View
  574. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  575. &GMainWindow::ToggleWindowMode);
  576. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  577. &GMainWindow::OnDisplayTitleBars);
  578. ui.action_Show_Filter_Bar->setShortcut(tr("CTRL+F"));
  579. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  580. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  581. // Fullscreen
  582. ui.action_Fullscreen->setShortcut(
  583. hotkey_registry.GetHotkey("Main Window", "Fullscreen", this)->key());
  584. connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
  585. // Movie
  586. connect(ui.action_Capture_Screenshot, &QAction::triggered, this,
  587. &GMainWindow::OnCaptureScreenshot);
  588. // Help
  589. connect(ui.action_Open_yuzu_Folder, &QAction::triggered, this, &GMainWindow::OnOpenYuzuFolder);
  590. connect(ui.action_Rederive, &QAction::triggered, this,
  591. std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning));
  592. connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
  593. }
  594. void GMainWindow::OnDisplayTitleBars(bool show) {
  595. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  596. if (show) {
  597. for (QDockWidget* widget : widgets) {
  598. QWidget* old = widget->titleBarWidget();
  599. widget->setTitleBarWidget(nullptr);
  600. if (old != nullptr)
  601. delete old;
  602. }
  603. } else {
  604. for (QDockWidget* widget : widgets) {
  605. QWidget* old = widget->titleBarWidget();
  606. widget->setTitleBarWidget(new QWidget());
  607. if (old != nullptr)
  608. delete old;
  609. }
  610. }
  611. }
  612. QStringList GMainWindow::GetUnsupportedGLExtensions() {
  613. QStringList unsupported_ext;
  614. if (!GLAD_GL_ARB_direct_state_access)
  615. unsupported_ext.append("ARB_direct_state_access");
  616. if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
  617. unsupported_ext.append("ARB_vertex_type_10f_11f_11f_rev");
  618. if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
  619. unsupported_ext.append("ARB_texture_mirror_clamp_to_edge");
  620. if (!GLAD_GL_ARB_multi_bind)
  621. unsupported_ext.append("ARB_multi_bind");
  622. // Extensions required to support some texture formats.
  623. if (!GLAD_GL_EXT_texture_compression_s3tc)
  624. unsupported_ext.append("EXT_texture_compression_s3tc");
  625. if (!GLAD_GL_ARB_texture_compression_rgtc)
  626. unsupported_ext.append("ARB_texture_compression_rgtc");
  627. if (!GLAD_GL_ARB_depth_buffer_float)
  628. unsupported_ext.append("ARB_depth_buffer_float");
  629. for (const QString& ext : unsupported_ext)
  630. LOG_CRITICAL(Frontend, "Unsupported GL extension: {}", ext.toStdString());
  631. return unsupported_ext;
  632. }
  633. bool GMainWindow::LoadROM(const QString& filename) {
  634. // Shutdown previous session if the emu thread is still active...
  635. if (emu_thread != nullptr)
  636. ShutdownGame();
  637. render_window->InitRenderTarget();
  638. {
  639. Core::Frontend::ScopeAcquireWindowContext acquire_context{*render_window};
  640. if (!gladLoadGL()) {
  641. QMessageBox::critical(this, tr("Error while initializing OpenGL 4.3 Core!"),
  642. tr("Your GPU may not support OpenGL 4.3, or you do not "
  643. "have the latest graphics driver."));
  644. return false;
  645. }
  646. }
  647. QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions();
  648. if (!unsupported_gl_extensions.empty()) {
  649. QMessageBox::critical(this, tr("Error while initializing OpenGL Core!"),
  650. tr("Your GPU may not support one or more required OpenGL"
  651. "extensions. Please ensure you have the latest graphics "
  652. "driver.<br><br>Unsupported extensions:<br>") +
  653. unsupported_gl_extensions.join("<br>"));
  654. return false;
  655. }
  656. Core::System& system{Core::System::GetInstance()};
  657. system.SetFilesystem(vfs);
  658. system.SetGPUDebugContext(debug_context);
  659. system.SetProfileSelector(std::make_unique<QtProfileSelector>(*this));
  660. system.SetSoftwareKeyboard(std::make_unique<QtSoftwareKeyboard>(*this));
  661. system.SetWebBrowser(std::make_unique<QtWebBrowser>(*this));
  662. const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
  663. const auto drd_callout =
  664. (UISettings::values.callout_flags & static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  665. if (result == Core::System::ResultStatus::Success &&
  666. system.GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  667. drd_callout) {
  668. UISettings::values.callout_flags |= static_cast<u32>(CalloutFlag::DRDDeprecation);
  669. QMessageBox::warning(
  670. this, tr("Warning Outdated Game Format"),
  671. tr("You are using the deconstructed ROM directory format for this game, which is an "
  672. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  673. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  674. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  675. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  676. "wiki</a>. This message will not be shown again."));
  677. }
  678. if (result != Core::System::ResultStatus::Success) {
  679. switch (result) {
  680. case Core::System::ResultStatus::ErrorGetLoader:
  681. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  682. QMessageBox::critical(this, tr("Error while loading ROM!"),
  683. tr("The ROM format is not supported."));
  684. break;
  685. case Core::System::ResultStatus::ErrorSystemMode:
  686. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  687. QMessageBox::critical(this, tr("Error while loading ROM!"),
  688. tr("Could not determine the system mode."));
  689. break;
  690. case Core::System::ResultStatus::ErrorVideoCore:
  691. QMessageBox::critical(
  692. this, tr("An error occurred initializing the video core."),
  693. tr("yuzu has encountered an error while running the video core, please see the "
  694. "log for more details."
  695. "For more information on accessing the log, please see the following page: "
  696. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  697. "to "
  698. "Upload the Log File</a>."
  699. "Ensure that you have the latest graphics drivers for your GPU."));
  700. break;
  701. default:
  702. if (static_cast<u32>(result) >
  703. static_cast<u32>(Core::System::ResultStatus::ErrorLoader)) {
  704. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  705. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  706. const u16 error_id = static_cast<u16>(result) - loader_id;
  707. QMessageBox::critical(
  708. this, tr("Error while loading ROM!"),
  709. QString::fromStdString(fmt::format(
  710. "While attempting to load the ROM requested, an error occured. Please "
  711. "refer to the yuzu wiki for more information or the yuzu discord for "
  712. "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
  713. loader_id, error_id, static_cast<Loader::ResultStatus>(error_id))));
  714. } else {
  715. QMessageBox::critical(
  716. this, tr("Error while loading ROM!"),
  717. tr("An unknown error occurred. Please see the log for more details."));
  718. }
  719. break;
  720. }
  721. return false;
  722. }
  723. game_path = filename;
  724. Core::Telemetry().AddField(Telemetry::FieldType::App, "Frontend", "Qt");
  725. return true;
  726. }
  727. void GMainWindow::SelectAndSetCurrentUser() {
  728. QtProfileSelectionDialog dialog(this);
  729. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  730. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  731. dialog.setWindowModality(Qt::WindowModal);
  732. dialog.exec();
  733. if (dialog.GetStatus()) {
  734. Settings::values.current_user = static_cast<s32>(dialog.GetIndex());
  735. }
  736. }
  737. void GMainWindow::BootGame(const QString& filename) {
  738. LOG_INFO(Frontend, "yuzu starting...");
  739. StoreRecentFile(filename); // Put the filename on top of the list
  740. if (UISettings::values.select_user_on_boot) {
  741. SelectAndSetCurrentUser();
  742. }
  743. if (!LoadROM(filename))
  744. return;
  745. // Create and start the emulation thread
  746. emu_thread = std::make_unique<EmuThread>(render_window);
  747. emit EmulationStarting(emu_thread.get());
  748. render_window->moveContext();
  749. emu_thread->start();
  750. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  751. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  752. // before the CPU continues
  753. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  754. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  755. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  756. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  757. // Update the GUI
  758. if (ui.action_Single_Window_Mode->isChecked()) {
  759. game_list->hide();
  760. }
  761. status_bar_update_timer.start(2000);
  762. std::string title_name;
  763. const auto res = Core::System::GetInstance().GetGameName(title_name);
  764. if (res != Loader::ResultStatus::Success) {
  765. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  766. const auto [nacp, icon_file] = FileSys::PatchManager(title_id).GetControlMetadata();
  767. if (nacp != nullptr)
  768. title_name = nacp->GetApplicationName();
  769. if (title_name.empty())
  770. title_name = FileUtil::GetFilename(filename.toStdString());
  771. }
  772. setWindowTitle(QString("yuzu %1| %4 | %2-%3")
  773. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc,
  774. QString::fromStdString(title_name)));
  775. loading_screen->Prepare(Core::System::GetInstance().GetAppLoader());
  776. loading_screen->show();
  777. emulation_running = true;
  778. if (ui.action_Fullscreen->isChecked()) {
  779. ShowFullscreen();
  780. }
  781. OnStartGame();
  782. }
  783. void GMainWindow::ShutdownGame() {
  784. discord_rpc->Pause();
  785. emu_thread->RequestStop();
  786. emit EmulationStopping();
  787. // Wait for emulation thread to complete and delete it
  788. emu_thread->wait();
  789. emu_thread = nullptr;
  790. discord_rpc->Update();
  791. // The emulation is stopped, so closing the window or not does not matter anymore
  792. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  793. // Update the GUI
  794. ui.action_Start->setEnabled(false);
  795. ui.action_Start->setText(tr("Start"));
  796. ui.action_Pause->setEnabled(false);
  797. ui.action_Stop->setEnabled(false);
  798. ui.action_Restart->setEnabled(false);
  799. ui.action_Report_Compatibility->setEnabled(false);
  800. ui.action_Load_Amiibo->setEnabled(false);
  801. ui.action_Capture_Screenshot->setEnabled(false);
  802. render_window->hide();
  803. loading_screen->hide();
  804. loading_screen->Clear();
  805. game_list->show();
  806. game_list->setFilterFocus();
  807. setWindowTitle(QString("yuzu %1| %2-%3")
  808. .arg(Common::g_build_fullname, Common::g_scm_branch, Common::g_scm_desc));
  809. // Disable status bar updates
  810. status_bar_update_timer.stop();
  811. message_label->setVisible(false);
  812. emu_speed_label->setVisible(false);
  813. game_fps_label->setVisible(false);
  814. emu_frametime_label->setVisible(false);
  815. emulation_running = false;
  816. game_path.clear();
  817. }
  818. void GMainWindow::StoreRecentFile(const QString& filename) {
  819. UISettings::values.recent_files.prepend(filename);
  820. UISettings::values.recent_files.removeDuplicates();
  821. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  822. UISettings::values.recent_files.removeLast();
  823. }
  824. UpdateRecentFiles();
  825. }
  826. void GMainWindow::UpdateRecentFiles() {
  827. const int num_recent_files =
  828. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  829. for (int i = 0; i < num_recent_files; i++) {
  830. const QString text = QString("&%1. %2").arg(i + 1).arg(
  831. QFileInfo(UISettings::values.recent_files[i]).fileName());
  832. actions_recent_files[i]->setText(text);
  833. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  834. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  835. actions_recent_files[i]->setVisible(true);
  836. }
  837. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  838. actions_recent_files[j]->setVisible(false);
  839. }
  840. // Enable the recent files menu if the list isn't empty
  841. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  842. }
  843. void GMainWindow::OnGameListLoadFile(QString game_path) {
  844. BootGame(game_path);
  845. }
  846. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target) {
  847. std::string path;
  848. std::string open_target;
  849. switch (target) {
  850. case GameListOpenTarget::SaveData: {
  851. open_target = "Save Data";
  852. const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
  853. ASSERT(program_id != 0);
  854. const auto select_profile = [this]() -> s32 {
  855. QtProfileSelectionDialog dialog(this);
  856. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  857. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  858. dialog.setWindowModality(Qt::WindowModal);
  859. dialog.exec();
  860. if (!dialog.GetStatus()) {
  861. return -1;
  862. }
  863. return dialog.GetIndex();
  864. };
  865. const auto index = select_profile();
  866. if (index == -1)
  867. return;
  868. Service::Account::ProfileManager manager;
  869. const auto user_id = manager.GetUser(index);
  870. ASSERT(user_id);
  871. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(FileSys::SaveDataSpaceId::NandUser,
  872. FileSys::SaveDataType::SaveData,
  873. program_id, user_id->uuid, 0);
  874. if (!FileUtil::Exists(path)) {
  875. FileUtil::CreateFullPath(path);
  876. FileUtil::CreateDir(path);
  877. }
  878. break;
  879. }
  880. case GameListOpenTarget::ModData: {
  881. open_target = "Mod Data";
  882. const auto load_dir = FileUtil::GetUserPath(FileUtil::UserPath::LoadDir);
  883. path = fmt::format("{}{:016X}", load_dir, program_id);
  884. break;
  885. }
  886. default:
  887. UNIMPLEMENTED();
  888. }
  889. const QString qpath = QString::fromStdString(path);
  890. const QDir dir(qpath);
  891. if (!dir.exists()) {
  892. QMessageBox::warning(this,
  893. tr("Error Opening %1 Folder").arg(QString::fromStdString(open_target)),
  894. tr("Folder does not exist!"));
  895. return;
  896. }
  897. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target, program_id);
  898. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  899. }
  900. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  901. std::size_t out = 0;
  902. for (const auto& subdir : dir->GetSubdirectories()) {
  903. out += 1 + CalculateRomFSEntrySize(subdir, full);
  904. }
  905. return out + (full ? dir->GetFiles().size() : 0);
  906. }
  907. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  908. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  909. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  910. return false;
  911. if (dialog.wasCanceled())
  912. return false;
  913. if (full) {
  914. for (const auto& file : src->GetFiles()) {
  915. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  916. if (!FileSys::VfsRawCopy(file, out, block_size))
  917. return false;
  918. dialog.setValue(dialog.value() + 1);
  919. if (dialog.wasCanceled())
  920. return false;
  921. }
  922. }
  923. for (const auto& dir : src->GetSubdirectories()) {
  924. const auto out = dest->CreateSubdirectory(dir->GetName());
  925. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  926. return false;
  927. dialog.setValue(dialog.value() + 1);
  928. if (dialog.wasCanceled())
  929. return false;
  930. }
  931. return true;
  932. }
  933. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path) {
  934. const auto failed = [this] {
  935. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  936. tr("There was an error copying the RomFS files or the user "
  937. "cancelled the operation."));
  938. };
  939. const auto loader = Loader::GetLoader(vfs->OpenFile(game_path, FileSys::Mode::Read));
  940. if (loader == nullptr) {
  941. failed();
  942. return;
  943. }
  944. FileSys::VirtualFile file;
  945. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  946. failed();
  947. return;
  948. }
  949. const auto installed = Service::FileSystem::GetUnionContents();
  950. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  951. if (!romfs_title_id) {
  952. failed();
  953. return;
  954. }
  955. const auto path = fmt::format(
  956. "{}{:016X}/romfs", FileUtil::GetUserPath(FileUtil::UserPath::DumpDir), *romfs_title_id);
  957. FileSys::VirtualFile romfs;
  958. if (*romfs_title_id == program_id) {
  959. romfs = file;
  960. } else {
  961. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  962. }
  963. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  964. if (extracted == nullptr) {
  965. failed();
  966. return;
  967. }
  968. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  969. if (out == nullptr) {
  970. failed();
  971. vfs->DeleteDirectory(path);
  972. return;
  973. }
  974. bool ok;
  975. const auto res = QInputDialog::getItem(
  976. this, tr("Select RomFS Dump Mode"),
  977. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  978. "files into the new directory while <br>skeleton will only create the directory "
  979. "structure."),
  980. {"Full", "Skeleton"}, 0, false, &ok);
  981. if (!ok) {
  982. failed();
  983. vfs->DeleteDirectory(path);
  984. return;
  985. }
  986. const auto full = res == "Full";
  987. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  988. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  989. static_cast<s32>(entry_size), this);
  990. progress.setWindowModality(Qt::WindowModal);
  991. progress.setMinimumDuration(100);
  992. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  993. progress.close();
  994. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  995. tr("The operation completed successfully."));
  996. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  997. } else {
  998. progress.close();
  999. failed();
  1000. vfs->DeleteDirectory(path);
  1001. }
  1002. }
  1003. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  1004. QClipboard* clipboard = QGuiApplication::clipboard();
  1005. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  1006. }
  1007. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  1008. const CompatibilityList& compatibility_list) {
  1009. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  1010. QString directory;
  1011. if (it != compatibility_list.end())
  1012. directory = it->second.second;
  1013. QDesktopServices::openUrl(QUrl("https://yuzu-emu.org/game/" + directory));
  1014. }
  1015. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  1016. u64 title_id{};
  1017. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  1018. const auto loader = Loader::GetLoader(v_file);
  1019. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  1020. QMessageBox::information(this, tr("Properties"),
  1021. tr("The game properties could not be loaded."));
  1022. return;
  1023. }
  1024. ConfigurePerGameGeneral dialog(this, title_id);
  1025. dialog.loadFromFile(v_file);
  1026. auto result = dialog.exec();
  1027. if (result == QDialog::Accepted) {
  1028. dialog.applyConfiguration();
  1029. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1030. if (reload) {
  1031. game_list->PopulateAsync(UISettings::values.gamedir,
  1032. UISettings::values.gamedir_deepscan);
  1033. }
  1034. config->Save();
  1035. }
  1036. }
  1037. void GMainWindow::OnMenuLoadFile() {
  1038. const QString extensions =
  1039. QString("*.").append(GameList::supported_file_extensions.join(" *.")).append(" main");
  1040. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  1041. "%1 is an identifier for the Switch executable file extensions.")
  1042. .arg(extensions);
  1043. const QString filename = QFileDialog::getOpenFileName(
  1044. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  1045. if (filename.isEmpty()) {
  1046. return;
  1047. }
  1048. UISettings::values.roms_path = QFileInfo(filename).path();
  1049. BootGame(filename);
  1050. }
  1051. void GMainWindow::OnMenuLoadFolder() {
  1052. const QString dir_path =
  1053. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  1054. if (dir_path.isNull()) {
  1055. return;
  1056. }
  1057. const QDir dir{dir_path};
  1058. const QStringList matching_main = dir.entryList(QStringList("main"), QDir::Files);
  1059. if (matching_main.size() == 1) {
  1060. BootGame(dir.path() + DIR_SEP + matching_main[0]);
  1061. } else {
  1062. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  1063. tr("The directory you have selected does not contain a 'main' file."));
  1064. }
  1065. }
  1066. void GMainWindow::OnMenuInstallToNAND() {
  1067. const QString file_filter =
  1068. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  1069. "(*.nca);;Nintendo Submissions Package (*.nsp);;NX Cartridge "
  1070. "Image (*.xci)");
  1071. QString filename = QFileDialog::getOpenFileName(this, tr("Install File"),
  1072. UISettings::values.roms_path, file_filter);
  1073. if (filename.isEmpty()) {
  1074. return;
  1075. }
  1076. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1077. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1078. if (src == nullptr || dest == nullptr)
  1079. return false;
  1080. if (!dest->Resize(src->GetSize()))
  1081. return false;
  1082. std::array<u8, 0x1000> buffer{};
  1083. const int progress_maximum = static_cast<int>(src->GetSize() / buffer.size());
  1084. QProgressDialog progress(
  1085. tr("Installing file \"%1\"...").arg(QString::fromStdString(src->GetName())),
  1086. tr("Cancel"), 0, progress_maximum, this);
  1087. progress.setWindowModality(Qt::WindowModal);
  1088. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1089. if (progress.wasCanceled()) {
  1090. dest->Resize(0);
  1091. return false;
  1092. }
  1093. const int progress_value = static_cast<int>(i / buffer.size());
  1094. progress.setValue(progress_value);
  1095. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1096. dest->Write(buffer.data(), read, i);
  1097. }
  1098. return true;
  1099. };
  1100. const auto success = [this]() {
  1101. QMessageBox::information(this, tr("Successfully Installed"),
  1102. tr("The file was successfully installed."));
  1103. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1104. };
  1105. const auto failed = [this]() {
  1106. QMessageBox::warning(
  1107. this, tr("Failed to Install"),
  1108. tr("There was an error while attempting to install the provided file. It "
  1109. "could have an incorrect format or be missing metadata. Please "
  1110. "double-check your file and try again."));
  1111. };
  1112. const auto overwrite = [this]() {
  1113. return QMessageBox::question(this, tr("Failed to Install"),
  1114. tr("The file you are attempting to install already exists "
  1115. "in the cache. Would you like to overwrite it?")) ==
  1116. QMessageBox::Yes;
  1117. };
  1118. if (filename.endsWith("xci", Qt::CaseInsensitive) ||
  1119. filename.endsWith("nsp", Qt::CaseInsensitive)) {
  1120. std::shared_ptr<FileSys::NSP> nsp;
  1121. if (filename.endsWith("nsp", Qt::CaseInsensitive)) {
  1122. nsp = std::make_shared<FileSys::NSP>(
  1123. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1124. if (nsp->IsExtractedType())
  1125. failed();
  1126. } else {
  1127. const auto xci = std::make_shared<FileSys::XCI>(
  1128. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1129. nsp = xci->GetSecurePartitionNSP();
  1130. }
  1131. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  1132. failed();
  1133. return;
  1134. }
  1135. const auto res =
  1136. Service::FileSystem::GetUserNANDContents()->InstallEntry(*nsp, false, qt_raw_copy);
  1137. if (res == FileSys::InstallResult::Success) {
  1138. success();
  1139. } else {
  1140. if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  1141. if (overwrite()) {
  1142. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  1143. *nsp, true, qt_raw_copy);
  1144. if (res2 == FileSys::InstallResult::Success) {
  1145. success();
  1146. } else {
  1147. failed();
  1148. }
  1149. }
  1150. } else {
  1151. failed();
  1152. }
  1153. }
  1154. } else {
  1155. const auto nca = std::make_shared<FileSys::NCA>(
  1156. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1157. const auto id = nca->GetStatus();
  1158. // Game updates necessary are missing base RomFS
  1159. if (id != Loader::ResultStatus::Success &&
  1160. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  1161. failed();
  1162. return;
  1163. }
  1164. const QStringList tt_options{tr("System Application"),
  1165. tr("System Archive"),
  1166. tr("System Application Update"),
  1167. tr("Firmware Package (Type A)"),
  1168. tr("Firmware Package (Type B)"),
  1169. tr("Game"),
  1170. tr("Game Update"),
  1171. tr("Game DLC"),
  1172. tr("Delta Title")};
  1173. bool ok;
  1174. const auto item = QInputDialog::getItem(
  1175. this, tr("Select NCA Install Type..."),
  1176. tr("Please select the type of title you would like to install this NCA as:\n(In "
  1177. "most instances, the default 'Game' is fine.)"),
  1178. tt_options, 5, false, &ok);
  1179. auto index = tt_options.indexOf(item);
  1180. if (!ok || index == -1) {
  1181. QMessageBox::warning(this, tr("Failed to Install"),
  1182. tr("The title type you selected for the NCA is invalid."));
  1183. return;
  1184. }
  1185. // If index is equal to or past Game, add the jump in TitleType.
  1186. if (index >= 5) {
  1187. index += static_cast<size_t>(FileSys::TitleType::Application) -
  1188. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  1189. }
  1190. FileSys::InstallResult res;
  1191. if (index >= static_cast<size_t>(FileSys::TitleType::Application)) {
  1192. res = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  1193. *nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  1194. } else {
  1195. res = Service::FileSystem::GetSystemNANDContents()->InstallEntry(
  1196. *nca, static_cast<FileSys::TitleType>(index), false, qt_raw_copy);
  1197. }
  1198. if (res == FileSys::InstallResult::Success) {
  1199. success();
  1200. } else if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  1201. if (overwrite()) {
  1202. const auto res2 = Service::FileSystem::GetUserNANDContents()->InstallEntry(
  1203. *nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1204. if (res2 == FileSys::InstallResult::Success) {
  1205. success();
  1206. } else {
  1207. failed();
  1208. }
  1209. }
  1210. } else {
  1211. failed();
  1212. }
  1213. }
  1214. }
  1215. void GMainWindow::OnMenuSelectGameListRoot() {
  1216. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1217. if (!dir_path.isEmpty()) {
  1218. UISettings::values.gamedir = dir_path;
  1219. game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan);
  1220. }
  1221. }
  1222. void GMainWindow::OnMenuSelectEmulatedDirectory(EmulatedDirectoryTarget target) {
  1223. const auto res = QMessageBox::information(
  1224. this, tr("Changing Emulated Directory"),
  1225. tr("You are about to change the emulated %1 directory of the system. Please note "
  1226. "that this does not also move the contents of the previous directory to the "
  1227. "new one and you will have to do that yourself.")
  1228. .arg(target == EmulatedDirectoryTarget::SDMC ? tr("SD card") : tr("NAND")),
  1229. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1230. if (res == QMessageBox::Cancel)
  1231. return;
  1232. QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1233. if (!dir_path.isEmpty()) {
  1234. FileUtil::GetUserPath(target == EmulatedDirectoryTarget::SDMC ? FileUtil::UserPath::SDMCDir
  1235. : FileUtil::UserPath::NANDDir,
  1236. dir_path.toStdString());
  1237. Service::FileSystem::CreateFactories(*vfs);
  1238. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1239. }
  1240. }
  1241. void GMainWindow::OnMenuRecentFile() {
  1242. QAction* action = qobject_cast<QAction*>(sender());
  1243. assert(action);
  1244. const QString filename = action->data().toString();
  1245. if (QFileInfo::exists(filename)) {
  1246. BootGame(filename);
  1247. } else {
  1248. // Display an error message and remove the file from the list.
  1249. QMessageBox::information(this, tr("File not found"),
  1250. tr("File \"%1\" not found").arg(filename));
  1251. UISettings::values.recent_files.removeOne(filename);
  1252. UpdateRecentFiles();
  1253. }
  1254. }
  1255. void GMainWindow::OnStartGame() {
  1256. emu_thread->SetRunning(true);
  1257. qRegisterMetaType<Core::Frontend::SoftwareKeyboardParameters>(
  1258. "Core::Frontend::SoftwareKeyboardParameters");
  1259. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  1260. qRegisterMetaType<std::string>("std::string");
  1261. qRegisterMetaType<std::optional<std::u16string>>("std::optional<std::u16string>");
  1262. qRegisterMetaType<std::string_view>("std::string_view");
  1263. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  1264. ui.action_Start->setEnabled(false);
  1265. ui.action_Start->setText(tr("Continue"));
  1266. ui.action_Pause->setEnabled(true);
  1267. ui.action_Stop->setEnabled(true);
  1268. ui.action_Restart->setEnabled(true);
  1269. ui.action_Report_Compatibility->setEnabled(true);
  1270. discord_rpc->Update();
  1271. ui.action_Load_Amiibo->setEnabled(true);
  1272. ui.action_Capture_Screenshot->setEnabled(true);
  1273. }
  1274. void GMainWindow::OnPauseGame() {
  1275. emu_thread->SetRunning(false);
  1276. ui.action_Start->setEnabled(true);
  1277. ui.action_Pause->setEnabled(false);
  1278. ui.action_Stop->setEnabled(true);
  1279. ui.action_Capture_Screenshot->setEnabled(false);
  1280. }
  1281. void GMainWindow::OnStopGame() {
  1282. ShutdownGame();
  1283. }
  1284. void GMainWindow::OnLoadComplete() {
  1285. loading_screen->OnLoadComplete();
  1286. }
  1287. void GMainWindow::OnMenuReportCompatibility() {
  1288. if (!Settings::values.yuzu_token.empty() && !Settings::values.yuzu_username.empty()) {
  1289. CompatDB compatdb{this};
  1290. compatdb.exec();
  1291. } else {
  1292. QMessageBox::critical(
  1293. this, tr("Missing yuzu Account"),
  1294. tr("In order to submit a game compatibility test case, you must link your yuzu "
  1295. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  1296. "&gt; "
  1297. "Web."));
  1298. }
  1299. }
  1300. void GMainWindow::ToggleFullscreen() {
  1301. if (!emulation_running) {
  1302. return;
  1303. }
  1304. if (ui.action_Fullscreen->isChecked()) {
  1305. ShowFullscreen();
  1306. } else {
  1307. HideFullscreen();
  1308. }
  1309. }
  1310. void GMainWindow::ShowFullscreen() {
  1311. if (ui.action_Single_Window_Mode->isChecked()) {
  1312. UISettings::values.geometry = saveGeometry();
  1313. ui.menubar->hide();
  1314. statusBar()->hide();
  1315. showFullScreen();
  1316. } else {
  1317. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1318. render_window->showFullScreen();
  1319. }
  1320. }
  1321. void GMainWindow::HideFullscreen() {
  1322. if (ui.action_Single_Window_Mode->isChecked()) {
  1323. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  1324. ui.menubar->show();
  1325. showNormal();
  1326. restoreGeometry(UISettings::values.geometry);
  1327. } else {
  1328. render_window->showNormal();
  1329. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  1330. }
  1331. }
  1332. void GMainWindow::ToggleWindowMode() {
  1333. if (ui.action_Single_Window_Mode->isChecked()) {
  1334. // Render in the main window...
  1335. render_window->BackupGeometry();
  1336. ui.horizontalLayout->addWidget(render_window);
  1337. render_window->setFocusPolicy(Qt::ClickFocus);
  1338. if (emulation_running) {
  1339. render_window->setVisible(true);
  1340. render_window->setFocus();
  1341. game_list->hide();
  1342. }
  1343. } else {
  1344. // Render in a separate window...
  1345. ui.horizontalLayout->removeWidget(render_window);
  1346. render_window->setParent(nullptr);
  1347. render_window->setFocusPolicy(Qt::NoFocus);
  1348. if (emulation_running) {
  1349. render_window->setVisible(true);
  1350. render_window->RestoreGeometry();
  1351. game_list->show();
  1352. }
  1353. }
  1354. }
  1355. void GMainWindow::OnConfigure() {
  1356. ConfigureDialog configureDialog(this, hotkey_registry);
  1357. auto old_theme = UISettings::values.theme;
  1358. const bool old_discord_presence = UISettings::values.enable_discord_presence;
  1359. auto result = configureDialog.exec();
  1360. if (result == QDialog::Accepted) {
  1361. configureDialog.applyConfiguration();
  1362. if (UISettings::values.theme != old_theme)
  1363. UpdateUITheme();
  1364. if (UISettings::values.enable_discord_presence != old_discord_presence)
  1365. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  1366. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1367. if (reload) {
  1368. game_list->PopulateAsync(UISettings::values.gamedir,
  1369. UISettings::values.gamedir_deepscan);
  1370. }
  1371. config->Save();
  1372. }
  1373. }
  1374. void GMainWindow::OnLoadAmiibo() {
  1375. const QString extensions{"*.bin"};
  1376. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  1377. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), "", file_filter);
  1378. if (filename.isEmpty()) {
  1379. return;
  1380. }
  1381. Core::System& system{Core::System::GetInstance()};
  1382. Service::SM::ServiceManager& sm = system.ServiceManager();
  1383. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  1384. if (nfc == nullptr) {
  1385. return;
  1386. }
  1387. QFile nfc_file{filename};
  1388. if (!nfc_file.open(QIODevice::ReadOnly)) {
  1389. QMessageBox::warning(this, tr("Error opening Amiibo data file"),
  1390. tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
  1391. return;
  1392. }
  1393. const u64 nfc_file_size = nfc_file.size();
  1394. std::vector<u8> buffer(nfc_file_size);
  1395. const u64 read_size = nfc_file.read(reinterpret_cast<char*>(buffer.data()), nfc_file_size);
  1396. if (nfc_file_size != read_size) {
  1397. QMessageBox::warning(this, tr("Error reading Amiibo data file"),
  1398. tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
  1399. "was only able to read %2 bytes.")
  1400. .arg(nfc_file_size)
  1401. .arg(read_size));
  1402. return;
  1403. }
  1404. if (!nfc->LoadAmiibo(buffer)) {
  1405. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  1406. tr("Unable to load Amiibo data."));
  1407. }
  1408. }
  1409. void GMainWindow::OnOpenYuzuFolder() {
  1410. QDesktopServices::openUrl(QUrl::fromLocalFile(
  1411. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::UserDir))));
  1412. }
  1413. void GMainWindow::OnAbout() {
  1414. AboutDialog aboutDialog(this);
  1415. aboutDialog.exec();
  1416. }
  1417. void GMainWindow::OnToggleFilterBar() {
  1418. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  1419. if (ui.action_Show_Filter_Bar->isChecked()) {
  1420. game_list->setFilterFocus();
  1421. } else {
  1422. game_list->clearFilter();
  1423. }
  1424. }
  1425. void GMainWindow::OnCaptureScreenshot() {
  1426. OnPauseGame();
  1427. QFileDialog png_dialog(this, tr("Capture Screenshot"), UISettings::values.screenshot_path,
  1428. tr("PNG Image (*.png)"));
  1429. png_dialog.setAcceptMode(QFileDialog::AcceptSave);
  1430. png_dialog.setDefaultSuffix("png");
  1431. png_dialog.exec();
  1432. const QString path = png_dialog.selectedFiles().first();
  1433. if (!path.isEmpty()) {
  1434. UISettings::values.screenshot_path = QFileInfo(path).path();
  1435. render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor, path);
  1436. }
  1437. OnStartGame();
  1438. }
  1439. void GMainWindow::UpdateStatusBar() {
  1440. if (emu_thread == nullptr) {
  1441. status_bar_update_timer.stop();
  1442. return;
  1443. }
  1444. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  1445. if (Settings::values.use_frame_limit) {
  1446. emu_speed_label->setText(tr("Speed: %1% / %2%")
  1447. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  1448. .arg(Settings::values.frame_limit));
  1449. } else {
  1450. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  1451. }
  1452. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  1453. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  1454. emu_speed_label->setVisible(true);
  1455. game_fps_label->setVisible(true);
  1456. emu_frametime_label->setVisible(true);
  1457. }
  1458. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  1459. QMessageBox::StandardButton answer;
  1460. QString status_message;
  1461. const QString common_message =
  1462. tr("The game you are trying to load requires additional files from your Switch to be "
  1463. "dumped "
  1464. "before playing.<br/><br/>For more information on dumping these files, please see the "
  1465. "following wiki page: <a "
  1466. "href='https://yuzu-emu.org/wiki/"
  1467. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  1468. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  1469. "quit "
  1470. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  1471. "data, or other bugs.");
  1472. switch (result) {
  1473. case Core::System::ResultStatus::ErrorSystemFiles: {
  1474. QString message = "yuzu was unable to locate a Switch system archive";
  1475. if (!details.empty()) {
  1476. message.append(tr(": %1. ").arg(details.c_str()));
  1477. } else {
  1478. message.append(". ");
  1479. }
  1480. message.append(common_message);
  1481. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  1482. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1483. status_message = "System Archive Missing";
  1484. break;
  1485. }
  1486. case Core::System::ResultStatus::ErrorSharedFont: {
  1487. QString message = tr("yuzu was unable to locate the Switch shared fonts. ");
  1488. message.append(common_message);
  1489. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  1490. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1491. status_message = "Shared Font Missing";
  1492. break;
  1493. }
  1494. default:
  1495. answer = QMessageBox::question(
  1496. this, tr("Fatal Error"),
  1497. tr("yuzu has encountered a fatal error, please see the log for more details. "
  1498. "For more information on accessing the log, please see the following page: "
  1499. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  1500. "to "
  1501. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  1502. "list? "
  1503. "Continuing emulation may result in crashes, corrupted save data, or other "
  1504. "bugs."),
  1505. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1506. status_message = "Fatal Error encountered";
  1507. break;
  1508. }
  1509. if (answer == QMessageBox::Yes) {
  1510. if (emu_thread) {
  1511. ShutdownGame();
  1512. }
  1513. } else {
  1514. // Only show the message if the game is still running.
  1515. if (emu_thread) {
  1516. emu_thread->SetRunning(true);
  1517. message_label->setText(status_message);
  1518. message_label->setVisible(true);
  1519. }
  1520. }
  1521. }
  1522. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  1523. if (behavior == ReinitializeKeyBehavior::Warning) {
  1524. const auto res = QMessageBox::information(
  1525. this, tr("Confirm Key Rederivation"),
  1526. tr("You are about to force rederive all of your keys. \nIf you do not know what this "
  1527. "means or what you are doing, \nthis is a potentially destructive action. \nPlease "
  1528. "make sure this is what you want \nand optionally make backups.\n\nThis will delete "
  1529. "your autogenerated key files and re-run the key derivation module."),
  1530. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1531. if (res == QMessageBox::Cancel)
  1532. return;
  1533. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1534. "prod.keys_autogenerated");
  1535. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1536. "console.keys_autogenerated");
  1537. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1538. "title.keys_autogenerated");
  1539. }
  1540. Core::Crypto::KeyManager keys{};
  1541. if (keys.BaseDeriveNecessary()) {
  1542. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory(
  1543. FileUtil::GetUserPath(FileUtil::UserPath::SysDataDir), FileSys::Mode::Read)};
  1544. const auto function = [this, &keys, &pdm] {
  1545. keys.PopulateFromPartitionData(pdm);
  1546. Service::FileSystem::CreateFactories(*vfs);
  1547. keys.DeriveETicket(pdm);
  1548. };
  1549. QString errors;
  1550. if (!pdm.HasFuses())
  1551. errors += tr("- Missing fuses - Cannot derive SBK\n");
  1552. if (!pdm.HasBoot0())
  1553. errors += tr("- Missing BOOT0 - Cannot derive master keys\n");
  1554. if (!pdm.HasPackage2())
  1555. errors += tr("- Missing BCPKG2-1-Normal-Main - Cannot derive general keys\n");
  1556. if (!pdm.HasProdInfo())
  1557. errors += tr("- Missing PRODINFO - Cannot derive title keys\n");
  1558. if (!errors.isEmpty()) {
  1559. QMessageBox::warning(
  1560. this, tr("Warning Missing Derivation Components"),
  1561. tr("The following are missing from your configuration that may hinder key "
  1562. "derivation. It will be attempted but may not complete.<br><br>") +
  1563. errors +
  1564. tr("<br><br>You can get all of these and dump all of your games easily by "
  1565. "following <a href='https://yuzu-emu.org/help/quickstart/'>the "
  1566. "quickstart guide</a>. Alternatively, you can use another method of dumping"
  1567. "to obtain all of your keys."));
  1568. }
  1569. QProgressDialog prog;
  1570. prog.setRange(0, 0);
  1571. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  1572. "system's performance."));
  1573. prog.setWindowTitle(tr("Deriving Keys"));
  1574. prog.show();
  1575. auto future = QtConcurrent::run(function);
  1576. while (!future.isFinished()) {
  1577. QCoreApplication::processEvents();
  1578. }
  1579. prog.close();
  1580. }
  1581. Service::FileSystem::CreateFactories(*vfs);
  1582. if (behavior == ReinitializeKeyBehavior::Warning) {
  1583. game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
  1584. }
  1585. }
  1586. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(
  1587. const FileSys::RegisteredCacheUnion& installed, u64 program_id) {
  1588. const auto dlc_entries =
  1589. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1590. std::vector<FileSys::RegisteredCacheEntry> dlc_match;
  1591. dlc_match.reserve(dlc_entries.size());
  1592. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  1593. [&program_id, &installed](const FileSys::RegisteredCacheEntry& entry) {
  1594. return (entry.title_id & DLC_BASE_TITLE_ID_MASK) == program_id &&
  1595. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  1596. });
  1597. std::vector<u64> romfs_tids;
  1598. romfs_tids.push_back(program_id);
  1599. for (const auto& entry : dlc_match)
  1600. romfs_tids.push_back(entry.title_id);
  1601. if (romfs_tids.size() > 1) {
  1602. QStringList list{"Base"};
  1603. for (std::size_t i = 1; i < romfs_tids.size(); ++i)
  1604. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  1605. bool ok;
  1606. const auto res = QInputDialog::getItem(
  1607. this, tr("Select RomFS Dump Target"),
  1608. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  1609. if (!ok) {
  1610. return {};
  1611. }
  1612. return romfs_tids[list.indexOf(res)];
  1613. }
  1614. return program_id;
  1615. }
  1616. bool GMainWindow::ConfirmClose() {
  1617. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  1618. return true;
  1619. QMessageBox::StandardButton answer =
  1620. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  1621. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1622. return answer != QMessageBox::No;
  1623. }
  1624. void GMainWindow::closeEvent(QCloseEvent* event) {
  1625. if (!ConfirmClose()) {
  1626. event->ignore();
  1627. return;
  1628. }
  1629. if (!ui.action_Fullscreen->isChecked()) {
  1630. UISettings::values.geometry = saveGeometry();
  1631. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1632. }
  1633. UISettings::values.state = saveState();
  1634. #if MICROPROFILE_ENABLED
  1635. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  1636. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  1637. #endif
  1638. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  1639. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  1640. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  1641. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  1642. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  1643. UISettings::values.first_start = false;
  1644. game_list->SaveInterfaceLayout();
  1645. hotkey_registry.SaveHotkeys();
  1646. // Shutdown session if the emu thread is active...
  1647. if (emu_thread != nullptr)
  1648. ShutdownGame();
  1649. render_window->close();
  1650. QWidget::closeEvent(event);
  1651. }
  1652. static bool IsSingleFileDropEvent(QDropEvent* event) {
  1653. const QMimeData* mimeData = event->mimeData();
  1654. return mimeData->hasUrls() && mimeData->urls().length() == 1;
  1655. }
  1656. void GMainWindow::dropEvent(QDropEvent* event) {
  1657. if (IsSingleFileDropEvent(event) && ConfirmChangeGame()) {
  1658. const QMimeData* mimeData = event->mimeData();
  1659. QString filename = mimeData->urls().at(0).toLocalFile();
  1660. BootGame(filename);
  1661. }
  1662. }
  1663. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  1664. if (IsSingleFileDropEvent(event)) {
  1665. event->acceptProposedAction();
  1666. }
  1667. }
  1668. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  1669. event->acceptProposedAction();
  1670. }
  1671. bool GMainWindow::ConfirmChangeGame() {
  1672. if (emu_thread == nullptr)
  1673. return true;
  1674. auto answer = QMessageBox::question(
  1675. this, tr("yuzu"),
  1676. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  1677. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1678. return answer != QMessageBox::No;
  1679. }
  1680. void GMainWindow::filterBarSetChecked(bool state) {
  1681. ui.action_Show_Filter_Bar->setChecked(state);
  1682. emit(OnToggleFilterBar());
  1683. }
  1684. void GMainWindow::UpdateUITheme() {
  1685. QStringList theme_paths(default_theme_paths);
  1686. if (UISettings::values.theme != UISettings::themes[0].second &&
  1687. !UISettings::values.theme.isEmpty()) {
  1688. const QString theme_uri(":" + UISettings::values.theme + "/style.qss");
  1689. QFile f(theme_uri);
  1690. if (f.open(QFile::ReadOnly | QFile::Text)) {
  1691. QTextStream ts(&f);
  1692. qApp->setStyleSheet(ts.readAll());
  1693. GMainWindow::setStyleSheet(ts.readAll());
  1694. } else {
  1695. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  1696. }
  1697. theme_paths.append(QStringList{":/icons/default", ":/icons/" + UISettings::values.theme});
  1698. QIcon::setThemeName(":/icons/" + UISettings::values.theme);
  1699. } else {
  1700. qApp->setStyleSheet("");
  1701. GMainWindow::setStyleSheet("");
  1702. theme_paths.append(QStringList{":/icons/default"});
  1703. QIcon::setThemeName(":/icons/default");
  1704. }
  1705. QIcon::setThemeSearchPaths(theme_paths);
  1706. emit UpdateThemedIcons();
  1707. }
  1708. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  1709. #ifdef USE_DISCORD_PRESENCE
  1710. if (state) {
  1711. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  1712. } else {
  1713. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1714. }
  1715. #else
  1716. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  1717. #endif
  1718. discord_rpc->Update();
  1719. }
  1720. #ifdef main
  1721. #undef main
  1722. #endif
  1723. int main(int argc, char* argv[]) {
  1724. Common::DetachedTasks detached_tasks;
  1725. MicroProfileOnThreadCreate("Frontend");
  1726. SCOPE_EXIT({ MicroProfileShutdown(); });
  1727. // Init settings params
  1728. QCoreApplication::setOrganizationName("yuzu team");
  1729. QCoreApplication::setApplicationName("yuzu");
  1730. QApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  1731. QApplication app(argc, argv);
  1732. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  1733. // generating shaders
  1734. setlocale(LC_ALL, "C");
  1735. GMainWindow main_window;
  1736. // After settings have been loaded by GMainWindow, apply the filter
  1737. main_window.show();
  1738. Settings::LogSettings();
  1739. int result = app.exec();
  1740. detached_tasks.WaitForAllTasks();
  1741. return result;
  1742. }