main.cpp 124 KB

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