main.cpp 134 KB

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