main.cpp 142 KB

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