RendererWidgetBase.cs 29 KB

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