RendererWidgetBase.cs 28 KB

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