main.cpp 79 KB

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