AvaloniaKeyboardDriver.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 => "AvaloniaKeyboardDriver";
  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 IGamepad GetGamepad(string id)
  44. {
  45. if (!_keyboardIdentifers[0].Equals(id))
  46. {
  47. return null;
  48. }
  49. return new AvaloniaKeyboard(this, _keyboardIdentifers[0], LocaleManager.Instance[LocaleKeys.AllKeyboards]);
  50. }
  51. protected virtual void Dispose(bool disposing)
  52. {
  53. if (disposing)
  54. {
  55. _control.KeyUp -= OnKeyPress;
  56. _control.KeyDown -= OnKeyRelease;
  57. }
  58. }
  59. protected void OnKeyPress(object sender, KeyEventArgs args)
  60. {
  61. _pressedKeys.Add(args.Key);
  62. KeyPressed?.Invoke(this, args);
  63. }
  64. protected void OnKeyRelease(object sender, KeyEventArgs args)
  65. {
  66. _pressedKeys.Remove(args.Key);
  67. KeyRelease?.Invoke(this, args);
  68. }
  69. internal bool IsPressed(Key key)
  70. {
  71. if (key == Key.Unbound || key == Key.Unknown)
  72. {
  73. return false;
  74. }
  75. AvaloniaKeyboardMappingHelper.TryGetAvaKey(key, out var nativeKey);
  76. return _pressedKeys.Contains(nativeKey);
  77. }
  78. public void Clear()
  79. {
  80. _pressedKeys.Clear();
  81. }
  82. public void Dispose()
  83. {
  84. Dispose(true);
  85. }
  86. }
  87. }