AppHost.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. using ARMeilleure.Translation;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.ApplicationLifetimes;
  4. using Avalonia.Input;
  5. using Avalonia.Threading;
  6. using LibHac.Tools.FsSystem;
  7. using Ryujinx.Audio.Backends.Dummy;
  8. using Ryujinx.Audio.Backends.OpenAL;
  9. using Ryujinx.Audio.Backends.SDL2;
  10. using Ryujinx.Audio.Backends.SoundIo;
  11. using Ryujinx.Audio.Integration;
  12. using Ryujinx.Ava.Common;
  13. using Ryujinx.Ava.Common.Locale;
  14. using Ryujinx.Ava.Input;
  15. using Ryujinx.Ava.UI.Controls;
  16. using Ryujinx.Ava.UI.Helpers;
  17. using Ryujinx.Ava.UI.Models;
  18. using Ryujinx.Ava.UI.ViewModels;
  19. using Ryujinx.Ava.UI.Windows;
  20. using Ryujinx.Common;
  21. using Ryujinx.Common.Configuration;
  22. using Ryujinx.Common.Logging;
  23. using Ryujinx.Common.SystemInterop;
  24. using Ryujinx.Graphics.GAL;
  25. using Ryujinx.Graphics.GAL.Multithreading;
  26. using Ryujinx.Graphics.Gpu;
  27. using Ryujinx.Graphics.OpenGL;
  28. using Ryujinx.Graphics.Vulkan;
  29. using Ryujinx.HLE.FileSystem;
  30. using Ryujinx.HLE.HOS;
  31. using Ryujinx.HLE.HOS.Services.Account.Acc;
  32. using Ryujinx.HLE.HOS.SystemState;
  33. using Ryujinx.Input;
  34. using Ryujinx.Input.HLE;
  35. using Ryujinx.Ui.Common;
  36. using Ryujinx.Ui.Common.Configuration;
  37. using Ryujinx.Ui.Common.Helper;
  38. using SixLabors.ImageSharp;
  39. using SixLabors.ImageSharp.Formats.Png;
  40. using SixLabors.ImageSharp.PixelFormats;
  41. using SixLabors.ImageSharp.Processing;
  42. using SPB.Graphics.Vulkan;
  43. using System;
  44. using System.Collections.Generic;
  45. using System.Diagnostics;
  46. using System.IO;
  47. using System.Runtime.Versioning;
  48. using System.Threading;
  49. using System.Threading.Tasks;
  50. using static Ryujinx.Ava.UI.Helpers.Win32NativeInterop;
  51. using Image = SixLabors.ImageSharp.Image;
  52. using InputManager = Ryujinx.Input.HLE.InputManager;
  53. using Key = Ryujinx.Input.Key;
  54. using MouseButton = Ryujinx.Input.MouseButton;
  55. using Size = Avalonia.Size;
  56. using Switch = Ryujinx.HLE.Switch;
  57. using WindowState = Avalonia.Controls.WindowState;
  58. namespace Ryujinx.Ava
  59. {
  60. internal class AppHost
  61. {
  62. private const int CursorHideIdleTime = 5; // Hide Cursor seconds.
  63. private const float MaxResolutionScale = 4.0f; // Max resolution hotkeys can scale to before wrapping.
  64. private const int TargetFps = 60;
  65. private const float VolumeDelta = 0.05f;
  66. private static readonly Cursor InvisibleCursor = new(StandardCursorType.None);
  67. private readonly IntPtr InvisibleCursorWin;
  68. private readonly IntPtr DefaultCursorWin;
  69. private readonly long _ticksPerFrame;
  70. private readonly Stopwatch _chrono;
  71. private long _ticks;
  72. private readonly AccountManager _accountManager;
  73. private readonly UserChannelPersistence _userChannelPersistence;
  74. private readonly InputManager _inputManager;
  75. private readonly MainWindowViewModel _viewModel;
  76. private readonly IKeyboard _keyboardInterface;
  77. private readonly TopLevel _topLevel;
  78. private readonly GraphicsDebugLevel _glLogLevel;
  79. private float _newVolume;
  80. private KeyboardHotkeyState _prevHotkeyState;
  81. private long _lastCursorMoveTime;
  82. private bool _isCursorInRenderer;
  83. private bool _isStopped;
  84. private bool _isActive;
  85. private bool _renderingStarted;
  86. private IRenderer _renderer;
  87. private readonly Thread _renderingThread;
  88. private readonly CancellationTokenSource _gpuCancellationTokenSource;
  89. private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  90. private bool _dialogShown;
  91. private readonly bool _isFirmwareTitle;
  92. private readonly object _lockObject = new();
  93. public event EventHandler AppExit;
  94. public event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  95. public RendererHost Renderer { get; }
  96. public VirtualFileSystem VirtualFileSystem { get; }
  97. public ContentManager ContentManager { get; }
  98. public NpadManager NpadManager { get; }
  99. public TouchScreenManager TouchScreenManager { get; }
  100. public Switch Device { get; set; }
  101. public int Width { get; private set; }
  102. public int Height { get; private set; }
  103. public string ApplicationPath { get; private set; }
  104. public bool ScreenshotRequested { get; set; }
  105. public AppHost(
  106. RendererHost renderer,
  107. InputManager inputManager,
  108. string applicationPath,
  109. VirtualFileSystem virtualFileSystem,
  110. ContentManager contentManager,
  111. AccountManager accountManager,
  112. UserChannelPersistence userChannelPersistence,
  113. MainWindowViewModel viewmodel,
  114. TopLevel topLevel)
  115. {
  116. _viewModel = viewmodel;
  117. _inputManager = inputManager;
  118. _accountManager = accountManager;
  119. _userChannelPersistence = userChannelPersistence;
  120. _renderingThread = new Thread(RenderLoop, 1 * 1024 * 1024) { Name = "GUI.RenderThread" };
  121. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  122. _glLogLevel = ConfigurationState.Instance.Logger.GraphicsDebugLevel;
  123. _topLevel = topLevel;
  124. _inputManager.SetMouseDriver(new AvaloniaMouseDriver(_topLevel, renderer));
  125. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  126. NpadManager = _inputManager.CreateNpadManager();
  127. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  128. Renderer = renderer;
  129. ApplicationPath = applicationPath;
  130. VirtualFileSystem = virtualFileSystem;
  131. ContentManager = contentManager;
  132. _chrono = new Stopwatch();
  133. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  134. if (ApplicationPath.StartsWith("@SystemContent"))
  135. {
  136. ApplicationPath = _viewModel.VirtualFileSystem.SwitchPathToSystemPath(ApplicationPath);
  137. _isFirmwareTitle = true;
  138. }
  139. ConfigurationState.Instance.HideCursorOnIdle.Event += HideCursorState_Changed;
  140. _topLevel.PointerMoved += TopLevel_PointerMoved;
  141. if (OperatingSystem.IsWindows())
  142. {
  143. InvisibleCursorWin = CreateEmptyCursor();
  144. DefaultCursorWin = CreateArrowCursor();
  145. }
  146. ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
  147. ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
  148. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  149. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  150. _gpuCancellationTokenSource = new CancellationTokenSource();
  151. }
  152. private void TopLevel_PointerMoved(object sender, PointerEventArgs e)
  153. {
  154. if (sender is MainWindow window)
  155. {
  156. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  157. if ((Renderer.Content as EmbeddedWindow).TransformedBounds != null)
  158. {
  159. var point = e.GetCurrentPoint(window).Position;
  160. var bounds = (Renderer.Content as EmbeddedWindow).TransformedBounds.Value.Clip;
  161. _isCursorInRenderer = point.X >= bounds.X &&
  162. point.X <= bounds.Width + bounds.X &&
  163. point.Y >= bounds.Y &&
  164. point.Y <= bounds.Height + bounds.Y;
  165. }
  166. }
  167. }
  168. private void ShowCursor()
  169. {
  170. Dispatcher.UIThread.Post(() =>
  171. {
  172. _viewModel.Cursor = Cursor.Default;
  173. if (OperatingSystem.IsWindows())
  174. {
  175. SetCursor(DefaultCursorWin);
  176. }
  177. });
  178. }
  179. private void HideCursor()
  180. {
  181. Dispatcher.UIThread.Post(() =>
  182. {
  183. _viewModel.Cursor = InvisibleCursor;
  184. if (OperatingSystem.IsWindows())
  185. {
  186. SetCursor(InvisibleCursorWin);
  187. }
  188. });
  189. }
  190. private void SetRendererWindowSize(Size size)
  191. {
  192. if (_renderer != null)
  193. {
  194. double scale = _topLevel.PlatformImpl.RenderScaling;
  195. _renderer.Window?.SetSize((int)(size.Width * scale), (int)(size.Height * scale));
  196. }
  197. }
  198. private unsafe void Renderer_ScreenCaptured(object sender, ScreenCaptureImageInfo e)
  199. {
  200. if (e.Data.Length > 0 && e.Height > 0 && e.Width > 0)
  201. {
  202. Task.Run(() =>
  203. {
  204. lock (_lockObject)
  205. {
  206. DateTime currentTime = DateTime.Now;
  207. string filename = $"ryujinx_capture_{currentTime}-{currentTime:D2}-{currentTime:D2}_{currentTime:D2}-{currentTime:D2}-{currentTime:D2}.png";
  208. string directory = AppDataManager.Mode switch
  209. {
  210. AppDataManager.LaunchMode.Portable => Path.Combine(AppDataManager.BaseDirPath, "screenshots"),
  211. _ => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx")
  212. };
  213. string path = Path.Combine(directory, filename);
  214. try
  215. {
  216. Directory.CreateDirectory(directory);
  217. }
  218. catch (Exception ex)
  219. {
  220. Logger.Error?.Print(LogClass.Application, $"Failed to create directory at path {directory}. Error : {ex.GetType().Name}", "Screenshot");
  221. return;
  222. }
  223. Image image = e.IsBgra ? Image.LoadPixelData<Bgra32>(e.Data, e.Width, e.Height)
  224. : Image.LoadPixelData<Rgba32>(e.Data, e.Width, e.Height);
  225. if (e.FlipX)
  226. {
  227. image.Mutate(x => x.Flip(FlipMode.Horizontal));
  228. }
  229. if (e.FlipY)
  230. {
  231. image.Mutate(x => x.Flip(FlipMode.Vertical));
  232. }
  233. image.SaveAsPng(path, new PngEncoder()
  234. {
  235. ColorType = PngColorType.Rgb
  236. });
  237. image.Dispose();
  238. Logger.Notice.Print(LogClass.Application, $"Screenshot saved to {path}", "Screenshot");
  239. }
  240. });
  241. }
  242. else
  243. {
  244. Logger.Error?.Print(LogClass.Application, $"Screenshot is empty. Size : {e.Data.Length} bytes. Resolution : {e.Width}x{e.Height}", "Screenshot");
  245. }
  246. }
  247. public void Start()
  248. {
  249. if (OperatingSystem.IsWindows())
  250. {
  251. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  252. }
  253. DisplaySleep.Prevent();
  254. NpadManager.Initialize(Device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  255. TouchScreenManager.Initialize(Device);
  256. _viewModel.IsGameRunning = true;
  257. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName) ? string.Empty : $" - {Device.Application.TitleName}";
  258. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion) ? string.Empty : $" v{Device.Application.DisplayVersion}";
  259. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText) ? string.Empty : $" ({Device.Application.TitleIdText.ToUpper()})";
  260. string titleArchSection = Device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  261. Dispatcher.UIThread.InvokeAsync(() =>
  262. {
  263. _viewModel.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  264. });
  265. _viewModel.SetUIProgressHandlers(Device);
  266. Renderer.SizeChanged += Window_SizeChanged;
  267. _isActive = true;
  268. _renderingThread.Start();
  269. _viewModel.Volume = ConfigurationState.Instance.System.AudioVolume.Value;
  270. MainLoop();
  271. Exit();
  272. }
  273. private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
  274. {
  275. if (Device != null)
  276. {
  277. Device.Configuration.IgnoreMissingServices = args.NewValue;
  278. }
  279. }
  280. private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
  281. {
  282. if (Device != null)
  283. {
  284. Device.Configuration.AspectRatio = args.NewValue;
  285. }
  286. }
  287. private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
  288. {
  289. Device?.System.ChangeDockedModeState(e.NewValue);
  290. }
  291. private void UpdateAudioVolumeState(object sender, ReactiveEventArgs<float> e)
  292. {
  293. Device?.SetVolume(e.NewValue);
  294. Dispatcher.UIThread.Post(() =>
  295. {
  296. _viewModel.Volume = e.NewValue;
  297. });
  298. }
  299. public void Stop()
  300. {
  301. _isActive = false;
  302. }
  303. private void Exit()
  304. {
  305. (_keyboardInterface as AvaloniaKeyboard)?.Clear();
  306. if (_isStopped)
  307. {
  308. return;
  309. }
  310. _isStopped = true;
  311. _isActive = false;
  312. }
  313. public void DisposeContext()
  314. {
  315. Dispose();
  316. _isActive = false;
  317. if (_renderingThread.IsAlive)
  318. {
  319. _renderingThread.Join();
  320. }
  321. DisplaySleep.Restore();
  322. NpadManager.Dispose();
  323. TouchScreenManager.Dispose();
  324. Device.Dispose();
  325. DisposeGpu();
  326. AppExit?.Invoke(this, EventArgs.Empty);
  327. }
  328. private void Dispose()
  329. {
  330. if (Device.Application != null)
  331. {
  332. _viewModel.UpdateGameMetadata(Device.Application.TitleIdText);
  333. }
  334. ConfigurationState.Instance.System.IgnoreMissingServices.Event -= UpdateIgnoreMissingServicesState;
  335. ConfigurationState.Instance.Graphics.AspectRatio.Event -= UpdateAspectRatioState;
  336. ConfigurationState.Instance.System.EnableDockedMode.Event -= UpdateDockedModeState;
  337. ConfigurationState.Instance.System.AudioVolume.Event -= UpdateAudioVolumeState;
  338. _topLevel.PointerMoved -= TopLevel_PointerMoved;
  339. _gpuCancellationTokenSource.Cancel();
  340. _gpuCancellationTokenSource.Dispose();
  341. _chrono.Stop();
  342. }
  343. public void DisposeGpu()
  344. {
  345. if (OperatingSystem.IsWindows())
  346. {
  347. _windowsMultimediaTimerResolution?.Dispose();
  348. _windowsMultimediaTimerResolution = null;
  349. }
  350. Renderer?.MakeCurrent();
  351. Device.DisposeGpu();
  352. Renderer?.MakeCurrent(null);
  353. }
  354. private void HideCursorState_Changed(object sender, ReactiveEventArgs<bool> state)
  355. {
  356. if (state.NewValue)
  357. {
  358. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  359. }
  360. }
  361. public async Task<bool> LoadGuestApplication()
  362. {
  363. InitializeSwitchInstance();
  364. MainWindow.UpdateGraphicsConfig();
  365. SystemVersion firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  366. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  367. {
  368. if (!SetupValidator.CanStartApplication(ContentManager, ApplicationPath, out UserError userError))
  369. {
  370. {
  371. if (SetupValidator.CanFixStartApplication(ContentManager, ApplicationPath, userError, out firmwareVersion))
  372. {
  373. if (userError == UserError.NoFirmware)
  374. {
  375. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  376. LocaleManager.Instance[LocaleKeys.DialogFirmwareNoFirmwareInstalledMessage],
  377. string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallEmbeddedMessage],
  378. firmwareVersion.VersionString),
  379. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  380. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  381. "");
  382. if (result != UserResult.Yes)
  383. {
  384. await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow));
  385. Device.Dispose();
  386. return false;
  387. }
  388. }
  389. if (!SetupValidator.TryFixStartApplication(ContentManager, ApplicationPath, userError, out _))
  390. {
  391. await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow));
  392. Device.Dispose();
  393. return false;
  394. }
  395. // Tell the user that we installed a firmware for them.
  396. if (userError == UserError.NoFirmware)
  397. {
  398. firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  399. _viewModel.RefreshFirmwareStatus();
  400. await ContentDialogHelper.CreateInfoDialog(
  401. string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstalledMessage],
  402. firmwareVersion.VersionString),
  403. string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallEmbeddedSuccessMessage],
  404. firmwareVersion.VersionString),
  405. LocaleManager.Instance[LocaleKeys.InputDialogOk],
  406. "",
  407. LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  408. }
  409. }
  410. else
  411. {
  412. await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow));
  413. Device.Dispose();
  414. return false;
  415. }
  416. }
  417. }
  418. }
  419. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  420. if (_isFirmwareTitle)
  421. {
  422. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  423. Device.LoadNca(ApplicationPath);
  424. }
  425. else if (Directory.Exists(ApplicationPath))
  426. {
  427. string[] romFsFiles = Directory.GetFiles(ApplicationPath, "*.istorage");
  428. if (romFsFiles.Length == 0)
  429. {
  430. romFsFiles = Directory.GetFiles(ApplicationPath, "*.romfs");
  431. }
  432. if (romFsFiles.Length > 0)
  433. {
  434. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  435. Device.LoadCart(ApplicationPath, romFsFiles[0]);
  436. }
  437. else
  438. {
  439. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  440. Device.LoadCart(ApplicationPath);
  441. }
  442. }
  443. else if (File.Exists(ApplicationPath))
  444. {
  445. switch (Path.GetExtension(ApplicationPath).ToLowerInvariant())
  446. {
  447. case ".xci":
  448. {
  449. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  450. Device.LoadXci(ApplicationPath);
  451. break;
  452. }
  453. case ".nca":
  454. {
  455. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  456. Device.LoadNca(ApplicationPath);
  457. break;
  458. }
  459. case ".nsp":
  460. case ".pfs0":
  461. {
  462. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  463. Device.LoadNsp(ApplicationPath);
  464. break;
  465. }
  466. default:
  467. {
  468. Logger.Info?.Print(LogClass.Application, "Loading as homebrew.");
  469. try
  470. {
  471. Device.LoadProgram(ApplicationPath);
  472. }
  473. catch (ArgumentOutOfRangeException)
  474. {
  475. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  476. Dispose();
  477. return false;
  478. }
  479. break;
  480. }
  481. }
  482. }
  483. else
  484. {
  485. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  486. Dispose();
  487. return false;
  488. }
  489. DiscordIntegrationModule.SwitchToPlayingState(Device.Application.TitleIdText, Device.Application.TitleName);
  490. _viewModel.ApplicationLibrary.LoadAndSaveMetaData(Device.Application.TitleIdText, appMetadata =>
  491. {
  492. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  493. });
  494. return true;
  495. }
  496. internal void Resume()
  497. {
  498. Device?.System.TogglePauseEmulation(false);
  499. _viewModel.IsPaused = false;
  500. }
  501. internal void Pause()
  502. {
  503. Device?.System.TogglePauseEmulation(true);
  504. _viewModel.IsPaused = true;
  505. }
  506. private void InitializeSwitchInstance()
  507. {
  508. // Initialize KeySet.
  509. VirtualFileSystem.ReloadKeySet();
  510. // Initialize Renderer.
  511. IRenderer renderer;
  512. if (Renderer.IsVulkan)
  513. {
  514. string preferredGpu = ConfigurationState.Instance.Graphics.PreferredGpu.Value;
  515. renderer = new VulkanRenderer(Renderer.CreateVulkanSurface, VulkanHelper.GetRequiredInstanceExtensions, preferredGpu);
  516. }
  517. else
  518. {
  519. renderer = new OpenGLRenderer();
  520. }
  521. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  522. var isGALthreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  523. if (isGALthreaded)
  524. {
  525. renderer = new ThreadedRenderer(renderer);
  526. }
  527. Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALthreaded}");
  528. // Initialize Configuration.
  529. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value ? HLE.MemoryConfiguration.MemoryConfiguration6GiB : HLE.MemoryConfiguration.MemoryConfiguration4GiB;
  530. HLE.HLEConfiguration configuration = new(VirtualFileSystem,
  531. _viewModel.LibHacHorizonManager,
  532. ContentManager,
  533. _accountManager,
  534. _userChannelPersistence,
  535. renderer,
  536. InitializeAudio(),
  537. memoryConfiguration,
  538. _viewModel.UiHandler,
  539. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  540. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  541. ConfigurationState.Instance.Graphics.EnableVsync,
  542. ConfigurationState.Instance.System.EnableDockedMode,
  543. ConfigurationState.Instance.System.EnablePtc,
  544. ConfigurationState.Instance.System.EnableInternetAccess,
  545. ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None,
  546. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  547. ConfigurationState.Instance.System.SystemTimeOffset,
  548. ConfigurationState.Instance.System.TimeZone,
  549. ConfigurationState.Instance.System.MemoryManagerMode,
  550. ConfigurationState.Instance.System.IgnoreMissingServices,
  551. ConfigurationState.Instance.Graphics.AspectRatio,
  552. ConfigurationState.Instance.System.AudioVolume);
  553. Device = new Switch(configuration);
  554. }
  555. private static IHardwareDeviceDriver InitializeAudio()
  556. {
  557. var availableBackends = new List<AudioBackend>()
  558. {
  559. AudioBackend.SDL2,
  560. AudioBackend.SoundIo,
  561. AudioBackend.OpenAl,
  562. AudioBackend.Dummy
  563. };
  564. AudioBackend preferredBackend = ConfigurationState.Instance.System.AudioBackend.Value;
  565. for (int i = 0; i < availableBackends.Count; i++)
  566. {
  567. if (availableBackends[i] == preferredBackend)
  568. {
  569. availableBackends.RemoveAt(i);
  570. availableBackends.Insert(0, preferredBackend);
  571. break;
  572. }
  573. }
  574. static IHardwareDeviceDriver InitializeAudioBackend<T>(AudioBackend backend, AudioBackend nextBackend) where T : IHardwareDeviceDriver, new()
  575. {
  576. if (T.IsSupported)
  577. {
  578. return new T();
  579. }
  580. else
  581. {
  582. Logger.Warning?.Print(LogClass.Audio, $"{backend} is not supported, falling back to {nextBackend}.");
  583. return null;
  584. }
  585. }
  586. IHardwareDeviceDriver deviceDriver = null;
  587. for (int i = 0; i < availableBackends.Count; i++)
  588. {
  589. AudioBackend currentBackend = availableBackends[i];
  590. AudioBackend nextBackend = i + 1 < availableBackends.Count ? availableBackends[i + 1] : AudioBackend.Dummy;
  591. deviceDriver = currentBackend switch
  592. {
  593. AudioBackend.SDL2 => InitializeAudioBackend<SDL2HardwareDeviceDriver>(AudioBackend.SDL2, nextBackend),
  594. AudioBackend.SoundIo => InitializeAudioBackend<SoundIoHardwareDeviceDriver>(AudioBackend.SoundIo, nextBackend),
  595. AudioBackend.OpenAl => InitializeAudioBackend<OpenALHardwareDeviceDriver>(AudioBackend.OpenAl, nextBackend),
  596. _ => new DummyHardwareDeviceDriver()
  597. };
  598. if (deviceDriver != null)
  599. {
  600. ConfigurationState.Instance.System.AudioBackend.Value = currentBackend;
  601. break;
  602. }
  603. }
  604. MainWindowViewModel.SaveConfig();
  605. return deviceDriver;
  606. }
  607. private void Window_SizeChanged(object sender, Size e)
  608. {
  609. Width = (int)e.Width;
  610. Height = (int)e.Height;
  611. SetRendererWindowSize(e);
  612. }
  613. private void MainLoop()
  614. {
  615. while (_isActive)
  616. {
  617. UpdateFrame();
  618. // Polling becomes expensive if it's not slept.
  619. Thread.Sleep(1);
  620. }
  621. }
  622. private unsafe void RenderLoop()
  623. {
  624. Dispatcher.UIThread.InvokeAsync(() =>
  625. {
  626. if (_viewModel.StartGamesInFullscreen)
  627. {
  628. _viewModel.WindowState = WindowState.FullScreen;
  629. }
  630. if (_viewModel.WindowState == WindowState.FullScreen)
  631. {
  632. _viewModel.ShowMenuAndStatusBar = false;
  633. }
  634. });
  635. _renderer = Device.Gpu.Renderer is ThreadedRenderer tr ? tr.BaseRenderer : Device.Gpu.Renderer;
  636. _renderer.ScreenCaptured += Renderer_ScreenCaptured;
  637. (_renderer as OpenGLRenderer)?.InitializeBackgroundContext(SPBOpenGLContext.CreateBackgroundContext(Renderer.GetContext()));
  638. Renderer.MakeCurrent();
  639. Device.Gpu.Renderer.Initialize(_glLogLevel);
  640. Width = (int)Renderer.Bounds.Width;
  641. Height = (int)Renderer.Bounds.Height;
  642. _renderer.Window.SetSize((int)(Width * _topLevel.PlatformImpl.RenderScaling), (int)(Height * _topLevel.PlatformImpl.RenderScaling));
  643. _chrono.Start();
  644. Device.Gpu.Renderer.RunLoop(() =>
  645. {
  646. Device.Gpu.SetGpuThread();
  647. Device.Gpu.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  648. Translator.IsReadyForTranslation.Set();
  649. while (_isActive)
  650. {
  651. _ticks += _chrono.ElapsedTicks;
  652. _chrono.Restart();
  653. if (Device.WaitFifo())
  654. {
  655. Device.Statistics.RecordFifoStart();
  656. Device.ProcessFrame();
  657. Device.Statistics.RecordFifoEnd();
  658. }
  659. while (Device.ConsumeFrameAvailable())
  660. {
  661. if (!_renderingStarted)
  662. {
  663. _renderingStarted = true;
  664. _viewModel.SwitchToRenderer(false);
  665. }
  666. Device.PresentFrame(() => Renderer?.SwapBuffers());
  667. }
  668. if (_ticks >= _ticksPerFrame)
  669. {
  670. UpdateStatus();
  671. }
  672. }
  673. });
  674. Renderer?.MakeCurrent(null);
  675. }
  676. public void UpdateStatus()
  677. {
  678. // Run a status update only when a frame is to be drawn. This prevents from updating the ui and wasting a render when no frame is queued.
  679. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? LocaleManager.Instance[LocaleKeys.Docked] : LocaleManager.Instance[LocaleKeys.Handheld];
  680. if (GraphicsConfig.ResScale != 1)
  681. {
  682. dockedMode += $" ({GraphicsConfig.ResScale}x)";
  683. }
  684. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  685. Device.EnableDeviceVsync,
  686. LocaleManager.Instance[LocaleKeys.VolumeShort] + $": {(int)(Device.GetVolume() * 100)}%",
  687. Renderer.IsVulkan ? "Vulkan" : "OpenGL",
  688. dockedMode,
  689. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  690. LocaleManager.Instance[LocaleKeys.Game] + $": {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  691. $"FIFO: {Device.Statistics.GetFifoPercent():00.00} %",
  692. $"GPU: {_renderer.GetHardwareInfo().GpuVendor}"));
  693. }
  694. public async Task ShowExitPrompt()
  695. {
  696. bool shouldExit = !ConfigurationState.Instance.ShowConfirmExit;
  697. if (!shouldExit)
  698. {
  699. if (_dialogShown)
  700. {
  701. return;
  702. }
  703. _dialogShown = true;
  704. shouldExit = await ContentDialogHelper.CreateStopEmulationDialog();
  705. _dialogShown = false;
  706. }
  707. if (shouldExit)
  708. {
  709. Stop();
  710. }
  711. }
  712. private bool UpdateFrame()
  713. {
  714. if (!_isActive)
  715. {
  716. return false;
  717. }
  718. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  719. if (_viewModel.IsActive)
  720. {
  721. if (ConfigurationState.Instance.Hid.EnableMouse)
  722. {
  723. if (_isCursorInRenderer)
  724. {
  725. HideCursor();
  726. }
  727. else
  728. {
  729. ShowCursor();
  730. }
  731. }
  732. else
  733. {
  734. if (ConfigurationState.Instance.HideCursorOnIdle)
  735. {
  736. if (Stopwatch.GetTimestamp() - _lastCursorMoveTime >= CursorHideIdleTime * Stopwatch.Frequency)
  737. {
  738. HideCursor();
  739. }
  740. else
  741. {
  742. ShowCursor();
  743. }
  744. }
  745. }
  746. Dispatcher.UIThread.Post(() =>
  747. {
  748. if (_keyboardInterface.GetKeyboardStateSnapshot().IsPressed(Key.Delete) && _viewModel.WindowState != WindowState.FullScreen)
  749. {
  750. Device.Application.DiskCacheLoadState?.Cancel();
  751. }
  752. });
  753. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  754. if (currentHotkeyState != _prevHotkeyState)
  755. {
  756. switch (currentHotkeyState)
  757. {
  758. case KeyboardHotkeyState.ToggleVSync:
  759. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  760. break;
  761. case KeyboardHotkeyState.Screenshot:
  762. ScreenshotRequested = true;
  763. break;
  764. case KeyboardHotkeyState.ShowUi:
  765. _viewModel.ShowMenuAndStatusBar = true;
  766. break;
  767. case KeyboardHotkeyState.Pause:
  768. if (_viewModel.IsPaused)
  769. {
  770. Resume();
  771. }
  772. else
  773. {
  774. Pause();
  775. }
  776. break;
  777. case KeyboardHotkeyState.ToggleMute:
  778. if (Device.IsAudioMuted())
  779. {
  780. Device.SetVolume(ConfigurationState.Instance.System.AudioVolume);
  781. }
  782. else
  783. {
  784. Device.SetVolume(0);
  785. }
  786. _viewModel.Volume = Device.GetVolume();
  787. break;
  788. case KeyboardHotkeyState.ResScaleUp:
  789. GraphicsConfig.ResScale = GraphicsConfig.ResScale % MaxResolutionScale + 1;
  790. break;
  791. case KeyboardHotkeyState.ResScaleDown:
  792. GraphicsConfig.ResScale =
  793. (MaxResolutionScale + GraphicsConfig.ResScale - 2) % MaxResolutionScale + 1;
  794. break;
  795. case KeyboardHotkeyState.VolumeUp:
  796. _newVolume = MathF.Round((Device.GetVolume() + VolumeDelta), 2);
  797. Device.SetVolume(_newVolume);
  798. _viewModel.Volume = Device.GetVolume();
  799. break;
  800. case KeyboardHotkeyState.VolumeDown:
  801. _newVolume = MathF.Round((Device.GetVolume() - VolumeDelta), 2);
  802. Device.SetVolume(_newVolume);
  803. _viewModel.Volume = Device.GetVolume();
  804. break;
  805. case KeyboardHotkeyState.None:
  806. (_keyboardInterface as AvaloniaKeyboard).Clear();
  807. break;
  808. }
  809. }
  810. _prevHotkeyState = currentHotkeyState;
  811. if (ScreenshotRequested)
  812. {
  813. ScreenshotRequested = false;
  814. _renderer.Screenshot();
  815. }
  816. }
  817. // Touchscreen.
  818. bool hasTouch = false;
  819. if (_viewModel.IsActive && !ConfigurationState.Instance.Hid.EnableMouse)
  820. {
  821. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as AvaloniaMouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  822. }
  823. if (!hasTouch)
  824. {
  825. Device.Hid.Touchscreen.Update();
  826. }
  827. Device.Hid.DebugPad.Update();
  828. return true;
  829. }
  830. private KeyboardHotkeyState GetHotkeyState()
  831. {
  832. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  833. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  834. {
  835. state = KeyboardHotkeyState.ToggleVSync;
  836. }
  837. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot))
  838. {
  839. state = KeyboardHotkeyState.Screenshot;
  840. }
  841. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi))
  842. {
  843. state = KeyboardHotkeyState.ShowUi;
  844. }
  845. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause))
  846. {
  847. state = KeyboardHotkeyState.Pause;
  848. }
  849. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleMute))
  850. {
  851. state = KeyboardHotkeyState.ToggleMute;
  852. }
  853. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleUp))
  854. {
  855. state = KeyboardHotkeyState.ResScaleUp;
  856. }
  857. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleDown))
  858. {
  859. state = KeyboardHotkeyState.ResScaleDown;
  860. }
  861. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeUp))
  862. {
  863. state = KeyboardHotkeyState.VolumeUp;
  864. }
  865. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeDown))
  866. {
  867. state = KeyboardHotkeyState.VolumeDown;
  868. }
  869. return state;
  870. }
  871. }
  872. }