main.cpp 87 KB

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