main.cpp 94 KB

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