main.cpp 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cinttypes>
  5. #include <clocale>
  6. #include <memory>
  7. #include <thread>
  8. #ifdef __APPLE__
  9. #include <unistd.h> // for chdir
  10. #endif
  11. // VFS includes must be before glad as they will conflict with Windows file api, which uses defines.
  12. #include "applets/error.h"
  13. #include "applets/profile_select.h"
  14. #include "applets/software_keyboard.h"
  15. #include "applets/web_browser.h"
  16. #include "configuration/configure_input.h"
  17. #include "configuration/configure_per_general.h"
  18. #include "core/file_sys/vfs.h"
  19. #include "core/file_sys/vfs_real.h"
  20. #include "core/frontend/applets/general_frontend.h"
  21. #include "core/hle/service/acc/profile_manager.h"
  22. #include "core/hle/service/am/applet_ae.h"
  23. #include "core/hle/service/am/applet_oe.h"
  24. #include "core/hle/service/am/applets/applets.h"
  25. #include "core/hle/service/hid/controllers/npad.h"
  26. #include "core/hle/service/hid/hid.h"
  27. // These are wrappers to avoid the calls to CreateDirectory and CreateFile because of the Windows
  28. // defines.
  29. static FileSys::VirtualDir VfsFilesystemCreateDirectoryWrapper(
  30. const FileSys::VirtualFilesystem& vfs, const std::string& path, FileSys::Mode mode) {
  31. return vfs->CreateDirectory(path, mode);
  32. }
  33. static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::VirtualDir& dir,
  34. const std::string& path) {
  35. return dir->CreateFile(path);
  36. }
  37. #include <fmt/ostream.h>
  38. #include <glad/glad.h>
  39. #define QT_NO_OPENGL
  40. #include <QClipboard>
  41. #include <QDesktopServices>
  42. #include <QDesktopWidget>
  43. #include <QDialogButtonBox>
  44. #include <QFile>
  45. #include <QFileDialog>
  46. #include <QInputDialog>
  47. #include <QMessageBox>
  48. #include <QProgressBar>
  49. #include <QProgressDialog>
  50. #include <QShortcut>
  51. #include <QStatusBar>
  52. #include <QSysInfo>
  53. #include <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. Settings::values.use_asynchronous_gpu_emulation =
  455. !Settings::values.use_asynchronous_gpu_emulation;
  456. async_status_button->setChecked(Settings::values.use_asynchronous_gpu_emulation);
  457. Settings::Apply();
  458. });
  459. async_status_button->setText(tr("ASYNC"));
  460. async_status_button->setCheckable(true);
  461. async_status_button->setChecked(Settings::values.use_asynchronous_gpu_emulation);
  462. statusBar()->insertPermanentWidget(0, async_status_button);
  463. // Setup Renderer API button
  464. renderer_status_button = new QPushButton();
  465. renderer_status_button->setObjectName(QStringLiteral("RendererStatusBarButton"));
  466. renderer_status_button->setCheckable(true);
  467. renderer_status_button->setFocusPolicy(Qt::NoFocus);
  468. connect(renderer_status_button, &QPushButton::toggled, [=](bool checked) {
  469. renderer_status_button->setText(checked ? tr("VULKAN") : tr("OPENGL"));
  470. });
  471. renderer_status_button->toggle();
  472. #ifndef HAS_VULKAN
  473. renderer_status_button->setChecked(false);
  474. renderer_status_button->setCheckable(false);
  475. renderer_status_button->setDisabled(true);
  476. #else
  477. renderer_status_button->setChecked(Settings::values.renderer_backend ==
  478. Settings::RendererBackend::Vulkan);
  479. connect(renderer_status_button, &QPushButton::clicked, [=] {
  480. if (emulation_running) {
  481. return;
  482. }
  483. if (renderer_status_button->isChecked()) {
  484. Settings::values.renderer_backend = Settings::RendererBackend::Vulkan;
  485. } else {
  486. Settings::values.renderer_backend = Settings::RendererBackend::OpenGL;
  487. }
  488. Settings::Apply();
  489. });
  490. #endif // HAS_VULKAN
  491. statusBar()->insertPermanentWidget(0, renderer_status_button);
  492. statusBar()->setVisible(true);
  493. setStyleSheet(QStringLiteral("QStatusBar::item{border: none;}"));
  494. }
  495. void GMainWindow::InitializeDebugWidgets() {
  496. QMenu* debug_menu = ui.menu_View_Debugging;
  497. #if MICROPROFILE_ENABLED
  498. microProfileDialog = new MicroProfileDialog(this);
  499. microProfileDialog->hide();
  500. debug_menu->addAction(microProfileDialog->toggleViewAction());
  501. #endif
  502. waitTreeWidget = new WaitTreeWidget(this);
  503. addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget);
  504. waitTreeWidget->hide();
  505. debug_menu->addAction(waitTreeWidget->toggleViewAction());
  506. connect(this, &GMainWindow::EmulationStarting, waitTreeWidget,
  507. &WaitTreeWidget::OnEmulationStarting);
  508. connect(this, &GMainWindow::EmulationStopping, waitTreeWidget,
  509. &WaitTreeWidget::OnEmulationStopping);
  510. }
  511. void GMainWindow::InitializeRecentFileMenuActions() {
  512. for (int i = 0; i < max_recent_files_item; ++i) {
  513. actions_recent_files[i] = new QAction(this);
  514. actions_recent_files[i]->setVisible(false);
  515. connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile);
  516. ui.menu_recent_files->addAction(actions_recent_files[i]);
  517. }
  518. ui.menu_recent_files->addSeparator();
  519. QAction* action_clear_recent_files = new QAction(this);
  520. action_clear_recent_files->setText(tr("Clear Recent Files"));
  521. connect(action_clear_recent_files, &QAction::triggered, this, [this] {
  522. UISettings::values.recent_files.clear();
  523. UpdateRecentFiles();
  524. });
  525. ui.menu_recent_files->addAction(action_clear_recent_files);
  526. UpdateRecentFiles();
  527. }
  528. void GMainWindow::InitializeHotkeys() {
  529. hotkey_registry.LoadHotkeys();
  530. const QString main_window = QStringLiteral("Main Window");
  531. const QString load_file = QStringLiteral("Load File");
  532. const QString load_amiibo = QStringLiteral("Load Amiibo");
  533. const QString exit_yuzu = QStringLiteral("Exit yuzu");
  534. const QString restart_emulation = QStringLiteral("Restart Emulation");
  535. const QString stop_emulation = QStringLiteral("Stop Emulation");
  536. const QString toggle_filter_bar = QStringLiteral("Toggle Filter Bar");
  537. const QString toggle_status_bar = QStringLiteral("Toggle Status Bar");
  538. const QString fullscreen = QStringLiteral("Fullscreen");
  539. const QString capture_screenshot = QStringLiteral("Capture Screenshot");
  540. ui.action_Load_File->setShortcut(hotkey_registry.GetKeySequence(main_window, load_file));
  541. ui.action_Load_File->setShortcutContext(
  542. hotkey_registry.GetShortcutContext(main_window, load_file));
  543. ui.action_Load_Amiibo->setShortcut(hotkey_registry.GetKeySequence(main_window, load_amiibo));
  544. ui.action_Load_Amiibo->setShortcutContext(
  545. hotkey_registry.GetShortcutContext(main_window, load_amiibo));
  546. ui.action_Exit->setShortcut(hotkey_registry.GetKeySequence(main_window, exit_yuzu));
  547. ui.action_Exit->setShortcutContext(hotkey_registry.GetShortcutContext(main_window, exit_yuzu));
  548. ui.action_Restart->setShortcut(hotkey_registry.GetKeySequence(main_window, restart_emulation));
  549. ui.action_Restart->setShortcutContext(
  550. hotkey_registry.GetShortcutContext(main_window, restart_emulation));
  551. ui.action_Stop->setShortcut(hotkey_registry.GetKeySequence(main_window, stop_emulation));
  552. ui.action_Stop->setShortcutContext(
  553. hotkey_registry.GetShortcutContext(main_window, stop_emulation));
  554. ui.action_Show_Filter_Bar->setShortcut(
  555. hotkey_registry.GetKeySequence(main_window, toggle_filter_bar));
  556. ui.action_Show_Filter_Bar->setShortcutContext(
  557. hotkey_registry.GetShortcutContext(main_window, toggle_filter_bar));
  558. ui.action_Show_Status_Bar->setShortcut(
  559. hotkey_registry.GetKeySequence(main_window, toggle_status_bar));
  560. ui.action_Show_Status_Bar->setShortcutContext(
  561. hotkey_registry.GetShortcutContext(main_window, toggle_status_bar));
  562. ui.action_Capture_Screenshot->setShortcut(
  563. hotkey_registry.GetKeySequence(main_window, capture_screenshot));
  564. ui.action_Capture_Screenshot->setShortcutContext(
  565. hotkey_registry.GetShortcutContext(main_window, capture_screenshot));
  566. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Load File"), this),
  567. &QShortcut::activated, this, &GMainWindow::OnMenuLoadFile);
  568. connect(
  569. hotkey_registry.GetHotkey(main_window, QStringLiteral("Continue/Pause Emulation"), this),
  570. &QShortcut::activated, this, [&] {
  571. if (emulation_running) {
  572. if (emu_thread->IsRunning()) {
  573. OnPauseGame();
  574. } else {
  575. OnStartGame();
  576. }
  577. }
  578. });
  579. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Restart Emulation"), this),
  580. &QShortcut::activated, this, [this] {
  581. if (!Core::System::GetInstance().IsPoweredOn()) {
  582. return;
  583. }
  584. BootGame(game_path);
  585. });
  586. connect(hotkey_registry.GetHotkey(main_window, fullscreen, render_window),
  587. &QShortcut::activated, ui.action_Fullscreen, &QAction::trigger);
  588. connect(hotkey_registry.GetHotkey(main_window, fullscreen, render_window),
  589. &QShortcut::activatedAmbiguously, ui.action_Fullscreen, &QAction::trigger);
  590. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Exit Fullscreen"), this),
  591. &QShortcut::activated, this, [&] {
  592. if (emulation_running) {
  593. ui.action_Fullscreen->setChecked(false);
  594. ToggleFullscreen();
  595. }
  596. });
  597. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Toggle Speed Limit"), this),
  598. &QShortcut::activated, this, [&] {
  599. Settings::values.use_frame_limit = !Settings::values.use_frame_limit;
  600. UpdateStatusBar();
  601. });
  602. constexpr u16 SPEED_LIMIT_STEP = 5;
  603. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Increase Speed Limit"), this),
  604. &QShortcut::activated, this, [&] {
  605. if (Settings::values.frame_limit < 9999 - SPEED_LIMIT_STEP) {
  606. Settings::values.frame_limit += SPEED_LIMIT_STEP;
  607. UpdateStatusBar();
  608. }
  609. });
  610. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Decrease Speed Limit"), this),
  611. &QShortcut::activated, this, [&] {
  612. if (Settings::values.frame_limit > SPEED_LIMIT_STEP) {
  613. Settings::values.frame_limit -= SPEED_LIMIT_STEP;
  614. UpdateStatusBar();
  615. }
  616. });
  617. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Load Amiibo"), this),
  618. &QShortcut::activated, this, [&] {
  619. if (ui.action_Load_Amiibo->isEnabled()) {
  620. OnLoadAmiibo();
  621. }
  622. });
  623. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Capture Screenshot"), this),
  624. &QShortcut::activated, this, [&] {
  625. if (emu_thread->IsRunning()) {
  626. OnCaptureScreenshot();
  627. }
  628. });
  629. connect(hotkey_registry.GetHotkey(main_window, QStringLiteral("Change Docked Mode"), this),
  630. &QShortcut::activated, this, [&] {
  631. Settings::values.use_docked_mode = !Settings::values.use_docked_mode;
  632. OnDockedModeChanged(!Settings::values.use_docked_mode,
  633. Settings::values.use_docked_mode);
  634. dock_status_button->setChecked(Settings::values.use_docked_mode);
  635. });
  636. }
  637. void GMainWindow::SetDefaultUIGeometry() {
  638. // geometry: 53% of the window contents are in the upper screen half, 47% in the lower half
  639. const QRect screenRect = QApplication::desktop()->screenGeometry(this);
  640. const int w = screenRect.width() * 2 / 3;
  641. const int h = screenRect.height() * 2 / 3;
  642. const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2;
  643. const int y = (screenRect.y() + screenRect.height()) / 2 - h * 53 / 100;
  644. setGeometry(x, y, w, h);
  645. }
  646. void GMainWindow::RestoreUIState() {
  647. restoreGeometry(UISettings::values.geometry);
  648. restoreState(UISettings::values.state);
  649. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  650. #if MICROPROFILE_ENABLED
  651. microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry);
  652. microProfileDialog->setVisible(UISettings::values.microprofile_visible);
  653. #endif
  654. game_list->LoadInterfaceLayout();
  655. ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode);
  656. ToggleWindowMode();
  657. ui.action_Fullscreen->setChecked(UISettings::values.fullscreen);
  658. ui.action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);
  659. OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked());
  660. ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar);
  661. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  662. ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);
  663. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  664. Debugger::ToggleConsole();
  665. }
  666. void GMainWindow::OnAppFocusStateChanged(Qt::ApplicationState state) {
  667. if (!UISettings::values.pause_when_in_background) {
  668. return;
  669. }
  670. if (state != Qt::ApplicationHidden && state != Qt::ApplicationInactive &&
  671. state != Qt::ApplicationActive) {
  672. LOG_DEBUG(Frontend, "ApplicationState unusual flag: {} ", state);
  673. }
  674. if (ui.action_Pause->isEnabled() &&
  675. (state & (Qt::ApplicationHidden | Qt::ApplicationInactive))) {
  676. auto_paused = true;
  677. OnPauseGame();
  678. } else if (ui.action_Start->isEnabled() && auto_paused && state == Qt::ApplicationActive) {
  679. auto_paused = false;
  680. OnStartGame();
  681. }
  682. }
  683. void GMainWindow::ConnectWidgetEvents() {
  684. connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile);
  685. connect(game_list, &GameList::OpenDirectory, this, &GMainWindow::OnGameListOpenDirectory);
  686. connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder);
  687. connect(game_list, &GameList::OpenTransferableShaderCacheRequested, this,
  688. &GMainWindow::OnTransferableShaderCacheOpenFile);
  689. connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS);
  690. connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID);
  691. connect(game_list, &GameList::NavigateToGamedbEntryRequested, this,
  692. &GMainWindow::OnGameListNavigateToGamedbEntry);
  693. connect(game_list, &GameList::AddDirectory, this, &GMainWindow::OnGameListAddDirectory);
  694. connect(game_list_placeholder, &GameListPlaceholder::AddDirectory, this,
  695. &GMainWindow::OnGameListAddDirectory);
  696. connect(game_list, &GameList::ShowList, this, &GMainWindow::OnGameListShowList);
  697. connect(game_list, &GameList::OpenPerGameGeneralRequested, this,
  698. &GMainWindow::OnGameListOpenPerGameProperties);
  699. connect(this, &GMainWindow::EmulationStarting, render_window,
  700. &GRenderWindow::OnEmulationStarting);
  701. connect(this, &GMainWindow::EmulationStopping, render_window,
  702. &GRenderWindow::OnEmulationStopping);
  703. connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar);
  704. }
  705. void GMainWindow::ConnectMenuEvents() {
  706. // File
  707. connect(ui.action_Load_File, &QAction::triggered, this, &GMainWindow::OnMenuLoadFile);
  708. connect(ui.action_Load_Folder, &QAction::triggered, this, &GMainWindow::OnMenuLoadFolder);
  709. connect(ui.action_Install_File_NAND, &QAction::triggered, this,
  710. &GMainWindow::OnMenuInstallToNAND);
  711. connect(ui.action_Exit, &QAction::triggered, this, &QMainWindow::close);
  712. connect(ui.action_Load_Amiibo, &QAction::triggered, this, &GMainWindow::OnLoadAmiibo);
  713. // Emulation
  714. connect(ui.action_Start, &QAction::triggered, this, &GMainWindow::OnStartGame);
  715. connect(ui.action_Pause, &QAction::triggered, this, &GMainWindow::OnPauseGame);
  716. connect(ui.action_Stop, &QAction::triggered, this, &GMainWindow::OnStopGame);
  717. connect(ui.action_Report_Compatibility, &QAction::triggered, this,
  718. &GMainWindow::OnMenuReportCompatibility);
  719. connect(ui.action_Open_Mods_Page, &QAction::triggered, this, &GMainWindow::OnOpenModsPage);
  720. connect(ui.action_Open_Quickstart_Guide, &QAction::triggered, this,
  721. &GMainWindow::OnQuickstartGuide);
  722. connect(ui.action_Open_FAQ, &QAction::triggered, this, &GMainWindow::OnFAQ);
  723. connect(ui.action_Restart, &QAction::triggered, this, [this] { BootGame(QString(game_path)); });
  724. connect(ui.action_Configure, &QAction::triggered, this, &GMainWindow::OnConfigure);
  725. // View
  726. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  727. &GMainWindow::ToggleWindowMode);
  728. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  729. &GMainWindow::OnDisplayTitleBars);
  730. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  731. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  732. connect(ui.action_Reset_Window_Size, &QAction::triggered, this, &GMainWindow::ResetWindowSize);
  733. // Fullscreen
  734. ui.action_Fullscreen->setShortcut(
  735. hotkey_registry
  736. .GetHotkey(QStringLiteral("Main Window"), QStringLiteral("Fullscreen"), this)
  737. ->key());
  738. connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
  739. // Movie
  740. connect(ui.action_Capture_Screenshot, &QAction::triggered, this,
  741. &GMainWindow::OnCaptureScreenshot);
  742. // Help
  743. connect(ui.action_Open_yuzu_Folder, &QAction::triggered, this, &GMainWindow::OnOpenYuzuFolder);
  744. connect(ui.action_Rederive, &QAction::triggered, this,
  745. std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning));
  746. connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
  747. }
  748. void GMainWindow::OnDisplayTitleBars(bool show) {
  749. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  750. if (show) {
  751. for (QDockWidget* widget : widgets) {
  752. QWidget* old = widget->titleBarWidget();
  753. widget->setTitleBarWidget(nullptr);
  754. if (old != nullptr)
  755. delete old;
  756. }
  757. } else {
  758. for (QDockWidget* widget : widgets) {
  759. QWidget* old = widget->titleBarWidget();
  760. widget->setTitleBarWidget(new QWidget());
  761. if (old != nullptr)
  762. delete old;
  763. }
  764. }
  765. }
  766. void GMainWindow::PreventOSSleep() {
  767. #ifdef _WIN32
  768. SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
  769. #endif
  770. }
  771. void GMainWindow::AllowOSSleep() {
  772. #ifdef _WIN32
  773. SetThreadExecutionState(ES_CONTINUOUS);
  774. #endif
  775. }
  776. bool GMainWindow::LoadROM(const QString& filename) {
  777. // Shutdown previous session if the emu thread is still active...
  778. if (emu_thread != nullptr)
  779. ShutdownGame();
  780. if (!render_window->InitRenderTarget()) {
  781. return false;
  782. }
  783. Core::System& system{Core::System::GetInstance()};
  784. system.SetFilesystem(vfs);
  785. system.SetAppletFrontendSet({
  786. nullptr, // Parental Controls
  787. std::make_unique<QtErrorDisplay>(*this), //
  788. nullptr, // Photo Viewer
  789. std::make_unique<QtProfileSelector>(*this), //
  790. std::make_unique<QtSoftwareKeyboard>(*this), //
  791. std::make_unique<QtWebBrowser>(*this), //
  792. nullptr, // E-Commerce
  793. });
  794. const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
  795. const auto drd_callout =
  796. (UISettings::values.callout_flags & static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  797. if (result == Core::System::ResultStatus::Success &&
  798. system.GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  799. drd_callout) {
  800. UISettings::values.callout_flags |= static_cast<u32>(CalloutFlag::DRDDeprecation);
  801. QMessageBox::warning(
  802. this, tr("Warning Outdated Game Format"),
  803. tr("You are using the deconstructed ROM directory format for this game, which is an "
  804. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  805. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  806. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  807. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  808. "wiki</a>. This message will not be shown again."));
  809. }
  810. if (result != Core::System::ResultStatus::Success) {
  811. switch (result) {
  812. case Core::System::ResultStatus::ErrorGetLoader:
  813. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  814. QMessageBox::critical(this, tr("Error while loading ROM!"),
  815. tr("The ROM format is not supported."));
  816. break;
  817. case Core::System::ResultStatus::ErrorVideoCore:
  818. QMessageBox::critical(
  819. this, tr("An error occurred initializing the video core."),
  820. tr("yuzu has encountered an error while running the video core, please see the "
  821. "log for more details."
  822. "For more information on accessing the log, please see the following page: "
  823. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  824. "to "
  825. "Upload the Log File</a>."
  826. "Ensure that you have the latest graphics drivers for your GPU."));
  827. break;
  828. default:
  829. if (static_cast<u32>(result) >
  830. static_cast<u32>(Core::System::ResultStatus::ErrorLoader)) {
  831. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  832. const u16 error_id = static_cast<u16>(result) - loader_id;
  833. const std::string error_code = fmt::format("({:04X}-{:04X})", loader_id, error_id);
  834. LOG_CRITICAL(Frontend, "Failed to load ROM! {}", error_code);
  835. QMessageBox::critical(
  836. this,
  837. tr("Error while loading ROM! ").append(QString::fromStdString(error_code)),
  838. QString::fromStdString(fmt::format(
  839. "{}<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the "
  840. "yuzu quickstart guide</a> to redump your files.<br>You can refer "
  841. "to the yuzu wiki</a> or the yuzu Discord</a> for help.",
  842. static_cast<Loader::ResultStatus>(error_id))));
  843. } else {
  844. QMessageBox::critical(
  845. this, tr("Error while loading ROM!"),
  846. tr("An unknown error occurred. Please see the log for more details."));
  847. }
  848. break;
  849. }
  850. return false;
  851. }
  852. game_path = filename;
  853. system.TelemetrySession().AddField(Telemetry::FieldType::App, "Frontend", "Qt");
  854. return true;
  855. }
  856. void GMainWindow::SelectAndSetCurrentUser() {
  857. QtProfileSelectionDialog dialog(this);
  858. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  859. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  860. dialog.setWindowModality(Qt::WindowModal);
  861. if (dialog.exec() == QDialog::Rejected) {
  862. return;
  863. }
  864. Settings::values.current_user = dialog.GetIndex();
  865. }
  866. void GMainWindow::BootGame(const QString& filename) {
  867. LOG_INFO(Frontend, "yuzu starting...");
  868. StoreRecentFile(filename); // Put the filename on top of the list
  869. if (UISettings::values.select_user_on_boot) {
  870. SelectAndSetCurrentUser();
  871. }
  872. if (!LoadROM(filename))
  873. return;
  874. // Create and start the emulation thread
  875. emu_thread = std::make_unique<EmuThread>();
  876. emit EmulationStarting(emu_thread.get());
  877. emu_thread->start();
  878. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  879. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  880. // before the CPU continues
  881. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  882. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  883. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  884. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  885. connect(emu_thread.get(), &EmuThread::LoadProgress, loading_screen,
  886. &LoadingScreen::OnLoadProgress, Qt::QueuedConnection);
  887. // Update the GUI
  888. if (ui.action_Single_Window_Mode->isChecked()) {
  889. game_list->hide();
  890. game_list_placeholder->hide();
  891. }
  892. status_bar_update_timer.start(2000);
  893. async_status_button->setDisabled(true);
  894. renderer_status_button->setDisabled(true);
  895. if (UISettings::values.hide_mouse) {
  896. mouse_hide_timer.start();
  897. setMouseTracking(true);
  898. ui.centralwidget->setMouseTracking(true);
  899. }
  900. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  901. std::string title_name;
  902. const auto res = Core::System::GetInstance().GetGameName(title_name);
  903. if (res != Loader::ResultStatus::Success) {
  904. const auto metadata = FileSys::PatchManager(title_id).GetControlMetadata();
  905. if (metadata.first != nullptr)
  906. title_name = metadata.first->GetApplicationName();
  907. if (title_name.empty())
  908. title_name = FileUtil::GetFilename(filename.toStdString());
  909. }
  910. LOG_INFO(Frontend, "Booting game: {:016X} | {}", title_id, title_name);
  911. UpdateWindowTitle(QString::fromStdString(title_name));
  912. loading_screen->Prepare(Core::System::GetInstance().GetAppLoader());
  913. loading_screen->show();
  914. emulation_running = true;
  915. if (ui.action_Fullscreen->isChecked()) {
  916. ShowFullscreen();
  917. }
  918. OnStartGame();
  919. }
  920. void GMainWindow::ShutdownGame() {
  921. if (!emulation_running) {
  922. return;
  923. }
  924. if (ui.action_Fullscreen->isChecked()) {
  925. HideFullscreen();
  926. }
  927. AllowOSSleep();
  928. discord_rpc->Pause();
  929. emu_thread->RequestStop();
  930. emit EmulationStopping();
  931. // Wait for emulation thread to complete and delete it
  932. emu_thread->wait();
  933. emu_thread = nullptr;
  934. discord_rpc->Update();
  935. // The emulation is stopped, so closing the window or not does not matter anymore
  936. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  937. // Update the GUI
  938. ui.action_Start->setEnabled(false);
  939. ui.action_Start->setText(tr("Start"));
  940. ui.action_Pause->setEnabled(false);
  941. ui.action_Stop->setEnabled(false);
  942. ui.action_Restart->setEnabled(false);
  943. ui.action_Report_Compatibility->setEnabled(false);
  944. ui.action_Load_Amiibo->setEnabled(false);
  945. ui.action_Capture_Screenshot->setEnabled(false);
  946. render_window->hide();
  947. loading_screen->hide();
  948. loading_screen->Clear();
  949. if (game_list->isEmpty())
  950. game_list_placeholder->show();
  951. else
  952. game_list->show();
  953. game_list->setFilterFocus();
  954. setMouseTracking(false);
  955. ui.centralwidget->setMouseTracking(false);
  956. UpdateWindowTitle();
  957. // Disable status bar updates
  958. status_bar_update_timer.stop();
  959. emu_speed_label->setVisible(false);
  960. game_fps_label->setVisible(false);
  961. emu_frametime_label->setVisible(false);
  962. async_status_button->setEnabled(true);
  963. #ifdef HAS_VULKAN
  964. renderer_status_button->setEnabled(true);
  965. #endif
  966. emulation_running = false;
  967. game_path.clear();
  968. // When closing the game, destroy the GLWindow to clear the context after the game is closed
  969. render_window->ReleaseRenderTarget();
  970. }
  971. void GMainWindow::StoreRecentFile(const QString& filename) {
  972. UISettings::values.recent_files.prepend(filename);
  973. UISettings::values.recent_files.removeDuplicates();
  974. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  975. UISettings::values.recent_files.removeLast();
  976. }
  977. UpdateRecentFiles();
  978. }
  979. void GMainWindow::UpdateRecentFiles() {
  980. const int num_recent_files =
  981. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  982. for (int i = 0; i < num_recent_files; i++) {
  983. const QString text = QStringLiteral("&%1. %2").arg(i + 1).arg(
  984. QFileInfo(UISettings::values.recent_files[i]).fileName());
  985. actions_recent_files[i]->setText(text);
  986. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  987. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  988. actions_recent_files[i]->setVisible(true);
  989. }
  990. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  991. actions_recent_files[j]->setVisible(false);
  992. }
  993. // Enable the recent files menu if the list isn't empty
  994. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  995. }
  996. void GMainWindow::OnGameListLoadFile(QString game_path) {
  997. BootGame(game_path);
  998. }
  999. void GMainWindow::OnGameListOpenFolder(GameListOpenTarget target, const std::string& game_path) {
  1000. std::string path;
  1001. QString open_target;
  1002. const auto v_file = Core::GetGameFileFromPath(vfs, game_path);
  1003. const auto loader = Loader::GetLoader(v_file);
  1004. FileSys::NACP control{};
  1005. u64 program_id{};
  1006. loader->ReadControlData(control);
  1007. loader->ReadProgramId(program_id);
  1008. const bool has_user_save{control.GetDefaultNormalSaveSize() > 0};
  1009. const bool has_device_save{control.GetDeviceSaveDataSize() > 0};
  1010. ASSERT_MSG(has_user_save != has_device_save, "Game uses both user and device savedata?");
  1011. switch (target) {
  1012. case GameListOpenTarget::SaveData: {
  1013. open_target = tr("Save Data");
  1014. const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
  1015. ASSERT(program_id != 0);
  1016. if (has_user_save) {
  1017. // User save data
  1018. const auto select_profile = [this] {
  1019. QtProfileSelectionDialog dialog(this);
  1020. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1021. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1022. dialog.setWindowModality(Qt::WindowModal);
  1023. if (dialog.exec() == QDialog::Rejected) {
  1024. return -1;
  1025. }
  1026. return dialog.GetIndex();
  1027. };
  1028. const auto index = select_profile();
  1029. if (index == -1) {
  1030. return;
  1031. }
  1032. Service::Account::ProfileManager manager;
  1033. const auto user_id = manager.GetUser(static_cast<std::size_t>(index));
  1034. ASSERT(user_id);
  1035. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(
  1036. FileSys::SaveDataSpaceId::NandUser,
  1037. FileSys::SaveDataType::SaveData, program_id, user_id->uuid, 0);
  1038. } else {
  1039. // Device save data
  1040. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(
  1041. FileSys::SaveDataSpaceId::NandUser,
  1042. FileSys::SaveDataType::SaveData, program_id, {}, 0);
  1043. }
  1044. if (!FileUtil::Exists(path)) {
  1045. FileUtil::CreateFullPath(path);
  1046. FileUtil::CreateDir(path);
  1047. }
  1048. break;
  1049. }
  1050. case GameListOpenTarget::ModData: {
  1051. open_target = tr("Mod Data");
  1052. const auto load_dir = FileUtil::GetUserPath(FileUtil::UserPath::LoadDir);
  1053. path = fmt::format("{}{:016X}", load_dir, program_id);
  1054. break;
  1055. }
  1056. default:
  1057. UNIMPLEMENTED();
  1058. }
  1059. const QString qpath = QString::fromStdString(path);
  1060. const QDir dir(qpath);
  1061. if (!dir.exists()) {
  1062. QMessageBox::warning(this, tr("Error Opening %1 Folder").arg(open_target),
  1063. tr("Folder does not exist!"));
  1064. return;
  1065. }
  1066. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target.toStdString(),
  1067. program_id);
  1068. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  1069. }
  1070. void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
  1071. ASSERT(program_id != 0);
  1072. const QString shader_dir =
  1073. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ShaderDir));
  1074. const QString tranferable_shader_cache_folder_path =
  1075. shader_dir + QStringLiteral("opengl") + QDir::separator() + QStringLiteral("transferable");
  1076. const QString transferable_shader_cache_file_path =
  1077. tranferable_shader_cache_folder_path + QDir::separator() +
  1078. QString::fromStdString(fmt::format("{:016X}.bin", program_id));
  1079. if (!QFile::exists(transferable_shader_cache_file_path)) {
  1080. QMessageBox::warning(this, tr("Error Opening Transferable Shader Cache"),
  1081. tr("A shader cache for this title does not exist."));
  1082. return;
  1083. }
  1084. // Windows supports opening a folder with selecting a specified file in explorer. On every other
  1085. // OS we just open the transferable shader cache folder without preselecting the transferable
  1086. // shader cache file for the selected game.
  1087. #if defined(Q_OS_WIN)
  1088. const QString explorer = QStringLiteral("explorer");
  1089. QStringList param;
  1090. if (!QFileInfo(transferable_shader_cache_file_path).isDir()) {
  1091. param << QStringLiteral("/select,");
  1092. }
  1093. param << QDir::toNativeSeparators(transferable_shader_cache_file_path);
  1094. QProcess::startDetached(explorer, param);
  1095. #else
  1096. QDesktopServices::openUrl(QUrl::fromLocalFile(tranferable_shader_cache_folder_path));
  1097. #endif
  1098. }
  1099. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  1100. std::size_t out = 0;
  1101. for (const auto& subdir : dir->GetSubdirectories()) {
  1102. out += 1 + CalculateRomFSEntrySize(subdir, full);
  1103. }
  1104. return out + (full ? dir->GetFiles().size() : 0);
  1105. }
  1106. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  1107. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  1108. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  1109. return false;
  1110. if (dialog.wasCanceled())
  1111. return false;
  1112. if (full) {
  1113. for (const auto& file : src->GetFiles()) {
  1114. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  1115. if (!FileSys::VfsRawCopy(file, out, block_size))
  1116. return false;
  1117. dialog.setValue(dialog.value() + 1);
  1118. if (dialog.wasCanceled())
  1119. return false;
  1120. }
  1121. }
  1122. for (const auto& dir : src->GetSubdirectories()) {
  1123. const auto out = dest->CreateSubdirectory(dir->GetName());
  1124. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  1125. return false;
  1126. dialog.setValue(dialog.value() + 1);
  1127. if (dialog.wasCanceled())
  1128. return false;
  1129. }
  1130. return true;
  1131. }
  1132. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path) {
  1133. const auto failed = [this] {
  1134. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1135. tr("There was an error copying the RomFS files or the user "
  1136. "cancelled the operation."));
  1137. };
  1138. const auto loader = Loader::GetLoader(vfs->OpenFile(game_path, FileSys::Mode::Read));
  1139. if (loader == nullptr) {
  1140. failed();
  1141. return;
  1142. }
  1143. FileSys::VirtualFile file;
  1144. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  1145. failed();
  1146. return;
  1147. }
  1148. const auto& installed = Core::System::GetInstance().GetContentProvider();
  1149. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  1150. if (!romfs_title_id) {
  1151. failed();
  1152. return;
  1153. }
  1154. const auto path = fmt::format(
  1155. "{}{:016X}/romfs", FileUtil::GetUserPath(FileUtil::UserPath::DumpDir), *romfs_title_id);
  1156. FileSys::VirtualFile romfs;
  1157. if (*romfs_title_id == program_id) {
  1158. const u64 ivfc_offset = loader->ReadRomFSIVFCOffset();
  1159. FileSys::PatchManager pm{program_id};
  1160. romfs = pm.PatchRomFS(file, ivfc_offset, FileSys::ContentRecordType::Program);
  1161. } else {
  1162. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  1163. }
  1164. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  1165. if (extracted == nullptr) {
  1166. failed();
  1167. return;
  1168. }
  1169. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  1170. if (out == nullptr) {
  1171. failed();
  1172. vfs->DeleteDirectory(path);
  1173. return;
  1174. }
  1175. bool ok = false;
  1176. const QStringList selections{tr("Full"), tr("Skeleton")};
  1177. const auto res = QInputDialog::getItem(
  1178. this, tr("Select RomFS Dump Mode"),
  1179. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  1180. "files into the new directory while <br>skeleton will only create the directory "
  1181. "structure."),
  1182. selections, 0, false, &ok);
  1183. if (!ok) {
  1184. failed();
  1185. vfs->DeleteDirectory(path);
  1186. return;
  1187. }
  1188. const auto full = res == selections.constFirst();
  1189. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  1190. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  1191. static_cast<s32>(entry_size), this);
  1192. progress.setWindowModality(Qt::WindowModal);
  1193. progress.setMinimumDuration(100);
  1194. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  1195. progress.close();
  1196. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  1197. tr("The operation completed successfully."));
  1198. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  1199. } else {
  1200. progress.close();
  1201. failed();
  1202. vfs->DeleteDirectory(path);
  1203. }
  1204. }
  1205. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  1206. QClipboard* clipboard = QGuiApplication::clipboard();
  1207. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  1208. }
  1209. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  1210. const CompatibilityList& compatibility_list) {
  1211. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  1212. QString directory;
  1213. if (it != compatibility_list.end()) {
  1214. directory = it->second.second;
  1215. }
  1216. QDesktopServices::openUrl(QUrl(QStringLiteral("https://yuzu-emu.org/game/") + directory));
  1217. }
  1218. void GMainWindow::OnGameListOpenDirectory(const QString& directory) {
  1219. QString path;
  1220. if (directory == QStringLiteral("SDMC")) {
  1221. path = QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir) +
  1222. "Nintendo/Contents/registered");
  1223. } else if (directory == QStringLiteral("UserNAND")) {
  1224. path = QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
  1225. "user/Contents/registered");
  1226. } else if (directory == QStringLiteral("SysNAND")) {
  1227. path = QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
  1228. "system/Contents/registered");
  1229. } else {
  1230. path = directory;
  1231. }
  1232. if (!QFileInfo::exists(path)) {
  1233. QMessageBox::critical(this, tr("Error Opening %1").arg(path), tr("Folder does not exist!"));
  1234. return;
  1235. }
  1236. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  1237. }
  1238. void GMainWindow::OnGameListAddDirectory() {
  1239. const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1240. if (dir_path.isEmpty())
  1241. return;
  1242. UISettings::GameDir game_dir{dir_path, false, true};
  1243. if (!UISettings::values.game_dirs.contains(game_dir)) {
  1244. UISettings::values.game_dirs.append(game_dir);
  1245. game_list->PopulateAsync(UISettings::values.game_dirs);
  1246. } else {
  1247. LOG_WARNING(Frontend, "Selected directory is already in the game list");
  1248. }
  1249. }
  1250. void GMainWindow::OnGameListShowList(bool show) {
  1251. if (emulation_running && ui.action_Single_Window_Mode->isChecked())
  1252. return;
  1253. game_list->setVisible(show);
  1254. game_list_placeholder->setVisible(!show);
  1255. };
  1256. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  1257. u64 title_id{};
  1258. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  1259. const auto loader = Loader::GetLoader(v_file);
  1260. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  1261. QMessageBox::information(this, tr("Properties"),
  1262. tr("The game properties could not be loaded."));
  1263. return;
  1264. }
  1265. ConfigurePerGameGeneral dialog(this, title_id);
  1266. dialog.LoadFromFile(v_file);
  1267. auto result = dialog.exec();
  1268. if (result == QDialog::Accepted) {
  1269. dialog.ApplyConfiguration();
  1270. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1271. if (reload) {
  1272. game_list->PopulateAsync(UISettings::values.game_dirs);
  1273. }
  1274. config->Save();
  1275. }
  1276. }
  1277. void GMainWindow::OnMenuLoadFile() {
  1278. const QString extensions =
  1279. QStringLiteral("*.")
  1280. .append(GameList::supported_file_extensions.join(QStringLiteral(" *.")))
  1281. .append(QStringLiteral(" main"));
  1282. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  1283. "%1 is an identifier for the Switch executable file extensions.")
  1284. .arg(extensions);
  1285. const QString filename = QFileDialog::getOpenFileName(
  1286. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  1287. if (filename.isEmpty()) {
  1288. return;
  1289. }
  1290. UISettings::values.roms_path = QFileInfo(filename).path();
  1291. BootGame(filename);
  1292. }
  1293. void GMainWindow::OnMenuLoadFolder() {
  1294. const QString dir_path =
  1295. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  1296. if (dir_path.isNull()) {
  1297. return;
  1298. }
  1299. const QDir dir{dir_path};
  1300. const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files);
  1301. if (matching_main.size() == 1) {
  1302. BootGame(dir.path() + QDir::separator() + matching_main[0]);
  1303. } else {
  1304. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  1305. tr("The directory you have selected does not contain a 'main' file."));
  1306. }
  1307. }
  1308. void GMainWindow::OnMenuInstallToNAND() {
  1309. const QString file_filter =
  1310. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  1311. "(*.nca);;Nintendo Submissions Package (*.nsp);;NX Cartridge "
  1312. "Image (*.xci)");
  1313. QString filename = QFileDialog::getOpenFileName(this, tr("Install File"),
  1314. UISettings::values.roms_path, file_filter);
  1315. if (filename.isEmpty()) {
  1316. return;
  1317. }
  1318. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1319. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1320. if (src == nullptr || dest == nullptr)
  1321. return false;
  1322. if (!dest->Resize(src->GetSize()))
  1323. return false;
  1324. std::array<u8, 0x1000> buffer{};
  1325. const int progress_maximum = static_cast<int>(src->GetSize() / buffer.size());
  1326. QProgressDialog progress(
  1327. tr("Installing file \"%1\"...").arg(QString::fromStdString(src->GetName())),
  1328. tr("Cancel"), 0, progress_maximum, this);
  1329. progress.setWindowModality(Qt::WindowModal);
  1330. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1331. if (progress.wasCanceled()) {
  1332. dest->Resize(0);
  1333. return false;
  1334. }
  1335. const int progress_value = static_cast<int>(i / buffer.size());
  1336. progress.setValue(progress_value);
  1337. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1338. dest->Write(buffer.data(), read, i);
  1339. }
  1340. return true;
  1341. };
  1342. const auto success = [this]() {
  1343. QMessageBox::information(this, tr("Successfully Installed"),
  1344. tr("The file was successfully installed."));
  1345. game_list->PopulateAsync(UISettings::values.game_dirs);
  1346. FileUtil::DeleteDirRecursively(FileUtil::GetUserPath(FileUtil::UserPath::CacheDir) +
  1347. DIR_SEP + "game_list");
  1348. };
  1349. const auto failed = [this]() {
  1350. QMessageBox::warning(
  1351. this, tr("Failed to Install"),
  1352. tr("There was an error while attempting to install the provided file. It "
  1353. "could have an incorrect format or be missing metadata. Please "
  1354. "double-check your file and try again."));
  1355. };
  1356. const auto overwrite = [this]() {
  1357. return QMessageBox::question(this, tr("Failed to Install"),
  1358. tr("The file you are attempting to install already exists "
  1359. "in the cache. Would you like to overwrite it?")) ==
  1360. QMessageBox::Yes;
  1361. };
  1362. if (filename.endsWith(QStringLiteral("xci"), Qt::CaseInsensitive) ||
  1363. filename.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1364. std::shared_ptr<FileSys::NSP> nsp;
  1365. if (filename.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1366. nsp = std::make_shared<FileSys::NSP>(
  1367. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1368. if (nsp->IsExtractedType())
  1369. failed();
  1370. } else {
  1371. const auto xci = std::make_shared<FileSys::XCI>(
  1372. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1373. nsp = xci->GetSecurePartitionNSP();
  1374. }
  1375. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  1376. failed();
  1377. return;
  1378. }
  1379. const auto res = Core::System::GetInstance()
  1380. .GetFileSystemController()
  1381. .GetUserNANDContents()
  1382. ->InstallEntry(*nsp, false, qt_raw_copy);
  1383. if (res == FileSys::InstallResult::Success) {
  1384. success();
  1385. } else {
  1386. if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  1387. if (overwrite()) {
  1388. const auto res2 = Core::System::GetInstance()
  1389. .GetFileSystemController()
  1390. .GetUserNANDContents()
  1391. ->InstallEntry(*nsp, true, qt_raw_copy);
  1392. if (res2 == FileSys::InstallResult::Success) {
  1393. success();
  1394. } else {
  1395. failed();
  1396. }
  1397. }
  1398. } else {
  1399. failed();
  1400. }
  1401. }
  1402. } else {
  1403. const auto nca = std::make_shared<FileSys::NCA>(
  1404. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1405. const auto id = nca->GetStatus();
  1406. // Game updates necessary are missing base RomFS
  1407. if (id != Loader::ResultStatus::Success &&
  1408. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  1409. failed();
  1410. return;
  1411. }
  1412. const QStringList tt_options{tr("System Application"),
  1413. tr("System Archive"),
  1414. tr("System Application Update"),
  1415. tr("Firmware Package (Type A)"),
  1416. tr("Firmware Package (Type B)"),
  1417. tr("Game"),
  1418. tr("Game Update"),
  1419. tr("Game DLC"),
  1420. tr("Delta Title")};
  1421. bool ok;
  1422. const auto item = QInputDialog::getItem(
  1423. this, tr("Select NCA Install Type..."),
  1424. tr("Please select the type of title you would like to install this NCA as:\n(In "
  1425. "most instances, the default 'Game' is fine.)"),
  1426. tt_options, 5, false, &ok);
  1427. auto index = tt_options.indexOf(item);
  1428. if (!ok || index == -1) {
  1429. QMessageBox::warning(this, tr("Failed to Install"),
  1430. tr("The title type you selected for the NCA is invalid."));
  1431. return;
  1432. }
  1433. // If index is equal to or past Game, add the jump in TitleType.
  1434. if (index >= 5) {
  1435. index += static_cast<size_t>(FileSys::TitleType::Application) -
  1436. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  1437. }
  1438. FileSys::InstallResult res;
  1439. if (index >= static_cast<s32>(FileSys::TitleType::Application)) {
  1440. res = Core::System::GetInstance()
  1441. .GetFileSystemController()
  1442. .GetUserNANDContents()
  1443. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), false,
  1444. qt_raw_copy);
  1445. } else {
  1446. res = Core::System::GetInstance()
  1447. .GetFileSystemController()
  1448. .GetSystemNANDContents()
  1449. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), false,
  1450. qt_raw_copy);
  1451. }
  1452. if (res == FileSys::InstallResult::Success) {
  1453. success();
  1454. } else if (res == FileSys::InstallResult::ErrorAlreadyExists) {
  1455. if (overwrite()) {
  1456. const auto res2 = Core::System::GetInstance()
  1457. .GetFileSystemController()
  1458. .GetUserNANDContents()
  1459. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index),
  1460. true, qt_raw_copy);
  1461. if (res2 == FileSys::InstallResult::Success) {
  1462. success();
  1463. } else {
  1464. failed();
  1465. }
  1466. }
  1467. } else {
  1468. failed();
  1469. }
  1470. }
  1471. }
  1472. void GMainWindow::OnMenuRecentFile() {
  1473. QAction* action = qobject_cast<QAction*>(sender());
  1474. assert(action);
  1475. const QString filename = action->data().toString();
  1476. if (QFileInfo::exists(filename)) {
  1477. BootGame(filename);
  1478. } else {
  1479. // Display an error message and remove the file from the list.
  1480. QMessageBox::information(this, tr("File not found"),
  1481. tr("File \"%1\" not found").arg(filename));
  1482. UISettings::values.recent_files.removeOne(filename);
  1483. UpdateRecentFiles();
  1484. }
  1485. }
  1486. void GMainWindow::OnStartGame() {
  1487. PreventOSSleep();
  1488. emu_thread->SetRunning(true);
  1489. qRegisterMetaType<Core::Frontend::SoftwareKeyboardParameters>(
  1490. "Core::Frontend::SoftwareKeyboardParameters");
  1491. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  1492. qRegisterMetaType<std::string>("std::string");
  1493. qRegisterMetaType<std::optional<std::u16string>>("std::optional<std::u16string>");
  1494. qRegisterMetaType<std::string_view>("std::string_view");
  1495. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  1496. ui.action_Start->setEnabled(false);
  1497. ui.action_Start->setText(tr("Continue"));
  1498. ui.action_Pause->setEnabled(true);
  1499. ui.action_Stop->setEnabled(true);
  1500. ui.action_Restart->setEnabled(true);
  1501. ui.action_Report_Compatibility->setEnabled(true);
  1502. discord_rpc->Update();
  1503. ui.action_Load_Amiibo->setEnabled(true);
  1504. ui.action_Capture_Screenshot->setEnabled(true);
  1505. }
  1506. void GMainWindow::OnPauseGame() {
  1507. emu_thread->SetRunning(false);
  1508. ui.action_Start->setEnabled(true);
  1509. ui.action_Pause->setEnabled(false);
  1510. ui.action_Stop->setEnabled(true);
  1511. ui.action_Capture_Screenshot->setEnabled(false);
  1512. AllowOSSleep();
  1513. }
  1514. void GMainWindow::OnStopGame() {
  1515. Core::System& system{Core::System::GetInstance()};
  1516. if (system.GetExitLock() && !ConfirmForceLockedExit()) {
  1517. return;
  1518. }
  1519. ShutdownGame();
  1520. }
  1521. void GMainWindow::OnLoadComplete() {
  1522. loading_screen->OnLoadComplete();
  1523. }
  1524. void GMainWindow::ErrorDisplayDisplayError(QString body) {
  1525. QMessageBox::critical(this, tr("Error Display"), body);
  1526. emit ErrorDisplayFinished();
  1527. }
  1528. void GMainWindow::OnMenuReportCompatibility() {
  1529. if (!Settings::values.yuzu_token.empty() && !Settings::values.yuzu_username.empty()) {
  1530. CompatDB compatdb{this};
  1531. compatdb.exec();
  1532. } else {
  1533. QMessageBox::critical(
  1534. this, tr("Missing yuzu Account"),
  1535. tr("In order to submit a game compatibility test case, you must link your yuzu "
  1536. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  1537. "&gt; "
  1538. "Web."));
  1539. }
  1540. }
  1541. void GMainWindow::OpenURL(const QUrl& url) {
  1542. const bool open = QDesktopServices::openUrl(url);
  1543. if (!open) {
  1544. QMessageBox::warning(this, tr("Error opening URL"),
  1545. tr("Unable to open the URL \"%1\".").arg(url.toString()));
  1546. }
  1547. }
  1548. void GMainWindow::OnOpenModsPage() {
  1549. OpenURL(QUrl(QStringLiteral("https://github.com/yuzu-emu/yuzu/wiki/Switch-Mods")));
  1550. }
  1551. void GMainWindow::OnQuickstartGuide() {
  1552. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/help/quickstart/")));
  1553. }
  1554. void GMainWindow::OnFAQ() {
  1555. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/wiki/faq/")));
  1556. }
  1557. void GMainWindow::ToggleFullscreen() {
  1558. if (!emulation_running) {
  1559. return;
  1560. }
  1561. if (ui.action_Fullscreen->isChecked()) {
  1562. ShowFullscreen();
  1563. } else {
  1564. HideFullscreen();
  1565. }
  1566. }
  1567. void GMainWindow::ShowFullscreen() {
  1568. if (ui.action_Single_Window_Mode->isChecked()) {
  1569. UISettings::values.geometry = saveGeometry();
  1570. ui.menubar->hide();
  1571. statusBar()->hide();
  1572. showFullScreen();
  1573. } else {
  1574. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1575. render_window->showFullScreen();
  1576. }
  1577. }
  1578. void GMainWindow::HideFullscreen() {
  1579. if (ui.action_Single_Window_Mode->isChecked()) {
  1580. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  1581. ui.menubar->show();
  1582. showNormal();
  1583. restoreGeometry(UISettings::values.geometry);
  1584. } else {
  1585. render_window->showNormal();
  1586. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  1587. }
  1588. }
  1589. void GMainWindow::ToggleWindowMode() {
  1590. if (ui.action_Single_Window_Mode->isChecked()) {
  1591. // Render in the main window...
  1592. render_window->BackupGeometry();
  1593. ui.horizontalLayout->addWidget(render_window);
  1594. render_window->setFocusPolicy(Qt::StrongFocus);
  1595. if (emulation_running) {
  1596. render_window->setVisible(true);
  1597. render_window->setFocus();
  1598. game_list->hide();
  1599. }
  1600. } else {
  1601. // Render in a separate window...
  1602. ui.horizontalLayout->removeWidget(render_window);
  1603. render_window->setParent(nullptr);
  1604. render_window->setFocusPolicy(Qt::NoFocus);
  1605. if (emulation_running) {
  1606. render_window->setVisible(true);
  1607. render_window->RestoreGeometry();
  1608. game_list->show();
  1609. }
  1610. }
  1611. }
  1612. void GMainWindow::ResetWindowSize() {
  1613. const auto aspect_ratio = Layout::EmulationAspectRatio(
  1614. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio),
  1615. static_cast<float>(Layout::ScreenUndocked::Height) / Layout::ScreenUndocked::Width);
  1616. if (!ui.action_Single_Window_Mode->isChecked()) {
  1617. render_window->resize(Layout::ScreenUndocked::Height / aspect_ratio,
  1618. Layout::ScreenUndocked::Height);
  1619. } else {
  1620. resize(Layout::ScreenUndocked::Height / aspect_ratio,
  1621. Layout::ScreenUndocked::Height + menuBar()->height() +
  1622. (ui.action_Show_Status_Bar->isChecked() ? statusBar()->height() : 0));
  1623. }
  1624. }
  1625. void GMainWindow::OnConfigure() {
  1626. const auto old_theme = UISettings::values.theme;
  1627. const bool old_discord_presence = UISettings::values.enable_discord_presence;
  1628. ConfigureDialog configure_dialog(this, hotkey_registry);
  1629. const auto result = configure_dialog.exec();
  1630. if (result != QDialog::Accepted) {
  1631. return;
  1632. }
  1633. configure_dialog.ApplyConfiguration();
  1634. InitializeHotkeys();
  1635. if (UISettings::values.theme != old_theme) {
  1636. UpdateUITheme();
  1637. }
  1638. if (UISettings::values.enable_discord_presence != old_discord_presence) {
  1639. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  1640. }
  1641. emit UpdateThemedIcons();
  1642. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1643. if (reload) {
  1644. game_list->PopulateAsync(UISettings::values.game_dirs);
  1645. }
  1646. config->Save();
  1647. if (UISettings::values.hide_mouse && emulation_running) {
  1648. setMouseTracking(true);
  1649. ui.centralwidget->setMouseTracking(true);
  1650. mouse_hide_timer.start();
  1651. } else {
  1652. setMouseTracking(false);
  1653. ui.centralwidget->setMouseTracking(false);
  1654. }
  1655. dock_status_button->setChecked(Settings::values.use_docked_mode);
  1656. async_status_button->setChecked(Settings::values.use_asynchronous_gpu_emulation);
  1657. #ifdef HAS_VULKAN
  1658. renderer_status_button->setChecked(Settings::values.renderer_backend ==
  1659. Settings::RendererBackend::Vulkan);
  1660. #endif
  1661. }
  1662. void GMainWindow::OnLoadAmiibo() {
  1663. const QString extensions{QStringLiteral("*.bin")};
  1664. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  1665. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter);
  1666. if (filename.isEmpty()) {
  1667. return;
  1668. }
  1669. LoadAmiibo(filename);
  1670. }
  1671. void GMainWindow::LoadAmiibo(const QString& filename) {
  1672. Core::System& system{Core::System::GetInstance()};
  1673. Service::SM::ServiceManager& sm = system.ServiceManager();
  1674. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  1675. if (nfc == nullptr) {
  1676. return;
  1677. }
  1678. QFile nfc_file{filename};
  1679. if (!nfc_file.open(QIODevice::ReadOnly)) {
  1680. QMessageBox::warning(this, tr("Error opening Amiibo data file"),
  1681. tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
  1682. return;
  1683. }
  1684. const u64 nfc_file_size = nfc_file.size();
  1685. std::vector<u8> buffer(nfc_file_size);
  1686. const u64 read_size = nfc_file.read(reinterpret_cast<char*>(buffer.data()), nfc_file_size);
  1687. if (nfc_file_size != read_size) {
  1688. QMessageBox::warning(this, tr("Error reading Amiibo data file"),
  1689. tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
  1690. "was only able to read %2 bytes.")
  1691. .arg(nfc_file_size)
  1692. .arg(read_size));
  1693. return;
  1694. }
  1695. if (!nfc->LoadAmiibo(buffer)) {
  1696. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  1697. tr("Unable to load Amiibo data."));
  1698. }
  1699. }
  1700. void GMainWindow::OnOpenYuzuFolder() {
  1701. QDesktopServices::openUrl(QUrl::fromLocalFile(
  1702. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::UserDir))));
  1703. }
  1704. void GMainWindow::OnAbout() {
  1705. AboutDialog aboutDialog(this);
  1706. aboutDialog.exec();
  1707. }
  1708. void GMainWindow::OnToggleFilterBar() {
  1709. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  1710. if (ui.action_Show_Filter_Bar->isChecked()) {
  1711. game_list->setFilterFocus();
  1712. } else {
  1713. game_list->clearFilter();
  1714. }
  1715. }
  1716. void GMainWindow::OnCaptureScreenshot() {
  1717. OnPauseGame();
  1718. QFileDialog png_dialog(this, tr("Capture Screenshot"), UISettings::values.screenshot_path,
  1719. tr("PNG Image (*.png)"));
  1720. png_dialog.setAcceptMode(QFileDialog::AcceptSave);
  1721. png_dialog.setDefaultSuffix(QStringLiteral("png"));
  1722. if (png_dialog.exec()) {
  1723. const QString path = png_dialog.selectedFiles().first();
  1724. if (!path.isEmpty()) {
  1725. UISettings::values.screenshot_path = QFileInfo(path).path();
  1726. render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor, path);
  1727. }
  1728. }
  1729. OnStartGame();
  1730. }
  1731. void GMainWindow::UpdateWindowTitle(const QString& title_name) {
  1732. const auto full_name = std::string(Common::g_build_fullname);
  1733. const auto branch_name = std::string(Common::g_scm_branch);
  1734. const auto description = std::string(Common::g_scm_desc);
  1735. const auto build_id = std::string(Common::g_build_id);
  1736. const auto date =
  1737. QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd")).toStdString();
  1738. if (title_name.isEmpty()) {
  1739. const auto fmt = std::string(Common::g_title_bar_format_idle);
  1740. setWindowTitle(QString::fromStdString(fmt::format(fmt.empty() ? "yuzu {0}| {1}-{2}" : fmt,
  1741. full_name, branch_name, description,
  1742. std::string{}, date, build_id)));
  1743. } else {
  1744. const auto fmt = std::string(Common::g_title_bar_format_running);
  1745. setWindowTitle(QString::fromStdString(
  1746. fmt::format(fmt.empty() ? "yuzu {0}| {3} | {1}-{2}" : fmt, full_name, branch_name,
  1747. description, title_name.toStdString(), date, build_id)));
  1748. }
  1749. }
  1750. void GMainWindow::UpdateStatusBar() {
  1751. if (emu_thread == nullptr) {
  1752. status_bar_update_timer.stop();
  1753. return;
  1754. }
  1755. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  1756. if (Settings::values.use_frame_limit) {
  1757. emu_speed_label->setText(tr("Speed: %1% / %2%")
  1758. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  1759. .arg(Settings::values.frame_limit));
  1760. } else {
  1761. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  1762. }
  1763. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  1764. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  1765. emu_speed_label->setVisible(true);
  1766. game_fps_label->setVisible(true);
  1767. emu_frametime_label->setVisible(true);
  1768. }
  1769. void GMainWindow::HideMouseCursor() {
  1770. if (emu_thread == nullptr || UISettings::values.hide_mouse == false) {
  1771. mouse_hide_timer.stop();
  1772. ShowMouseCursor();
  1773. return;
  1774. }
  1775. setCursor(QCursor(Qt::BlankCursor));
  1776. }
  1777. void GMainWindow::ShowMouseCursor() {
  1778. unsetCursor();
  1779. if (emu_thread != nullptr && UISettings::values.hide_mouse) {
  1780. mouse_hide_timer.start();
  1781. }
  1782. }
  1783. void GMainWindow::mouseMoveEvent(QMouseEvent* event) {
  1784. ShowMouseCursor();
  1785. }
  1786. void GMainWindow::mousePressEvent(QMouseEvent* event) {
  1787. ShowMouseCursor();
  1788. }
  1789. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  1790. QMessageBox::StandardButton answer;
  1791. QString status_message;
  1792. const QString common_message =
  1793. tr("The game you are trying to load requires additional files from your Switch to be "
  1794. "dumped "
  1795. "before playing.<br/><br/>For more information on dumping these files, please see the "
  1796. "following wiki page: <a "
  1797. "href='https://yuzu-emu.org/wiki/"
  1798. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  1799. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  1800. "quit "
  1801. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  1802. "data, or other bugs.");
  1803. switch (result) {
  1804. case Core::System::ResultStatus::ErrorSystemFiles: {
  1805. QString message;
  1806. if (details.empty()) {
  1807. message =
  1808. tr("yuzu was unable to locate a Switch system archive. %1").arg(common_message);
  1809. } else {
  1810. message = tr("yuzu was unable to locate a Switch system archive: %1. %2")
  1811. .arg(QString::fromStdString(details), common_message);
  1812. }
  1813. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  1814. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1815. status_message = tr("System Archive Missing");
  1816. break;
  1817. }
  1818. case Core::System::ResultStatus::ErrorSharedFont: {
  1819. const QString message =
  1820. tr("yuzu was unable to locate the Switch shared fonts. %1").arg(common_message);
  1821. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  1822. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1823. status_message = tr("Shared Font Missing");
  1824. break;
  1825. }
  1826. default:
  1827. answer = QMessageBox::question(
  1828. this, tr("Fatal Error"),
  1829. tr("yuzu has encountered a fatal error, please see the log for more details. "
  1830. "For more information on accessing the log, please see the following page: "
  1831. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  1832. "to "
  1833. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  1834. "list? "
  1835. "Continuing emulation may result in crashes, corrupted save data, or other "
  1836. "bugs."),
  1837. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1838. status_message = tr("Fatal Error encountered");
  1839. break;
  1840. }
  1841. if (answer == QMessageBox::Yes) {
  1842. if (emu_thread) {
  1843. ShutdownGame();
  1844. }
  1845. } else {
  1846. // Only show the message if the game is still running.
  1847. if (emu_thread) {
  1848. emu_thread->SetRunning(true);
  1849. message_label->setText(status_message);
  1850. }
  1851. }
  1852. }
  1853. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  1854. if (behavior == ReinitializeKeyBehavior::Warning) {
  1855. const auto res = QMessageBox::information(
  1856. this, tr("Confirm Key Rederivation"),
  1857. tr("You are about to force rederive all of your keys. \nIf you do not know what this "
  1858. "means or what you are doing, \nthis is a potentially destructive action. \nPlease "
  1859. "make sure this is what you want \nand optionally make backups.\n\nThis will delete "
  1860. "your autogenerated key files and re-run the key derivation module."),
  1861. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  1862. if (res == QMessageBox::Cancel)
  1863. return;
  1864. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1865. "prod.keys_autogenerated");
  1866. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1867. "console.keys_autogenerated");
  1868. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  1869. "title.keys_autogenerated");
  1870. }
  1871. Core::Crypto::KeyManager keys{};
  1872. if (keys.BaseDeriveNecessary()) {
  1873. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory(
  1874. FileUtil::GetUserPath(FileUtil::UserPath::SysDataDir), FileSys::Mode::Read)};
  1875. const auto function = [this, &keys, &pdm] {
  1876. keys.PopulateFromPartitionData(pdm);
  1877. Core::System::GetInstance().GetFileSystemController().CreateFactories(*vfs);
  1878. keys.DeriveETicket(pdm);
  1879. };
  1880. QString errors;
  1881. if (!pdm.HasFuses()) {
  1882. errors += tr("Missing fuses");
  1883. }
  1884. if (!pdm.HasBoot0()) {
  1885. errors += tr(" - Missing BOOT0");
  1886. }
  1887. if (!pdm.HasPackage2()) {
  1888. errors += tr(" - Missing BCPKG2-1-Normal-Main");
  1889. }
  1890. if (!pdm.HasProdInfo()) {
  1891. errors += tr(" - Missing PRODINFO");
  1892. }
  1893. if (!errors.isEmpty()) {
  1894. QMessageBox::warning(
  1895. this, tr("Derivation Components Missing"),
  1896. tr("Components are missing that may hinder key derivation from completing. "
  1897. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  1898. "quickstart guide</a> to get all your keys and "
  1899. "games.<br><br><small>(%1)</small>")
  1900. .arg(errors));
  1901. }
  1902. QProgressDialog prog;
  1903. prog.setRange(0, 0);
  1904. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  1905. "system's performance."));
  1906. prog.setWindowTitle(tr("Deriving Keys"));
  1907. prog.show();
  1908. auto future = QtConcurrent::run(function);
  1909. while (!future.isFinished()) {
  1910. QCoreApplication::processEvents();
  1911. }
  1912. prog.close();
  1913. }
  1914. Core::System::GetInstance().GetFileSystemController().CreateFactories(*vfs);
  1915. if (behavior == ReinitializeKeyBehavior::Warning) {
  1916. game_list->PopulateAsync(UISettings::values.game_dirs);
  1917. }
  1918. }
  1919. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
  1920. u64 program_id) {
  1921. const auto dlc_entries =
  1922. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1923. std::vector<FileSys::ContentProviderEntry> dlc_match;
  1924. dlc_match.reserve(dlc_entries.size());
  1925. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  1926. [&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
  1927. return (entry.title_id & DLC_BASE_TITLE_ID_MASK) == program_id &&
  1928. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  1929. });
  1930. std::vector<u64> romfs_tids;
  1931. romfs_tids.push_back(program_id);
  1932. for (const auto& entry : dlc_match) {
  1933. romfs_tids.push_back(entry.title_id);
  1934. }
  1935. if (romfs_tids.size() > 1) {
  1936. QStringList list{QStringLiteral("Base")};
  1937. for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
  1938. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  1939. }
  1940. bool ok;
  1941. const auto res = QInputDialog::getItem(
  1942. this, tr("Select RomFS Dump Target"),
  1943. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  1944. if (!ok) {
  1945. return {};
  1946. }
  1947. return romfs_tids[list.indexOf(res)];
  1948. }
  1949. return program_id;
  1950. }
  1951. bool GMainWindow::ConfirmClose() {
  1952. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  1953. return true;
  1954. QMessageBox::StandardButton answer =
  1955. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  1956. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  1957. return answer != QMessageBox::No;
  1958. }
  1959. void GMainWindow::closeEvent(QCloseEvent* event) {
  1960. if (!ConfirmClose()) {
  1961. event->ignore();
  1962. return;
  1963. }
  1964. if (!ui.action_Fullscreen->isChecked()) {
  1965. UISettings::values.geometry = saveGeometry();
  1966. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1967. }
  1968. UISettings::values.state = saveState();
  1969. #if MICROPROFILE_ENABLED
  1970. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  1971. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  1972. #endif
  1973. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  1974. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  1975. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  1976. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  1977. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  1978. UISettings::values.first_start = false;
  1979. game_list->SaveInterfaceLayout();
  1980. hotkey_registry.SaveHotkeys();
  1981. // Shutdown session if the emu thread is active...
  1982. if (emu_thread != nullptr)
  1983. ShutdownGame();
  1984. render_window->close();
  1985. QWidget::closeEvent(event);
  1986. }
  1987. static bool IsSingleFileDropEvent(const QMimeData* mime) {
  1988. return mime->hasUrls() && mime->urls().length() == 1;
  1989. }
  1990. void GMainWindow::AcceptDropEvent(QDropEvent* event) {
  1991. if (IsSingleFileDropEvent(event->mimeData())) {
  1992. event->setDropAction(Qt::DropAction::LinkAction);
  1993. event->accept();
  1994. }
  1995. }
  1996. bool GMainWindow::DropAction(QDropEvent* event) {
  1997. if (!IsSingleFileDropEvent(event->mimeData())) {
  1998. return false;
  1999. }
  2000. const QMimeData* mime_data = event->mimeData();
  2001. const QString& filename = mime_data->urls().at(0).toLocalFile();
  2002. if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
  2003. // Amiibo
  2004. LoadAmiibo(filename);
  2005. } else {
  2006. // Game
  2007. if (ConfirmChangeGame()) {
  2008. BootGame(filename);
  2009. }
  2010. }
  2011. return true;
  2012. }
  2013. void GMainWindow::dropEvent(QDropEvent* event) {
  2014. DropAction(event);
  2015. }
  2016. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  2017. AcceptDropEvent(event);
  2018. }
  2019. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  2020. AcceptDropEvent(event);
  2021. }
  2022. bool GMainWindow::ConfirmChangeGame() {
  2023. if (emu_thread == nullptr)
  2024. return true;
  2025. const auto answer = QMessageBox::question(
  2026. this, tr("yuzu"),
  2027. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  2028. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2029. return answer != QMessageBox::No;
  2030. }
  2031. bool GMainWindow::ConfirmForceLockedExit() {
  2032. if (emu_thread == nullptr)
  2033. return true;
  2034. const auto answer =
  2035. QMessageBox::question(this, tr("yuzu"),
  2036. tr("The currently running application has requested yuzu to not "
  2037. "exit.\n\nWould you like to bypass this and exit anyway?"),
  2038. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2039. return answer != QMessageBox::No;
  2040. }
  2041. void GMainWindow::RequestGameExit() {
  2042. auto& sm{Core::System::GetInstance().ServiceManager()};
  2043. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  2044. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  2045. bool has_signalled = false;
  2046. if (applet_oe != nullptr) {
  2047. applet_oe->GetMessageQueue()->RequestExit();
  2048. has_signalled = true;
  2049. }
  2050. if (applet_ae != nullptr && !has_signalled) {
  2051. applet_ae->GetMessageQueue()->RequestExit();
  2052. }
  2053. }
  2054. void GMainWindow::filterBarSetChecked(bool state) {
  2055. ui.action_Show_Filter_Bar->setChecked(state);
  2056. emit(OnToggleFilterBar());
  2057. }
  2058. void GMainWindow::UpdateUITheme() {
  2059. const QString default_icons = QStringLiteral(":/icons/default");
  2060. const QString& current_theme = UISettings::values.theme;
  2061. const bool is_default_theme = current_theme == QString::fromUtf8(UISettings::themes[0].second);
  2062. QStringList theme_paths(default_theme_paths);
  2063. if (is_default_theme || current_theme.isEmpty()) {
  2064. const QString theme_uri(QStringLiteral(":default/style.qss"));
  2065. QFile f(theme_uri);
  2066. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2067. QTextStream ts(&f);
  2068. qApp->setStyleSheet(ts.readAll());
  2069. setStyleSheet(ts.readAll());
  2070. } else {
  2071. qApp->setStyleSheet({});
  2072. setStyleSheet({});
  2073. }
  2074. theme_paths.append(default_icons);
  2075. QIcon::setThemeName(default_icons);
  2076. } else {
  2077. const QString theme_uri(QLatin1Char{':'} + current_theme + QStringLiteral("/style.qss"));
  2078. QFile f(theme_uri);
  2079. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2080. QTextStream ts(&f);
  2081. qApp->setStyleSheet(ts.readAll());
  2082. setStyleSheet(ts.readAll());
  2083. } else {
  2084. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  2085. }
  2086. const QString theme_name = QStringLiteral(":/icons/") + current_theme;
  2087. theme_paths.append({default_icons, theme_name});
  2088. QIcon::setThemeName(theme_name);
  2089. }
  2090. QIcon::setThemeSearchPaths(theme_paths);
  2091. }
  2092. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  2093. #ifdef USE_DISCORD_PRESENCE
  2094. if (state) {
  2095. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  2096. } else {
  2097. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2098. }
  2099. #else
  2100. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2101. #endif
  2102. discord_rpc->Update();
  2103. }
  2104. #ifdef main
  2105. #undef main
  2106. #endif
  2107. int main(int argc, char* argv[]) {
  2108. Common::DetachedTasks detached_tasks;
  2109. MicroProfileOnThreadCreate("Frontend");
  2110. SCOPE_EXIT({ MicroProfileShutdown(); });
  2111. // Init settings params
  2112. QCoreApplication::setOrganizationName(QStringLiteral("yuzu team"));
  2113. QCoreApplication::setApplicationName(QStringLiteral("yuzu"));
  2114. #ifdef __APPLE__
  2115. // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/".
  2116. // But since we require the working directory to be the executable path for the location of the
  2117. // user folder in the Qt Frontend, we need to cd into that working directory
  2118. const std::string bin_path = FileUtil::GetBundleDirectory() + DIR_SEP + "..";
  2119. chdir(bin_path.c_str());
  2120. #endif
  2121. // Enables the core to make the qt created contexts current on std::threads
  2122. QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  2123. QApplication app(argc, argv);
  2124. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  2125. // generating shaders
  2126. setlocale(LC_ALL, "C");
  2127. GMainWindow main_window;
  2128. // After settings have been loaded by GMainWindow, apply the filter
  2129. main_window.show();
  2130. QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
  2131. &GMainWindow::OnAppFocusStateChanged);
  2132. Settings::LogSettings();
  2133. int result = app.exec();
  2134. detached_tasks.WaitForAllTasks();
  2135. return result;
  2136. }