main.cpp 146 KB

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