main.cpp 133 KB

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