RendererWidgetBase.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. using ARMeilleure.Translation;
  2. using Gdk;
  3. using Gtk;
  4. using Ryujinx.Common;
  5. using Ryujinx.Common.Configuration;
  6. using Ryujinx.Common.Logging;
  7. using Ryujinx.Ui.Common.Configuration;
  8. using Ryujinx.Graphics.Gpu;
  9. using Ryujinx.Graphics.GAL;
  10. using Ryujinx.Graphics.GAL.Multithreading;
  11. using Ryujinx.Input;
  12. using Ryujinx.Input.GTK3;
  13. using Ryujinx.Input.HLE;
  14. using Ryujinx.Ui.Widgets;
  15. using SixLabors.ImageSharp;
  16. using SixLabors.ImageSharp.Formats.Png;
  17. using SixLabors.ImageSharp.PixelFormats;
  18. using SixLabors.ImageSharp.Processing;
  19. using System;
  20. using System.Diagnostics;
  21. using System.IO;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. namespace Ryujinx.Ui
  25. {
  26. using Image = SixLabors.ImageSharp.Image;
  27. using Key = Input.Key;
  28. using Switch = HLE.Switch;
  29. public abstract class RendererWidgetBase : DrawingArea
  30. {
  31. private const int SwitchPanelWidth = 1280;
  32. private const int SwitchPanelHeight = 720;
  33. private const int TargetFps = 60;
  34. private const float MaxResolutionScale = 4.0f; // Max resolution hotkeys can scale to before wrapping.
  35. private const float VolumeDelta = 0.05f;
  36. public ManualResetEvent WaitEvent { get; set; }
  37. public NpadManager NpadManager { get; }
  38. public TouchScreenManager TouchScreenManager { get; }
  39. public Switch Device { get; private set; }
  40. public IRenderer Renderer { get; private set; }
  41. public bool ScreenshotRequested { get; set; }
  42. protected int WindowWidth { get; private set; }
  43. protected int WindowHeight { get; private set; }
  44. public static event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  45. private bool _isActive;
  46. private bool _isStopped;
  47. private bool _toggleFullscreen;
  48. private bool _toggleDockedMode;
  49. private readonly long _ticksPerFrame;
  50. private long _ticks = 0;
  51. private float _newVolume;
  52. private readonly Stopwatch _chrono;
  53. private KeyboardHotkeyState _prevHotkeyState;
  54. private readonly ManualResetEvent _exitEvent;
  55. private readonly CancellationTokenSource _gpuCancellationTokenSource;
  56. // Hide Cursor
  57. const int CursorHideIdleTime = 5; // seconds
  58. private static readonly Cursor _invisibleCursor = new Cursor(Display.Default, CursorType.BlankCursor);
  59. private long _lastCursorMoveTime;
  60. private bool _hideCursorOnIdle;
  61. private InputManager _inputManager;
  62. private IKeyboard _keyboardInterface;
  63. private GraphicsDebugLevel _glLogLevel;
  64. private string _gpuBackendName;
  65. private string _gpuVendorName;
  66. private bool _isMouseInClient;
  67. public RendererWidgetBase(InputManager inputManager, GraphicsDebugLevel glLogLevel)
  68. {
  69. var mouseDriver = new GTK3MouseDriver(this);
  70. _inputManager = inputManager;
  71. _inputManager.SetMouseDriver(mouseDriver);
  72. NpadManager = _inputManager.CreateNpadManager();
  73. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  74. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  75. WaitEvent = new ManualResetEvent(false);
  76. _glLogLevel = glLogLevel;
  77. Destroyed += Renderer_Destroyed;
  78. _chrono = new Stopwatch();
  79. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  80. AddEvents((int)(EventMask.ButtonPressMask
  81. | EventMask.ButtonReleaseMask
  82. | EventMask.PointerMotionMask
  83. | EventMask.ScrollMask
  84. | EventMask.EnterNotifyMask
  85. | EventMask.LeaveNotifyMask
  86. | EventMask.KeyPressMask
  87. | EventMask.KeyReleaseMask));
  88. _exitEvent = new ManualResetEvent(false);
  89. _gpuCancellationTokenSource = new CancellationTokenSource();
  90. _hideCursorOnIdle = ConfigurationState.Instance.HideCursorOnIdle;
  91. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  92. ConfigurationState.Instance.HideCursorOnIdle.Event += HideCursorStateChanged;
  93. }
  94. public abstract void InitializeRenderer();
  95. public abstract void SwapBuffers();
  96. protected abstract string GetGpuBackendName();
  97. private string GetGpuVendorName()
  98. {
  99. return Renderer.GetHardwareInfo().GpuVendor;
  100. }
  101. private void HideCursorStateChanged(object sender, ReactiveEventArgs<bool> state)
  102. {
  103. Application.Invoke(delegate
  104. {
  105. _hideCursorOnIdle = state.NewValue;
  106. if (_hideCursorOnIdle)
  107. {
  108. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  109. }
  110. else
  111. {
  112. Window.Cursor = null;
  113. }
  114. });
  115. }
  116. private void Renderer_Destroyed(object sender, EventArgs e)
  117. {
  118. ConfigurationState.Instance.HideCursorOnIdle.Event -= HideCursorStateChanged;
  119. NpadManager.Dispose();
  120. Dispose();
  121. }
  122. protected override bool OnMotionNotifyEvent(EventMotion evnt)
  123. {
  124. if (_hideCursorOnIdle)
  125. {
  126. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  127. }
  128. if (ConfigurationState.Instance.Hid.EnableMouse)
  129. {
  130. Window.Cursor = _invisibleCursor;
  131. }
  132. _isMouseInClient = true;
  133. return false;
  134. }
  135. protected override bool OnEnterNotifyEvent(EventCrossing evnt)
  136. {
  137. Window.Cursor = ConfigurationState.Instance.Hid.EnableMouse ? _invisibleCursor : null;
  138. _isMouseInClient = true;
  139. return base.OnEnterNotifyEvent(evnt);
  140. }
  141. protected override bool OnLeaveNotifyEvent(EventCrossing evnt)
  142. {
  143. Window.Cursor = null;
  144. _isMouseInClient = false;
  145. return base.OnLeaveNotifyEvent(evnt);
  146. }
  147. protected override void OnGetPreferredHeight(out int minimumHeight, out int naturalHeight)
  148. {
  149. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  150. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  151. if (monitor.Geometry.Height >= 1080)
  152. {
  153. minimumHeight = SwitchPanelHeight;
  154. }
  155. // Otherwise, we default minimal size to 480p 16:9.
  156. else
  157. {
  158. minimumHeight = 480;
  159. }
  160. naturalHeight = minimumHeight;
  161. }
  162. protected override void OnGetPreferredWidth(out int minimumWidth, out int naturalWidth)
  163. {
  164. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  165. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  166. if (monitor.Geometry.Height >= 1080)
  167. {
  168. minimumWidth = SwitchPanelWidth;
  169. }
  170. // Otherwise, we default minimal size to 480p 16:9.
  171. else
  172. {
  173. minimumWidth = 854;
  174. }
  175. naturalWidth = minimumWidth;
  176. }
  177. protected override bool OnConfigureEvent(EventConfigure evnt)
  178. {
  179. bool result = base.OnConfigureEvent(evnt);
  180. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  181. WindowWidth = evnt.Width * monitor.ScaleFactor;
  182. WindowHeight = evnt.Height * monitor.ScaleFactor;
  183. Renderer?.Window?.SetSize(WindowWidth, WindowHeight);
  184. return result;
  185. }
  186. private void HandleScreenState(KeyboardStateSnapshot keyboard)
  187. {
  188. bool toggleFullscreen = keyboard.IsPressed(Key.F11)
  189. || ((keyboard.IsPressed(Key.AltLeft)
  190. || keyboard.IsPressed(Key.AltRight))
  191. && keyboard.IsPressed(Key.Enter))
  192. || keyboard.IsPressed(Key.Escape);
  193. bool fullScreenToggled = ParentWindow.State.HasFlag(WindowState.Fullscreen);
  194. if (toggleFullscreen != _toggleFullscreen)
  195. {
  196. if (toggleFullscreen)
  197. {
  198. if (fullScreenToggled)
  199. {
  200. ParentWindow.Unfullscreen();
  201. (Toplevel as MainWindow)?.ToggleExtraWidgets(true);
  202. }
  203. else
  204. {
  205. if (keyboard.IsPressed(Key.Escape))
  206. {
  207. if (!ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  208. {
  209. Exit();
  210. }
  211. }
  212. else
  213. {
  214. ParentWindow.Fullscreen();
  215. (Toplevel as MainWindow)?.ToggleExtraWidgets(false);
  216. }
  217. }
  218. }
  219. }
  220. _toggleFullscreen = toggleFullscreen;
  221. bool toggleDockedMode = keyboard.IsPressed(Key.F9);
  222. if (toggleDockedMode != _toggleDockedMode)
  223. {
  224. if (toggleDockedMode)
  225. {
  226. ConfigurationState.Instance.System.EnableDockedMode.Value =
  227. !ConfigurationState.Instance.System.EnableDockedMode.Value;
  228. }
  229. }
  230. _toggleDockedMode = toggleDockedMode;
  231. if (_hideCursorOnIdle && !ConfigurationState.Instance.Hid.EnableMouse)
  232. {
  233. long cursorMoveDelta = Stopwatch.GetTimestamp() - _lastCursorMoveTime;
  234. Window.Cursor = (cursorMoveDelta >= CursorHideIdleTime * Stopwatch.Frequency) ? _invisibleCursor : null;
  235. }
  236. if(ConfigurationState.Instance.Hid.EnableMouse && _isMouseInClient)
  237. {
  238. Window.Cursor = _invisibleCursor;
  239. }
  240. }
  241. public void Initialize(Switch device)
  242. {
  243. Device = device;
  244. IRenderer renderer = Device.Gpu.Renderer;
  245. if (renderer is ThreadedRenderer tr)
  246. {
  247. renderer = tr.BaseRenderer;
  248. }
  249. Renderer = renderer;
  250. Renderer?.Window?.SetSize(WindowWidth, WindowHeight);
  251. if (Renderer != null)
  252. {
  253. Renderer.ScreenCaptured += Renderer_ScreenCaptured;
  254. }
  255. NpadManager.Initialize(device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  256. TouchScreenManager.Initialize(device);
  257. }
  258. private unsafe void Renderer_ScreenCaptured(object sender, ScreenCaptureImageInfo e)
  259. {
  260. if (e.Data.Length > 0 && e.Height > 0 && e.Width > 0)
  261. {
  262. Task.Run(() =>
  263. {
  264. lock (this)
  265. {
  266. var currentTime = DateTime.Now;
  267. string filename = $"ryujinx_capture_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png";
  268. string directory = AppDataManager.Mode switch
  269. {
  270. AppDataManager.LaunchMode.Portable => System.IO.Path.Combine(AppDataManager.BaseDirPath, "screenshots"),
  271. _ => System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx")
  272. };
  273. string path = System.IO.Path.Combine(directory, filename);
  274. try
  275. {
  276. Directory.CreateDirectory(directory);
  277. }
  278. catch (Exception ex)
  279. {
  280. Logger.Error?.Print(LogClass.Application, $"Failed to create directory at path {directory}. Error : {ex.GetType().Name}", "Screenshot");
  281. return;
  282. }
  283. Image image = e.IsBgra ? Image.LoadPixelData<Bgra32>(e.Data, e.Width, e.Height)
  284. : Image.LoadPixelData<Rgba32>(e.Data, e.Width, e.Height);
  285. if (e.FlipX)
  286. {
  287. image.Mutate(x => x.Flip(FlipMode.Horizontal));
  288. }
  289. if (e.FlipY)
  290. {
  291. image.Mutate(x => x.Flip(FlipMode.Vertical));
  292. }
  293. image.SaveAsPng(path, new PngEncoder()
  294. {
  295. ColorType = PngColorType.Rgb
  296. });
  297. image.Dispose();
  298. Logger.Notice.Print(LogClass.Application, $"Screenshot saved to {path}", "Screenshot");
  299. }
  300. });
  301. }
  302. else
  303. {
  304. Logger.Error?.Print(LogClass.Application, $"Screenshot is empty. Size : {e.Data.Length} bytes. Resolution : {e.Width}x{e.Height}", "Screenshot");
  305. }
  306. }
  307. public void Render()
  308. {
  309. Gtk.Window parent = Toplevel as Gtk.Window;
  310. parent.Present();
  311. InitializeRenderer();
  312. Device.Gpu.Renderer.Initialize(_glLogLevel);
  313. _gpuBackendName = GetGpuBackendName();
  314. _gpuVendorName = GetGpuVendorName();
  315. Device.Gpu.Renderer.RunLoop(() =>
  316. {
  317. Device.Gpu.SetGpuThread();
  318. Device.Gpu.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  319. Translator.IsReadyForTranslation.Set();
  320. Renderer.Window.ChangeVSyncMode(Device.EnableDeviceVsync);
  321. (Toplevel as MainWindow)?.ActivatePauseMenu();
  322. while (_isActive)
  323. {
  324. if (_isStopped)
  325. {
  326. return;
  327. }
  328. _ticks += _chrono.ElapsedTicks;
  329. _chrono.Restart();
  330. if (Device.WaitFifo())
  331. {
  332. Device.Statistics.RecordFifoStart();
  333. Device.ProcessFrame();
  334. Device.Statistics.RecordFifoEnd();
  335. }
  336. while (Device.ConsumeFrameAvailable())
  337. {
  338. Device.PresentFrame(SwapBuffers);
  339. }
  340. if (_ticks >= _ticksPerFrame)
  341. {
  342. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? "Docked" : "Handheld";
  343. float scale = GraphicsConfig.ResScale;
  344. if (scale != 1)
  345. {
  346. dockedMode += $" ({scale}x)";
  347. }
  348. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  349. Device.EnableDeviceVsync,
  350. Device.GetVolume(),
  351. _gpuBackendName,
  352. dockedMode,
  353. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  354. $"Game: {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  355. $"FIFO: {Device.Statistics.GetFifoPercent():0.00} %",
  356. $"GPU: {_gpuVendorName}"));
  357. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  358. }
  359. }
  360. });
  361. }
  362. public void Start()
  363. {
  364. _chrono.Restart();
  365. _isActive = true;
  366. Gtk.Window parent = Toplevel as Gtk.Window;
  367. Application.Invoke(delegate
  368. {
  369. parent.Present();
  370. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName) ? string.Empty
  371. : $" - {Device.Application.TitleName}";
  372. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion) ? string.Empty
  373. : $" v{Device.Application.DisplayVersion}";
  374. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText) ? string.Empty
  375. : $" ({Device.Application.TitleIdText.ToUpper()})";
  376. string titleArchSection = Device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  377. parent.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  378. });
  379. Thread renderLoopThread = new Thread(Render)
  380. {
  381. Name = "GUI.RenderLoop"
  382. };
  383. renderLoopThread.Start();
  384. Thread nvStutterWorkaround = null;
  385. if (Renderer is Graphics.OpenGL.OpenGLRenderer)
  386. {
  387. nvStutterWorkaround = new Thread(NVStutterWorkaround)
  388. {
  389. Name = "GUI.NVStutterWorkaround"
  390. };
  391. nvStutterWorkaround.Start();
  392. }
  393. MainLoop();
  394. renderLoopThread.Join();
  395. nvStutterWorkaround?.Join();
  396. Exit();
  397. }
  398. public void Exit()
  399. {
  400. TouchScreenManager?.Dispose();
  401. NpadManager?.Dispose();
  402. if (_isStopped)
  403. {
  404. return;
  405. }
  406. _gpuCancellationTokenSource.Cancel();
  407. _isStopped = true;
  408. if (_isActive)
  409. {
  410. _isActive = false;
  411. _exitEvent.WaitOne();
  412. _exitEvent.Dispose();
  413. }
  414. }
  415. private void NVStutterWorkaround()
  416. {
  417. while (_isActive)
  418. {
  419. // When NVIDIA Threaded Optimization is on, the driver will snapshot all threads in the system whenever the application creates any new ones.
  420. // The ThreadPool has something called a "GateThread" which terminates itself after some inactivity.
  421. // However, it immediately starts up again, since the rules regarding when to terminate and when to start differ.
  422. // This creates a new thread every second or so.
  423. // The main problem with this is that the thread snapshot can take 70ms, is on the OpenGL thread and will delay rendering any graphics.
  424. // This is a little over budget on a frame time of 16ms, so creates a large stutter.
  425. // The solution is to keep the ThreadPool active so that it never has a reason to terminate the GateThread.
  426. // TODO: This should be removed when the issue with the GateThread is resolved.
  427. ThreadPool.QueueUserWorkItem((state) => { });
  428. Thread.Sleep(300);
  429. }
  430. }
  431. public void MainLoop()
  432. {
  433. while (_isActive)
  434. {
  435. UpdateFrame();
  436. // Polling becomes expensive if it's not slept
  437. Thread.Sleep(1);
  438. }
  439. _exitEvent.Set();
  440. }
  441. private bool UpdateFrame()
  442. {
  443. if (!_isActive)
  444. {
  445. return true;
  446. }
  447. if (_isStopped)
  448. {
  449. return false;
  450. }
  451. if ((Toplevel as MainWindow).IsFocused)
  452. {
  453. Application.Invoke(delegate
  454. {
  455. KeyboardStateSnapshot keyboard = _keyboardInterface.GetKeyboardStateSnapshot();
  456. HandleScreenState(keyboard);
  457. if (keyboard.IsPressed(Key.Delete))
  458. {
  459. if (!ParentWindow.State.HasFlag(WindowState.Fullscreen))
  460. {
  461. Device.Application.DiskCacheLoadState?.Cancel();
  462. }
  463. }
  464. });
  465. }
  466. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  467. if ((Toplevel as MainWindow).IsFocused)
  468. {
  469. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  470. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync) &&
  471. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync))
  472. {
  473. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  474. }
  475. if ((currentHotkeyState.HasFlag(KeyboardHotkeyState.Screenshot) &&
  476. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.Screenshot)) || ScreenshotRequested)
  477. {
  478. ScreenshotRequested = false;
  479. Renderer.Screenshot();
  480. }
  481. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ShowUi) &&
  482. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ShowUi))
  483. {
  484. (Toplevel as MainWindow).ToggleExtraWidgets(true);
  485. }
  486. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.Pause) &&
  487. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.Pause))
  488. {
  489. (Toplevel as MainWindow)?.TogglePause();
  490. }
  491. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ToggleMute) &&
  492. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ToggleMute))
  493. {
  494. if (Device.IsAudioMuted())
  495. {
  496. Device.SetVolume(ConfigurationState.Instance.System.AudioVolume);
  497. }
  498. else
  499. {
  500. Device.SetVolume(0);
  501. }
  502. }
  503. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ResScaleUp) &&
  504. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ResScaleUp))
  505. {
  506. GraphicsConfig.ResScale = GraphicsConfig.ResScale % MaxResolutionScale + 1;
  507. }
  508. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ResScaleDown) &&
  509. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ResScaleDown))
  510. {
  511. GraphicsConfig.ResScale =
  512. (MaxResolutionScale + GraphicsConfig.ResScale - 2) % MaxResolutionScale + 1;
  513. }
  514. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.VolumeUp) &&
  515. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.VolumeUp))
  516. {
  517. _newVolume = MathF.Round((Device.GetVolume() + VolumeDelta), 2);
  518. Device.SetVolume(_newVolume);
  519. }
  520. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.VolumeDown) &&
  521. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.VolumeDown))
  522. {
  523. _newVolume = MathF.Round((Device.GetVolume() - VolumeDelta), 2);
  524. Device.SetVolume(_newVolume);
  525. }
  526. _prevHotkeyState = currentHotkeyState;
  527. }
  528. // Touchscreen
  529. bool hasTouch = false;
  530. // Get screen touch position
  531. if ((Toplevel as MainWindow).IsFocused && !ConfigurationState.Instance.Hid.EnableMouse)
  532. {
  533. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as GTK3MouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  534. }
  535. if (!hasTouch)
  536. {
  537. TouchScreenManager.Update(false);
  538. }
  539. Device.Hid.DebugPad.Update();
  540. return true;
  541. }
  542. [Flags]
  543. private enum KeyboardHotkeyState
  544. {
  545. None = 0,
  546. ToggleVSync = 1 << 0,
  547. Screenshot = 1 << 1,
  548. ShowUi = 1 << 2,
  549. Pause = 1 << 3,
  550. ToggleMute = 1 << 4,
  551. ResScaleUp = 1 << 5,
  552. ResScaleDown = 1 << 6,
  553. VolumeUp = 1 << 7,
  554. VolumeDown = 1 << 8
  555. }
  556. private KeyboardHotkeyState GetHotkeyState()
  557. {
  558. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  559. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  560. {
  561. state |= KeyboardHotkeyState.ToggleVSync;
  562. }
  563. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot))
  564. {
  565. state |= KeyboardHotkeyState.Screenshot;
  566. }
  567. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi))
  568. {
  569. state |= KeyboardHotkeyState.ShowUi;
  570. }
  571. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause))
  572. {
  573. state |= KeyboardHotkeyState.Pause;
  574. }
  575. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleMute))
  576. {
  577. state |= KeyboardHotkeyState.ToggleMute;
  578. }
  579. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleUp))
  580. {
  581. state |= KeyboardHotkeyState.ResScaleUp;
  582. }
  583. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleDown))
  584. {
  585. state |= KeyboardHotkeyState.ResScaleDown;
  586. }
  587. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeUp))
  588. {
  589. state |= KeyboardHotkeyState.VolumeUp;
  590. }
  591. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeDown))
  592. {
  593. state |= KeyboardHotkeyState.VolumeDown;
  594. }
  595. return state;
  596. }
  597. }
  598. }