main.cpp 98 KB

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