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