main.cpp 143 KB

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