main.cpp 92 KB

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