main.cpp 139 KB

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