main.cpp 130 KB

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