main.cpp 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885
  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 = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
  162. FileUtil::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, [=](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, [=] {
  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. // View
  773. connect(ui.action_Single_Window_Mode, &QAction::triggered, this,
  774. &GMainWindow::ToggleWindowMode);
  775. connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,
  776. &GMainWindow::OnDisplayTitleBars);
  777. connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);
  778. connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);
  779. connect(ui.action_Reset_Window_Size, &QAction::triggered, this, &GMainWindow::ResetWindowSize);
  780. // Fullscreen
  781. connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
  782. // Movie
  783. connect(ui.action_Capture_Screenshot, &QAction::triggered, this,
  784. &GMainWindow::OnCaptureScreenshot);
  785. // Help
  786. connect(ui.action_Open_yuzu_Folder, &QAction::triggered, this, &GMainWindow::OnOpenYuzuFolder);
  787. connect(ui.action_Rederive, &QAction::triggered, this,
  788. std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning));
  789. connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
  790. }
  791. void GMainWindow::OnDisplayTitleBars(bool show) {
  792. QList<QDockWidget*> widgets = findChildren<QDockWidget*>();
  793. if (show) {
  794. for (QDockWidget* widget : widgets) {
  795. QWidget* old = widget->titleBarWidget();
  796. widget->setTitleBarWidget(nullptr);
  797. if (old != nullptr)
  798. delete old;
  799. }
  800. } else {
  801. for (QDockWidget* widget : widgets) {
  802. QWidget* old = widget->titleBarWidget();
  803. widget->setTitleBarWidget(new QWidget());
  804. if (old != nullptr)
  805. delete old;
  806. }
  807. }
  808. }
  809. void GMainWindow::PreventOSSleep() {
  810. #ifdef _WIN32
  811. SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
  812. #endif
  813. }
  814. void GMainWindow::AllowOSSleep() {
  815. #ifdef _WIN32
  816. SetThreadExecutionState(ES_CONTINUOUS);
  817. #endif
  818. }
  819. bool GMainWindow::LoadROM(const QString& filename) {
  820. // Shutdown previous session if the emu thread is still active...
  821. if (emu_thread != nullptr)
  822. ShutdownGame();
  823. if (!render_window->InitRenderTarget()) {
  824. return false;
  825. }
  826. Core::System& system{Core::System::GetInstance()};
  827. system.SetFilesystem(vfs);
  828. system.SetAppletFrontendSet({
  829. nullptr, // Parental Controls
  830. std::make_unique<QtErrorDisplay>(*this), //
  831. nullptr, // Photo Viewer
  832. std::make_unique<QtProfileSelector>(*this), //
  833. std::make_unique<QtSoftwareKeyboard>(*this), //
  834. std::make_unique<QtWebBrowser>(*this), //
  835. nullptr, // E-Commerce
  836. });
  837. system.RegisterHostThread();
  838. const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
  839. const auto drd_callout =
  840. (UISettings::values.callout_flags & static_cast<u32>(CalloutFlag::DRDDeprecation)) == 0;
  841. if (result == Core::System::ResultStatus::Success &&
  842. system.GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory &&
  843. drd_callout) {
  844. UISettings::values.callout_flags |= static_cast<u32>(CalloutFlag::DRDDeprecation);
  845. QMessageBox::warning(
  846. this, tr("Warning Outdated Game Format"),
  847. tr("You are using the deconstructed ROM directory format for this game, which is an "
  848. "outdated format that has been superseded by others such as NCA, NAX, XCI, or "
  849. "NSP. Deconstructed ROM directories lack icons, metadata, and update "
  850. "support.<br><br>For an explanation of the various Switch formats yuzu supports, <a "
  851. "href='https://yuzu-emu.org/wiki/overview-of-switch-game-formats'>check out our "
  852. "wiki</a>. This message will not be shown again."));
  853. }
  854. if (result != Core::System::ResultStatus::Success) {
  855. switch (result) {
  856. case Core::System::ResultStatus::ErrorGetLoader:
  857. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString());
  858. QMessageBox::critical(this, tr("Error while loading ROM!"),
  859. tr("The ROM format is not supported."));
  860. break;
  861. case Core::System::ResultStatus::ErrorVideoCore:
  862. QMessageBox::critical(
  863. this, tr("An error occurred initializing the video core."),
  864. tr("yuzu has encountered an error while running the video core, please see the "
  865. "log for more details."
  866. "For more information on accessing the log, please see the following page: "
  867. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  868. "to "
  869. "Upload the Log File</a>."
  870. "Ensure that you have the latest graphics drivers for your GPU."));
  871. break;
  872. default:
  873. if (static_cast<u32>(result) >
  874. static_cast<u32>(Core::System::ResultStatus::ErrorLoader)) {
  875. const u16 loader_id = static_cast<u16>(Core::System::ResultStatus::ErrorLoader);
  876. const u16 error_id = static_cast<u16>(result) - loader_id;
  877. const std::string error_code = fmt::format("({:04X}-{:04X})", loader_id, error_id);
  878. LOG_CRITICAL(Frontend, "Failed to load ROM! {}", error_code);
  879. QMessageBox::critical(
  880. this,
  881. tr("Error while loading ROM! ").append(QString::fromStdString(error_code)),
  882. QString::fromStdString(fmt::format(
  883. "{}<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the "
  884. "yuzu quickstart guide</a> to redump your files.<br>You can refer "
  885. "to the yuzu wiki</a> or the yuzu Discord</a> for help.",
  886. static_cast<Loader::ResultStatus>(error_id))));
  887. } else {
  888. QMessageBox::critical(
  889. this, tr("Error while loading ROM!"),
  890. tr("An unknown error occurred. Please see the log for more details."));
  891. }
  892. break;
  893. }
  894. return false;
  895. }
  896. game_path = filename;
  897. system.TelemetrySession().AddField(Telemetry::FieldType::App, "Frontend", "Qt");
  898. return true;
  899. }
  900. void GMainWindow::SelectAndSetCurrentUser() {
  901. QtProfileSelectionDialog dialog(this);
  902. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  903. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  904. dialog.setWindowModality(Qt::WindowModal);
  905. if (dialog.exec() == QDialog::Rejected) {
  906. return;
  907. }
  908. Settings::values.current_user = dialog.GetIndex();
  909. }
  910. void GMainWindow::BootGame(const QString& filename) {
  911. LOG_INFO(Frontend, "yuzu starting...");
  912. StoreRecentFile(filename); // Put the filename on top of the list
  913. u64 title_id{0};
  914. const auto v_file = Core::GetGameFileFromPath(vfs, filename.toUtf8().constData());
  915. const auto loader = Loader::GetLoader(v_file);
  916. if (!(loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success)) {
  917. // Load per game settings
  918. Config per_game_config(fmt::format("{:016X}.ini", title_id), false);
  919. }
  920. Settings::LogSettings();
  921. if (UISettings::values.select_user_on_boot) {
  922. SelectAndSetCurrentUser();
  923. }
  924. if (!LoadROM(filename))
  925. return;
  926. // Create and start the emulation thread
  927. emu_thread = std::make_unique<EmuThread>();
  928. emit EmulationStarting(emu_thread.get());
  929. emu_thread->start();
  930. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  931. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  932. // before the CPU continues
  933. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  934. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  935. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  936. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  937. connect(emu_thread.get(), &EmuThread::LoadProgress, loading_screen,
  938. &LoadingScreen::OnLoadProgress, Qt::QueuedConnection);
  939. // Update the GUI
  940. UpdateStatusButtons();
  941. if (ui.action_Single_Window_Mode->isChecked()) {
  942. game_list->hide();
  943. game_list_placeholder->hide();
  944. }
  945. status_bar_update_timer.start(2000);
  946. async_status_button->setDisabled(true);
  947. multicore_status_button->setDisabled(true);
  948. renderer_status_button->setDisabled(true);
  949. if (UISettings::values.hide_mouse) {
  950. mouse_hide_timer.start();
  951. setMouseTracking(true);
  952. ui.centralwidget->setMouseTracking(true);
  953. }
  954. std::string title_name;
  955. std::string title_version;
  956. const auto res = Core::System::GetInstance().GetGameName(title_name);
  957. const auto metadata = FileSys::PatchManager(title_id).GetControlMetadata();
  958. if (metadata.first != nullptr) {
  959. title_version = metadata.first->GetVersionString();
  960. title_name = metadata.first->GetApplicationName();
  961. }
  962. if (res != Loader::ResultStatus::Success || title_name.empty()) {
  963. title_name = FileUtil::GetFilename(filename.toStdString());
  964. }
  965. LOG_INFO(Frontend, "Booting game: {:016X} | {} | {}", title_id, title_name, title_version);
  966. UpdateWindowTitle(title_name, title_version);
  967. loading_screen->Prepare(Core::System::GetInstance().GetAppLoader());
  968. loading_screen->show();
  969. emulation_running = true;
  970. if (ui.action_Fullscreen->isChecked()) {
  971. ShowFullscreen();
  972. }
  973. OnStartGame();
  974. }
  975. void GMainWindow::ShutdownGame() {
  976. if (!emulation_running) {
  977. return;
  978. }
  979. if (ui.action_Fullscreen->isChecked()) {
  980. HideFullscreen();
  981. }
  982. AllowOSSleep();
  983. discord_rpc->Pause();
  984. emu_thread->RequestStop();
  985. emit EmulationStopping();
  986. // Wait for emulation thread to complete and delete it
  987. emu_thread->wait();
  988. emu_thread = nullptr;
  989. discord_rpc->Update();
  990. // The emulation is stopped, so closing the window or not does not matter anymore
  991. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  992. // Update the GUI
  993. ui.action_Start->setEnabled(false);
  994. ui.action_Start->setText(tr("Start"));
  995. ui.action_Pause->setEnabled(false);
  996. ui.action_Stop->setEnabled(false);
  997. ui.action_Restart->setEnabled(false);
  998. ui.action_Report_Compatibility->setEnabled(false);
  999. ui.action_Load_Amiibo->setEnabled(false);
  1000. ui.action_Capture_Screenshot->setEnabled(false);
  1001. render_window->hide();
  1002. loading_screen->hide();
  1003. loading_screen->Clear();
  1004. if (game_list->isEmpty())
  1005. game_list_placeholder->show();
  1006. else
  1007. game_list->show();
  1008. game_list->setFilterFocus();
  1009. setMouseTracking(false);
  1010. ui.centralwidget->setMouseTracking(false);
  1011. UpdateWindowTitle();
  1012. // Disable status bar updates
  1013. status_bar_update_timer.stop();
  1014. shader_building_label->setVisible(false);
  1015. emu_speed_label->setVisible(false);
  1016. game_fps_label->setVisible(false);
  1017. emu_frametime_label->setVisible(false);
  1018. async_status_button->setEnabled(true);
  1019. multicore_status_button->setEnabled(true);
  1020. #ifdef HAS_VULKAN
  1021. renderer_status_button->setEnabled(true);
  1022. #endif
  1023. emulation_running = false;
  1024. game_path.clear();
  1025. // When closing the game, destroy the GLWindow to clear the context after the game is closed
  1026. render_window->ReleaseRenderTarget();
  1027. }
  1028. void GMainWindow::StoreRecentFile(const QString& filename) {
  1029. UISettings::values.recent_files.prepend(filename);
  1030. UISettings::values.recent_files.removeDuplicates();
  1031. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  1032. UISettings::values.recent_files.removeLast();
  1033. }
  1034. UpdateRecentFiles();
  1035. }
  1036. void GMainWindow::UpdateRecentFiles() {
  1037. const int num_recent_files =
  1038. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  1039. for (int i = 0; i < num_recent_files; i++) {
  1040. const QString text = QStringLiteral("&%1. %2").arg(i + 1).arg(
  1041. QFileInfo(UISettings::values.recent_files[i]).fileName());
  1042. actions_recent_files[i]->setText(text);
  1043. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  1044. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  1045. actions_recent_files[i]->setVisible(true);
  1046. }
  1047. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  1048. actions_recent_files[j]->setVisible(false);
  1049. }
  1050. // Enable the recent files menu if the list isn't empty
  1051. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  1052. }
  1053. void GMainWindow::OnGameListLoadFile(QString game_path) {
  1054. BootGame(game_path);
  1055. }
  1056. void GMainWindow::OnGameListOpenFolder(GameListOpenTarget target, const std::string& game_path) {
  1057. std::string path;
  1058. QString open_target;
  1059. const auto v_file = Core::GetGameFileFromPath(vfs, game_path);
  1060. const auto loader = Loader::GetLoader(v_file);
  1061. FileSys::NACP control{};
  1062. u64 program_id{};
  1063. loader->ReadControlData(control);
  1064. loader->ReadProgramId(program_id);
  1065. const bool has_user_save{control.GetDefaultNormalSaveSize() > 0};
  1066. const bool has_device_save{control.GetDeviceSaveDataSize() > 0};
  1067. ASSERT_MSG(has_user_save != has_device_save, "Game uses both user and device savedata?");
  1068. switch (target) {
  1069. case GameListOpenTarget::SaveData: {
  1070. open_target = tr("Save Data");
  1071. const std::string nand_dir = FileUtil::GetUserPath(FileUtil::UserPath::NANDDir);
  1072. if (has_user_save) {
  1073. // User save data
  1074. const auto select_profile = [this] {
  1075. QtProfileSelectionDialog dialog(this);
  1076. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1077. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1078. dialog.setWindowModality(Qt::WindowModal);
  1079. if (dialog.exec() == QDialog::Rejected) {
  1080. return -1;
  1081. }
  1082. return dialog.GetIndex();
  1083. };
  1084. const auto index = select_profile();
  1085. if (index == -1) {
  1086. return;
  1087. }
  1088. Service::Account::ProfileManager manager;
  1089. const auto user_id = manager.GetUser(static_cast<std::size_t>(index));
  1090. ASSERT(user_id);
  1091. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(
  1092. FileSys::SaveDataSpaceId::NandUser,
  1093. FileSys::SaveDataType::SaveData, program_id, user_id->uuid, 0);
  1094. } else {
  1095. // Device save data
  1096. path = nand_dir + FileSys::SaveDataFactory::GetFullPath(
  1097. FileSys::SaveDataSpaceId::NandUser,
  1098. FileSys::SaveDataType::SaveData, program_id, {}, 0);
  1099. }
  1100. if (!FileUtil::Exists(path)) {
  1101. FileUtil::CreateFullPath(path);
  1102. FileUtil::CreateDir(path);
  1103. }
  1104. break;
  1105. }
  1106. case GameListOpenTarget::ModData: {
  1107. open_target = tr("Mod Data");
  1108. const auto load_dir = FileUtil::GetUserPath(FileUtil::UserPath::LoadDir);
  1109. path = fmt::format("{}{:016X}", load_dir, program_id);
  1110. break;
  1111. }
  1112. default:
  1113. UNIMPLEMENTED();
  1114. }
  1115. const QString qpath = QString::fromStdString(path);
  1116. const QDir dir(qpath);
  1117. if (!dir.exists()) {
  1118. QMessageBox::warning(this, tr("Error Opening %1 Folder").arg(open_target),
  1119. tr("Folder does not exist!"));
  1120. return;
  1121. }
  1122. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target.toStdString(),
  1123. program_id);
  1124. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  1125. }
  1126. void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
  1127. const QString shader_dir =
  1128. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ShaderDir));
  1129. const QString transferable_shader_cache_folder_path =
  1130. shader_dir + QStringLiteral("opengl") + QDir::separator() + QStringLiteral("transferable");
  1131. const QString transferable_shader_cache_file_path =
  1132. transferable_shader_cache_folder_path + QDir::separator() +
  1133. QString::fromStdString(fmt::format("{:016X}.bin", program_id));
  1134. if (!QFile::exists(transferable_shader_cache_file_path)) {
  1135. QMessageBox::warning(this, tr("Error Opening Transferable Shader Cache"),
  1136. tr("A shader cache for this title does not exist."));
  1137. return;
  1138. }
  1139. // Windows supports opening a folder with selecting a specified file in explorer. On every other
  1140. // OS we just open the transferable shader cache folder without preselecting the transferable
  1141. // shader cache file for the selected game.
  1142. #if defined(Q_OS_WIN)
  1143. const QString explorer = QStringLiteral("explorer");
  1144. QStringList param;
  1145. if (!QFileInfo(transferable_shader_cache_file_path).isDir()) {
  1146. param << QStringLiteral("/select,");
  1147. }
  1148. param << QDir::toNativeSeparators(transferable_shader_cache_file_path);
  1149. QProcess::startDetached(explorer, param);
  1150. #else
  1151. QDesktopServices::openUrl(QUrl::fromLocalFile(transferable_shader_cache_folder_path));
  1152. #endif
  1153. }
  1154. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  1155. std::size_t out = 0;
  1156. for (const auto& subdir : dir->GetSubdirectories()) {
  1157. out += 1 + CalculateRomFSEntrySize(subdir, full);
  1158. }
  1159. return out + (full ? dir->GetFiles().size() : 0);
  1160. }
  1161. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  1162. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  1163. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  1164. return false;
  1165. if (dialog.wasCanceled())
  1166. return false;
  1167. if (full) {
  1168. for (const auto& file : src->GetFiles()) {
  1169. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  1170. if (!FileSys::VfsRawCopy(file, out, block_size))
  1171. return false;
  1172. dialog.setValue(dialog.value() + 1);
  1173. if (dialog.wasCanceled())
  1174. return false;
  1175. }
  1176. }
  1177. for (const auto& dir : src->GetSubdirectories()) {
  1178. const auto out = dest->CreateSubdirectory(dir->GetName());
  1179. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  1180. return false;
  1181. dialog.setValue(dialog.value() + 1);
  1182. if (dialog.wasCanceled())
  1183. return false;
  1184. }
  1185. return true;
  1186. }
  1187. void GMainWindow::OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type) {
  1188. const QString entry_type = [this, type] {
  1189. switch (type) {
  1190. case InstalledEntryType::Game:
  1191. return tr("Contents");
  1192. case InstalledEntryType::Update:
  1193. return tr("Update");
  1194. case InstalledEntryType::AddOnContent:
  1195. return tr("DLC");
  1196. default:
  1197. return QString{};
  1198. }
  1199. }();
  1200. if (QMessageBox::question(
  1201. this, tr("Remove Entry"), tr("Remove Installed Game %1?").arg(entry_type),
  1202. QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
  1203. return;
  1204. }
  1205. switch (type) {
  1206. case InstalledEntryType::Game:
  1207. RemoveBaseContent(program_id, entry_type);
  1208. [[fallthrough]];
  1209. case InstalledEntryType::Update:
  1210. RemoveUpdateContent(program_id, entry_type);
  1211. if (type != InstalledEntryType::Game) {
  1212. break;
  1213. }
  1214. [[fallthrough]];
  1215. case InstalledEntryType::AddOnContent:
  1216. RemoveAddOnContent(program_id, entry_type);
  1217. break;
  1218. }
  1219. FileUtil::DeleteDirRecursively(FileUtil::GetUserPath(FileUtil::UserPath::CacheDir) + DIR_SEP +
  1220. "game_list");
  1221. game_list->PopulateAsync(UISettings::values.game_dirs);
  1222. }
  1223. void GMainWindow::RemoveBaseContent(u64 program_id, const QString& entry_type) {
  1224. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1225. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(program_id) ||
  1226. fs_controller.GetSDMCContents()->RemoveExistingEntry(program_id);
  1227. if (res) {
  1228. QMessageBox::information(this, tr("Successfully Removed"),
  1229. tr("Successfully removed the installed base game."));
  1230. } else {
  1231. QMessageBox::warning(
  1232. this, tr("Error Removing %1").arg(entry_type),
  1233. tr("The base game is not installed in the NAND and cannot be removed."));
  1234. }
  1235. }
  1236. void GMainWindow::RemoveUpdateContent(u64 program_id, const QString& entry_type) {
  1237. const auto update_id = program_id | 0x800;
  1238. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1239. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(update_id) ||
  1240. fs_controller.GetSDMCContents()->RemoveExistingEntry(update_id);
  1241. if (res) {
  1242. QMessageBox::information(this, tr("Successfully Removed"),
  1243. tr("Successfully removed the installed update."));
  1244. } else {
  1245. QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
  1246. tr("There is no update installed for this title."));
  1247. }
  1248. }
  1249. void GMainWindow::RemoveAddOnContent(u64 program_id, const QString& entry_type) {
  1250. u32 count{};
  1251. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1252. const auto dlc_entries = Core::System::GetInstance().GetContentProvider().ListEntriesFilter(
  1253. FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1254. for (const auto& entry : dlc_entries) {
  1255. if ((entry.title_id & DLC_BASE_TITLE_ID_MASK) == program_id) {
  1256. const auto res =
  1257. fs_controller.GetUserNANDContents()->RemoveExistingEntry(entry.title_id) ||
  1258. fs_controller.GetSDMCContents()->RemoveExistingEntry(entry.title_id);
  1259. if (res) {
  1260. ++count;
  1261. }
  1262. }
  1263. }
  1264. if (count == 0) {
  1265. QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
  1266. tr("There are no DLC installed for this title."));
  1267. return;
  1268. }
  1269. QMessageBox::information(this, tr("Successfully Removed"),
  1270. tr("Successfully removed %1 installed DLC.").arg(count));
  1271. }
  1272. void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target) {
  1273. const QString question = [this, target] {
  1274. switch (target) {
  1275. case GameListRemoveTarget::ShaderCache:
  1276. return tr("Delete Transferable Shader Cache?");
  1277. case GameListRemoveTarget::CustomConfiguration:
  1278. return tr("Remove Custom Game Configuration?");
  1279. default:
  1280. return QString{};
  1281. }
  1282. }();
  1283. if (QMessageBox::question(this, tr("Remove File"), question, QMessageBox::Yes | QMessageBox::No,
  1284. QMessageBox::No) != QMessageBox::Yes) {
  1285. return;
  1286. }
  1287. switch (target) {
  1288. case GameListRemoveTarget::ShaderCache:
  1289. RemoveTransferableShaderCache(program_id);
  1290. break;
  1291. case GameListRemoveTarget::CustomConfiguration:
  1292. RemoveCustomConfiguration(program_id);
  1293. break;
  1294. }
  1295. }
  1296. void GMainWindow::RemoveTransferableShaderCache(u64 program_id) {
  1297. const QString shader_dir =
  1298. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ShaderDir));
  1299. const QString transferable_shader_cache_folder_path =
  1300. shader_dir + QStringLiteral("opengl") + QDir::separator() + QStringLiteral("transferable");
  1301. const QString transferable_shader_cache_file_path =
  1302. transferable_shader_cache_folder_path + QDir::separator() +
  1303. QString::fromStdString(fmt::format("{:016X}.bin", program_id));
  1304. if (!QFile::exists(transferable_shader_cache_file_path)) {
  1305. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1306. tr("A shader cache for this title does not exist."));
  1307. return;
  1308. }
  1309. if (QFile::remove(transferable_shader_cache_file_path)) {
  1310. QMessageBox::information(this, tr("Successfully Removed"),
  1311. tr("Successfully removed the transferable shader cache."));
  1312. } else {
  1313. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1314. tr("Failed to remove the transferable shader cache."));
  1315. }
  1316. }
  1317. void GMainWindow::RemoveCustomConfiguration(u64 program_id) {
  1318. const QString config_dir =
  1319. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::ConfigDir));
  1320. const QString custom_config_file_path =
  1321. config_dir + QString::fromStdString(fmt::format("{:016X}.ini", program_id));
  1322. if (!QFile::exists(custom_config_file_path)) {
  1323. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1324. tr("A custom configuration for this title does not exist."));
  1325. return;
  1326. }
  1327. if (QFile::remove(custom_config_file_path)) {
  1328. QMessageBox::information(this, tr("Successfully Removed"),
  1329. tr("Successfully removed the custom game configuration."));
  1330. } else {
  1331. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1332. tr("Failed to remove the custom game configuration."));
  1333. }
  1334. }
  1335. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path) {
  1336. const auto failed = [this] {
  1337. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1338. tr("There was an error copying the RomFS files or the user "
  1339. "cancelled the operation."));
  1340. };
  1341. const auto loader = Loader::GetLoader(vfs->OpenFile(game_path, FileSys::Mode::Read));
  1342. if (loader == nullptr) {
  1343. failed();
  1344. return;
  1345. }
  1346. FileSys::VirtualFile file;
  1347. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  1348. failed();
  1349. return;
  1350. }
  1351. const auto& installed = Core::System::GetInstance().GetContentProvider();
  1352. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  1353. if (!romfs_title_id) {
  1354. failed();
  1355. return;
  1356. }
  1357. const auto path = fmt::format(
  1358. "{}{:016X}/romfs", FileUtil::GetUserPath(FileUtil::UserPath::DumpDir), *romfs_title_id);
  1359. FileSys::VirtualFile romfs;
  1360. if (*romfs_title_id == program_id) {
  1361. const u64 ivfc_offset = loader->ReadRomFSIVFCOffset();
  1362. FileSys::PatchManager pm{program_id};
  1363. romfs = pm.PatchRomFS(file, ivfc_offset, FileSys::ContentRecordType::Program);
  1364. } else {
  1365. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  1366. }
  1367. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  1368. if (extracted == nullptr) {
  1369. failed();
  1370. return;
  1371. }
  1372. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  1373. if (out == nullptr) {
  1374. failed();
  1375. vfs->DeleteDirectory(path);
  1376. return;
  1377. }
  1378. bool ok = false;
  1379. const QStringList selections{tr("Full"), tr("Skeleton")};
  1380. const auto res = QInputDialog::getItem(
  1381. this, tr("Select RomFS Dump Mode"),
  1382. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  1383. "files into the new directory while <br>skeleton will only create the directory "
  1384. "structure."),
  1385. selections, 0, false, &ok);
  1386. if (!ok) {
  1387. failed();
  1388. vfs->DeleteDirectory(path);
  1389. return;
  1390. }
  1391. const auto full = res == selections.constFirst();
  1392. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  1393. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  1394. static_cast<s32>(entry_size), this);
  1395. progress.setWindowModality(Qt::WindowModal);
  1396. progress.setMinimumDuration(100);
  1397. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  1398. progress.close();
  1399. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  1400. tr("The operation completed successfully."));
  1401. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  1402. } else {
  1403. progress.close();
  1404. failed();
  1405. vfs->DeleteDirectory(path);
  1406. }
  1407. }
  1408. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  1409. QClipboard* clipboard = QGuiApplication::clipboard();
  1410. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  1411. }
  1412. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  1413. const CompatibilityList& compatibility_list) {
  1414. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  1415. QString directory;
  1416. if (it != compatibility_list.end()) {
  1417. directory = it->second.second;
  1418. }
  1419. QDesktopServices::openUrl(QUrl(QStringLiteral("https://yuzu-emu.org/game/") + directory));
  1420. }
  1421. void GMainWindow::OnGameListOpenDirectory(const QString& directory) {
  1422. QString path;
  1423. if (directory == QStringLiteral("SDMC")) {
  1424. path = QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir) +
  1425. "Nintendo/Contents/registered");
  1426. } else if (directory == QStringLiteral("UserNAND")) {
  1427. path = QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
  1428. "user/Contents/registered");
  1429. } else if (directory == QStringLiteral("SysNAND")) {
  1430. path = QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir) +
  1431. "system/Contents/registered");
  1432. } else {
  1433. path = directory;
  1434. }
  1435. if (!QFileInfo::exists(path)) {
  1436. QMessageBox::critical(this, tr("Error Opening %1").arg(path), tr("Folder does not exist!"));
  1437. return;
  1438. }
  1439. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  1440. }
  1441. void GMainWindow::OnGameListAddDirectory() {
  1442. const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1443. if (dir_path.isEmpty())
  1444. return;
  1445. UISettings::GameDir game_dir{dir_path, false, true};
  1446. if (!UISettings::values.game_dirs.contains(game_dir)) {
  1447. UISettings::values.game_dirs.append(game_dir);
  1448. game_list->PopulateAsync(UISettings::values.game_dirs);
  1449. } else {
  1450. LOG_WARNING(Frontend, "Selected directory is already in the game list");
  1451. }
  1452. }
  1453. void GMainWindow::OnGameListShowList(bool show) {
  1454. if (emulation_running && ui.action_Single_Window_Mode->isChecked())
  1455. return;
  1456. game_list->setVisible(show);
  1457. game_list_placeholder->setVisible(!show);
  1458. };
  1459. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  1460. u64 title_id{};
  1461. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  1462. const auto loader = Loader::GetLoader(v_file);
  1463. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  1464. QMessageBox::information(this, tr("Properties"),
  1465. tr("The game properties could not be loaded."));
  1466. return;
  1467. }
  1468. ConfigurePerGame dialog(this, title_id);
  1469. dialog.LoadFromFile(v_file);
  1470. auto result = dialog.exec();
  1471. if (result == QDialog::Accepted) {
  1472. dialog.ApplyConfiguration();
  1473. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1474. if (reload) {
  1475. game_list->PopulateAsync(UISettings::values.game_dirs);
  1476. }
  1477. // Do not cause the global config to write local settings into the config file
  1478. Settings::RestoreGlobalState();
  1479. if (!Core::System::GetInstance().IsPoweredOn()) {
  1480. config->Save();
  1481. }
  1482. } else {
  1483. Settings::RestoreGlobalState();
  1484. }
  1485. }
  1486. void GMainWindow::OnMenuLoadFile() {
  1487. const QString extensions =
  1488. QStringLiteral("*.")
  1489. .append(GameList::supported_file_extensions.join(QStringLiteral(" *.")))
  1490. .append(QStringLiteral(" main"));
  1491. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  1492. "%1 is an identifier for the Switch executable file extensions.")
  1493. .arg(extensions);
  1494. const QString filename = QFileDialog::getOpenFileName(
  1495. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  1496. if (filename.isEmpty()) {
  1497. return;
  1498. }
  1499. UISettings::values.roms_path = QFileInfo(filename).path();
  1500. BootGame(filename);
  1501. }
  1502. void GMainWindow::OnMenuLoadFolder() {
  1503. const QString dir_path =
  1504. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  1505. if (dir_path.isNull()) {
  1506. return;
  1507. }
  1508. const QDir dir{dir_path};
  1509. const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files);
  1510. if (matching_main.size() == 1) {
  1511. BootGame(dir.path() + QDir::separator() + matching_main[0]);
  1512. } else {
  1513. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  1514. tr("The directory you have selected does not contain a 'main' file."));
  1515. }
  1516. }
  1517. void GMainWindow::IncrementInstallProgress() {
  1518. install_progress->setValue(install_progress->value() + 1);
  1519. }
  1520. void GMainWindow::OnMenuInstallToNAND() {
  1521. const QString file_filter =
  1522. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  1523. "(*.nca);;Nintendo Submission Package (*.nsp);;NX Cartridge "
  1524. "Image (*.xci)");
  1525. QStringList filenames = QFileDialog::getOpenFileNames(
  1526. this, tr("Install Files"), UISettings::values.roms_path, file_filter);
  1527. if (filenames.isEmpty()) {
  1528. return;
  1529. }
  1530. InstallDialog installDialog(this, filenames);
  1531. if (installDialog.exec() == QDialog::Rejected) {
  1532. return;
  1533. }
  1534. const QStringList files = installDialog.GetFiles();
  1535. if (files.isEmpty()) {
  1536. return;
  1537. }
  1538. int remaining = filenames.size();
  1539. // This would only overflow above 2^43 bytes (8.796 TB)
  1540. int total_size = 0;
  1541. for (const QString& file : files) {
  1542. total_size += static_cast<int>(QFile(file).size() / 0x1000);
  1543. }
  1544. if (total_size < 0) {
  1545. LOG_CRITICAL(Frontend, "Attempting to install too many files, aborting.");
  1546. return;
  1547. }
  1548. QStringList new_files{}; // Newly installed files that do not yet exist in the NAND
  1549. QStringList overwritten_files{}; // Files that overwrote those existing in the NAND
  1550. QStringList failed_files{}; // Files that failed to install due to errors
  1551. ui.action_Install_File_NAND->setEnabled(false);
  1552. install_progress = new QProgressDialog(QStringLiteral(""), tr("Cancel"), 0, total_size, this);
  1553. install_progress->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint &
  1554. ~Qt::WindowMaximizeButtonHint);
  1555. install_progress->setAttribute(Qt::WA_DeleteOnClose, true);
  1556. install_progress->setFixedWidth(installDialog.GetMinimumWidth() + 40);
  1557. install_progress->show();
  1558. for (const QString& file : files) {
  1559. install_progress->setWindowTitle(tr("%n file(s) remaining", "", remaining));
  1560. install_progress->setLabelText(
  1561. tr("Installing file \"%1\"...").arg(QFileInfo(file).fileName()));
  1562. QFuture<InstallResult> future;
  1563. InstallResult result;
  1564. if (file.endsWith(QStringLiteral("xci"), Qt::CaseInsensitive) ||
  1565. file.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1566. future = QtConcurrent::run([this, &file] { return InstallNSPXCI(file); });
  1567. while (!future.isFinished()) {
  1568. QCoreApplication::processEvents();
  1569. }
  1570. result = future.result();
  1571. } else {
  1572. result = InstallNCA(file);
  1573. }
  1574. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1575. switch (result) {
  1576. case InstallResult::Success:
  1577. new_files.append(QFileInfo(file).fileName());
  1578. break;
  1579. case InstallResult::Overwrite:
  1580. overwritten_files.append(QFileInfo(file).fileName());
  1581. break;
  1582. case InstallResult::Failure:
  1583. failed_files.append(QFileInfo(file).fileName());
  1584. break;
  1585. }
  1586. --remaining;
  1587. }
  1588. install_progress->close();
  1589. const QString install_results =
  1590. (new_files.isEmpty() ? QStringLiteral("")
  1591. : tr("%n file(s) were newly installed\n", "", new_files.size())) +
  1592. (overwritten_files.isEmpty()
  1593. ? QStringLiteral("")
  1594. : tr("%n file(s) were overwritten\n", "", overwritten_files.size())) +
  1595. (failed_files.isEmpty() ? QStringLiteral("")
  1596. : tr("%n file(s) failed to install\n", "", failed_files.size()));
  1597. QMessageBox::information(this, tr("Install Results"), install_results);
  1598. FileUtil::DeleteDirRecursively(FileUtil::GetUserPath(FileUtil::UserPath::CacheDir) + DIR_SEP +
  1599. "game_list");
  1600. game_list->PopulateAsync(UISettings::values.game_dirs);
  1601. ui.action_Install_File_NAND->setEnabled(true);
  1602. }
  1603. InstallResult GMainWindow::InstallNSPXCI(const QString& filename) {
  1604. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1605. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1606. if (src == nullptr || dest == nullptr) {
  1607. return false;
  1608. }
  1609. if (!dest->Resize(src->GetSize())) {
  1610. return false;
  1611. }
  1612. std::array<u8, 0x1000> buffer{};
  1613. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1614. if (install_progress->wasCanceled()) {
  1615. dest->Resize(0);
  1616. return false;
  1617. }
  1618. emit UpdateInstallProgress();
  1619. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1620. dest->Write(buffer.data(), read, i);
  1621. }
  1622. return true;
  1623. };
  1624. std::shared_ptr<FileSys::NSP> nsp;
  1625. if (filename.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1626. nsp = std::make_shared<FileSys::NSP>(
  1627. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1628. if (nsp->IsExtractedType()) {
  1629. return InstallResult::Failure;
  1630. }
  1631. } else {
  1632. const auto xci = std::make_shared<FileSys::XCI>(
  1633. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1634. nsp = xci->GetSecurePartitionNSP();
  1635. }
  1636. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  1637. return InstallResult::Failure;
  1638. }
  1639. const auto res =
  1640. Core::System::GetInstance().GetFileSystemController().GetUserNANDContents()->InstallEntry(
  1641. *nsp, true, qt_raw_copy);
  1642. if (res == FileSys::InstallResult::Success) {
  1643. return InstallResult::Success;
  1644. } else if (res == FileSys::InstallResult::OverwriteExisting) {
  1645. return InstallResult::Overwrite;
  1646. } else {
  1647. return InstallResult::Failure;
  1648. }
  1649. }
  1650. InstallResult GMainWindow::InstallNCA(const QString& filename) {
  1651. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1652. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1653. if (src == nullptr || dest == nullptr) {
  1654. return false;
  1655. }
  1656. if (!dest->Resize(src->GetSize())) {
  1657. return false;
  1658. }
  1659. std::array<u8, 0x1000> buffer{};
  1660. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1661. if (install_progress->wasCanceled()) {
  1662. dest->Resize(0);
  1663. return false;
  1664. }
  1665. emit UpdateInstallProgress();
  1666. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1667. dest->Write(buffer.data(), read, i);
  1668. }
  1669. return true;
  1670. };
  1671. const auto nca =
  1672. std::make_shared<FileSys::NCA>(vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1673. const auto id = nca->GetStatus();
  1674. // Game updates necessary are missing base RomFS
  1675. if (id != Loader::ResultStatus::Success &&
  1676. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  1677. return InstallResult::Failure;
  1678. }
  1679. const QStringList tt_options{tr("System Application"),
  1680. tr("System Archive"),
  1681. tr("System Application Update"),
  1682. tr("Firmware Package (Type A)"),
  1683. tr("Firmware Package (Type B)"),
  1684. tr("Game"),
  1685. tr("Game Update"),
  1686. tr("Game DLC"),
  1687. tr("Delta Title")};
  1688. bool ok;
  1689. const auto item = QInputDialog::getItem(
  1690. this, tr("Select NCA Install Type..."),
  1691. tr("Please select the type of title you would like to install this NCA as:\n(In "
  1692. "most instances, the default 'Game' is fine.)"),
  1693. tt_options, 5, false, &ok);
  1694. auto index = tt_options.indexOf(item);
  1695. if (!ok || index == -1) {
  1696. QMessageBox::warning(this, tr("Failed to Install"),
  1697. tr("The title type you selected for the NCA is invalid."));
  1698. return InstallResult::Failure;
  1699. }
  1700. // If index is equal to or past Game, add the jump in TitleType.
  1701. if (index >= 5) {
  1702. index += static_cast<size_t>(FileSys::TitleType::Application) -
  1703. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  1704. }
  1705. FileSys::InstallResult res;
  1706. if (index >= static_cast<s32>(FileSys::TitleType::Application)) {
  1707. res = Core::System::GetInstance()
  1708. .GetFileSystemController()
  1709. .GetUserNANDContents()
  1710. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1711. } else {
  1712. res = Core::System::GetInstance()
  1713. .GetFileSystemController()
  1714. .GetSystemNANDContents()
  1715. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1716. }
  1717. if (res == FileSys::InstallResult::Success) {
  1718. return InstallResult::Success;
  1719. } else if (res == FileSys::InstallResult::OverwriteExisting) {
  1720. return InstallResult::Overwrite;
  1721. } else {
  1722. return InstallResult::Failure;
  1723. }
  1724. }
  1725. void GMainWindow::OnMenuRecentFile() {
  1726. QAction* action = qobject_cast<QAction*>(sender());
  1727. assert(action);
  1728. const QString filename = action->data().toString();
  1729. if (QFileInfo::exists(filename)) {
  1730. BootGame(filename);
  1731. } else {
  1732. // Display an error message and remove the file from the list.
  1733. QMessageBox::information(this, tr("File not found"),
  1734. tr("File \"%1\" not found").arg(filename));
  1735. UISettings::values.recent_files.removeOne(filename);
  1736. UpdateRecentFiles();
  1737. }
  1738. }
  1739. void GMainWindow::OnStartGame() {
  1740. PreventOSSleep();
  1741. emu_thread->SetRunning(true);
  1742. qRegisterMetaType<Core::Frontend::SoftwareKeyboardParameters>(
  1743. "Core::Frontend::SoftwareKeyboardParameters");
  1744. qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
  1745. qRegisterMetaType<std::string>("std::string");
  1746. qRegisterMetaType<std::optional<std::u16string>>("std::optional<std::u16string>");
  1747. qRegisterMetaType<std::string_view>("std::string_view");
  1748. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  1749. ui.action_Start->setEnabled(false);
  1750. ui.action_Start->setText(tr("Continue"));
  1751. ui.action_Pause->setEnabled(true);
  1752. ui.action_Stop->setEnabled(true);
  1753. ui.action_Restart->setEnabled(true);
  1754. ui.action_Report_Compatibility->setEnabled(true);
  1755. discord_rpc->Update();
  1756. ui.action_Load_Amiibo->setEnabled(true);
  1757. ui.action_Capture_Screenshot->setEnabled(true);
  1758. }
  1759. void GMainWindow::OnPauseGame() {
  1760. emu_thread->SetRunning(false);
  1761. ui.action_Start->setEnabled(true);
  1762. ui.action_Pause->setEnabled(false);
  1763. ui.action_Stop->setEnabled(true);
  1764. ui.action_Capture_Screenshot->setEnabled(false);
  1765. AllowOSSleep();
  1766. }
  1767. void GMainWindow::OnStopGame() {
  1768. Core::System& system{Core::System::GetInstance()};
  1769. if (system.GetExitLock() && !ConfirmForceLockedExit()) {
  1770. return;
  1771. }
  1772. ShutdownGame();
  1773. Settings::RestoreGlobalState();
  1774. UpdateStatusButtons();
  1775. }
  1776. void GMainWindow::OnLoadComplete() {
  1777. loading_screen->OnLoadComplete();
  1778. }
  1779. void GMainWindow::ErrorDisplayDisplayError(QString body) {
  1780. QMessageBox::critical(this, tr("Error Display"), body);
  1781. emit ErrorDisplayFinished();
  1782. }
  1783. void GMainWindow::OnMenuReportCompatibility() {
  1784. if (!Settings::values.yuzu_token.empty() && !Settings::values.yuzu_username.empty()) {
  1785. CompatDB compatdb{this};
  1786. compatdb.exec();
  1787. } else {
  1788. QMessageBox::critical(
  1789. this, tr("Missing yuzu Account"),
  1790. tr("In order to submit a game compatibility test case, you must link your yuzu "
  1791. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  1792. "&gt; "
  1793. "Web."));
  1794. }
  1795. }
  1796. void GMainWindow::OpenURL(const QUrl& url) {
  1797. const bool open = QDesktopServices::openUrl(url);
  1798. if (!open) {
  1799. QMessageBox::warning(this, tr("Error opening URL"),
  1800. tr("Unable to open the URL \"%1\".").arg(url.toString()));
  1801. }
  1802. }
  1803. void GMainWindow::OnOpenModsPage() {
  1804. OpenURL(QUrl(QStringLiteral("https://github.com/yuzu-emu/yuzu/wiki/Switch-Mods")));
  1805. }
  1806. void GMainWindow::OnOpenQuickstartGuide() {
  1807. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/help/quickstart/")));
  1808. }
  1809. void GMainWindow::OnOpenFAQ() {
  1810. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/wiki/faq/")));
  1811. }
  1812. void GMainWindow::ToggleFullscreen() {
  1813. if (!emulation_running) {
  1814. return;
  1815. }
  1816. if (ui.action_Fullscreen->isChecked()) {
  1817. ShowFullscreen();
  1818. } else {
  1819. HideFullscreen();
  1820. }
  1821. }
  1822. void GMainWindow::ShowFullscreen() {
  1823. if (ui.action_Single_Window_Mode->isChecked()) {
  1824. UISettings::values.geometry = saveGeometry();
  1825. ui.menubar->hide();
  1826. statusBar()->hide();
  1827. showFullScreen();
  1828. } else {
  1829. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  1830. render_window->showFullScreen();
  1831. }
  1832. }
  1833. void GMainWindow::HideFullscreen() {
  1834. if (ui.action_Single_Window_Mode->isChecked()) {
  1835. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  1836. ui.menubar->show();
  1837. showNormal();
  1838. restoreGeometry(UISettings::values.geometry);
  1839. } else {
  1840. render_window->showNormal();
  1841. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  1842. }
  1843. }
  1844. void GMainWindow::ToggleWindowMode() {
  1845. if (ui.action_Single_Window_Mode->isChecked()) {
  1846. // Render in the main window...
  1847. render_window->BackupGeometry();
  1848. ui.horizontalLayout->addWidget(render_window);
  1849. render_window->setFocusPolicy(Qt::StrongFocus);
  1850. if (emulation_running) {
  1851. render_window->setVisible(true);
  1852. render_window->setFocus();
  1853. game_list->hide();
  1854. }
  1855. } else {
  1856. // Render in a separate window...
  1857. ui.horizontalLayout->removeWidget(render_window);
  1858. render_window->setParent(nullptr);
  1859. render_window->setFocusPolicy(Qt::NoFocus);
  1860. if (emulation_running) {
  1861. render_window->setVisible(true);
  1862. render_window->RestoreGeometry();
  1863. game_list->show();
  1864. }
  1865. }
  1866. }
  1867. void GMainWindow::ResetWindowSize() {
  1868. const auto aspect_ratio = Layout::EmulationAspectRatio(
  1869. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  1870. static_cast<float>(Layout::ScreenUndocked::Height) / Layout::ScreenUndocked::Width);
  1871. if (!ui.action_Single_Window_Mode->isChecked()) {
  1872. render_window->resize(Layout::ScreenUndocked::Height / aspect_ratio,
  1873. Layout::ScreenUndocked::Height);
  1874. } else {
  1875. resize(Layout::ScreenUndocked::Height / aspect_ratio,
  1876. Layout::ScreenUndocked::Height + menuBar()->height() +
  1877. (ui.action_Show_Status_Bar->isChecked() ? statusBar()->height() : 0));
  1878. }
  1879. }
  1880. void GMainWindow::OnConfigure() {
  1881. const auto old_theme = UISettings::values.theme;
  1882. const bool old_discord_presence = UISettings::values.enable_discord_presence;
  1883. ConfigureDialog configure_dialog(this, hotkey_registry);
  1884. connect(&configure_dialog, &ConfigureDialog::LanguageChanged, this,
  1885. &GMainWindow::OnLanguageChanged);
  1886. const auto result = configure_dialog.exec();
  1887. if (result != QDialog::Accepted) {
  1888. return;
  1889. }
  1890. configure_dialog.ApplyConfiguration();
  1891. InitializeHotkeys();
  1892. if (UISettings::values.theme != old_theme) {
  1893. UpdateUITheme();
  1894. }
  1895. if (UISettings::values.enable_discord_presence != old_discord_presence) {
  1896. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  1897. }
  1898. emit UpdateThemedIcons();
  1899. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  1900. if (reload) {
  1901. game_list->PopulateAsync(UISettings::values.game_dirs);
  1902. }
  1903. config->Save();
  1904. if (UISettings::values.hide_mouse && emulation_running) {
  1905. setMouseTracking(true);
  1906. ui.centralwidget->setMouseTracking(true);
  1907. mouse_hide_timer.start();
  1908. } else {
  1909. setMouseTracking(false);
  1910. ui.centralwidget->setMouseTracking(false);
  1911. }
  1912. UpdateStatusButtons();
  1913. }
  1914. void GMainWindow::OnLoadAmiibo() {
  1915. const QString extensions{QStringLiteral("*.bin")};
  1916. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  1917. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter);
  1918. if (filename.isEmpty()) {
  1919. return;
  1920. }
  1921. LoadAmiibo(filename);
  1922. }
  1923. void GMainWindow::LoadAmiibo(const QString& filename) {
  1924. Core::System& system{Core::System::GetInstance()};
  1925. Service::SM::ServiceManager& sm = system.ServiceManager();
  1926. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  1927. if (nfc == nullptr) {
  1928. return;
  1929. }
  1930. QFile nfc_file{filename};
  1931. if (!nfc_file.open(QIODevice::ReadOnly)) {
  1932. QMessageBox::warning(this, tr("Error opening Amiibo data file"),
  1933. tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
  1934. return;
  1935. }
  1936. const u64 nfc_file_size = nfc_file.size();
  1937. std::vector<u8> buffer(nfc_file_size);
  1938. const u64 read_size = nfc_file.read(reinterpret_cast<char*>(buffer.data()), nfc_file_size);
  1939. if (nfc_file_size != read_size) {
  1940. QMessageBox::warning(this, tr("Error reading Amiibo data file"),
  1941. tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
  1942. "was only able to read %2 bytes.")
  1943. .arg(nfc_file_size)
  1944. .arg(read_size));
  1945. return;
  1946. }
  1947. if (!nfc->LoadAmiibo(buffer)) {
  1948. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  1949. tr("Unable to load Amiibo data."));
  1950. }
  1951. }
  1952. void GMainWindow::OnOpenYuzuFolder() {
  1953. QDesktopServices::openUrl(QUrl::fromLocalFile(
  1954. QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::UserDir))));
  1955. }
  1956. void GMainWindow::OnAbout() {
  1957. AboutDialog aboutDialog(this);
  1958. aboutDialog.exec();
  1959. }
  1960. void GMainWindow::OnToggleFilterBar() {
  1961. game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  1962. if (ui.action_Show_Filter_Bar->isChecked()) {
  1963. game_list->setFilterFocus();
  1964. } else {
  1965. game_list->clearFilter();
  1966. }
  1967. }
  1968. void GMainWindow::OnCaptureScreenshot() {
  1969. OnPauseGame();
  1970. QFileDialog png_dialog(this, tr("Capture Screenshot"), UISettings::values.screenshot_path,
  1971. tr("PNG Image (*.png)"));
  1972. png_dialog.setAcceptMode(QFileDialog::AcceptSave);
  1973. png_dialog.setDefaultSuffix(QStringLiteral("png"));
  1974. if (png_dialog.exec()) {
  1975. const QString path = png_dialog.selectedFiles().first();
  1976. if (!path.isEmpty()) {
  1977. UISettings::values.screenshot_path = QFileInfo(path).path();
  1978. render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor, path);
  1979. }
  1980. }
  1981. OnStartGame();
  1982. }
  1983. void GMainWindow::UpdateWindowTitle(const std::string& title_name,
  1984. const std::string& title_version) {
  1985. const auto full_name = std::string(Common::g_build_fullname);
  1986. const auto branch_name = std::string(Common::g_scm_branch);
  1987. const auto description = std::string(Common::g_scm_desc);
  1988. const auto build_id = std::string(Common::g_build_id);
  1989. const auto date =
  1990. QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd")).toStdString();
  1991. if (title_name.empty()) {
  1992. const auto fmt = std::string(Common::g_title_bar_format_idle);
  1993. setWindowTitle(QString::fromStdString(fmt::format(fmt.empty() ? "yuzu {0}| {1}-{2}" : fmt,
  1994. full_name, branch_name, description,
  1995. std::string{}, date, build_id)));
  1996. } else {
  1997. const auto fmt = std::string(Common::g_title_bar_format_running);
  1998. setWindowTitle(QString::fromStdString(
  1999. fmt::format(fmt.empty() ? "yuzu {0}| {3} | {6} | {1}-{2}" : fmt, full_name, branch_name,
  2000. description, title_name, date, build_id, title_version)));
  2001. }
  2002. }
  2003. void GMainWindow::UpdateStatusBar() {
  2004. if (emu_thread == nullptr) {
  2005. status_bar_update_timer.stop();
  2006. return;
  2007. }
  2008. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  2009. auto& shader_notify = Core::System::GetInstance().GPU().ShaderNotify();
  2010. const auto shaders_building = shader_notify.GetShadersBuilding();
  2011. if (shaders_building != 0) {
  2012. shader_building_label->setText(
  2013. tr("Building: %1 shader").arg(shaders_building) +
  2014. (shaders_building != 1 ? QString::fromStdString("s") : QString::fromStdString("")));
  2015. shader_building_label->setVisible(true);
  2016. } else {
  2017. shader_building_label->setVisible(false);
  2018. }
  2019. if (Settings::values.use_frame_limit.GetValue()) {
  2020. emu_speed_label->setText(tr("Speed: %1% / %2%")
  2021. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  2022. .arg(Settings::values.frame_limit.GetValue()));
  2023. } else {
  2024. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  2025. }
  2026. game_fps_label->setText(tr("Game: %1 FPS").arg(results.game_fps, 0, 'f', 0));
  2027. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  2028. emu_speed_label->setVisible(!Settings::values.use_multi_core.GetValue());
  2029. game_fps_label->setVisible(true);
  2030. emu_frametime_label->setVisible(true);
  2031. }
  2032. void GMainWindow::UpdateStatusButtons() {
  2033. dock_status_button->setChecked(Settings::values.use_docked_mode);
  2034. multicore_status_button->setChecked(Settings::values.use_multi_core.GetValue());
  2035. Settings::values.use_asynchronous_gpu_emulation.SetValue(
  2036. Settings::values.use_asynchronous_gpu_emulation.GetValue() ||
  2037. Settings::values.use_multi_core.GetValue());
  2038. async_status_button->setChecked(Settings::values.use_asynchronous_gpu_emulation.GetValue());
  2039. #ifdef HAS_VULKAN
  2040. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  2041. Settings::RendererBackend::Vulkan);
  2042. #endif
  2043. }
  2044. void GMainWindow::HideMouseCursor() {
  2045. if (emu_thread == nullptr || UISettings::values.hide_mouse == false) {
  2046. mouse_hide_timer.stop();
  2047. ShowMouseCursor();
  2048. return;
  2049. }
  2050. setCursor(QCursor(Qt::BlankCursor));
  2051. }
  2052. void GMainWindow::ShowMouseCursor() {
  2053. unsetCursor();
  2054. if (emu_thread != nullptr && UISettings::values.hide_mouse) {
  2055. mouse_hide_timer.start();
  2056. }
  2057. }
  2058. void GMainWindow::mouseMoveEvent(QMouseEvent* event) {
  2059. ShowMouseCursor();
  2060. }
  2061. void GMainWindow::mousePressEvent(QMouseEvent* event) {
  2062. ShowMouseCursor();
  2063. }
  2064. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  2065. QMessageBox::StandardButton answer;
  2066. QString status_message;
  2067. const QString common_message =
  2068. tr("The game you are trying to load requires additional files from your Switch to be "
  2069. "dumped "
  2070. "before playing.<br/><br/>For more information on dumping these files, please see the "
  2071. "following wiki page: <a "
  2072. "href='https://yuzu-emu.org/wiki/"
  2073. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  2074. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  2075. "quit "
  2076. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  2077. "data, or other bugs.");
  2078. switch (result) {
  2079. case Core::System::ResultStatus::ErrorSystemFiles: {
  2080. QString message;
  2081. if (details.empty()) {
  2082. message =
  2083. tr("yuzu was unable to locate a Switch system archive. %1").arg(common_message);
  2084. } else {
  2085. message = tr("yuzu was unable to locate a Switch system archive: %1. %2")
  2086. .arg(QString::fromStdString(details), common_message);
  2087. }
  2088. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  2089. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2090. status_message = tr("System Archive Missing");
  2091. break;
  2092. }
  2093. case Core::System::ResultStatus::ErrorSharedFont: {
  2094. const QString message =
  2095. tr("yuzu was unable to locate the Switch shared fonts. %1").arg(common_message);
  2096. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  2097. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2098. status_message = tr("Shared Font Missing");
  2099. break;
  2100. }
  2101. default:
  2102. answer = QMessageBox::question(
  2103. this, tr("Fatal Error"),
  2104. tr("yuzu has encountered a fatal error, please see the log for more details. "
  2105. "For more information on accessing the log, please see the following page: "
  2106. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  2107. "to "
  2108. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  2109. "list? "
  2110. "Continuing emulation may result in crashes, corrupted save data, or other "
  2111. "bugs."),
  2112. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2113. status_message = tr("Fatal Error encountered");
  2114. break;
  2115. }
  2116. if (answer == QMessageBox::Yes) {
  2117. if (emu_thread) {
  2118. ShutdownGame();
  2119. Settings::RestoreGlobalState();
  2120. UpdateStatusButtons();
  2121. }
  2122. } else {
  2123. // Only show the message if the game is still running.
  2124. if (emu_thread) {
  2125. emu_thread->SetRunning(true);
  2126. message_label->setText(status_message);
  2127. }
  2128. }
  2129. }
  2130. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  2131. if (behavior == ReinitializeKeyBehavior::Warning) {
  2132. const auto res = QMessageBox::information(
  2133. this, tr("Confirm Key Rederivation"),
  2134. tr("You are about to force rederive all of your keys. \nIf you do not know what "
  2135. "this "
  2136. "means or what you are doing, \nthis is a potentially destructive action. "
  2137. "\nPlease "
  2138. "make sure this is what you want \nand optionally make backups.\n\nThis will "
  2139. "delete "
  2140. "your autogenerated key files and re-run the key derivation module."),
  2141. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  2142. if (res == QMessageBox::Cancel)
  2143. return;
  2144. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  2145. "prod.keys_autogenerated");
  2146. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  2147. "console.keys_autogenerated");
  2148. FileUtil::Delete(FileUtil::GetUserPath(FileUtil::UserPath::KeysDir) +
  2149. "title.keys_autogenerated");
  2150. }
  2151. Core::Crypto::KeyManager& keys = Core::Crypto::KeyManager::Instance();
  2152. if (keys.BaseDeriveNecessary()) {
  2153. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory(
  2154. FileUtil::GetUserPath(FileUtil::UserPath::SysDataDir), FileSys::Mode::Read)};
  2155. const auto function = [this, &keys, &pdm] {
  2156. keys.PopulateFromPartitionData(pdm);
  2157. Core::System::GetInstance().GetFileSystemController().CreateFactories(*vfs);
  2158. keys.DeriveETicket(pdm);
  2159. };
  2160. QString errors;
  2161. if (!pdm.HasFuses()) {
  2162. errors += tr("Missing fuses");
  2163. }
  2164. if (!pdm.HasBoot0()) {
  2165. errors += tr(" - Missing BOOT0");
  2166. }
  2167. if (!pdm.HasPackage2()) {
  2168. errors += tr(" - Missing BCPKG2-1-Normal-Main");
  2169. }
  2170. if (!pdm.HasProdInfo()) {
  2171. errors += tr(" - Missing PRODINFO");
  2172. }
  2173. if (!errors.isEmpty()) {
  2174. QMessageBox::warning(
  2175. this, tr("Derivation Components Missing"),
  2176. tr("Components are missing that may hinder key derivation from completing. "
  2177. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  2178. "quickstart guide</a> to get all your keys and "
  2179. "games.<br><br><small>(%1)</small>")
  2180. .arg(errors));
  2181. }
  2182. QProgressDialog prog;
  2183. prog.setRange(0, 0);
  2184. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  2185. "system's performance."));
  2186. prog.setWindowTitle(tr("Deriving Keys"));
  2187. prog.show();
  2188. auto future = QtConcurrent::run(function);
  2189. while (!future.isFinished()) {
  2190. QCoreApplication::processEvents();
  2191. }
  2192. prog.close();
  2193. }
  2194. Core::System::GetInstance().GetFileSystemController().CreateFactories(*vfs);
  2195. if (behavior == ReinitializeKeyBehavior::Warning) {
  2196. game_list->PopulateAsync(UISettings::values.game_dirs);
  2197. }
  2198. }
  2199. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
  2200. u64 program_id) {
  2201. const auto dlc_entries =
  2202. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  2203. std::vector<FileSys::ContentProviderEntry> dlc_match;
  2204. dlc_match.reserve(dlc_entries.size());
  2205. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  2206. [&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
  2207. return (entry.title_id & DLC_BASE_TITLE_ID_MASK) == program_id &&
  2208. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  2209. });
  2210. std::vector<u64> romfs_tids;
  2211. romfs_tids.push_back(program_id);
  2212. for (const auto& entry : dlc_match) {
  2213. romfs_tids.push_back(entry.title_id);
  2214. }
  2215. if (romfs_tids.size() > 1) {
  2216. QStringList list{QStringLiteral("Base")};
  2217. for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
  2218. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  2219. }
  2220. bool ok;
  2221. const auto res = QInputDialog::getItem(
  2222. this, tr("Select RomFS Dump Target"),
  2223. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  2224. if (!ok) {
  2225. return {};
  2226. }
  2227. return romfs_tids[list.indexOf(res)];
  2228. }
  2229. return program_id;
  2230. }
  2231. bool GMainWindow::ConfirmClose() {
  2232. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  2233. return true;
  2234. QMessageBox::StandardButton answer =
  2235. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  2236. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2237. return answer != QMessageBox::No;
  2238. }
  2239. void GMainWindow::closeEvent(QCloseEvent* event) {
  2240. if (!ConfirmClose()) {
  2241. event->ignore();
  2242. return;
  2243. }
  2244. if (!ui.action_Fullscreen->isChecked()) {
  2245. UISettings::values.geometry = saveGeometry();
  2246. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2247. }
  2248. UISettings::values.state = saveState();
  2249. #if MICROPROFILE_ENABLED
  2250. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  2251. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  2252. #endif
  2253. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  2254. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  2255. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  2256. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  2257. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  2258. UISettings::values.first_start = false;
  2259. game_list->SaveInterfaceLayout();
  2260. hotkey_registry.SaveHotkeys();
  2261. // Shutdown session if the emu thread is active...
  2262. if (emu_thread != nullptr) {
  2263. ShutdownGame();
  2264. Settings::RestoreGlobalState();
  2265. UpdateStatusButtons();
  2266. }
  2267. render_window->close();
  2268. QWidget::closeEvent(event);
  2269. }
  2270. static bool IsSingleFileDropEvent(const QMimeData* mime) {
  2271. return mime->hasUrls() && mime->urls().length() == 1;
  2272. }
  2273. void GMainWindow::AcceptDropEvent(QDropEvent* event) {
  2274. if (IsSingleFileDropEvent(event->mimeData())) {
  2275. event->setDropAction(Qt::DropAction::LinkAction);
  2276. event->accept();
  2277. }
  2278. }
  2279. bool GMainWindow::DropAction(QDropEvent* event) {
  2280. if (!IsSingleFileDropEvent(event->mimeData())) {
  2281. return false;
  2282. }
  2283. const QMimeData* mime_data = event->mimeData();
  2284. const QString& filename = mime_data->urls().at(0).toLocalFile();
  2285. if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
  2286. // Amiibo
  2287. LoadAmiibo(filename);
  2288. } else {
  2289. // Game
  2290. if (ConfirmChangeGame()) {
  2291. BootGame(filename);
  2292. }
  2293. }
  2294. return true;
  2295. }
  2296. void GMainWindow::dropEvent(QDropEvent* event) {
  2297. DropAction(event);
  2298. }
  2299. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  2300. AcceptDropEvent(event);
  2301. }
  2302. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  2303. AcceptDropEvent(event);
  2304. }
  2305. bool GMainWindow::ConfirmChangeGame() {
  2306. if (emu_thread == nullptr)
  2307. return true;
  2308. const auto answer = QMessageBox::question(
  2309. this, tr("yuzu"),
  2310. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  2311. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2312. return answer != QMessageBox::No;
  2313. }
  2314. bool GMainWindow::ConfirmForceLockedExit() {
  2315. if (emu_thread == nullptr)
  2316. return true;
  2317. const auto answer =
  2318. QMessageBox::question(this, tr("yuzu"),
  2319. tr("The currently running application has requested yuzu to not "
  2320. "exit.\n\nWould you like to bypass this and exit anyway?"),
  2321. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2322. return answer != QMessageBox::No;
  2323. }
  2324. void GMainWindow::RequestGameExit() {
  2325. auto& sm{Core::System::GetInstance().ServiceManager()};
  2326. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  2327. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  2328. bool has_signalled = false;
  2329. if (applet_oe != nullptr) {
  2330. applet_oe->GetMessageQueue()->RequestExit();
  2331. has_signalled = true;
  2332. }
  2333. if (applet_ae != nullptr && !has_signalled) {
  2334. applet_ae->GetMessageQueue()->RequestExit();
  2335. }
  2336. }
  2337. void GMainWindow::filterBarSetChecked(bool state) {
  2338. ui.action_Show_Filter_Bar->setChecked(state);
  2339. emit(OnToggleFilterBar());
  2340. }
  2341. void GMainWindow::UpdateUITheme() {
  2342. const QString default_icons = QStringLiteral(":/icons/default");
  2343. const QString& current_theme = UISettings::values.theme;
  2344. const bool is_default_theme = current_theme == QString::fromUtf8(UISettings::themes[0].second);
  2345. QStringList theme_paths(default_theme_paths);
  2346. if (is_default_theme || current_theme.isEmpty()) {
  2347. const QString theme_uri(QStringLiteral(":default/style.qss"));
  2348. QFile f(theme_uri);
  2349. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2350. QTextStream ts(&f);
  2351. qApp->setStyleSheet(ts.readAll());
  2352. setStyleSheet(ts.readAll());
  2353. } else {
  2354. qApp->setStyleSheet({});
  2355. setStyleSheet({});
  2356. }
  2357. theme_paths.append(default_icons);
  2358. QIcon::setThemeName(default_icons);
  2359. } else {
  2360. const QString theme_uri(QLatin1Char{':'} + current_theme + QStringLiteral("/style.qss"));
  2361. QFile f(theme_uri);
  2362. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2363. QTextStream ts(&f);
  2364. qApp->setStyleSheet(ts.readAll());
  2365. setStyleSheet(ts.readAll());
  2366. } else {
  2367. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  2368. }
  2369. const QString theme_name = QStringLiteral(":/icons/") + current_theme;
  2370. theme_paths.append({default_icons, theme_name});
  2371. QIcon::setThemeName(theme_name);
  2372. }
  2373. QIcon::setThemeSearchPaths(theme_paths);
  2374. }
  2375. void GMainWindow::LoadTranslation() {
  2376. // If the selected language is English, no need to install any translation
  2377. if (UISettings::values.language == QStringLiteral("en")) {
  2378. return;
  2379. }
  2380. bool loaded;
  2381. if (UISettings::values.language.isEmpty()) {
  2382. // If the selected language is empty, use system locale
  2383. loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/"));
  2384. } else {
  2385. // Otherwise load from the specified file
  2386. loaded = translator.load(UISettings::values.language, QStringLiteral(":/languages/"));
  2387. }
  2388. if (loaded) {
  2389. qApp->installTranslator(&translator);
  2390. } else {
  2391. UISettings::values.language = QStringLiteral("en");
  2392. }
  2393. }
  2394. void GMainWindow::OnLanguageChanged(const QString& locale) {
  2395. if (UISettings::values.language != QStringLiteral("en")) {
  2396. qApp->removeTranslator(&translator);
  2397. }
  2398. UISettings::values.language = locale;
  2399. LoadTranslation();
  2400. ui.retranslateUi(this);
  2401. UpdateWindowTitle();
  2402. if (emulation_running)
  2403. ui.action_Start->setText(tr("Continue"));
  2404. }
  2405. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  2406. #ifdef USE_DISCORD_PRESENCE
  2407. if (state) {
  2408. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  2409. } else {
  2410. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2411. }
  2412. #else
  2413. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2414. #endif
  2415. discord_rpc->Update();
  2416. }
  2417. #ifdef main
  2418. #undef main
  2419. #endif
  2420. int main(int argc, char* argv[]) {
  2421. Common::DetachedTasks detached_tasks;
  2422. MicroProfileOnThreadCreate("Frontend");
  2423. SCOPE_EXIT({ MicroProfileShutdown(); });
  2424. // Init settings params
  2425. QCoreApplication::setOrganizationName(QStringLiteral("yuzu team"));
  2426. QCoreApplication::setApplicationName(QStringLiteral("yuzu"));
  2427. #ifdef __APPLE__
  2428. // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/".
  2429. // But since we require the working directory to be the executable path for the location of
  2430. // the user folder in the Qt Frontend, we need to cd into that working directory
  2431. const std::string bin_path = FileUtil::GetBundleDirectory() + DIR_SEP + "..";
  2432. chdir(bin_path.c_str());
  2433. #endif
  2434. // Enables the core to make the qt created contexts current on std::threads
  2435. QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  2436. QApplication app(argc, argv);
  2437. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  2438. // generating shaders
  2439. setlocale(LC_ALL, "C");
  2440. GMainWindow main_window;
  2441. // After settings have been loaded by GMainWindow, apply the filter
  2442. main_window.show();
  2443. QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
  2444. &GMainWindow::OnAppFocusStateChanged);
  2445. int result = app.exec();
  2446. detached_tasks.WaitForAllTasks();
  2447. return result;
  2448. }