main.cpp 126 KB

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