main.cpp 114 KB

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