AppHost.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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.Helpers;
  16. using Ryujinx.Ava.UI.Models;
  17. using Ryujinx.Ava.UI.Renderer;
  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.Threading;
  48. using System.Threading.Tasks;
  49. using static Ryujinx.Ava.UI.Helpers.Win32NativeInterop;
  50. using Image = SixLabors.ImageSharp.Image;
  51. using InputManager = Ryujinx.Input.HLE.InputManager;
  52. using Key = Ryujinx.Input.Key;
  53. using MouseButton = Ryujinx.Input.MouseButton;
  54. using Size = Avalonia.Size;
  55. using Switch = Ryujinx.HLE.Switch;
  56. using WindowState = Avalonia.Controls.WindowState;
  57. namespace Ryujinx.Ava
  58. {
  59. internal class AppHost
  60. {
  61. private const int CursorHideIdleTime = 5; // Hide Cursor seconds.
  62. private const float MaxResolutionScale = 4.0f; // Max resolution hotkeys can scale to before wrapping.
  63. private const int TargetFps = 60;
  64. private const float VolumeDelta = 0.05f;
  65. private static readonly Cursor InvisibleCursor = new(StandardCursorType.None);
  66. private readonly IntPtr InvisibleCursorWin;
  67. private readonly IntPtr DefaultCursorWin;
  68. private readonly long _ticksPerFrame;
  69. private readonly Stopwatch _chrono;
  70. private long _ticks;
  71. private readonly AccountManager _accountManager;
  72. private readonly UserChannelPersistence _userChannelPersistence;
  73. private readonly InputManager _inputManager;
  74. private readonly MainWindowViewModel _viewModel;
  75. private readonly IKeyboard _keyboardInterface;
  76. private readonly TopLevel _topLevel;
  77. public RendererHost _rendererHost;
  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 VirtualFileSystem VirtualFileSystem { get; }
  96. public ContentManager ContentManager { get; }
  97. public NpadManager NpadManager { get; }
  98. public TouchScreenManager TouchScreenManager { get; }
  99. public Switch Device { get; set; }
  100. public int Width { get; private set; }
  101. public int Height { get; private set; }
  102. public string ApplicationPath { get; private set; }
  103. public bool ScreenshotRequested { get; set; }
  104. public AppHost(
  105. RendererHost renderer,
  106. InputManager inputManager,
  107. string applicationPath,
  108. VirtualFileSystem virtualFileSystem,
  109. ContentManager contentManager,
  110. AccountManager accountManager,
  111. UserChannelPersistence userChannelPersistence,
  112. MainWindowViewModel viewmodel,
  113. TopLevel topLevel)
  114. {
  115. _viewModel = viewmodel;
  116. _inputManager = inputManager;
  117. _accountManager = accountManager;
  118. _userChannelPersistence = userChannelPersistence;
  119. _renderingThread = new Thread(RenderLoop, 1 * 1024 * 1024) { Name = "GUI.RenderThread" };
  120. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  121. _glLogLevel = ConfigurationState.Instance.Logger.GraphicsDebugLevel;
  122. _topLevel = topLevel;
  123. _inputManager.SetMouseDriver(new AvaloniaMouseDriver(_topLevel, renderer));
  124. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  125. NpadManager = _inputManager.CreateNpadManager();
  126. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  127. ApplicationPath = applicationPath;
  128. VirtualFileSystem = virtualFileSystem;
  129. ContentManager = contentManager;
  130. _rendererHost = renderer;
  131. _chrono = new Stopwatch();
  132. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  133. if (ApplicationPath.StartsWith("@SystemContent"))
  134. {
  135. ApplicationPath = _viewModel.VirtualFileSystem.SwitchPathToSystemPath(ApplicationPath);
  136. _isFirmwareTitle = true;
  137. }
  138. ConfigurationState.Instance.HideCursorOnIdle.Event += HideCursorState_Changed;
  139. _topLevel.PointerMoved += TopLevel_PointerMoved;
  140. if (OperatingSystem.IsWindows())
  141. {
  142. InvisibleCursorWin = CreateEmptyCursor();
  143. DefaultCursorWin = CreateArrowCursor();
  144. }
  145. ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
  146. ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
  147. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  148. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  149. _gpuCancellationTokenSource = new CancellationTokenSource();
  150. }
  151. private void TopLevel_PointerMoved(object sender, PointerEventArgs e)
  152. {
  153. if (sender is MainWindow window)
  154. {
  155. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  156. if (_rendererHost.EmbeddedWindow.TransformedBounds != null)
  157. {
  158. var point = e.GetCurrentPoint(window).Position;
  159. var bounds = _rendererHost.EmbeddedWindow.TransformedBounds.Value.Clip;
  160. _isCursorInRenderer = point.X >= bounds.X &&
  161. point.X <= bounds.Width + bounds.X &&
  162. point.Y >= bounds.Y &&
  163. point.Y <= bounds.Height + bounds.Y;
  164. }
  165. }
  166. }
  167. private void ShowCursor()
  168. {
  169. Dispatcher.UIThread.Post(() =>
  170. {
  171. _viewModel.Cursor = Cursor.Default;
  172. if (OperatingSystem.IsWindows())
  173. {
  174. SetCursor(DefaultCursorWin);
  175. }
  176. });
  177. }
  178. private void HideCursor()
  179. {
  180. Dispatcher.UIThread.Post(() =>
  181. {
  182. _viewModel.Cursor = InvisibleCursor;
  183. if (OperatingSystem.IsWindows())
  184. {
  185. SetCursor(InvisibleCursorWin);
  186. }
  187. });
  188. }
  189. private void SetRendererWindowSize(Size size)
  190. {
  191. if (_renderer != null)
  192. {
  193. double scale = _topLevel.PlatformImpl.RenderScaling;
  194. _renderer.Window?.SetSize((int)(size.Width * scale), (int)(size.Height * scale));
  195. }
  196. }
  197. private unsafe void Renderer_ScreenCaptured(object sender, ScreenCaptureImageInfo e)
  198. {
  199. if (e.Data.Length > 0 && e.Height > 0 && e.Width > 0)
  200. {
  201. Task.Run(() =>
  202. {
  203. lock (_lockObject)
  204. {
  205. DateTime currentTime = DateTime.Now;
  206. string filename = $"ryujinx_capture_{currentTime}-{currentTime:D2}-{currentTime:D2}_{currentTime:D2}-{currentTime:D2}-{currentTime:D2}.png";
  207. string directory = AppDataManager.Mode switch
  208. {
  209. AppDataManager.LaunchMode.Portable => Path.Combine(AppDataManager.BaseDirPath, "screenshots"),
  210. _ => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx")
  211. };
  212. string path = Path.Combine(directory, filename);
  213. try
  214. {
  215. Directory.CreateDirectory(directory);
  216. }
  217. catch (Exception ex)
  218. {
  219. Logger.Error?.Print(LogClass.Application, $"Failed to create directory at path {directory}. Error : {ex.GetType().Name}", "Screenshot");
  220. return;
  221. }
  222. Image image = e.IsBgra ? Image.LoadPixelData<Bgra32>(e.Data, e.Width, e.Height)
  223. : Image.LoadPixelData<Rgba32>(e.Data, e.Width, e.Height);
  224. if (e.FlipX)
  225. {
  226. image.Mutate(x => x.Flip(FlipMode.Horizontal));
  227. }
  228. if (e.FlipY)
  229. {
  230. image.Mutate(x => x.Flip(FlipMode.Vertical));
  231. }
  232. image.SaveAsPng(path, new PngEncoder()
  233. {
  234. ColorType = PngColorType.Rgb
  235. });
  236. image.Dispose();
  237. Logger.Notice.Print(LogClass.Application, $"Screenshot saved to {path}", "Screenshot");
  238. }
  239. });
  240. }
  241. else
  242. {
  243. Logger.Error?.Print(LogClass.Application, $"Screenshot is empty. Size : {e.Data.Length} bytes. Resolution : {e.Width}x{e.Height}", "Screenshot");
  244. }
  245. }
  246. public void Start()
  247. {
  248. if (OperatingSystem.IsWindows())
  249. {
  250. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  251. }
  252. DisplaySleep.Prevent();
  253. NpadManager.Initialize(Device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  254. TouchScreenManager.Initialize(Device);
  255. _viewModel.IsGameRunning = true;
  256. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName) ? string.Empty : $" - {Device.Application.TitleName}";
  257. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion) ? string.Empty : $" v{Device.Application.DisplayVersion}";
  258. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText) ? string.Empty : $" ({Device.Application.TitleIdText.ToUpper()})";
  259. string titleArchSection = Device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  260. Dispatcher.UIThread.InvokeAsync(() =>
  261. {
  262. _viewModel.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  263. });
  264. _viewModel.SetUIProgressHandlers(Device);
  265. _rendererHost.SizeChanged += Window_SizeChanged;
  266. _isActive = true;
  267. _renderingThread.Start();
  268. _viewModel.Volume = ConfigurationState.Instance.System.AudioVolume.Value;
  269. MainLoop();
  270. Exit();
  271. }
  272. private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
  273. {
  274. if (Device != null)
  275. {
  276. Device.Configuration.IgnoreMissingServices = args.NewValue;
  277. }
  278. }
  279. private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
  280. {
  281. if (Device != null)
  282. {
  283. Device.Configuration.AspectRatio = args.NewValue;
  284. }
  285. }
  286. private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
  287. {
  288. Device?.System.ChangeDockedModeState(e.NewValue);
  289. }
  290. private void UpdateAudioVolumeState(object sender, ReactiveEventArgs<float> e)
  291. {
  292. Device?.SetVolume(e.NewValue);
  293. Dispatcher.UIThread.Post(() =>
  294. {
  295. _viewModel.Volume = e.NewValue;
  296. });
  297. }
  298. public void Stop()
  299. {
  300. _isActive = false;
  301. }
  302. private void Exit()
  303. {
  304. (_keyboardInterface as AvaloniaKeyboard)?.Clear();
  305. if (_isStopped)
  306. {
  307. return;
  308. }
  309. _isStopped = true;
  310. _isActive = false;
  311. }
  312. public void DisposeContext()
  313. {
  314. Dispose();
  315. _isActive = false;
  316. if (_renderingThread.IsAlive)
  317. {
  318. _renderingThread.Join();
  319. }
  320. DisplaySleep.Restore();
  321. NpadManager.Dispose();
  322. TouchScreenManager.Dispose();
  323. Device.Dispose();
  324. DisposeGpu();
  325. AppExit?.Invoke(this, EventArgs.Empty);
  326. }
  327. private void Dispose()
  328. {
  329. if (Device.Application != null)
  330. {
  331. _viewModel.UpdateGameMetadata(Device.Application.TitleIdText);
  332. }
  333. ConfigurationState.Instance.System.IgnoreMissingServices.Event -= UpdateIgnoreMissingServicesState;
  334. ConfigurationState.Instance.Graphics.AspectRatio.Event -= UpdateAspectRatioState;
  335. ConfigurationState.Instance.System.EnableDockedMode.Event -= UpdateDockedModeState;
  336. ConfigurationState.Instance.System.AudioVolume.Event -= UpdateAudioVolumeState;
  337. _topLevel.PointerMoved -= TopLevel_PointerMoved;
  338. _gpuCancellationTokenSource.Cancel();
  339. _gpuCancellationTokenSource.Dispose();
  340. _chrono.Stop();
  341. }
  342. public void DisposeGpu()
  343. {
  344. if (OperatingSystem.IsWindows())
  345. {
  346. _windowsMultimediaTimerResolution?.Dispose();
  347. _windowsMultimediaTimerResolution = null;
  348. }
  349. (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent();
  350. Device.DisposeGpu();
  351. (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent(null);
  352. }
  353. private void HideCursorState_Changed(object sender, ReactiveEventArgs<bool> state)
  354. {
  355. if (state.NewValue)
  356. {
  357. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  358. }
  359. }
  360. public async Task<bool> LoadGuestApplication()
  361. {
  362. InitializeSwitchInstance();
  363. MainWindow.UpdateGraphicsConfig();
  364. SystemVersion firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  365. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  366. {
  367. if (!SetupValidator.CanStartApplication(ContentManager, ApplicationPath, out UserError userError))
  368. {
  369. {
  370. if (SetupValidator.CanFixStartApplication(ContentManager, ApplicationPath, userError, out firmwareVersion))
  371. {
  372. if (userError == UserError.NoFirmware)
  373. {
  374. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  375. LocaleManager.Instance[LocaleKeys.DialogFirmwareNoFirmwareInstalledMessage],
  376. string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallEmbeddedMessage],
  377. firmwareVersion.VersionString),
  378. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  379. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  380. "");
  381. if (result != UserResult.Yes)
  382. {
  383. await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow));
  384. Device.Dispose();
  385. return false;
  386. }
  387. }
  388. if (!SetupValidator.TryFixStartApplication(ContentManager, ApplicationPath, userError, out _))
  389. {
  390. await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow));
  391. Device.Dispose();
  392. return false;
  393. }
  394. // Tell the user that we installed a firmware for them.
  395. if (userError == UserError.NoFirmware)
  396. {
  397. firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  398. _viewModel.RefreshFirmwareStatus();
  399. await ContentDialogHelper.CreateInfoDialog(
  400. string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstalledMessage],
  401. firmwareVersion.VersionString),
  402. string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallEmbeddedSuccessMessage],
  403. firmwareVersion.VersionString),
  404. LocaleManager.Instance[LocaleKeys.InputDialogOk],
  405. "",
  406. LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  407. }
  408. }
  409. else
  410. {
  411. await UserErrorDialog.ShowUserErrorDialog(userError, (desktop.MainWindow as MainWindow));
  412. Device.Dispose();
  413. return false;
  414. }
  415. }
  416. }
  417. }
  418. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  419. if (_isFirmwareTitle)
  420. {
  421. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  422. Device.LoadNca(ApplicationPath);
  423. }
  424. else if (Directory.Exists(ApplicationPath))
  425. {
  426. string[] romFsFiles = Directory.GetFiles(ApplicationPath, "*.istorage");
  427. if (romFsFiles.Length == 0)
  428. {
  429. romFsFiles = Directory.GetFiles(ApplicationPath, "*.romfs");
  430. }
  431. if (romFsFiles.Length > 0)
  432. {
  433. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  434. Device.LoadCart(ApplicationPath, romFsFiles[0]);
  435. }
  436. else
  437. {
  438. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  439. Device.LoadCart(ApplicationPath);
  440. }
  441. }
  442. else if (File.Exists(ApplicationPath))
  443. {
  444. switch (Path.GetExtension(ApplicationPath).ToLowerInvariant())
  445. {
  446. case ".xci":
  447. {
  448. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  449. Device.LoadXci(ApplicationPath);
  450. break;
  451. }
  452. case ".nca":
  453. {
  454. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  455. Device.LoadNca(ApplicationPath);
  456. break;
  457. }
  458. case ".nsp":
  459. case ".pfs0":
  460. {
  461. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  462. Device.LoadNsp(ApplicationPath);
  463. break;
  464. }
  465. default:
  466. {
  467. Logger.Info?.Print(LogClass.Application, "Loading as homebrew.");
  468. try
  469. {
  470. Device.LoadProgram(ApplicationPath);
  471. }
  472. catch (ArgumentOutOfRangeException)
  473. {
  474. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  475. Dispose();
  476. return false;
  477. }
  478. break;
  479. }
  480. }
  481. }
  482. else
  483. {
  484. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  485. Dispose();
  486. return false;
  487. }
  488. DiscordIntegrationModule.SwitchToPlayingState(Device.Application.TitleIdText, Device.Application.TitleName);
  489. _viewModel.ApplicationLibrary.LoadAndSaveMetaData(Device.Application.TitleIdText, appMetadata =>
  490. {
  491. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  492. });
  493. return true;
  494. }
  495. internal void Resume()
  496. {
  497. Device?.System.TogglePauseEmulation(false);
  498. _viewModel.IsPaused = false;
  499. }
  500. internal void Pause()
  501. {
  502. Device?.System.TogglePauseEmulation(true);
  503. _viewModel.IsPaused = true;
  504. }
  505. private void InitializeSwitchInstance()
  506. {
  507. // Initialize KeySet.
  508. VirtualFileSystem.ReloadKeySet();
  509. // Initialize Renderer.
  510. IRenderer renderer;
  511. if (ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.Vulkan)
  512. {
  513. renderer = new VulkanRenderer(
  514. (_rendererHost.EmbeddedWindow as EmbeddedWindowVulkan).CreateSurface,
  515. VulkanHelper.GetRequiredInstanceExtensions,
  516. ConfigurationState.Instance.Graphics.PreferredGpu.Value);
  517. }
  518. else
  519. {
  520. renderer = new OpenGLRenderer();
  521. }
  522. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  523. var isGALthreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  524. if (isGALthreaded)
  525. {
  526. renderer = new ThreadedRenderer(renderer);
  527. }
  528. Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALthreaded}");
  529. // Initialize Configuration.
  530. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value ? HLE.MemoryConfiguration.MemoryConfiguration6GiB : HLE.MemoryConfiguration.MemoryConfiguration4GiB;
  531. HLE.HLEConfiguration configuration = new(VirtualFileSystem,
  532. _viewModel.LibHacHorizonManager,
  533. ContentManager,
  534. _accountManager,
  535. _userChannelPersistence,
  536. renderer,
  537. InitializeAudio(),
  538. memoryConfiguration,
  539. _viewModel.UiHandler,
  540. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  541. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  542. ConfigurationState.Instance.Graphics.EnableVsync,
  543. ConfigurationState.Instance.System.EnableDockedMode,
  544. ConfigurationState.Instance.System.EnablePtc,
  545. ConfigurationState.Instance.System.EnableInternetAccess,
  546. ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None,
  547. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  548. ConfigurationState.Instance.System.SystemTimeOffset,
  549. ConfigurationState.Instance.System.TimeZone,
  550. ConfigurationState.Instance.System.MemoryManagerMode,
  551. ConfigurationState.Instance.System.IgnoreMissingServices,
  552. ConfigurationState.Instance.Graphics.AspectRatio,
  553. ConfigurationState.Instance.System.AudioVolume);
  554. Device = new Switch(configuration);
  555. }
  556. private static IHardwareDeviceDriver InitializeAudio()
  557. {
  558. var availableBackends = new List<AudioBackend>()
  559. {
  560. AudioBackend.SDL2,
  561. AudioBackend.SoundIo,
  562. AudioBackend.OpenAl,
  563. AudioBackend.Dummy
  564. };
  565. AudioBackend preferredBackend = ConfigurationState.Instance.System.AudioBackend.Value;
  566. for (int i = 0; i < availableBackends.Count; i++)
  567. {
  568. if (availableBackends[i] == preferredBackend)
  569. {
  570. availableBackends.RemoveAt(i);
  571. availableBackends.Insert(0, preferredBackend);
  572. break;
  573. }
  574. }
  575. static IHardwareDeviceDriver InitializeAudioBackend<T>(AudioBackend backend, AudioBackend nextBackend) where T : IHardwareDeviceDriver, new()
  576. {
  577. if (T.IsSupported)
  578. {
  579. return new T();
  580. }
  581. else
  582. {
  583. Logger.Warning?.Print(LogClass.Audio, $"{backend} is not supported, falling back to {nextBackend}.");
  584. return null;
  585. }
  586. }
  587. IHardwareDeviceDriver deviceDriver = null;
  588. for (int i = 0; i < availableBackends.Count; i++)
  589. {
  590. AudioBackend currentBackend = availableBackends[i];
  591. AudioBackend nextBackend = i + 1 < availableBackends.Count ? availableBackends[i + 1] : AudioBackend.Dummy;
  592. deviceDriver = currentBackend switch
  593. {
  594. AudioBackend.SDL2 => InitializeAudioBackend<SDL2HardwareDeviceDriver>(AudioBackend.SDL2, nextBackend),
  595. AudioBackend.SoundIo => InitializeAudioBackend<SoundIoHardwareDeviceDriver>(AudioBackend.SoundIo, nextBackend),
  596. AudioBackend.OpenAl => InitializeAudioBackend<OpenALHardwareDeviceDriver>(AudioBackend.OpenAl, nextBackend),
  597. _ => new DummyHardwareDeviceDriver()
  598. };
  599. if (deviceDriver != null)
  600. {
  601. ConfigurationState.Instance.System.AudioBackend.Value = currentBackend;
  602. break;
  603. }
  604. }
  605. MainWindowViewModel.SaveConfig();
  606. return deviceDriver;
  607. }
  608. private void Window_SizeChanged(object sender, Size e)
  609. {
  610. Width = (int)e.Width;
  611. Height = (int)e.Height;
  612. SetRendererWindowSize(e);
  613. }
  614. private void MainLoop()
  615. {
  616. while (_isActive)
  617. {
  618. UpdateFrame();
  619. // Polling becomes expensive if it's not slept.
  620. Thread.Sleep(1);
  621. }
  622. }
  623. private unsafe void RenderLoop()
  624. {
  625. Dispatcher.UIThread.InvokeAsync(() =>
  626. {
  627. if (_viewModel.StartGamesInFullscreen)
  628. {
  629. _viewModel.WindowState = WindowState.FullScreen;
  630. }
  631. if (_viewModel.WindowState == WindowState.FullScreen)
  632. {
  633. _viewModel.ShowMenuAndStatusBar = false;
  634. }
  635. });
  636. _renderer = Device.Gpu.Renderer is ThreadedRenderer tr ? tr.BaseRenderer : Device.Gpu.Renderer;
  637. _renderer.ScreenCaptured += Renderer_ScreenCaptured;
  638. (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.InitializeBackgroundContext(_renderer);
  639. Device.Gpu.Renderer.Initialize(_glLogLevel);
  640. Width = (int)_rendererHost.Bounds.Width;
  641. Height = (int)_rendererHost.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(() => (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.SwapBuffers());
  667. }
  668. if (_ticks >= _ticksPerFrame)
  669. {
  670. UpdateStatus();
  671. }
  672. }
  673. });
  674. (_rendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.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. ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.Vulkan ? "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. }