main.cpp 115 KB

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