main.cpp 140 KB

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