main.cpp 135 KB

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