main.cpp 110 KB

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