AppHost.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. using Avalonia;
  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.Configuration.Multiplayer;
  23. using Ryujinx.Common.Logging;
  24. using Ryujinx.Common.SystemInterop;
  25. using Ryujinx.Common.Utilities;
  26. using Ryujinx.Graphics.GAL;
  27. using Ryujinx.Graphics.GAL.Multithreading;
  28. using Ryujinx.Graphics.Gpu;
  29. using Ryujinx.Graphics.OpenGL;
  30. using Ryujinx.Graphics.Vulkan;
  31. using Ryujinx.HLE;
  32. using Ryujinx.HLE.FileSystem;
  33. using Ryujinx.HLE.HOS;
  34. using Ryujinx.HLE.HOS.Services.Account.Acc;
  35. using Ryujinx.HLE.HOS.SystemState;
  36. using Ryujinx.Input;
  37. using Ryujinx.Input.HLE;
  38. using Ryujinx.UI.App.Common;
  39. using Ryujinx.UI.Common;
  40. using Ryujinx.UI.Common.Configuration;
  41. using Ryujinx.UI.Common.Helper;
  42. using Silk.NET.Vulkan;
  43. using SkiaSharp;
  44. using SPB.Graphics.Vulkan;
  45. using System;
  46. using System.Collections.Generic;
  47. using System.Diagnostics;
  48. using System.IO;
  49. using System.Runtime.InteropServices;
  50. using System.Threading;
  51. using System.Threading.Tasks;
  52. using static Ryujinx.Ava.UI.Helpers.Win32NativeInterop;
  53. using AntiAliasing = Ryujinx.Common.Configuration.AntiAliasing;
  54. using InputManager = Ryujinx.Input.HLE.InputManager;
  55. using IRenderer = Ryujinx.Graphics.GAL.IRenderer;
  56. using Key = Ryujinx.Input.Key;
  57. using MouseButton = Ryujinx.Input.MouseButton;
  58. using ScalingFilter = Ryujinx.Common.Configuration.ScalingFilter;
  59. using Size = Avalonia.Size;
  60. using Switch = Ryujinx.HLE.Switch;
  61. namespace Ryujinx.Ava
  62. {
  63. internal class AppHost
  64. {
  65. private const int CursorHideIdleTime = 5; // Hide Cursor seconds.
  66. private const float MaxResolutionScale = 4.0f; // Max resolution hotkeys can scale to before wrapping.
  67. private const int TargetFps = 60;
  68. private const float VolumeDelta = 0.05f;
  69. private static readonly Cursor _invisibleCursor = new(StandardCursorType.None);
  70. private readonly IntPtr _invisibleCursorWin;
  71. private readonly IntPtr _defaultCursorWin;
  72. private readonly long _ticksPerFrame;
  73. private readonly Stopwatch _chrono;
  74. private long _ticks;
  75. private readonly AccountManager _accountManager;
  76. private readonly UserChannelPersistence _userChannelPersistence;
  77. private readonly InputManager _inputManager;
  78. private readonly MainWindowViewModel _viewModel;
  79. private readonly IKeyboard _keyboardInterface;
  80. private readonly TopLevel _topLevel;
  81. public RendererHost RendererHost;
  82. private readonly GraphicsDebugLevel _glLogLevel;
  83. private float _newVolume;
  84. private KeyboardHotkeyState _prevHotkeyState;
  85. private long _lastCursorMoveTime;
  86. private bool _isCursorInRenderer = true;
  87. private bool _ignoreCursorState = false;
  88. private enum CursorStates
  89. {
  90. CursorIsHidden,
  91. CursorIsVisible,
  92. ForceChangeCursor
  93. };
  94. private CursorStates _cursorState = !ConfigurationState.Instance.Hid.EnableMouse.Value ?
  95. CursorStates.CursorIsVisible : CursorStates.CursorIsHidden;
  96. private bool _isStopped;
  97. private bool _isActive;
  98. private bool _renderingStarted;
  99. private readonly ManualResetEvent _gpuDoneEvent;
  100. private IRenderer _renderer;
  101. private readonly Thread _renderingThread;
  102. private readonly CancellationTokenSource _gpuCancellationTokenSource;
  103. private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  104. private bool _dialogShown;
  105. private readonly bool _isFirmwareTitle;
  106. private readonly object _lockObject = new();
  107. public event EventHandler AppExit;
  108. public event EventHandler<StatusInitEventArgs> StatusInitEvent;
  109. public event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  110. public VirtualFileSystem VirtualFileSystem { get; }
  111. public ContentManager ContentManager { get; }
  112. public NpadManager NpadManager { get; }
  113. public TouchScreenManager TouchScreenManager { get; }
  114. public Switch Device { get; set; }
  115. public int Width { get; private set; }
  116. public int Height { get; private set; }
  117. public string ApplicationPath { get; private set; }
  118. public ulong ApplicationId { get; private set; }
  119. public bool ScreenshotRequested { get; set; }
  120. public AppHost(
  121. RendererHost renderer,
  122. InputManager inputManager,
  123. string applicationPath,
  124. ulong applicationId,
  125. VirtualFileSystem virtualFileSystem,
  126. ContentManager contentManager,
  127. AccountManager accountManager,
  128. UserChannelPersistence userChannelPersistence,
  129. MainWindowViewModel viewmodel,
  130. TopLevel topLevel)
  131. {
  132. _viewModel = viewmodel;
  133. _inputManager = inputManager;
  134. _accountManager = accountManager;
  135. _userChannelPersistence = userChannelPersistence;
  136. _renderingThread = new Thread(RenderLoop) { Name = "GUI.RenderThread" };
  137. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  138. _glLogLevel = ConfigurationState.Instance.Logger.GraphicsDebugLevel;
  139. _topLevel = topLevel;
  140. _inputManager.SetMouseDriver(new AvaloniaMouseDriver(_topLevel, renderer));
  141. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  142. NpadManager = _inputManager.CreateNpadManager();
  143. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  144. ApplicationPath = applicationPath;
  145. ApplicationId = applicationId;
  146. VirtualFileSystem = virtualFileSystem;
  147. ContentManager = contentManager;
  148. RendererHost = renderer;
  149. _chrono = new Stopwatch();
  150. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  151. if (ApplicationPath.StartsWith("@SystemContent"))
  152. {
  153. ApplicationPath = VirtualFileSystem.SwitchPathToSystemPath(ApplicationPath);
  154. _isFirmwareTitle = true;
  155. }
  156. ConfigurationState.Instance.HideCursor.Event += HideCursorState_Changed;
  157. _topLevel.PointerMoved += TopLevel_PointerEnteredOrMoved;
  158. _topLevel.PointerEntered += TopLevel_PointerEnteredOrMoved;
  159. _topLevel.PointerExited += TopLevel_PointerExited;
  160. if (OperatingSystem.IsWindows())
  161. {
  162. _invisibleCursorWin = CreateEmptyCursor();
  163. _defaultCursorWin = CreateArrowCursor();
  164. }
  165. ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
  166. ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
  167. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  168. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  169. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  170. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  171. ConfigurationState.Instance.Graphics.AntiAliasing.Event += UpdateAntiAliasing;
  172. ConfigurationState.Instance.Graphics.ScalingFilter.Event += UpdateScalingFilter;
  173. ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event += UpdateScalingFilterLevel;
  174. ConfigurationState.Instance.Graphics.EnableColorSpacePassthrough.Event += UpdateColorSpacePassthrough;
  175. ConfigurationState.Instance.System.EnableInternetAccess.Event += UpdateEnableInternetAccessState;
  176. ConfigurationState.Instance.Multiplayer.LanInterfaceId.Event += UpdateLanInterfaceIdState;
  177. ConfigurationState.Instance.Multiplayer.Mode.Event += UpdateMultiplayerModeState;
  178. _gpuCancellationTokenSource = new CancellationTokenSource();
  179. _gpuDoneEvent = new ManualResetEvent(false);
  180. }
  181. private void TopLevel_PointerEnteredOrMoved(object sender, PointerEventArgs e)
  182. {
  183. if (!_viewModel.IsActive)
  184. {
  185. _isCursorInRenderer = false;
  186. _ignoreCursorState = false;
  187. return;
  188. }
  189. if (sender is MainWindow window)
  190. {
  191. if (ConfigurationState.Instance.HideCursor.Value == HideCursorMode.OnIdle)
  192. {
  193. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  194. }
  195. var point = e.GetCurrentPoint(window).Position;
  196. var bounds = RendererHost.EmbeddedWindow.Bounds;
  197. var windowYOffset = bounds.Y + window.MenuBarHeight;
  198. var windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1;
  199. if (!_viewModel.ShowMenuAndStatusBar)
  200. {
  201. windowYOffset -= window.MenuBarHeight;
  202. windowYLimit += window.StatusBarHeight + 1;
  203. }
  204. _isCursorInRenderer = point.X >= bounds.X &&
  205. Math.Ceiling(point.X) <= (int)window.Bounds.Width &&
  206. point.Y >= windowYOffset &&
  207. point.Y <= windowYLimit &&
  208. !_viewModel.IsSubMenuOpen;
  209. _ignoreCursorState = false;
  210. }
  211. }
  212. private void TopLevel_PointerExited(object sender, PointerEventArgs e)
  213. {
  214. _isCursorInRenderer = false;
  215. if (sender is MainWindow window)
  216. {
  217. var point = e.GetCurrentPoint(window).Position;
  218. var bounds = RendererHost.EmbeddedWindow.Bounds;
  219. var windowYOffset = bounds.Y + window.MenuBarHeight;
  220. var windowYLimit = (int)window.Bounds.Height - window.StatusBarHeight - 1;
  221. if (!_viewModel.ShowMenuAndStatusBar)
  222. {
  223. windowYOffset -= window.MenuBarHeight;
  224. windowYLimit += window.StatusBarHeight + 1;
  225. }
  226. _ignoreCursorState = (point.X == bounds.X ||
  227. Math.Ceiling(point.X) == (int)window.Bounds.Width) &&
  228. point.Y >= windowYOffset &&
  229. point.Y <= windowYLimit;
  230. }
  231. _cursorState = CursorStates.ForceChangeCursor;
  232. }
  233. private void UpdateScalingFilterLevel(object sender, ReactiveEventArgs<int> e)
  234. {
  235. _renderer.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value);
  236. _renderer.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value);
  237. }
  238. private void UpdateScalingFilter(object sender, ReactiveEventArgs<ScalingFilter> e)
  239. {
  240. _renderer.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value);
  241. _renderer.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value);
  242. }
  243. private void UpdateColorSpacePassthrough(object sender, ReactiveEventArgs<bool> e)
  244. {
  245. _renderer.Window?.SetColorSpacePassthrough((bool)ConfigurationState.Instance.Graphics.EnableColorSpacePassthrough.Value);
  246. }
  247. private void ShowCursor()
  248. {
  249. Dispatcher.UIThread.Post(() =>
  250. {
  251. _viewModel.Cursor = Cursor.Default;
  252. if (OperatingSystem.IsWindows())
  253. {
  254. if (_cursorState != CursorStates.CursorIsHidden && !_ignoreCursorState)
  255. {
  256. SetCursor(_defaultCursorWin);
  257. }
  258. }
  259. });
  260. _cursorState = CursorStates.CursorIsVisible;
  261. }
  262. private void HideCursor()
  263. {
  264. Dispatcher.UIThread.Post(() =>
  265. {
  266. _viewModel.Cursor = _invisibleCursor;
  267. if (OperatingSystem.IsWindows())
  268. {
  269. SetCursor(_invisibleCursorWin);
  270. }
  271. });
  272. _cursorState = CursorStates.CursorIsHidden;
  273. }
  274. private void SetRendererWindowSize(Size size)
  275. {
  276. if (_renderer != null)
  277. {
  278. double scale = _topLevel.RenderScaling;
  279. _renderer.Window?.SetSize((int)(size.Width * scale), (int)(size.Height * scale));
  280. }
  281. }
  282. private void Renderer_ScreenCaptured(object sender, ScreenCaptureImageInfo e)
  283. {
  284. if (e.Data.Length > 0 && e.Height > 0 && e.Width > 0)
  285. {
  286. Task.Run(() =>
  287. {
  288. lock (_lockObject)
  289. {
  290. string applicationName = Device.Processes.ActiveApplication.Name;
  291. string sanitizedApplicationName = FileSystemUtils.SanitizeFileName(applicationName);
  292. DateTime currentTime = DateTime.Now;
  293. string filename = $"{sanitizedApplicationName}_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png";
  294. string directory = AppDataManager.Mode switch
  295. {
  296. AppDataManager.LaunchMode.Portable or AppDataManager.LaunchMode.Custom => Path.Combine(AppDataManager.BaseDirPath, "screenshots"),
  297. _ => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx"),
  298. };
  299. string path = Path.Combine(directory, filename);
  300. try
  301. {
  302. Directory.CreateDirectory(directory);
  303. }
  304. catch (Exception ex)
  305. {
  306. Logger.Error?.Print(LogClass.Application, $"Failed to create directory at path {directory}. Error : {ex.GetType().Name}", "Screenshot");
  307. return;
  308. }
  309. var colorType = e.IsBgra ? SKColorType.Bgra8888 : SKColorType.Rgba8888;
  310. using var bitmap = new SKBitmap(new SKImageInfo(e.Width, e.Height, colorType, SKAlphaType.Premul));
  311. Marshal.Copy(e.Data, 0, bitmap.GetPixels(), e.Data.Length);
  312. SKBitmap bitmapToSave = null;
  313. if (e.FlipX || e.FlipY)
  314. {
  315. bitmapToSave = new SKBitmap(bitmap.Width, bitmap.Height);
  316. using var canvas = new SKCanvas(bitmapToSave);
  317. canvas.Clear(SKColors.Transparent);
  318. float scaleX = e.FlipX ? -1 : 1;
  319. float scaleY = e.FlipY ? -1 : 1;
  320. var matrix = SKMatrix.CreateScale(scaleX, scaleY, bitmap.Width / 2f, bitmap.Height / 2f);
  321. canvas.SetMatrix(matrix);
  322. canvas.DrawBitmap(bitmap, new SKPoint(e.FlipX ? -bitmap.Width : 0, e.FlipY ? -bitmap.Height : 0));
  323. }
  324. SaveBitmapAsPng(bitmapToSave ?? bitmap, path);
  325. bitmapToSave?.Dispose();
  326. Logger.Notice.Print(LogClass.Application, $"Screenshot saved to {path}", "Screenshot");
  327. }
  328. });
  329. }
  330. else
  331. {
  332. Logger.Error?.Print(LogClass.Application, $"Screenshot is empty. Size : {e.Data.Length} bytes. Resolution : {e.Width}x{e.Height}", "Screenshot");
  333. }
  334. }
  335. private void SaveBitmapAsPng(SKBitmap bitmap, string path)
  336. {
  337. using var data = bitmap.Encode(SKEncodedImageFormat.Png, 100);
  338. using var stream = File.OpenWrite(path);
  339. data.SaveTo(stream);
  340. }
  341. public void Start()
  342. {
  343. if (OperatingSystem.IsWindows())
  344. {
  345. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  346. }
  347. DisplaySleep.Prevent();
  348. NpadManager.Initialize(Device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  349. TouchScreenManager.Initialize(Device);
  350. _viewModel.IsGameRunning = true;
  351. Dispatcher.UIThread.InvokeAsync(() =>
  352. {
  353. _viewModel.Title = TitleHelper.ActiveApplicationTitle(Device.Processes.ActiveApplication, Program.Version);
  354. });
  355. _viewModel.SetUiProgressHandlers(Device);
  356. RendererHost.BoundsChanged += Window_BoundsChanged;
  357. _isActive = true;
  358. _renderingThread.Start();
  359. _viewModel.Volume = ConfigurationState.Instance.System.AudioVolume.Value;
  360. MainLoop();
  361. Exit();
  362. }
  363. private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
  364. {
  365. if (Device != null)
  366. {
  367. Device.Configuration.IgnoreMissingServices = args.NewValue;
  368. }
  369. }
  370. private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
  371. {
  372. if (Device != null)
  373. {
  374. Device.Configuration.AspectRatio = args.NewValue;
  375. }
  376. }
  377. private void UpdateAntiAliasing(object sender, ReactiveEventArgs<AntiAliasing> e)
  378. {
  379. _renderer?.Window?.SetAntiAliasing((Graphics.GAL.AntiAliasing)e.NewValue);
  380. }
  381. private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
  382. {
  383. Device?.System.ChangeDockedModeState(e.NewValue);
  384. }
  385. private void UpdateAudioVolumeState(object sender, ReactiveEventArgs<float> e)
  386. {
  387. Device?.SetVolume(e.NewValue);
  388. Dispatcher.UIThread.Post(() =>
  389. {
  390. _viewModel.Volume = e.NewValue;
  391. });
  392. }
  393. private void UpdateEnableInternetAccessState(object sender, ReactiveEventArgs<bool> e)
  394. {
  395. Device.Configuration.EnableInternetAccess = e.NewValue;
  396. }
  397. private void UpdateLanInterfaceIdState(object sender, ReactiveEventArgs<string> e)
  398. {
  399. Device.Configuration.MultiplayerLanInterfaceId = e.NewValue;
  400. }
  401. private void UpdateMultiplayerModeState(object sender, ReactiveEventArgs<MultiplayerMode> e)
  402. {
  403. Device.Configuration.MultiplayerMode = e.NewValue;
  404. }
  405. public void ToggleVSync()
  406. {
  407. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  408. _renderer.Window.ChangeVSyncMode(Device.EnableDeviceVsync);
  409. }
  410. public void Stop()
  411. {
  412. _isActive = false;
  413. }
  414. private void Exit()
  415. {
  416. (_keyboardInterface as AvaloniaKeyboard)?.Clear();
  417. if (_isStopped)
  418. {
  419. return;
  420. }
  421. _isStopped = true;
  422. _isActive = false;
  423. }
  424. public void DisposeContext()
  425. {
  426. Dispose();
  427. _isActive = false;
  428. // NOTE: The render loop is allowed to stay alive until the renderer itself is disposed, as it may handle resource dispose.
  429. // We only need to wait for all commands submitted during the main gpu loop to be processed.
  430. _gpuDoneEvent.WaitOne();
  431. _gpuDoneEvent.Dispose();
  432. DisplaySleep.Restore();
  433. NpadManager.Dispose();
  434. TouchScreenManager.Dispose();
  435. Device.Dispose();
  436. DisposeGpu();
  437. AppExit?.Invoke(this, EventArgs.Empty);
  438. }
  439. private void Dispose()
  440. {
  441. if (Device.Processes != null)
  442. {
  443. MainWindowViewModel.UpdateGameMetadata(Device.Processes.ActiveApplication.ProgramIdText);
  444. }
  445. ConfigurationState.Instance.System.IgnoreMissingServices.Event -= UpdateIgnoreMissingServicesState;
  446. ConfigurationState.Instance.Graphics.AspectRatio.Event -= UpdateAspectRatioState;
  447. ConfigurationState.Instance.System.EnableDockedMode.Event -= UpdateDockedModeState;
  448. ConfigurationState.Instance.System.AudioVolume.Event -= UpdateAudioVolumeState;
  449. ConfigurationState.Instance.Graphics.ScalingFilter.Event -= UpdateScalingFilter;
  450. ConfigurationState.Instance.Graphics.ScalingFilterLevel.Event -= UpdateScalingFilterLevel;
  451. ConfigurationState.Instance.Graphics.AntiAliasing.Event -= UpdateAntiAliasing;
  452. ConfigurationState.Instance.Graphics.EnableColorSpacePassthrough.Event -= UpdateColorSpacePassthrough;
  453. _topLevel.PointerMoved -= TopLevel_PointerEnteredOrMoved;
  454. _topLevel.PointerEntered -= TopLevel_PointerEnteredOrMoved;
  455. _topLevel.PointerExited -= TopLevel_PointerExited;
  456. _gpuCancellationTokenSource.Cancel();
  457. _gpuCancellationTokenSource.Dispose();
  458. _chrono.Stop();
  459. }
  460. public void DisposeGpu()
  461. {
  462. if (OperatingSystem.IsWindows())
  463. {
  464. _windowsMultimediaTimerResolution?.Dispose();
  465. _windowsMultimediaTimerResolution = null;
  466. }
  467. if (RendererHost.EmbeddedWindow is EmbeddedWindowOpenGL openGlWindow)
  468. {
  469. // Try to bind the OpenGL context before calling the shutdown event.
  470. openGlWindow.MakeCurrent(false, false);
  471. Device.DisposeGpu();
  472. // Unbind context and destroy everything.
  473. openGlWindow.MakeCurrent(true, false);
  474. }
  475. else
  476. {
  477. Device.DisposeGpu();
  478. }
  479. }
  480. private void HideCursorState_Changed(object sender, ReactiveEventArgs<HideCursorMode> state)
  481. {
  482. if (state.NewValue == HideCursorMode.OnIdle)
  483. {
  484. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  485. }
  486. _cursorState = CursorStates.ForceChangeCursor;
  487. }
  488. public async Task<bool> LoadGuestApplication()
  489. {
  490. InitializeSwitchInstance();
  491. MainWindow.UpdateGraphicsConfig();
  492. SystemVersion firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  493. if (Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  494. {
  495. if (!SetupValidator.CanStartApplication(ContentManager, ApplicationPath, out UserError userError))
  496. {
  497. {
  498. if (SetupValidator.CanFixStartApplication(ContentManager, ApplicationPath, userError, out firmwareVersion))
  499. {
  500. if (userError == UserError.NoFirmware)
  501. {
  502. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  503. LocaleManager.Instance[LocaleKeys.DialogFirmwareNoFirmwareInstalledMessage],
  504. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallEmbeddedMessage, firmwareVersion.VersionString),
  505. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  506. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  507. "");
  508. if (result != UserResult.Yes)
  509. {
  510. await UserErrorDialog.ShowUserErrorDialog(userError);
  511. Device.Dispose();
  512. return false;
  513. }
  514. }
  515. if (!SetupValidator.TryFixStartApplication(ContentManager, ApplicationPath, userError, out _))
  516. {
  517. await UserErrorDialog.ShowUserErrorDialog(userError);
  518. Device.Dispose();
  519. return false;
  520. }
  521. // Tell the user that we installed a firmware for them.
  522. if (userError == UserError.NoFirmware)
  523. {
  524. firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  525. _viewModel.RefreshFirmwareStatus();
  526. await ContentDialogHelper.CreateInfoDialog(
  527. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstalledMessage, firmwareVersion.VersionString),
  528. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallEmbeddedSuccessMessage, firmwareVersion.VersionString),
  529. LocaleManager.Instance[LocaleKeys.InputDialogOk],
  530. "",
  531. LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  532. }
  533. }
  534. else
  535. {
  536. await UserErrorDialog.ShowUserErrorDialog(userError);
  537. Device.Dispose();
  538. return false;
  539. }
  540. }
  541. }
  542. }
  543. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  544. if (_isFirmwareTitle)
  545. {
  546. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  547. if (!Device.LoadNca(ApplicationPath))
  548. {
  549. Device.Dispose();
  550. return false;
  551. }
  552. }
  553. else if (Directory.Exists(ApplicationPath))
  554. {
  555. string[] romFsFiles = Directory.GetFiles(ApplicationPath, "*.istorage");
  556. if (romFsFiles.Length == 0)
  557. {
  558. romFsFiles = Directory.GetFiles(ApplicationPath, "*.romfs");
  559. }
  560. if (romFsFiles.Length > 0)
  561. {
  562. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  563. if (!Device.LoadCart(ApplicationPath, romFsFiles[0]))
  564. {
  565. Device.Dispose();
  566. return false;
  567. }
  568. }
  569. else
  570. {
  571. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  572. if (!Device.LoadCart(ApplicationPath))
  573. {
  574. Device.Dispose();
  575. return false;
  576. }
  577. }
  578. }
  579. else if (File.Exists(ApplicationPath))
  580. {
  581. switch (Path.GetExtension(ApplicationPath).ToLowerInvariant())
  582. {
  583. case ".xci":
  584. {
  585. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  586. if (!Device.LoadXci(ApplicationPath, ApplicationId))
  587. {
  588. Device.Dispose();
  589. return false;
  590. }
  591. break;
  592. }
  593. case ".nca":
  594. {
  595. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  596. if (!Device.LoadNca(ApplicationPath))
  597. {
  598. Device.Dispose();
  599. return false;
  600. }
  601. break;
  602. }
  603. case ".nsp":
  604. case ".pfs0":
  605. {
  606. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  607. if (!Device.LoadNsp(ApplicationPath, ApplicationId))
  608. {
  609. Device.Dispose();
  610. return false;
  611. }
  612. break;
  613. }
  614. default:
  615. {
  616. Logger.Info?.Print(LogClass.Application, "Loading as homebrew.");
  617. try
  618. {
  619. if (!Device.LoadProgram(ApplicationPath))
  620. {
  621. Device.Dispose();
  622. return false;
  623. }
  624. }
  625. catch (ArgumentOutOfRangeException)
  626. {
  627. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  628. Device.Dispose();
  629. return false;
  630. }
  631. break;
  632. }
  633. }
  634. }
  635. else
  636. {
  637. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  638. Device.Dispose();
  639. return false;
  640. }
  641. DiscordIntegrationModule.SwitchToPlayingState(Device.Processes.ActiveApplication.ProgramIdText, Device.Processes.ActiveApplication.Name);
  642. ApplicationLibrary.LoadAndSaveMetaData(Device.Processes.ActiveApplication.ProgramIdText, appMetadata =>
  643. {
  644. appMetadata.UpdatePreGame();
  645. });
  646. return true;
  647. }
  648. internal void Resume()
  649. {
  650. Device?.System.TogglePauseEmulation(false);
  651. _viewModel.IsPaused = false;
  652. _viewModel.Title = TitleHelper.ActiveApplicationTitle(Device?.Processes.ActiveApplication, Program.Version);
  653. Logger.Info?.Print(LogClass.Emulation, "Emulation was resumed");
  654. }
  655. internal void Pause()
  656. {
  657. Device?.System.TogglePauseEmulation(true);
  658. _viewModel.IsPaused = true;
  659. _viewModel.Title = TitleHelper.ActiveApplicationTitle(Device?.Processes.ActiveApplication, Program.Version, LocaleManager.Instance[LocaleKeys.Paused]);
  660. Logger.Info?.Print(LogClass.Emulation, "Emulation was paused");
  661. }
  662. private void InitializeSwitchInstance()
  663. {
  664. // Initialize KeySet.
  665. VirtualFileSystem.ReloadKeySet();
  666. // Initialize Renderer.
  667. IRenderer renderer;
  668. if (ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.Vulkan)
  669. {
  670. renderer = new VulkanRenderer(
  671. Vk.GetApi(),
  672. (RendererHost.EmbeddedWindow as EmbeddedWindowVulkan).CreateSurface,
  673. VulkanHelper.GetRequiredInstanceExtensions,
  674. ConfigurationState.Instance.Graphics.PreferredGpu.Value);
  675. }
  676. else
  677. {
  678. renderer = new OpenGLRenderer();
  679. }
  680. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  681. var isGALThreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  682. if (isGALThreaded)
  683. {
  684. renderer = new ThreadedRenderer(renderer);
  685. }
  686. Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALThreaded}");
  687. // Initialize Configuration.
  688. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value ? MemoryConfiguration.MemoryConfiguration6GiB : MemoryConfiguration.MemoryConfiguration4GiB;
  689. HLEConfiguration configuration = new(VirtualFileSystem,
  690. _viewModel.LibHacHorizonManager,
  691. ContentManager,
  692. _accountManager,
  693. _userChannelPersistence,
  694. renderer,
  695. InitializeAudio(),
  696. memoryConfiguration,
  697. _viewModel.UiHandler,
  698. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  699. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  700. ConfigurationState.Instance.Graphics.EnableVsync,
  701. ConfigurationState.Instance.System.EnableDockedMode,
  702. ConfigurationState.Instance.System.EnablePtc,
  703. ConfigurationState.Instance.System.EnableInternetAccess,
  704. ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None,
  705. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  706. ConfigurationState.Instance.System.SystemTimeOffset,
  707. ConfigurationState.Instance.System.TimeZone,
  708. ConfigurationState.Instance.System.MemoryManagerMode,
  709. ConfigurationState.Instance.System.IgnoreMissingServices,
  710. ConfigurationState.Instance.Graphics.AspectRatio,
  711. ConfigurationState.Instance.System.AudioVolume,
  712. ConfigurationState.Instance.System.UseHypervisor,
  713. ConfigurationState.Instance.Multiplayer.LanInterfaceId.Value,
  714. ConfigurationState.Instance.Multiplayer.Mode);
  715. Device = new Switch(configuration);
  716. }
  717. private static IHardwareDeviceDriver InitializeAudio()
  718. {
  719. var availableBackends = new List<AudioBackend>
  720. {
  721. AudioBackend.SDL2,
  722. AudioBackend.SoundIo,
  723. AudioBackend.OpenAl,
  724. AudioBackend.Dummy,
  725. };
  726. AudioBackend preferredBackend = ConfigurationState.Instance.System.AudioBackend.Value;
  727. for (int i = 0; i < availableBackends.Count; i++)
  728. {
  729. if (availableBackends[i] == preferredBackend)
  730. {
  731. availableBackends.RemoveAt(i);
  732. availableBackends.Insert(0, preferredBackend);
  733. break;
  734. }
  735. }
  736. static IHardwareDeviceDriver InitializeAudioBackend<T>(AudioBackend backend, AudioBackend nextBackend) where T : IHardwareDeviceDriver, new()
  737. {
  738. if (T.IsSupported)
  739. {
  740. return new T();
  741. }
  742. Logger.Warning?.Print(LogClass.Audio, $"{backend} is not supported, falling back to {nextBackend}.");
  743. return null;
  744. }
  745. IHardwareDeviceDriver deviceDriver = null;
  746. for (int i = 0; i < availableBackends.Count; i++)
  747. {
  748. AudioBackend currentBackend = availableBackends[i];
  749. AudioBackend nextBackend = i + 1 < availableBackends.Count ? availableBackends[i + 1] : AudioBackend.Dummy;
  750. deviceDriver = currentBackend switch
  751. {
  752. AudioBackend.SDL2 => InitializeAudioBackend<SDL2HardwareDeviceDriver>(AudioBackend.SDL2, nextBackend),
  753. AudioBackend.SoundIo => InitializeAudioBackend<SoundIoHardwareDeviceDriver>(AudioBackend.SoundIo, nextBackend),
  754. AudioBackend.OpenAl => InitializeAudioBackend<OpenALHardwareDeviceDriver>(AudioBackend.OpenAl, nextBackend),
  755. _ => new DummyHardwareDeviceDriver(),
  756. };
  757. if (deviceDriver != null)
  758. {
  759. ConfigurationState.Instance.System.AudioBackend.Value = currentBackend;
  760. break;
  761. }
  762. }
  763. MainWindowViewModel.SaveConfig();
  764. return deviceDriver;
  765. }
  766. private void Window_BoundsChanged(object sender, Size e)
  767. {
  768. Width = (int)e.Width;
  769. Height = (int)e.Height;
  770. SetRendererWindowSize(e);
  771. }
  772. private void MainLoop()
  773. {
  774. while (_isActive)
  775. {
  776. UpdateFrame();
  777. // Polling becomes expensive if it's not slept.
  778. Thread.Sleep(1);
  779. }
  780. }
  781. private void RenderLoop()
  782. {
  783. Dispatcher.UIThread.InvokeAsync(() =>
  784. {
  785. if (_viewModel.StartGamesInFullscreen)
  786. {
  787. _viewModel.WindowState = WindowState.FullScreen;
  788. }
  789. if (_viewModel.WindowState == WindowState.FullScreen)
  790. {
  791. _viewModel.ShowMenuAndStatusBar = false;
  792. }
  793. });
  794. _renderer = Device.Gpu.Renderer is ThreadedRenderer tr ? tr.BaseRenderer : Device.Gpu.Renderer;
  795. _renderer.ScreenCaptured += Renderer_ScreenCaptured;
  796. (RendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.InitializeBackgroundContext(_renderer);
  797. Device.Gpu.Renderer.Initialize(_glLogLevel);
  798. _renderer?.Window?.SetAntiAliasing((Graphics.GAL.AntiAliasing)ConfigurationState.Instance.Graphics.AntiAliasing.Value);
  799. _renderer?.Window?.SetScalingFilter((Graphics.GAL.ScalingFilter)ConfigurationState.Instance.Graphics.ScalingFilter.Value);
  800. _renderer?.Window?.SetScalingFilterLevel(ConfigurationState.Instance.Graphics.ScalingFilterLevel.Value);
  801. _renderer?.Window?.SetColorSpacePassthrough(ConfigurationState.Instance.Graphics.EnableColorSpacePassthrough.Value);
  802. Width = (int)RendererHost.Bounds.Width;
  803. Height = (int)RendererHost.Bounds.Height;
  804. _renderer.Window.SetSize((int)(Width * _topLevel.RenderScaling), (int)(Height * _topLevel.RenderScaling));
  805. _chrono.Start();
  806. Device.Gpu.Renderer.RunLoop(() =>
  807. {
  808. Device.Gpu.SetGpuThread();
  809. Device.Gpu.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  810. _renderer.Window.ChangeVSyncMode(Device.EnableDeviceVsync);
  811. while (_isActive)
  812. {
  813. _ticks += _chrono.ElapsedTicks;
  814. _chrono.Restart();
  815. if (Device.WaitFifo())
  816. {
  817. Device.Statistics.RecordFifoStart();
  818. Device.ProcessFrame();
  819. Device.Statistics.RecordFifoEnd();
  820. }
  821. while (Device.ConsumeFrameAvailable())
  822. {
  823. if (!_renderingStarted)
  824. {
  825. _renderingStarted = true;
  826. _viewModel.SwitchToRenderer(false);
  827. InitStatus();
  828. }
  829. Device.PresentFrame(() => (RendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.SwapBuffers());
  830. }
  831. if (_ticks >= _ticksPerFrame)
  832. {
  833. UpdateStatus();
  834. }
  835. }
  836. // Make sure all commands in the run loop are fully executed before leaving the loop.
  837. if (Device.Gpu.Renderer is ThreadedRenderer threaded)
  838. {
  839. threaded.FlushThreadedCommands();
  840. }
  841. _gpuDoneEvent.Set();
  842. });
  843. (RendererHost.EmbeddedWindow as EmbeddedWindowOpenGL)?.MakeCurrent(true);
  844. }
  845. public void InitStatus()
  846. {
  847. StatusInitEvent?.Invoke(this, new StatusInitEventArgs(
  848. ConfigurationState.Instance.Graphics.GraphicsBackend.Value switch
  849. {
  850. GraphicsBackend.Vulkan => "Vulkan",
  851. GraphicsBackend.OpenGl => "OpenGL",
  852. _ => throw new NotImplementedException()
  853. },
  854. $"GPU: {_renderer.GetHardwareInfo().GpuDriver}"));
  855. }
  856. public void UpdateStatus()
  857. {
  858. // 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.
  859. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? LocaleManager.Instance[LocaleKeys.Docked] : LocaleManager.Instance[LocaleKeys.Handheld];
  860. if (GraphicsConfig.ResScale != 1)
  861. {
  862. dockedMode += $" ({GraphicsConfig.ResScale}x)";
  863. }
  864. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  865. Device.EnableDeviceVsync,
  866. LocaleManager.Instance[LocaleKeys.VolumeShort] + $": {(int)(Device.GetVolume() * 100)}%",
  867. dockedMode,
  868. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  869. LocaleManager.Instance[LocaleKeys.Game] + $": {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  870. $"FIFO: {Device.Statistics.GetFifoPercent():00.00} %"));
  871. }
  872. public async Task ShowExitPrompt()
  873. {
  874. bool shouldExit = !ConfigurationState.Instance.ShowConfirmExit;
  875. if (!shouldExit)
  876. {
  877. if (_dialogShown)
  878. {
  879. return;
  880. }
  881. _dialogShown = true;
  882. shouldExit = await ContentDialogHelper.CreateStopEmulationDialog();
  883. _dialogShown = false;
  884. }
  885. if (shouldExit)
  886. {
  887. Stop();
  888. }
  889. }
  890. private bool UpdateFrame()
  891. {
  892. if (!_isActive)
  893. {
  894. return false;
  895. }
  896. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  897. if (_viewModel.IsActive)
  898. {
  899. bool isCursorVisible = true;
  900. if (_isCursorInRenderer && !_viewModel.ShowLoadProgress)
  901. {
  902. if (ConfigurationState.Instance.Hid.EnableMouse.Value)
  903. {
  904. isCursorVisible = ConfigurationState.Instance.HideCursor.Value == HideCursorMode.Never;
  905. }
  906. else
  907. {
  908. isCursorVisible = ConfigurationState.Instance.HideCursor.Value == HideCursorMode.Never ||
  909. (ConfigurationState.Instance.HideCursor.Value == HideCursorMode.OnIdle &&
  910. Stopwatch.GetTimestamp() - _lastCursorMoveTime < CursorHideIdleTime * Stopwatch.Frequency);
  911. }
  912. }
  913. if (_cursorState != (isCursorVisible ? CursorStates.CursorIsVisible : CursorStates.CursorIsHidden))
  914. {
  915. if (isCursorVisible)
  916. {
  917. ShowCursor();
  918. }
  919. else
  920. {
  921. HideCursor();
  922. }
  923. }
  924. Dispatcher.UIThread.Post(() =>
  925. {
  926. if (_keyboardInterface.GetKeyboardStateSnapshot().IsPressed(Key.Delete) && _viewModel.WindowState != WindowState.FullScreen)
  927. {
  928. Device.Processes.ActiveApplication.DiskCacheLoadState?.Cancel();
  929. }
  930. });
  931. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  932. if (currentHotkeyState != _prevHotkeyState)
  933. {
  934. switch (currentHotkeyState)
  935. {
  936. case KeyboardHotkeyState.ToggleVSync:
  937. ToggleVSync();
  938. break;
  939. case KeyboardHotkeyState.Screenshot:
  940. ScreenshotRequested = true;
  941. break;
  942. case KeyboardHotkeyState.ShowUI:
  943. _viewModel.ShowMenuAndStatusBar = !_viewModel.ShowMenuAndStatusBar;
  944. break;
  945. case KeyboardHotkeyState.Pause:
  946. if (_viewModel.IsPaused)
  947. {
  948. Resume();
  949. }
  950. else
  951. {
  952. Pause();
  953. }
  954. break;
  955. case KeyboardHotkeyState.ToggleMute:
  956. if (Device.IsAudioMuted())
  957. {
  958. Device.SetVolume(_viewModel.VolumeBeforeMute);
  959. }
  960. else
  961. {
  962. _viewModel.VolumeBeforeMute = Device.GetVolume();
  963. Device.SetVolume(0);
  964. }
  965. _viewModel.Volume = Device.GetVolume();
  966. break;
  967. case KeyboardHotkeyState.ResScaleUp:
  968. GraphicsConfig.ResScale = GraphicsConfig.ResScale % MaxResolutionScale + 1;
  969. break;
  970. case KeyboardHotkeyState.ResScaleDown:
  971. GraphicsConfig.ResScale =
  972. (MaxResolutionScale + GraphicsConfig.ResScale - 2) % MaxResolutionScale + 1;
  973. break;
  974. case KeyboardHotkeyState.VolumeUp:
  975. _newVolume = MathF.Round((Device.GetVolume() + VolumeDelta), 2);
  976. Device.SetVolume(_newVolume);
  977. _viewModel.Volume = Device.GetVolume();
  978. break;
  979. case KeyboardHotkeyState.VolumeDown:
  980. _newVolume = MathF.Round((Device.GetVolume() - VolumeDelta), 2);
  981. Device.SetVolume(_newVolume);
  982. _viewModel.Volume = Device.GetVolume();
  983. break;
  984. case KeyboardHotkeyState.None:
  985. (_keyboardInterface as AvaloniaKeyboard).Clear();
  986. break;
  987. }
  988. }
  989. _prevHotkeyState = currentHotkeyState;
  990. if (ScreenshotRequested)
  991. {
  992. ScreenshotRequested = false;
  993. _renderer.Screenshot();
  994. }
  995. }
  996. // Touchscreen.
  997. bool hasTouch = false;
  998. if (_viewModel.IsActive && !ConfigurationState.Instance.Hid.EnableMouse.Value)
  999. {
  1000. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as AvaloniaMouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  1001. }
  1002. if (!hasTouch)
  1003. {
  1004. Device.Hid.Touchscreen.Update();
  1005. }
  1006. Device.Hid.DebugPad.Update();
  1007. return true;
  1008. }
  1009. private KeyboardHotkeyState GetHotkeyState()
  1010. {
  1011. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  1012. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  1013. {
  1014. state = KeyboardHotkeyState.ToggleVSync;
  1015. }
  1016. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot))
  1017. {
  1018. state = KeyboardHotkeyState.Screenshot;
  1019. }
  1020. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUI))
  1021. {
  1022. state = KeyboardHotkeyState.ShowUI;
  1023. }
  1024. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause))
  1025. {
  1026. state = KeyboardHotkeyState.Pause;
  1027. }
  1028. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleMute))
  1029. {
  1030. state = KeyboardHotkeyState.ToggleMute;
  1031. }
  1032. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleUp))
  1033. {
  1034. state = KeyboardHotkeyState.ResScaleUp;
  1035. }
  1036. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleDown))
  1037. {
  1038. state = KeyboardHotkeyState.ResScaleDown;
  1039. }
  1040. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeUp))
  1041. {
  1042. state = KeyboardHotkeyState.VolumeUp;
  1043. }
  1044. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeDown))
  1045. {
  1046. state = KeyboardHotkeyState.VolumeDown;
  1047. }
  1048. return state;
  1049. }
  1050. }
  1051. }