main.cpp 81 KB

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