main.cpp 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335
  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. Config per_game_config(fmt::format("{:016X}", title_id), Config::ConfigType::PerGameConfig);
  1123. }
  1124. ConfigureVibration::SetAllVibrationDevices();
  1125. // Save configurations
  1126. UpdateUISettings();
  1127. game_list->SaveInterfaceLayout();
  1128. config->Save();
  1129. Settings::LogSettings();
  1130. if (UISettings::values.select_user_on_boot) {
  1131. SelectAndSetCurrentUser();
  1132. }
  1133. if (!LoadROM(filename, program_index))
  1134. return;
  1135. // Create and start the emulation thread
  1136. emu_thread = std::make_unique<EmuThread>();
  1137. emit EmulationStarting(emu_thread.get());
  1138. emu_thread->start();
  1139. // Register an ExecuteProgram callback such that Core can execute a sub-program
  1140. system.RegisterExecuteProgramCallback(
  1141. [this](std::size_t program_index) { render_window->ExecuteProgram(program_index); });
  1142. connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1143. connect(render_window, &GRenderWindow::MouseActivity, this, &GMainWindow::OnMouseActivity);
  1144. // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views
  1145. // before the CPU continues
  1146. connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget,
  1147. &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection);
  1148. connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget,
  1149. &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection);
  1150. connect(emu_thread.get(), &EmuThread::LoadProgress, loading_screen,
  1151. &LoadingScreen::OnLoadProgress, Qt::QueuedConnection);
  1152. // Update the GUI
  1153. UpdateStatusButtons();
  1154. if (ui.action_Single_Window_Mode->isChecked()) {
  1155. game_list->hide();
  1156. game_list_placeholder->hide();
  1157. }
  1158. status_bar_update_timer.start(500);
  1159. async_status_button->setDisabled(true);
  1160. multicore_status_button->setDisabled(true);
  1161. renderer_status_button->setDisabled(true);
  1162. if (UISettings::values.hide_mouse || Settings::values.mouse_panning) {
  1163. render_window->installEventFilter(render_window);
  1164. render_window->setAttribute(Qt::WA_Hover, true);
  1165. }
  1166. if (UISettings::values.hide_mouse) {
  1167. mouse_hide_timer.start();
  1168. }
  1169. std::string title_name;
  1170. std::string title_version;
  1171. const auto res = system.GetGameName(title_name);
  1172. const auto metadata = [&system, title_id] {
  1173. const FileSys::PatchManager pm(title_id, system.GetFileSystemController(),
  1174. system.GetContentProvider());
  1175. return pm.GetControlMetadata();
  1176. }();
  1177. if (metadata.first != nullptr) {
  1178. title_version = metadata.first->GetVersionString();
  1179. title_name = metadata.first->GetApplicationName();
  1180. }
  1181. if (res != Loader::ResultStatus::Success || title_name.empty()) {
  1182. title_name = Common::FS::PathToUTF8String(
  1183. std::filesystem::path{filename.toStdU16String()}.filename());
  1184. }
  1185. LOG_INFO(Frontend, "Booting game: {:016X} | {} | {}", title_id, title_name, title_version);
  1186. UpdateWindowTitle(title_name, title_version);
  1187. loading_screen->Prepare(system.GetAppLoader());
  1188. loading_screen->show();
  1189. emulation_running = true;
  1190. if (ui.action_Fullscreen->isChecked()) {
  1191. ShowFullscreen();
  1192. }
  1193. OnStartGame();
  1194. }
  1195. void GMainWindow::ShutdownGame() {
  1196. if (!emulation_running) {
  1197. return;
  1198. }
  1199. if (ui.action_Fullscreen->isChecked()) {
  1200. HideFullscreen();
  1201. }
  1202. AllowOSSleep();
  1203. discord_rpc->Pause();
  1204. emu_thread->RequestStop();
  1205. emit EmulationStopping();
  1206. // Wait for emulation thread to complete and delete it
  1207. emu_thread->wait();
  1208. emu_thread = nullptr;
  1209. discord_rpc->Update();
  1210. // The emulation is stopped, so closing the window or not does not matter anymore
  1211. disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame);
  1212. // Update the GUI
  1213. ui.action_Start->setEnabled(false);
  1214. ui.action_Start->setText(tr("Start"));
  1215. ui.action_Pause->setEnabled(false);
  1216. ui.action_Stop->setEnabled(false);
  1217. ui.action_Restart->setEnabled(false);
  1218. ui.action_Configure_Current_Game->setEnabled(false);
  1219. ui.action_Report_Compatibility->setEnabled(false);
  1220. ui.action_Load_Amiibo->setEnabled(false);
  1221. ui.action_Capture_Screenshot->setEnabled(false);
  1222. render_window->hide();
  1223. loading_screen->hide();
  1224. loading_screen->Clear();
  1225. if (game_list->IsEmpty()) {
  1226. game_list_placeholder->show();
  1227. } else {
  1228. game_list->show();
  1229. }
  1230. game_list->SetFilterFocus();
  1231. render_window->removeEventFilter(render_window);
  1232. render_window->setAttribute(Qt::WA_Hover, false);
  1233. UpdateWindowTitle();
  1234. // Disable status bar updates
  1235. status_bar_update_timer.stop();
  1236. shader_building_label->setVisible(false);
  1237. emu_speed_label->setVisible(false);
  1238. game_fps_label->setVisible(false);
  1239. emu_frametime_label->setVisible(false);
  1240. async_status_button->setEnabled(true);
  1241. multicore_status_button->setEnabled(true);
  1242. renderer_status_button->setEnabled(true);
  1243. emulation_running = false;
  1244. game_path.clear();
  1245. // When closing the game, destroy the GLWindow to clear the context after the game is closed
  1246. render_window->ReleaseRenderTarget();
  1247. }
  1248. void GMainWindow::StoreRecentFile(const QString& filename) {
  1249. UISettings::values.recent_files.prepend(filename);
  1250. UISettings::values.recent_files.removeDuplicates();
  1251. while (UISettings::values.recent_files.size() > max_recent_files_item) {
  1252. UISettings::values.recent_files.removeLast();
  1253. }
  1254. UpdateRecentFiles();
  1255. }
  1256. void GMainWindow::UpdateRecentFiles() {
  1257. const int num_recent_files =
  1258. std::min(UISettings::values.recent_files.size(), max_recent_files_item);
  1259. for (int i = 0; i < num_recent_files; i++) {
  1260. const QString text = QStringLiteral("&%1. %2").arg(i + 1).arg(
  1261. QFileInfo(UISettings::values.recent_files[i]).fileName());
  1262. actions_recent_files[i]->setText(text);
  1263. actions_recent_files[i]->setData(UISettings::values.recent_files[i]);
  1264. actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]);
  1265. actions_recent_files[i]->setVisible(true);
  1266. }
  1267. for (int j = num_recent_files; j < max_recent_files_item; ++j) {
  1268. actions_recent_files[j]->setVisible(false);
  1269. }
  1270. // Enable the recent files menu if the list isn't empty
  1271. ui.menu_recent_files->setEnabled(num_recent_files != 0);
  1272. }
  1273. void GMainWindow::OnGameListLoadFile(QString game_path) {
  1274. BootGame(game_path);
  1275. }
  1276. void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target,
  1277. const std::string& game_path) {
  1278. std::filesystem::path path;
  1279. QString open_target;
  1280. auto& system = Core::System::GetInstance();
  1281. const auto [user_save_size, device_save_size] = [this, &game_path, &program_id, &system] {
  1282. const FileSys::PatchManager pm{program_id, system.GetFileSystemController(),
  1283. system.GetContentProvider()};
  1284. const auto control = pm.GetControlMetadata().first;
  1285. if (control != nullptr) {
  1286. return std::make_pair(control->GetDefaultNormalSaveSize(),
  1287. control->GetDeviceSaveDataSize());
  1288. } else {
  1289. const auto file = Core::GetGameFileFromPath(vfs, game_path);
  1290. const auto loader = Loader::GetLoader(system, file);
  1291. FileSys::NACP nacp{};
  1292. loader->ReadControlData(nacp);
  1293. return std::make_pair(nacp.GetDefaultNormalSaveSize(), nacp.GetDeviceSaveDataSize());
  1294. }
  1295. }();
  1296. const bool has_user_save{user_save_size > 0};
  1297. const bool has_device_save{device_save_size > 0};
  1298. ASSERT_MSG(has_user_save != has_device_save, "Game uses both user and device savedata?");
  1299. switch (target) {
  1300. case GameListOpenTarget::SaveData: {
  1301. open_target = tr("Save Data");
  1302. const auto nand_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir);
  1303. if (has_user_save) {
  1304. // User save data
  1305. const auto select_profile = [this] {
  1306. QtProfileSelectionDialog dialog(this);
  1307. dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
  1308. Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
  1309. dialog.setWindowModality(Qt::WindowModal);
  1310. if (dialog.exec() == QDialog::Rejected) {
  1311. return -1;
  1312. }
  1313. return dialog.GetIndex();
  1314. };
  1315. const auto index = select_profile();
  1316. if (index == -1) {
  1317. return;
  1318. }
  1319. Service::Account::ProfileManager manager;
  1320. const auto user_id = manager.GetUser(static_cast<std::size_t>(index));
  1321. ASSERT(user_id);
  1322. const auto user_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1323. system, FileSys::SaveDataSpaceId::NandUser, FileSys::SaveDataType::SaveData,
  1324. program_id, user_id->uuid, 0);
  1325. path = Common::FS::ConcatPathSafe(nand_dir, user_save_data_path);
  1326. } else {
  1327. // Device save data
  1328. const auto device_save_data_path = FileSys::SaveDataFactory::GetFullPath(
  1329. system, FileSys::SaveDataSpaceId::NandUser, FileSys::SaveDataType::SaveData,
  1330. program_id, {}, 0);
  1331. path = Common::FS::ConcatPathSafe(nand_dir, device_save_data_path);
  1332. }
  1333. if (!Common::FS::CreateDirs(path)) {
  1334. LOG_ERROR(Frontend, "Unable to create the directories for save data");
  1335. }
  1336. break;
  1337. }
  1338. case GameListOpenTarget::ModData: {
  1339. open_target = tr("Mod Data");
  1340. path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::LoadDir) /
  1341. fmt::format("{:016X}", program_id);
  1342. break;
  1343. }
  1344. default:
  1345. UNIMPLEMENTED();
  1346. }
  1347. const QString qpath = QString::fromStdString(Common::FS::PathToUTF8String(path));
  1348. const QDir dir(qpath);
  1349. if (!dir.exists()) {
  1350. QMessageBox::warning(this, tr("Error Opening %1 Folder").arg(open_target),
  1351. tr("Folder does not exist!"));
  1352. return;
  1353. }
  1354. LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target.toStdString(),
  1355. program_id);
  1356. QDesktopServices::openUrl(QUrl::fromLocalFile(qpath));
  1357. }
  1358. void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) {
  1359. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1360. const auto transferable_shader_cache_folder_path = shader_cache_dir / "opengl" / "transferable";
  1361. const auto transferable_shader_cache_file_path =
  1362. transferable_shader_cache_folder_path / fmt::format("{:016X}.bin", program_id);
  1363. if (!Common::FS::Exists(transferable_shader_cache_file_path)) {
  1364. QMessageBox::warning(this, tr("Error Opening Transferable Shader Cache"),
  1365. tr("A shader cache for this title does not exist."));
  1366. return;
  1367. }
  1368. const auto qt_shader_cache_folder_path =
  1369. QString::fromStdString(Common::FS::PathToUTF8String(transferable_shader_cache_folder_path));
  1370. const auto qt_shader_cache_file_path =
  1371. QString::fromStdString(Common::FS::PathToUTF8String(transferable_shader_cache_file_path));
  1372. // Windows supports opening a folder with selecting a specified file in explorer. On every other
  1373. // OS we just open the transferable shader cache folder without preselecting the transferable
  1374. // shader cache file for the selected game.
  1375. #if defined(Q_OS_WIN)
  1376. const QString explorer = QStringLiteral("explorer");
  1377. QStringList param;
  1378. if (!QFileInfo(qt_shader_cache_file_path).isDir()) {
  1379. param << QStringLiteral("/select,");
  1380. }
  1381. param << QDir::toNativeSeparators(qt_shader_cache_file_path);
  1382. QProcess::startDetached(explorer, param);
  1383. #else
  1384. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_shader_cache_folder_path));
  1385. #endif
  1386. }
  1387. static std::size_t CalculateRomFSEntrySize(const FileSys::VirtualDir& dir, bool full) {
  1388. std::size_t out = 0;
  1389. for (const auto& subdir : dir->GetSubdirectories()) {
  1390. out += 1 + CalculateRomFSEntrySize(subdir, full);
  1391. }
  1392. return out + (full ? dir->GetFiles().size() : 0);
  1393. }
  1394. static bool RomFSRawCopy(QProgressDialog& dialog, const FileSys::VirtualDir& src,
  1395. const FileSys::VirtualDir& dest, std::size_t block_size, bool full) {
  1396. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  1397. return false;
  1398. if (dialog.wasCanceled())
  1399. return false;
  1400. if (full) {
  1401. for (const auto& file : src->GetFiles()) {
  1402. const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName());
  1403. if (!FileSys::VfsRawCopy(file, out, block_size))
  1404. return false;
  1405. dialog.setValue(dialog.value() + 1);
  1406. if (dialog.wasCanceled())
  1407. return false;
  1408. }
  1409. }
  1410. for (const auto& dir : src->GetSubdirectories()) {
  1411. const auto out = dest->CreateSubdirectory(dir->GetName());
  1412. if (!RomFSRawCopy(dialog, dir, out, block_size, full))
  1413. return false;
  1414. dialog.setValue(dialog.value() + 1);
  1415. if (dialog.wasCanceled())
  1416. return false;
  1417. }
  1418. return true;
  1419. }
  1420. void GMainWindow::OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type) {
  1421. const QString entry_type = [this, type] {
  1422. switch (type) {
  1423. case InstalledEntryType::Game:
  1424. return tr("Contents");
  1425. case InstalledEntryType::Update:
  1426. return tr("Update");
  1427. case InstalledEntryType::AddOnContent:
  1428. return tr("DLC");
  1429. default:
  1430. return QString{};
  1431. }
  1432. }();
  1433. if (QMessageBox::question(
  1434. this, tr("Remove Entry"), tr("Remove Installed Game %1?").arg(entry_type),
  1435. QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
  1436. return;
  1437. }
  1438. switch (type) {
  1439. case InstalledEntryType::Game:
  1440. RemoveBaseContent(program_id, entry_type);
  1441. [[fallthrough]];
  1442. case InstalledEntryType::Update:
  1443. RemoveUpdateContent(program_id, entry_type);
  1444. if (type != InstalledEntryType::Game) {
  1445. break;
  1446. }
  1447. [[fallthrough]];
  1448. case InstalledEntryType::AddOnContent:
  1449. RemoveAddOnContent(program_id, entry_type);
  1450. break;
  1451. }
  1452. void(Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  1453. "game_list"));
  1454. game_list->PopulateAsync(UISettings::values.game_dirs);
  1455. }
  1456. void GMainWindow::RemoveBaseContent(u64 program_id, const QString& entry_type) {
  1457. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1458. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(program_id) ||
  1459. fs_controller.GetSDMCContents()->RemoveExistingEntry(program_id);
  1460. if (res) {
  1461. QMessageBox::information(this, tr("Successfully Removed"),
  1462. tr("Successfully removed the installed base game."));
  1463. } else {
  1464. QMessageBox::warning(
  1465. this, tr("Error Removing %1").arg(entry_type),
  1466. tr("The base game is not installed in the NAND and cannot be removed."));
  1467. }
  1468. }
  1469. void GMainWindow::RemoveUpdateContent(u64 program_id, const QString& entry_type) {
  1470. const auto update_id = program_id | 0x800;
  1471. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1472. const auto res = fs_controller.GetUserNANDContents()->RemoveExistingEntry(update_id) ||
  1473. fs_controller.GetSDMCContents()->RemoveExistingEntry(update_id);
  1474. if (res) {
  1475. QMessageBox::information(this, tr("Successfully Removed"),
  1476. tr("Successfully removed the installed update."));
  1477. } else {
  1478. QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
  1479. tr("There is no update installed for this title."));
  1480. }
  1481. }
  1482. void GMainWindow::RemoveAddOnContent(u64 program_id, const QString& entry_type) {
  1483. u32 count{};
  1484. const auto& fs_controller = Core::System::GetInstance().GetFileSystemController();
  1485. const auto dlc_entries = Core::System::GetInstance().GetContentProvider().ListEntriesFilter(
  1486. FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  1487. for (const auto& entry : dlc_entries) {
  1488. if (FileSys::GetBaseTitleID(entry.title_id) == program_id) {
  1489. const auto res =
  1490. fs_controller.GetUserNANDContents()->RemoveExistingEntry(entry.title_id) ||
  1491. fs_controller.GetSDMCContents()->RemoveExistingEntry(entry.title_id);
  1492. if (res) {
  1493. ++count;
  1494. }
  1495. }
  1496. }
  1497. if (count == 0) {
  1498. QMessageBox::warning(this, tr("Error Removing %1").arg(entry_type),
  1499. tr("There are no DLC installed for this title."));
  1500. return;
  1501. }
  1502. QMessageBox::information(this, tr("Successfully Removed"),
  1503. tr("Successfully removed %1 installed DLC.").arg(count));
  1504. }
  1505. void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target) {
  1506. const QString question = [this, target] {
  1507. switch (target) {
  1508. case GameListRemoveTarget::ShaderCache:
  1509. return tr("Delete Transferable Shader Cache?");
  1510. case GameListRemoveTarget::CustomConfiguration:
  1511. return tr("Remove Custom Game Configuration?");
  1512. default:
  1513. return QString{};
  1514. }
  1515. }();
  1516. if (QMessageBox::question(this, tr("Remove File"), question, QMessageBox::Yes | QMessageBox::No,
  1517. QMessageBox::No) != QMessageBox::Yes) {
  1518. return;
  1519. }
  1520. switch (target) {
  1521. case GameListRemoveTarget::ShaderCache:
  1522. RemoveTransferableShaderCache(program_id);
  1523. break;
  1524. case GameListRemoveTarget::CustomConfiguration:
  1525. RemoveCustomConfiguration(program_id);
  1526. break;
  1527. }
  1528. }
  1529. void GMainWindow::RemoveTransferableShaderCache(u64 program_id) {
  1530. const auto shader_cache_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ShaderDir);
  1531. const auto transferable_shader_cache_file_path =
  1532. shader_cache_dir / "opengl" / "transferable" / fmt::format("{:016X}.bin", program_id);
  1533. if (!Common::FS::Exists(transferable_shader_cache_file_path)) {
  1534. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1535. tr("A shader cache for this title does not exist."));
  1536. return;
  1537. }
  1538. if (Common::FS::RemoveFile(transferable_shader_cache_file_path)) {
  1539. QMessageBox::information(this, tr("Successfully Removed"),
  1540. tr("Successfully removed the transferable shader cache."));
  1541. } else {
  1542. QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"),
  1543. tr("Failed to remove the transferable shader cache."));
  1544. }
  1545. }
  1546. void GMainWindow::RemoveCustomConfiguration(u64 program_id) {
  1547. const auto custom_config_file_path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir) /
  1548. "custom" / fmt::format("{:016X}.ini", program_id);
  1549. if (!Common::FS::Exists(custom_config_file_path)) {
  1550. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1551. tr("A custom configuration for this title does not exist."));
  1552. return;
  1553. }
  1554. if (Common::FS::RemoveFile(custom_config_file_path)) {
  1555. QMessageBox::information(this, tr("Successfully Removed"),
  1556. tr("Successfully removed the custom game configuration."));
  1557. } else {
  1558. QMessageBox::warning(this, tr("Error Removing Custom Configuration"),
  1559. tr("Failed to remove the custom game configuration."));
  1560. }
  1561. }
  1562. void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path) {
  1563. const auto failed = [this] {
  1564. QMessageBox::warning(this, tr("RomFS Extraction Failed!"),
  1565. tr("There was an error copying the RomFS files or the user "
  1566. "cancelled the operation."));
  1567. };
  1568. auto& system = Core::System::GetInstance();
  1569. const auto loader = Loader::GetLoader(system, vfs->OpenFile(game_path, FileSys::Mode::Read));
  1570. if (loader == nullptr) {
  1571. failed();
  1572. return;
  1573. }
  1574. FileSys::VirtualFile file;
  1575. if (loader->ReadRomFS(file) != Loader::ResultStatus::Success) {
  1576. failed();
  1577. return;
  1578. }
  1579. const auto& installed = system.GetContentProvider();
  1580. const auto romfs_title_id = SelectRomFSDumpTarget(installed, program_id);
  1581. if (!romfs_title_id) {
  1582. failed();
  1583. return;
  1584. }
  1585. const auto dump_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::DumpDir);
  1586. const auto romfs_dir = fmt::format("{:016X}/romfs", *romfs_title_id);
  1587. const auto path = Common::FS::PathToUTF8String(dump_dir / romfs_dir);
  1588. FileSys::VirtualFile romfs;
  1589. if (*romfs_title_id == program_id) {
  1590. const u64 ivfc_offset = loader->ReadRomFSIVFCOffset();
  1591. const FileSys::PatchManager pm{program_id, system.GetFileSystemController(), installed};
  1592. romfs = pm.PatchRomFS(file, ivfc_offset, FileSys::ContentRecordType::Program);
  1593. } else {
  1594. romfs = installed.GetEntry(*romfs_title_id, FileSys::ContentRecordType::Data)->GetRomFS();
  1595. }
  1596. const auto extracted = FileSys::ExtractRomFS(romfs, FileSys::RomFSExtractionType::Full);
  1597. if (extracted == nullptr) {
  1598. failed();
  1599. return;
  1600. }
  1601. const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::Mode::ReadWrite);
  1602. if (out == nullptr) {
  1603. failed();
  1604. vfs->DeleteDirectory(path);
  1605. return;
  1606. }
  1607. bool ok = false;
  1608. const QStringList selections{tr("Full"), tr("Skeleton")};
  1609. const auto res = QInputDialog::getItem(
  1610. this, tr("Select RomFS Dump Mode"),
  1611. tr("Please select the how you would like the RomFS dumped.<br>Full will copy all of the "
  1612. "files into the new directory while <br>skeleton will only create the directory "
  1613. "structure."),
  1614. selections, 0, false, &ok);
  1615. if (!ok) {
  1616. failed();
  1617. vfs->DeleteDirectory(path);
  1618. return;
  1619. }
  1620. const auto full = res == selections.constFirst();
  1621. const auto entry_size = CalculateRomFSEntrySize(extracted, full);
  1622. QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
  1623. static_cast<s32>(entry_size), this);
  1624. progress.setWindowModality(Qt::WindowModal);
  1625. progress.setMinimumDuration(100);
  1626. if (RomFSRawCopy(progress, extracted, out, 0x400000, full)) {
  1627. progress.close();
  1628. QMessageBox::information(this, tr("RomFS Extraction Succeeded!"),
  1629. tr("The operation completed successfully."));
  1630. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path)));
  1631. } else {
  1632. progress.close();
  1633. failed();
  1634. vfs->DeleteDirectory(path);
  1635. }
  1636. }
  1637. void GMainWindow::OnGameListCopyTID(u64 program_id) {
  1638. QClipboard* clipboard = QGuiApplication::clipboard();
  1639. clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id)));
  1640. }
  1641. void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id,
  1642. const CompatibilityList& compatibility_list) {
  1643. const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id);
  1644. QString directory;
  1645. if (it != compatibility_list.end()) {
  1646. directory = it->second.second;
  1647. }
  1648. QDesktopServices::openUrl(QUrl(QStringLiteral("https://yuzu-emu.org/game/") + directory));
  1649. }
  1650. void GMainWindow::OnGameListOpenDirectory(const QString& directory) {
  1651. std::filesystem::path fs_path;
  1652. if (directory == QStringLiteral("SDMC")) {
  1653. fs_path =
  1654. Common::FS::GetYuzuPath(Common::FS::YuzuPath::SDMCDir) / "Nintendo/Contents/registered";
  1655. } else if (directory == QStringLiteral("UserNAND")) {
  1656. fs_path =
  1657. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "user/Contents/registered";
  1658. } else if (directory == QStringLiteral("SysNAND")) {
  1659. fs_path =
  1660. Common::FS::GetYuzuPath(Common::FS::YuzuPath::NANDDir) / "system/Contents/registered";
  1661. } else {
  1662. fs_path = directory.toStdString();
  1663. }
  1664. const auto qt_path = QString::fromStdString(Common::FS::PathToUTF8String(fs_path));
  1665. if (!Common::FS::IsDir(fs_path)) {
  1666. QMessageBox::critical(this, tr("Error Opening %1").arg(qt_path),
  1667. tr("Folder does not exist!"));
  1668. return;
  1669. }
  1670. QDesktopServices::openUrl(QUrl::fromLocalFile(qt_path));
  1671. }
  1672. void GMainWindow::OnGameListAddDirectory() {
  1673. const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory"));
  1674. if (dir_path.isEmpty()) {
  1675. return;
  1676. }
  1677. UISettings::GameDir game_dir{dir_path, false, true};
  1678. if (!UISettings::values.game_dirs.contains(game_dir)) {
  1679. UISettings::values.game_dirs.append(game_dir);
  1680. game_list->PopulateAsync(UISettings::values.game_dirs);
  1681. } else {
  1682. LOG_WARNING(Frontend, "Selected directory is already in the game list");
  1683. }
  1684. }
  1685. void GMainWindow::OnGameListShowList(bool show) {
  1686. if (emulation_running && ui.action_Single_Window_Mode->isChecked())
  1687. return;
  1688. game_list->setVisible(show);
  1689. game_list_placeholder->setVisible(!show);
  1690. };
  1691. void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) {
  1692. u64 title_id{};
  1693. const auto v_file = Core::GetGameFileFromPath(vfs, file);
  1694. const auto loader = Loader::GetLoader(Core::System::GetInstance(), v_file);
  1695. if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) {
  1696. QMessageBox::information(this, tr("Properties"),
  1697. tr("The game properties could not be loaded."));
  1698. return;
  1699. }
  1700. OpenPerGameConfiguration(title_id, file);
  1701. }
  1702. void GMainWindow::OnMenuLoadFile() {
  1703. const QString extensions =
  1704. QStringLiteral("*.")
  1705. .append(GameList::supported_file_extensions.join(QStringLiteral(" *.")))
  1706. .append(QStringLiteral(" main"));
  1707. const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)",
  1708. "%1 is an identifier for the Switch executable file extensions.")
  1709. .arg(extensions);
  1710. const QString filename = QFileDialog::getOpenFileName(
  1711. this, tr("Load File"), UISettings::values.roms_path, file_filter);
  1712. if (filename.isEmpty()) {
  1713. return;
  1714. }
  1715. UISettings::values.roms_path = QFileInfo(filename).path();
  1716. BootGame(filename);
  1717. }
  1718. void GMainWindow::OnMenuLoadFolder() {
  1719. const QString dir_path =
  1720. QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory"));
  1721. if (dir_path.isNull()) {
  1722. return;
  1723. }
  1724. const QDir dir{dir_path};
  1725. const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files);
  1726. if (matching_main.size() == 1) {
  1727. BootGame(dir.path() + QDir::separator() + matching_main[0]);
  1728. } else {
  1729. QMessageBox::warning(this, tr("Invalid Directory Selected"),
  1730. tr("The directory you have selected does not contain a 'main' file."));
  1731. }
  1732. }
  1733. void GMainWindow::IncrementInstallProgress() {
  1734. install_progress->setValue(install_progress->value() + 1);
  1735. }
  1736. void GMainWindow::OnMenuInstallToNAND() {
  1737. const QString file_filter =
  1738. tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive "
  1739. "(*.nca);;Nintendo Submission Package (*.nsp);;NX Cartridge "
  1740. "Image (*.xci)");
  1741. QStringList filenames = QFileDialog::getOpenFileNames(
  1742. this, tr("Install Files"), UISettings::values.roms_path, file_filter);
  1743. if (filenames.isEmpty()) {
  1744. return;
  1745. }
  1746. InstallDialog installDialog(this, filenames);
  1747. if (installDialog.exec() == QDialog::Rejected) {
  1748. return;
  1749. }
  1750. const QStringList files = installDialog.GetFiles();
  1751. if (files.isEmpty()) {
  1752. return;
  1753. }
  1754. int remaining = filenames.size();
  1755. // This would only overflow above 2^43 bytes (8.796 TB)
  1756. int total_size = 0;
  1757. for (const QString& file : files) {
  1758. total_size += static_cast<int>(QFile(file).size() / 0x1000);
  1759. }
  1760. if (total_size < 0) {
  1761. LOG_CRITICAL(Frontend, "Attempting to install too many files, aborting.");
  1762. return;
  1763. }
  1764. QStringList new_files{}; // Newly installed files that do not yet exist in the NAND
  1765. QStringList overwritten_files{}; // Files that overwrote those existing in the NAND
  1766. QStringList failed_files{}; // Files that failed to install due to errors
  1767. bool detected_base_install{}; // Whether a base game was attempted to be installed
  1768. ui.action_Install_File_NAND->setEnabled(false);
  1769. install_progress = new QProgressDialog(QString{}, tr("Cancel"), 0, total_size, this);
  1770. install_progress->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint &
  1771. ~Qt::WindowMaximizeButtonHint);
  1772. install_progress->setAttribute(Qt::WA_DeleteOnClose, true);
  1773. install_progress->setFixedWidth(installDialog.GetMinimumWidth() + 40);
  1774. install_progress->show();
  1775. for (const QString& file : files) {
  1776. install_progress->setWindowTitle(tr("%n file(s) remaining", "", remaining));
  1777. install_progress->setLabelText(
  1778. tr("Installing file \"%1\"...").arg(QFileInfo(file).fileName()));
  1779. QFuture<InstallResult> future;
  1780. InstallResult result;
  1781. if (file.endsWith(QStringLiteral("xci"), Qt::CaseInsensitive) ||
  1782. file.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1783. future = QtConcurrent::run([this, &file] { return InstallNSPXCI(file); });
  1784. while (!future.isFinished()) {
  1785. QCoreApplication::processEvents();
  1786. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1787. }
  1788. result = future.result();
  1789. } else {
  1790. result = InstallNCA(file);
  1791. }
  1792. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1793. switch (result) {
  1794. case InstallResult::Success:
  1795. new_files.append(QFileInfo(file).fileName());
  1796. break;
  1797. case InstallResult::Overwrite:
  1798. overwritten_files.append(QFileInfo(file).fileName());
  1799. break;
  1800. case InstallResult::Failure:
  1801. failed_files.append(QFileInfo(file).fileName());
  1802. break;
  1803. case InstallResult::BaseInstallAttempted:
  1804. failed_files.append(QFileInfo(file).fileName());
  1805. detected_base_install = true;
  1806. break;
  1807. }
  1808. --remaining;
  1809. }
  1810. install_progress->close();
  1811. if (detected_base_install) {
  1812. QMessageBox::warning(
  1813. this, tr("Install Results"),
  1814. tr("To avoid possible conflicts, we discourage users from installing base games to the "
  1815. "NAND.\nPlease, only use this feature to install updates and DLC."));
  1816. }
  1817. const QString install_results =
  1818. (new_files.isEmpty() ? QString{}
  1819. : tr("%n file(s) were newly installed\n", "", new_files.size())) +
  1820. (overwritten_files.isEmpty()
  1821. ? QString{}
  1822. : tr("%n file(s) were overwritten\n", "", overwritten_files.size())) +
  1823. (failed_files.isEmpty() ? QString{}
  1824. : tr("%n file(s) failed to install\n", "", failed_files.size()));
  1825. QMessageBox::information(this, tr("Install Results"), install_results);
  1826. void(Common::FS::RemoveDirRecursively(Common::FS::GetYuzuPath(Common::FS::YuzuPath::CacheDir) /
  1827. "game_list"));
  1828. game_list->PopulateAsync(UISettings::values.game_dirs);
  1829. ui.action_Install_File_NAND->setEnabled(true);
  1830. }
  1831. InstallResult GMainWindow::InstallNSPXCI(const QString& filename) {
  1832. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1833. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1834. if (src == nullptr || dest == nullptr) {
  1835. return false;
  1836. }
  1837. if (!dest->Resize(src->GetSize())) {
  1838. return false;
  1839. }
  1840. std::array<u8, 0x1000> buffer{};
  1841. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1842. if (install_progress->wasCanceled()) {
  1843. dest->Resize(0);
  1844. return false;
  1845. }
  1846. emit UpdateInstallProgress();
  1847. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1848. dest->Write(buffer.data(), read, i);
  1849. }
  1850. return true;
  1851. };
  1852. std::shared_ptr<FileSys::NSP> nsp;
  1853. if (filename.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) {
  1854. nsp = std::make_shared<FileSys::NSP>(
  1855. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1856. if (nsp->IsExtractedType()) {
  1857. return InstallResult::Failure;
  1858. }
  1859. } else {
  1860. const auto xci = std::make_shared<FileSys::XCI>(
  1861. vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1862. nsp = xci->GetSecurePartitionNSP();
  1863. }
  1864. if (nsp->GetStatus() != Loader::ResultStatus::Success) {
  1865. return InstallResult::Failure;
  1866. }
  1867. const auto res =
  1868. Core::System::GetInstance().GetFileSystemController().GetUserNANDContents()->InstallEntry(
  1869. *nsp, true, qt_raw_copy);
  1870. switch (res) {
  1871. case FileSys::InstallResult::Success:
  1872. return InstallResult::Success;
  1873. case FileSys::InstallResult::OverwriteExisting:
  1874. return InstallResult::Overwrite;
  1875. case FileSys::InstallResult::ErrorBaseInstall:
  1876. return InstallResult::BaseInstallAttempted;
  1877. default:
  1878. return InstallResult::Failure;
  1879. }
  1880. }
  1881. InstallResult GMainWindow::InstallNCA(const QString& filename) {
  1882. const auto qt_raw_copy = [this](const FileSys::VirtualFile& src,
  1883. const FileSys::VirtualFile& dest, std::size_t block_size) {
  1884. if (src == nullptr || dest == nullptr) {
  1885. return false;
  1886. }
  1887. if (!dest->Resize(src->GetSize())) {
  1888. return false;
  1889. }
  1890. std::array<u8, 0x1000> buffer{};
  1891. for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
  1892. if (install_progress->wasCanceled()) {
  1893. dest->Resize(0);
  1894. return false;
  1895. }
  1896. emit UpdateInstallProgress();
  1897. const auto read = src->Read(buffer.data(), buffer.size(), i);
  1898. dest->Write(buffer.data(), read, i);
  1899. }
  1900. return true;
  1901. };
  1902. const auto nca =
  1903. std::make_shared<FileSys::NCA>(vfs->OpenFile(filename.toStdString(), FileSys::Mode::Read));
  1904. const auto id = nca->GetStatus();
  1905. // Game updates necessary are missing base RomFS
  1906. if (id != Loader::ResultStatus::Success &&
  1907. id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  1908. return InstallResult::Failure;
  1909. }
  1910. const QStringList tt_options{tr("System Application"),
  1911. tr("System Archive"),
  1912. tr("System Application Update"),
  1913. tr("Firmware Package (Type A)"),
  1914. tr("Firmware Package (Type B)"),
  1915. tr("Game"),
  1916. tr("Game Update"),
  1917. tr("Game DLC"),
  1918. tr("Delta Title")};
  1919. bool ok;
  1920. const auto item = QInputDialog::getItem(
  1921. this, tr("Select NCA Install Type..."),
  1922. tr("Please select the type of title you would like to install this NCA as:\n(In "
  1923. "most instances, the default 'Game' is fine.)"),
  1924. tt_options, 5, false, &ok);
  1925. auto index = tt_options.indexOf(item);
  1926. if (!ok || index == -1) {
  1927. QMessageBox::warning(this, tr("Failed to Install"),
  1928. tr("The title type you selected for the NCA is invalid."));
  1929. return InstallResult::Failure;
  1930. }
  1931. // If index is equal to or past Game, add the jump in TitleType.
  1932. if (index >= 5) {
  1933. index += static_cast<size_t>(FileSys::TitleType::Application) -
  1934. static_cast<size_t>(FileSys::TitleType::FirmwarePackageB);
  1935. }
  1936. FileSys::InstallResult res;
  1937. if (index >= static_cast<s32>(FileSys::TitleType::Application)) {
  1938. res = Core::System::GetInstance()
  1939. .GetFileSystemController()
  1940. .GetUserNANDContents()
  1941. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1942. } else {
  1943. res = Core::System::GetInstance()
  1944. .GetFileSystemController()
  1945. .GetSystemNANDContents()
  1946. ->InstallEntry(*nca, static_cast<FileSys::TitleType>(index), true, qt_raw_copy);
  1947. }
  1948. if (res == FileSys::InstallResult::Success) {
  1949. return InstallResult::Success;
  1950. } else if (res == FileSys::InstallResult::OverwriteExisting) {
  1951. return InstallResult::Overwrite;
  1952. } else {
  1953. return InstallResult::Failure;
  1954. }
  1955. }
  1956. void GMainWindow::OnMenuRecentFile() {
  1957. QAction* action = qobject_cast<QAction*>(sender());
  1958. assert(action);
  1959. const QString filename = action->data().toString();
  1960. if (QFileInfo::exists(filename)) {
  1961. BootGame(filename);
  1962. } else {
  1963. // Display an error message and remove the file from the list.
  1964. QMessageBox::information(this, tr("File not found"),
  1965. tr("File \"%1\" not found").arg(filename));
  1966. UISettings::values.recent_files.removeOne(filename);
  1967. UpdateRecentFiles();
  1968. }
  1969. }
  1970. void GMainWindow::OnStartGame() {
  1971. PreventOSSleep();
  1972. emu_thread->SetRunning(true);
  1973. connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
  1974. ui.action_Start->setEnabled(false);
  1975. ui.action_Start->setText(tr("&Continue"));
  1976. ui.action_Pause->setEnabled(true);
  1977. ui.action_Stop->setEnabled(true);
  1978. ui.action_Restart->setEnabled(true);
  1979. ui.action_Configure_Current_Game->setEnabled(true);
  1980. ui.action_Report_Compatibility->setEnabled(true);
  1981. discord_rpc->Update();
  1982. ui.action_Load_Amiibo->setEnabled(true);
  1983. ui.action_Capture_Screenshot->setEnabled(true);
  1984. }
  1985. void GMainWindow::OnPauseGame() {
  1986. emu_thread->SetRunning(false);
  1987. ui.action_Start->setEnabled(true);
  1988. ui.action_Pause->setEnabled(false);
  1989. ui.action_Stop->setEnabled(true);
  1990. ui.action_Capture_Screenshot->setEnabled(false);
  1991. AllowOSSleep();
  1992. }
  1993. void GMainWindow::OnStopGame() {
  1994. auto& system{Core::System::GetInstance()};
  1995. if (system.GetExitLock() && !ConfirmForceLockedExit()) {
  1996. return;
  1997. }
  1998. ShutdownGame();
  1999. Settings::RestoreGlobalState(system.IsPoweredOn());
  2000. UpdateStatusButtons();
  2001. }
  2002. void GMainWindow::OnLoadComplete() {
  2003. loading_screen->OnLoadComplete();
  2004. }
  2005. void GMainWindow::OnExecuteProgram(std::size_t program_index) {
  2006. ShutdownGame();
  2007. BootGame(last_filename_booted, program_index);
  2008. }
  2009. void GMainWindow::ErrorDisplayDisplayError(QString error_code, QString error_text) {
  2010. OverlayDialog dialog(render_window, Core::System::GetInstance(), error_code, error_text,
  2011. QString{}, tr("OK"), Qt::AlignLeft | Qt::AlignVCenter);
  2012. dialog.exec();
  2013. emit ErrorDisplayFinished();
  2014. }
  2015. void GMainWindow::OnMenuReportCompatibility() {
  2016. if (!Settings::values.yuzu_token.empty() && !Settings::values.yuzu_username.empty()) {
  2017. CompatDB compatdb{this};
  2018. compatdb.exec();
  2019. } else {
  2020. QMessageBox::critical(
  2021. this, tr("Missing yuzu Account"),
  2022. tr("In order to submit a game compatibility test case, you must link your yuzu "
  2023. "account.<br><br/>To link your yuzu account, go to Emulation &gt; Configuration "
  2024. "&gt; "
  2025. "Web."));
  2026. }
  2027. }
  2028. void GMainWindow::OpenURL(const QUrl& url) {
  2029. const bool open = QDesktopServices::openUrl(url);
  2030. if (!open) {
  2031. QMessageBox::warning(this, tr("Error opening URL"),
  2032. tr("Unable to open the URL \"%1\".").arg(url.toString()));
  2033. }
  2034. }
  2035. void GMainWindow::OnOpenModsPage() {
  2036. OpenURL(QUrl(QStringLiteral("https://github.com/yuzu-emu/yuzu/wiki/Switch-Mods")));
  2037. }
  2038. void GMainWindow::OnOpenQuickstartGuide() {
  2039. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/help/quickstart/")));
  2040. }
  2041. void GMainWindow::OnOpenFAQ() {
  2042. OpenURL(QUrl(QStringLiteral("https://yuzu-emu.org/wiki/faq/")));
  2043. }
  2044. void GMainWindow::ToggleFullscreen() {
  2045. if (!emulation_running) {
  2046. return;
  2047. }
  2048. if (ui.action_Fullscreen->isChecked()) {
  2049. ShowFullscreen();
  2050. } else {
  2051. HideFullscreen();
  2052. }
  2053. }
  2054. void GMainWindow::ShowFullscreen() {
  2055. if (ui.action_Single_Window_Mode->isChecked()) {
  2056. UISettings::values.geometry = saveGeometry();
  2057. ui.menubar->hide();
  2058. statusBar()->hide();
  2059. if (Settings::values.fullscreen_mode.GetValue() == 1) {
  2060. showFullScreen();
  2061. return;
  2062. }
  2063. hide();
  2064. setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
  2065. const auto screen_geometry = QApplication::desktop()->screenGeometry(this);
  2066. setGeometry(screen_geometry.x(), screen_geometry.y(), screen_geometry.width(),
  2067. screen_geometry.height() + 1);
  2068. raise();
  2069. showNormal();
  2070. } else {
  2071. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2072. if (Settings::values.fullscreen_mode.GetValue() == 1) {
  2073. render_window->showFullScreen();
  2074. return;
  2075. }
  2076. render_window->hide();
  2077. render_window->setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
  2078. const auto screen_geometry = QApplication::desktop()->screenGeometry(this);
  2079. render_window->setGeometry(screen_geometry.x(), screen_geometry.y(),
  2080. screen_geometry.width(), screen_geometry.height() + 1);
  2081. render_window->raise();
  2082. render_window->showNormal();
  2083. }
  2084. }
  2085. void GMainWindow::HideFullscreen() {
  2086. if (ui.action_Single_Window_Mode->isChecked()) {
  2087. if (Settings::values.fullscreen_mode.GetValue() == 1) {
  2088. showNormal();
  2089. restoreGeometry(UISettings::values.geometry);
  2090. } else {
  2091. hide();
  2092. setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2093. restoreGeometry(UISettings::values.geometry);
  2094. raise();
  2095. show();
  2096. }
  2097. statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());
  2098. ui.menubar->show();
  2099. } else {
  2100. if (Settings::values.fullscreen_mode.GetValue() == 1) {
  2101. render_window->showNormal();
  2102. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2103. } else {
  2104. render_window->hide();
  2105. render_window->setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint);
  2106. render_window->restoreGeometry(UISettings::values.renderwindow_geometry);
  2107. render_window->raise();
  2108. render_window->show();
  2109. }
  2110. }
  2111. }
  2112. void GMainWindow::ToggleWindowMode() {
  2113. if (ui.action_Single_Window_Mode->isChecked()) {
  2114. // Render in the main window...
  2115. render_window->BackupGeometry();
  2116. ui.horizontalLayout->addWidget(render_window);
  2117. render_window->setFocusPolicy(Qt::StrongFocus);
  2118. if (emulation_running) {
  2119. render_window->setVisible(true);
  2120. render_window->setFocus();
  2121. game_list->hide();
  2122. }
  2123. } else {
  2124. // Render in a separate window...
  2125. ui.horizontalLayout->removeWidget(render_window);
  2126. render_window->setParent(nullptr);
  2127. render_window->setFocusPolicy(Qt::NoFocus);
  2128. if (emulation_running) {
  2129. render_window->setVisible(true);
  2130. render_window->RestoreGeometry();
  2131. game_list->show();
  2132. }
  2133. }
  2134. }
  2135. void GMainWindow::ResetWindowSize720() {
  2136. const auto aspect_ratio = Layout::EmulationAspectRatio(
  2137. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  2138. static_cast<float>(Layout::ScreenUndocked::Height) / Layout::ScreenUndocked::Width);
  2139. if (!ui.action_Single_Window_Mode->isChecked()) {
  2140. render_window->resize(Layout::ScreenUndocked::Height / aspect_ratio,
  2141. Layout::ScreenUndocked::Height);
  2142. } else {
  2143. resize(Layout::ScreenUndocked::Height / aspect_ratio,
  2144. Layout::ScreenUndocked::Height + menuBar()->height() +
  2145. (ui.action_Show_Status_Bar->isChecked() ? statusBar()->height() : 0));
  2146. }
  2147. }
  2148. void GMainWindow::ResetWindowSize1080() {
  2149. const auto aspect_ratio = Layout::EmulationAspectRatio(
  2150. static_cast<Layout::AspectRatio>(Settings::values.aspect_ratio.GetValue()),
  2151. static_cast<float>(Layout::ScreenDocked::Height) / Layout::ScreenDocked::Width);
  2152. if (!ui.action_Single_Window_Mode->isChecked()) {
  2153. render_window->resize(Layout::ScreenDocked::Height / aspect_ratio,
  2154. Layout::ScreenDocked::Height);
  2155. } else {
  2156. resize(Layout::ScreenDocked::Height / aspect_ratio,
  2157. Layout::ScreenDocked::Height + menuBar()->height() +
  2158. (ui.action_Show_Status_Bar->isChecked() ? statusBar()->height() : 0));
  2159. }
  2160. }
  2161. void GMainWindow::OnConfigure() {
  2162. const auto old_theme = UISettings::values.theme;
  2163. const bool old_discord_presence = UISettings::values.enable_discord_presence;
  2164. ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get());
  2165. connect(&configure_dialog, &ConfigureDialog::LanguageChanged, this,
  2166. &GMainWindow::OnLanguageChanged);
  2167. const auto result = configure_dialog.exec();
  2168. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  2169. return;
  2170. } else if (result == QDialog::Accepted) {
  2171. configure_dialog.ApplyConfiguration();
  2172. controller_dialog->refreshConfiguration();
  2173. }
  2174. InitializeHotkeys();
  2175. if (UISettings::values.theme != old_theme) {
  2176. UpdateUITheme();
  2177. }
  2178. if (UISettings::values.enable_discord_presence != old_discord_presence) {
  2179. SetDiscordEnabled(UISettings::values.enable_discord_presence);
  2180. }
  2181. emit UpdateThemedIcons();
  2182. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2183. if (reload) {
  2184. game_list->PopulateAsync(UISettings::values.game_dirs);
  2185. }
  2186. UISettings::values.configuration_applied = false;
  2187. config->Save();
  2188. if ((UISettings::values.hide_mouse || Settings::values.mouse_panning) && emulation_running) {
  2189. render_window->installEventFilter(render_window);
  2190. render_window->setAttribute(Qt::WA_Hover, true);
  2191. } else {
  2192. render_window->removeEventFilter(render_window);
  2193. render_window->setAttribute(Qt::WA_Hover, false);
  2194. }
  2195. if (UISettings::values.hide_mouse) {
  2196. mouse_hide_timer.start();
  2197. }
  2198. UpdateStatusButtons();
  2199. }
  2200. void GMainWindow::OnConfigurePerGame() {
  2201. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  2202. OpenPerGameConfiguration(title_id, game_path.toStdString());
  2203. }
  2204. void GMainWindow::OpenPerGameConfiguration(u64 title_id, const std::string& file_name) {
  2205. const auto v_file = Core::GetGameFileFromPath(vfs, file_name);
  2206. const auto& system = Core::System::GetInstance();
  2207. ConfigurePerGame dialog(this, title_id);
  2208. dialog.LoadFromFile(v_file);
  2209. const auto result = dialog.exec();
  2210. if (result != QDialog::Accepted && !UISettings::values.configuration_applied) {
  2211. Settings::RestoreGlobalState(system.IsPoweredOn());
  2212. return;
  2213. } else if (result == QDialog::Accepted) {
  2214. dialog.ApplyConfiguration();
  2215. }
  2216. const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
  2217. if (reload) {
  2218. game_list->PopulateAsync(UISettings::values.game_dirs);
  2219. }
  2220. // Do not cause the global config to write local settings into the config file
  2221. const bool is_powered_on = system.IsPoweredOn();
  2222. Settings::RestoreGlobalState(is_powered_on);
  2223. UISettings::values.configuration_applied = false;
  2224. if (!is_powered_on) {
  2225. config->Save();
  2226. }
  2227. }
  2228. void GMainWindow::OnLoadAmiibo() {
  2229. const QString extensions{QStringLiteral("*.bin")};
  2230. const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions);
  2231. const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter);
  2232. if (filename.isEmpty()) {
  2233. return;
  2234. }
  2235. LoadAmiibo(filename);
  2236. }
  2237. void GMainWindow::LoadAmiibo(const QString& filename) {
  2238. Core::System& system{Core::System::GetInstance()};
  2239. Service::SM::ServiceManager& sm = system.ServiceManager();
  2240. auto nfc = sm.GetService<Service::NFP::Module::Interface>("nfp:user");
  2241. if (nfc == nullptr) {
  2242. return;
  2243. }
  2244. QFile nfc_file{filename};
  2245. if (!nfc_file.open(QIODevice::ReadOnly)) {
  2246. QMessageBox::warning(this, tr("Error opening Amiibo data file"),
  2247. tr("Unable to open Amiibo file \"%1\" for reading.").arg(filename));
  2248. return;
  2249. }
  2250. const u64 nfc_file_size = nfc_file.size();
  2251. std::vector<u8> buffer(nfc_file_size);
  2252. const u64 read_size = nfc_file.read(reinterpret_cast<char*>(buffer.data()), nfc_file_size);
  2253. if (nfc_file_size != read_size) {
  2254. QMessageBox::warning(this, tr("Error reading Amiibo data file"),
  2255. tr("Unable to fully read Amiibo data. Expected to read %1 bytes, but "
  2256. "was only able to read %2 bytes.")
  2257. .arg(nfc_file_size)
  2258. .arg(read_size));
  2259. return;
  2260. }
  2261. if (!nfc->LoadAmiibo(buffer)) {
  2262. QMessageBox::warning(this, tr("Error loading Amiibo data"),
  2263. tr("Unable to load Amiibo data."));
  2264. }
  2265. }
  2266. void GMainWindow::OnOpenYuzuFolder() {
  2267. QDesktopServices::openUrl(QUrl::fromLocalFile(
  2268. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::YuzuDir))));
  2269. }
  2270. void GMainWindow::OnAbout() {
  2271. AboutDialog aboutDialog(this);
  2272. aboutDialog.exec();
  2273. }
  2274. void GMainWindow::OnToggleFilterBar() {
  2275. game_list->SetFilterVisible(ui.action_Show_Filter_Bar->isChecked());
  2276. if (ui.action_Show_Filter_Bar->isChecked()) {
  2277. game_list->SetFilterFocus();
  2278. } else {
  2279. game_list->ClearFilter();
  2280. }
  2281. }
  2282. void GMainWindow::OnCaptureScreenshot() {
  2283. OnPauseGame();
  2284. const u64 title_id = Core::System::GetInstance().CurrentProcess()->GetTitleID();
  2285. const auto screenshot_path =
  2286. QString::fromStdString(Common::FS::GetYuzuPathString(Common::FS::YuzuPath::ScreenshotsDir));
  2287. const auto date =
  2288. QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd_hh-mm-ss-zzz"));
  2289. QString filename = QStringLiteral("%1%2_%3.png")
  2290. .arg(screenshot_path)
  2291. .arg(title_id, 16, 16, QLatin1Char{'0'})
  2292. .arg(date);
  2293. if (!Common::FS::CreateDir(screenshot_path.toStdString())) {
  2294. OnStartGame();
  2295. return;
  2296. }
  2297. #ifdef _WIN32
  2298. if (UISettings::values.enable_screenshot_save_as) {
  2299. filename = QFileDialog::getSaveFileName(this, tr("Capture Screenshot"), filename,
  2300. tr("PNG Image (*.png)"));
  2301. if (filename.isEmpty()) {
  2302. OnStartGame();
  2303. return;
  2304. }
  2305. }
  2306. #endif
  2307. render_window->CaptureScreenshot(UISettings::values.screenshot_resolution_factor, filename);
  2308. OnStartGame();
  2309. }
  2310. // TODO: Written 2020-10-01: Remove per-game config migration code when it is irrelevant
  2311. void GMainWindow::MigrateConfigFiles() {
  2312. const auto config_dir_fs_path = Common::FS::GetYuzuPath(Common::FS::YuzuPath::ConfigDir);
  2313. const QDir config_dir =
  2314. QDir(QString::fromStdString(Common::FS::PathToUTF8String(config_dir_fs_path)));
  2315. const QStringList config_dir_list = config_dir.entryList(QStringList(QStringLiteral("*.ini")));
  2316. if (!Common::FS::CreateDirs(config_dir_fs_path / "custom")) {
  2317. LOG_ERROR(Frontend, "Failed to create new config file directory");
  2318. }
  2319. for (auto it = config_dir_list.constBegin(); it != config_dir_list.constEnd(); ++it) {
  2320. const auto filename = it->toStdString();
  2321. if (filename.find_first_not_of("0123456789abcdefACBDEF", 0) < 16) {
  2322. continue;
  2323. }
  2324. const auto origin = config_dir_fs_path / filename;
  2325. const auto destination = config_dir_fs_path / "custom" / filename;
  2326. LOG_INFO(Frontend, "Migrating config file from {} to {}", origin, destination);
  2327. if (!Common::FS::RenameFile(origin, destination)) {
  2328. // Delete the old config file if one already exists in the new location.
  2329. void(Common::FS::RemoveFile(origin));
  2330. }
  2331. }
  2332. }
  2333. void GMainWindow::UpdateWindowTitle(const std::string& title_name,
  2334. const std::string& title_version) {
  2335. const auto branch_name = std::string(Common::g_scm_branch);
  2336. const auto description = std::string(Common::g_scm_desc);
  2337. const auto build_id = std::string(Common::g_build_id);
  2338. const auto yuzu_title = fmt::format("yuzu | {}-{}", branch_name, description);
  2339. const auto override_title = fmt::format(std::string(Common::g_title_bar_format_idle), build_id);
  2340. const auto window_title = override_title.empty() ? yuzu_title : override_title;
  2341. if (title_name.empty()) {
  2342. setWindowTitle(QString::fromStdString(window_title));
  2343. } else {
  2344. const auto run_title = fmt::format("{} | {} | {}", window_title, title_name, title_version);
  2345. setWindowTitle(QString::fromStdString(run_title));
  2346. }
  2347. }
  2348. void GMainWindow::UpdateStatusBar() {
  2349. if (emu_thread == nullptr) {
  2350. status_bar_update_timer.stop();
  2351. return;
  2352. }
  2353. auto results = Core::System::GetInstance().GetAndResetPerfStats();
  2354. auto& shader_notify = Core::System::GetInstance().GPU().ShaderNotify();
  2355. const auto shaders_building = shader_notify.GetShadersBuilding();
  2356. if (shaders_building != 0) {
  2357. shader_building_label->setText(
  2358. tr("Building: %n shader(s)", "", static_cast<int>(shaders_building)));
  2359. shader_building_label->setVisible(true);
  2360. } else {
  2361. shader_building_label->setVisible(false);
  2362. }
  2363. if (Settings::values.use_frame_limit.GetValue()) {
  2364. emu_speed_label->setText(tr("Speed: %1% / %2%")
  2365. .arg(results.emulation_speed * 100.0, 0, 'f', 0)
  2366. .arg(Settings::values.frame_limit.GetValue()));
  2367. } else {
  2368. emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0));
  2369. }
  2370. game_fps_label->setText(tr("Game: %1 FPS").arg(results.average_game_fps, 0, 'f', 0));
  2371. emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2));
  2372. emu_speed_label->setVisible(!Settings::values.use_multi_core.GetValue());
  2373. game_fps_label->setVisible(true);
  2374. emu_frametime_label->setVisible(true);
  2375. }
  2376. void GMainWindow::UpdateStatusButtons() {
  2377. dock_status_button->setChecked(Settings::values.use_docked_mode.GetValue());
  2378. multicore_status_button->setChecked(Settings::values.use_multi_core.GetValue());
  2379. async_status_button->setChecked(Settings::values.use_asynchronous_gpu_emulation.GetValue());
  2380. renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() ==
  2381. Settings::RendererBackend::Vulkan);
  2382. }
  2383. void GMainWindow::UpdateUISettings() {
  2384. if (!ui.action_Fullscreen->isChecked()) {
  2385. UISettings::values.geometry = saveGeometry();
  2386. UISettings::values.renderwindow_geometry = render_window->saveGeometry();
  2387. }
  2388. UISettings::values.state = saveState();
  2389. #if MICROPROFILE_ENABLED
  2390. UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry();
  2391. UISettings::values.microprofile_visible = microProfileDialog->isVisible();
  2392. #endif
  2393. UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();
  2394. UISettings::values.fullscreen = ui.action_Fullscreen->isChecked();
  2395. UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked();
  2396. UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();
  2397. UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();
  2398. UISettings::values.first_start = false;
  2399. }
  2400. void GMainWindow::HideMouseCursor() {
  2401. if (emu_thread == nullptr && UISettings::values.hide_mouse) {
  2402. mouse_hide_timer.stop();
  2403. ShowMouseCursor();
  2404. return;
  2405. }
  2406. render_window->setCursor(QCursor(Qt::BlankCursor));
  2407. }
  2408. void GMainWindow::ShowMouseCursor() {
  2409. render_window->unsetCursor();
  2410. if (emu_thread != nullptr && UISettings::values.hide_mouse) {
  2411. mouse_hide_timer.start();
  2412. }
  2413. }
  2414. void GMainWindow::OnMouseActivity() {
  2415. if (!Settings::values.mouse_panning) {
  2416. ShowMouseCursor();
  2417. }
  2418. }
  2419. void GMainWindow::OnCoreError(Core::System::ResultStatus result, std::string details) {
  2420. QMessageBox::StandardButton answer;
  2421. QString status_message;
  2422. const QString common_message =
  2423. tr("The game you are trying to load requires additional files from your Switch to be "
  2424. "dumped "
  2425. "before playing.<br/><br/>For more information on dumping these files, please see the "
  2426. "following wiki page: <a "
  2427. "href='https://yuzu-emu.org/wiki/"
  2428. "dumping-system-archives-and-the-shared-fonts-from-a-switch-console/'>Dumping System "
  2429. "Archives and the Shared Fonts from a Switch Console</a>.<br/><br/>Would you like to "
  2430. "quit "
  2431. "back to the game list? Continuing emulation may result in crashes, corrupted save "
  2432. "data, or other bugs.");
  2433. switch (result) {
  2434. case Core::System::ResultStatus::ErrorSystemFiles: {
  2435. QString message;
  2436. if (details.empty()) {
  2437. message =
  2438. tr("yuzu was unable to locate a Switch system archive. %1").arg(common_message);
  2439. } else {
  2440. message = tr("yuzu was unable to locate a Switch system archive: %1. %2")
  2441. .arg(QString::fromStdString(details), common_message);
  2442. }
  2443. answer = QMessageBox::question(this, tr("System Archive Not Found"), message,
  2444. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2445. status_message = tr("System Archive Missing");
  2446. break;
  2447. }
  2448. case Core::System::ResultStatus::ErrorSharedFont: {
  2449. const QString message =
  2450. tr("yuzu was unable to locate the Switch shared fonts. %1").arg(common_message);
  2451. answer = QMessageBox::question(this, tr("Shared Fonts Not Found"), message,
  2452. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2453. status_message = tr("Shared Font Missing");
  2454. break;
  2455. }
  2456. default:
  2457. answer = QMessageBox::question(
  2458. this, tr("Fatal Error"),
  2459. tr("yuzu has encountered a fatal error, please see the log for more details. "
  2460. "For more information on accessing the log, please see the following page: "
  2461. "<a href='https://community.citra-emu.org/t/how-to-upload-the-log-file/296'>How "
  2462. "to "
  2463. "Upload the Log File</a>.<br/><br/>Would you like to quit back to the game "
  2464. "list? "
  2465. "Continuing emulation may result in crashes, corrupted save data, or other "
  2466. "bugs."),
  2467. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2468. status_message = tr("Fatal Error encountered");
  2469. break;
  2470. }
  2471. if (answer == QMessageBox::Yes) {
  2472. if (emu_thread) {
  2473. ShutdownGame();
  2474. Settings::RestoreGlobalState(Core::System::GetInstance().IsPoweredOn());
  2475. UpdateStatusButtons();
  2476. }
  2477. } else {
  2478. // Only show the message if the game is still running.
  2479. if (emu_thread) {
  2480. emu_thread->SetRunning(true);
  2481. message_label->setText(status_message);
  2482. }
  2483. }
  2484. }
  2485. void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
  2486. if (behavior == ReinitializeKeyBehavior::Warning) {
  2487. const auto res = QMessageBox::information(
  2488. this, tr("Confirm Key Rederivation"),
  2489. tr("You are about to force rederive all of your keys. \nIf you do not know what "
  2490. "this "
  2491. "means or what you are doing, \nthis is a potentially destructive action. "
  2492. "\nPlease "
  2493. "make sure this is what you want \nand optionally make backups.\n\nThis will "
  2494. "delete "
  2495. "your autogenerated key files and re-run the key derivation module."),
  2496. QMessageBox::StandardButtons{QMessageBox::Ok, QMessageBox::Cancel});
  2497. if (res == QMessageBox::Cancel)
  2498. return;
  2499. const auto keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
  2500. void(Common::FS::RemoveFile(keys_dir / "prod.keys_autogenerated"));
  2501. void(Common::FS::RemoveFile(keys_dir / "console.keys_autogenerated"));
  2502. void(Common::FS::RemoveFile(keys_dir / "title.keys_autogenerated"));
  2503. }
  2504. Core::Crypto::KeyManager& keys = Core::Crypto::KeyManager::Instance();
  2505. if (keys.BaseDeriveNecessary()) {
  2506. Core::Crypto::PartitionDataManager pdm{vfs->OpenDirectory("", FileSys::Mode::Read)};
  2507. const auto function = [this, &keys, &pdm] {
  2508. keys.PopulateFromPartitionData(pdm);
  2509. auto& system = Core::System::GetInstance();
  2510. system.GetFileSystemController().CreateFactories(*vfs);
  2511. keys.DeriveETicket(pdm, system.GetContentProvider());
  2512. };
  2513. QString errors;
  2514. if (!pdm.HasFuses()) {
  2515. errors += tr("Missing fuses");
  2516. }
  2517. if (!pdm.HasBoot0()) {
  2518. errors += tr(" - Missing BOOT0");
  2519. }
  2520. if (!pdm.HasPackage2()) {
  2521. errors += tr(" - Missing BCPKG2-1-Normal-Main");
  2522. }
  2523. if (!pdm.HasProdInfo()) {
  2524. errors += tr(" - Missing PRODINFO");
  2525. }
  2526. if (!errors.isEmpty()) {
  2527. QMessageBox::warning(
  2528. this, tr("Derivation Components Missing"),
  2529. tr("Components are missing that may hinder key derivation from completing. "
  2530. "<br>Please follow <a href='https://yuzu-emu.org/help/quickstart/'>the yuzu "
  2531. "quickstart guide</a> to get all your keys and "
  2532. "games.<br><br><small>(%1)</small>")
  2533. .arg(errors));
  2534. }
  2535. QProgressDialog prog(this);
  2536. prog.setRange(0, 0);
  2537. prog.setLabelText(tr("Deriving keys...\nThis may take up to a minute depending \non your "
  2538. "system's performance."));
  2539. prog.setWindowTitle(tr("Deriving Keys"));
  2540. prog.show();
  2541. auto future = QtConcurrent::run(function);
  2542. while (!future.isFinished()) {
  2543. QCoreApplication::processEvents();
  2544. }
  2545. prog.close();
  2546. }
  2547. Core::System::GetInstance().GetFileSystemController().CreateFactories(*vfs);
  2548. if (behavior == ReinitializeKeyBehavior::Warning) {
  2549. game_list->PopulateAsync(UISettings::values.game_dirs);
  2550. }
  2551. }
  2552. std::optional<u64> GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed,
  2553. u64 program_id) {
  2554. const auto dlc_entries =
  2555. installed.ListEntriesFilter(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
  2556. std::vector<FileSys::ContentProviderEntry> dlc_match;
  2557. dlc_match.reserve(dlc_entries.size());
  2558. std::copy_if(dlc_entries.begin(), dlc_entries.end(), std::back_inserter(dlc_match),
  2559. [&program_id, &installed](const FileSys::ContentProviderEntry& entry) {
  2560. return FileSys::GetBaseTitleID(entry.title_id) == program_id &&
  2561. installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success;
  2562. });
  2563. std::vector<u64> romfs_tids;
  2564. romfs_tids.push_back(program_id);
  2565. for (const auto& entry : dlc_match) {
  2566. romfs_tids.push_back(entry.title_id);
  2567. }
  2568. if (romfs_tids.size() > 1) {
  2569. QStringList list{QStringLiteral("Base")};
  2570. for (std::size_t i = 1; i < romfs_tids.size(); ++i) {
  2571. list.push_back(QStringLiteral("DLC %1").arg(romfs_tids[i] & 0x7FF));
  2572. }
  2573. bool ok;
  2574. const auto res = QInputDialog::getItem(
  2575. this, tr("Select RomFS Dump Target"),
  2576. tr("Please select which RomFS you would like to dump."), list, 0, false, &ok);
  2577. if (!ok) {
  2578. return {};
  2579. }
  2580. return romfs_tids[list.indexOf(res)];
  2581. }
  2582. return program_id;
  2583. }
  2584. bool GMainWindow::ConfirmClose() {
  2585. if (emu_thread == nullptr || !UISettings::values.confirm_before_closing)
  2586. return true;
  2587. QMessageBox::StandardButton answer =
  2588. QMessageBox::question(this, tr("yuzu"), tr("Are you sure you want to close yuzu?"),
  2589. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2590. return answer != QMessageBox::No;
  2591. }
  2592. void GMainWindow::closeEvent(QCloseEvent* event) {
  2593. if (!ConfirmClose()) {
  2594. event->ignore();
  2595. return;
  2596. }
  2597. UpdateUISettings();
  2598. game_list->SaveInterfaceLayout();
  2599. hotkey_registry.SaveHotkeys();
  2600. // Shutdown session if the emu thread is active...
  2601. if (emu_thread != nullptr) {
  2602. ShutdownGame();
  2603. Settings::RestoreGlobalState(Core::System::GetInstance().IsPoweredOn());
  2604. UpdateStatusButtons();
  2605. }
  2606. render_window->close();
  2607. QWidget::closeEvent(event);
  2608. }
  2609. static bool IsSingleFileDropEvent(const QMimeData* mime) {
  2610. return mime->hasUrls() && mime->urls().length() == 1;
  2611. }
  2612. void GMainWindow::AcceptDropEvent(QDropEvent* event) {
  2613. if (IsSingleFileDropEvent(event->mimeData())) {
  2614. event->setDropAction(Qt::DropAction::LinkAction);
  2615. event->accept();
  2616. }
  2617. }
  2618. bool GMainWindow::DropAction(QDropEvent* event) {
  2619. if (!IsSingleFileDropEvent(event->mimeData())) {
  2620. return false;
  2621. }
  2622. const QMimeData* mime_data = event->mimeData();
  2623. const QString& filename = mime_data->urls().at(0).toLocalFile();
  2624. if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) {
  2625. // Amiibo
  2626. LoadAmiibo(filename);
  2627. } else {
  2628. // Game
  2629. if (ConfirmChangeGame()) {
  2630. BootGame(filename);
  2631. }
  2632. }
  2633. return true;
  2634. }
  2635. void GMainWindow::dropEvent(QDropEvent* event) {
  2636. DropAction(event);
  2637. }
  2638. void GMainWindow::dragEnterEvent(QDragEnterEvent* event) {
  2639. AcceptDropEvent(event);
  2640. }
  2641. void GMainWindow::dragMoveEvent(QDragMoveEvent* event) {
  2642. AcceptDropEvent(event);
  2643. }
  2644. bool GMainWindow::ConfirmChangeGame() {
  2645. if (emu_thread == nullptr)
  2646. return true;
  2647. const auto answer = QMessageBox::question(
  2648. this, tr("yuzu"),
  2649. tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."),
  2650. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2651. return answer != QMessageBox::No;
  2652. }
  2653. bool GMainWindow::ConfirmForceLockedExit() {
  2654. if (emu_thread == nullptr)
  2655. return true;
  2656. const auto answer =
  2657. QMessageBox::question(this, tr("yuzu"),
  2658. tr("The currently running application has requested yuzu to not "
  2659. "exit.\n\nWould you like to bypass this and exit anyway?"),
  2660. QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  2661. return answer != QMessageBox::No;
  2662. }
  2663. void GMainWindow::RequestGameExit() {
  2664. auto& sm{Core::System::GetInstance().ServiceManager()};
  2665. auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
  2666. auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
  2667. bool has_signalled = false;
  2668. if (applet_oe != nullptr) {
  2669. applet_oe->GetMessageQueue()->RequestExit();
  2670. has_signalled = true;
  2671. }
  2672. if (applet_ae != nullptr && !has_signalled) {
  2673. applet_ae->GetMessageQueue()->RequestExit();
  2674. }
  2675. }
  2676. void GMainWindow::filterBarSetChecked(bool state) {
  2677. ui.action_Show_Filter_Bar->setChecked(state);
  2678. emit(OnToggleFilterBar());
  2679. }
  2680. void GMainWindow::UpdateUITheme() {
  2681. const QString default_icons = QStringLiteral("default");
  2682. const QString& current_theme = UISettings::values.theme;
  2683. const bool is_default_theme = current_theme == QString::fromUtf8(UISettings::themes[0].second);
  2684. QStringList theme_paths(default_theme_paths);
  2685. if (is_default_theme || current_theme.isEmpty()) {
  2686. const QString theme_uri(QStringLiteral(":default/style.qss"));
  2687. QFile f(theme_uri);
  2688. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2689. QTextStream ts(&f);
  2690. qApp->setStyleSheet(ts.readAll());
  2691. setStyleSheet(ts.readAll());
  2692. } else {
  2693. qApp->setStyleSheet({});
  2694. setStyleSheet({});
  2695. }
  2696. QIcon::setThemeName(default_icons);
  2697. } else {
  2698. const QString theme_uri(QLatin1Char{':'} + current_theme + QStringLiteral("/style.qss"));
  2699. QFile f(theme_uri);
  2700. if (f.open(QFile::ReadOnly | QFile::Text)) {
  2701. QTextStream ts(&f);
  2702. qApp->setStyleSheet(ts.readAll());
  2703. setStyleSheet(ts.readAll());
  2704. } else {
  2705. LOG_ERROR(Frontend, "Unable to set style, stylesheet file not found");
  2706. }
  2707. QIcon::setThemeName(current_theme);
  2708. }
  2709. QIcon::setThemeSearchPaths(theme_paths);
  2710. }
  2711. void GMainWindow::LoadTranslation() {
  2712. // If the selected language is English, no need to install any translation
  2713. if (UISettings::values.language == QStringLiteral("en")) {
  2714. return;
  2715. }
  2716. bool loaded;
  2717. if (UISettings::values.language.isEmpty()) {
  2718. // If the selected language is empty, use system locale
  2719. loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/"));
  2720. } else {
  2721. // Otherwise load from the specified file
  2722. loaded = translator.load(UISettings::values.language, QStringLiteral(":/languages/"));
  2723. }
  2724. if (loaded) {
  2725. qApp->installTranslator(&translator);
  2726. } else {
  2727. UISettings::values.language = QStringLiteral("en");
  2728. }
  2729. }
  2730. void GMainWindow::OnLanguageChanged(const QString& locale) {
  2731. if (UISettings::values.language != QStringLiteral("en")) {
  2732. qApp->removeTranslator(&translator);
  2733. }
  2734. UISettings::values.language = locale;
  2735. LoadTranslation();
  2736. ui.retranslateUi(this);
  2737. UpdateWindowTitle();
  2738. if (emulation_running)
  2739. ui.action_Start->setText(tr("&Continue"));
  2740. }
  2741. void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) {
  2742. #ifdef USE_DISCORD_PRESENCE
  2743. if (state) {
  2744. discord_rpc = std::make_unique<DiscordRPC::DiscordImpl>();
  2745. } else {
  2746. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2747. }
  2748. #else
  2749. discord_rpc = std::make_unique<DiscordRPC::NullImpl>();
  2750. #endif
  2751. discord_rpc->Update();
  2752. }
  2753. #ifdef main
  2754. #undef main
  2755. #endif
  2756. int main(int argc, char* argv[]) {
  2757. Common::DetachedTasks detached_tasks;
  2758. MicroProfileOnThreadCreate("Frontend");
  2759. SCOPE_EXIT({ MicroProfileShutdown(); });
  2760. Common::ConfigureNvidiaEnvironmentFlags();
  2761. // Init settings params
  2762. QCoreApplication::setOrganizationName(QStringLiteral("yuzu team"));
  2763. QCoreApplication::setApplicationName(QStringLiteral("yuzu"));
  2764. #ifdef _WIN32
  2765. // Increases the maximum open file limit to 4096
  2766. _setmaxstdio(4096);
  2767. #endif
  2768. #ifdef __APPLE__
  2769. // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/".
  2770. // But since we require the working directory to be the executable path for the location of
  2771. // the user folder in the Qt Frontend, we need to cd into that working directory
  2772. const auto bin_path = Common::FS::GetBundleDirectory() / "..";
  2773. chdir(Common::FS::PathToUTF8String(bin_path).c_str());
  2774. #endif
  2775. #ifdef __linux__
  2776. // Set the DISPLAY variable in order to open web browsers
  2777. // TODO (lat9nq): Find a better solution for AppImages to start external applications
  2778. if (QString::fromLocal8Bit(qgetenv("DISPLAY")).isEmpty()) {
  2779. qputenv("DISPLAY", ":0");
  2780. }
  2781. #endif
  2782. // Enables the core to make the qt created contexts current on std::threads
  2783. QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
  2784. QApplication app(argc, argv);
  2785. // Qt changes the locale and causes issues in float conversion using std::to_string() when
  2786. // generating shaders
  2787. setlocale(LC_ALL, "C");
  2788. GMainWindow main_window;
  2789. // After settings have been loaded by GMainWindow, apply the filter
  2790. main_window.show();
  2791. QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window,
  2792. &GMainWindow::OnAppFocusStateChanged);
  2793. int result = app.exec();
  2794. detached_tasks.WaitForAllTasks();
  2795. return result;
  2796. }