main.cpp 88 KB

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