main.cpp 99 KB

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