RendererWidgetBase.cs 26 KB

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