AvaloniaKeyboardDriver.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using Avalonia.Controls;
  2. using Avalonia.Input;
  3. using Ryujinx.Ava.Common.Locale;
  4. using Ryujinx.Input;
  5. using System;
  6. using System.Collections.Generic;
  7. using AvaKey = Avalonia.Input.Key;
  8. using Key = Ryujinx.Input.Key;
  9. namespace Ryujinx.Ava.Input
  10. {
  11. internal class AvaloniaKeyboardDriver : IGamepadDriver
  12. {
  13. private static readonly string[] _keyboardIdentifers = new string[1] { "0" };
  14. private readonly Control _control;
  15. private readonly HashSet<AvaKey> _pressedKeys;
  16. public event EventHandler<KeyEventArgs> KeyPressed;
  17. public event EventHandler<KeyEventArgs> KeyRelease;
  18. public event EventHandler<string> TextInput;
  19. public string DriverName => "Avalonia";
  20. public ReadOnlySpan<string> GamepadsIds => _keyboardIdentifers;
  21. public AvaloniaKeyboardDriver(Control control)
  22. {
  23. _control = control;
  24. _pressedKeys = new HashSet<AvaKey>();
  25. _control.KeyDown += OnKeyPress;
  26. _control.KeyUp += OnKeyRelease;
  27. _control.TextInput += Control_TextInput;
  28. }
  29. private void Control_TextInput(object sender, TextInputEventArgs e)
  30. {
  31. TextInput?.Invoke(this, e.Text);
  32. }
  33. public event Action<string> OnGamepadConnected
  34. {
  35. add { }
  36. remove { }
  37. }
  38. public event Action<string> OnGamepadDisconnected
  39. {
  40. add { }
  41. remove { }
  42. }
  43. public void Dispose()
  44. {
  45. Dispose(true);
  46. }
  47. public IGamepad GetGamepad(string id)
  48. {
  49. if (!_keyboardIdentifers[0].Equals(id))
  50. {
  51. return null;
  52. }
  53. return new AvaloniaKeyboard(this, _keyboardIdentifers[0], LocaleManager.Instance["AllKeyboards"]);
  54. }
  55. protected virtual void Dispose(bool disposing)
  56. {
  57. if (disposing)
  58. {
  59. _control.KeyUp -= OnKeyPress;
  60. _control.KeyDown -= OnKeyRelease;
  61. }
  62. }
  63. protected void OnKeyPress(object sender, KeyEventArgs args)
  64. {
  65. AvaKey key = args.Key;
  66. _pressedKeys.Add(args.Key);
  67. KeyPressed?.Invoke(this, args);
  68. }
  69. protected void OnKeyRelease(object sender, KeyEventArgs args)
  70. {
  71. _pressedKeys.Remove(args.Key);
  72. KeyRelease?.Invoke(this, args);
  73. }
  74. internal bool IsPressed(Key key)
  75. {
  76. if (key == Key.Unbound || key == Key.Unknown)
  77. {
  78. return false;
  79. }
  80. AvaloniaMappingHelper.TryGetAvaKey(key, out var nativeKey);
  81. return _pressedKeys.Contains(nativeKey);
  82. }
  83. public void ResetKeys()
  84. {
  85. _pressedKeys.Clear();
  86. }
  87. }
  88. }