AndroidKeyboardEventsHelper.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using Android.Views;
  3. using Avalonia.Android.Platform.Input;
  4. using Avalonia.Android.Platform.SkiaPlatform;
  5. using Avalonia.Input;
  6. using Avalonia.Input.Raw;
  7. namespace Avalonia.Android.Platform.Specific.Helpers
  8. {
  9. internal class AndroidKeyboardEventsHelper<TView> : IDisposable where TView : TopLevelImpl, IAndroidView
  10. {
  11. private readonly TView _view;
  12. public bool HandleEvents { get; set; }
  13. public AndroidKeyboardEventsHelper(TView view)
  14. {
  15. _view = view;
  16. HandleEvents = true;
  17. }
  18. public bool? DispatchKeyEvent(KeyEvent e, out bool callBase)
  19. {
  20. if (!HandleEvents)
  21. {
  22. callBase = true;
  23. return null;
  24. }
  25. return DispatchKeyEventInternal(e, out callBase);
  26. }
  27. string UnicodeTextInput(KeyEvent keyEvent)
  28. {
  29. return keyEvent.Action == KeyEventActions.Multiple
  30. && keyEvent.RepeatCount == 0
  31. && !string.IsNullOrEmpty(keyEvent?.Characters)
  32. ? keyEvent.Characters
  33. : null;
  34. }
  35. private bool? DispatchKeyEventInternal(KeyEvent e, out bool callBase)
  36. {
  37. var unicodeTextInput = UnicodeTextInput(e);
  38. if (e.Action == KeyEventActions.Multiple && unicodeTextInput == null)
  39. {
  40. callBase = true;
  41. return null;
  42. }
  43. var rawKeyEvent = new RawKeyEventArgs(
  44. AndroidKeyboardDevice.Instance,
  45. Convert.ToUInt64(e.EventTime),
  46. _view.InputRoot,
  47. e.Action == KeyEventActions.Down ? RawKeyEventType.KeyDown : RawKeyEventType.KeyUp,
  48. AndroidKeyboardDevice.ConvertKey(e.KeyCode), GetModifierKeys(e));
  49. _view.Input(rawKeyEvent);
  50. if ((e.Action == KeyEventActions.Down && e.UnicodeChar >= 32)
  51. || unicodeTextInput != null)
  52. {
  53. var rawTextEvent = new RawTextInputEventArgs(
  54. AndroidKeyboardDevice.Instance,
  55. Convert.ToUInt64(e.EventTime),
  56. _view.InputRoot,
  57. unicodeTextInput ?? Convert.ToChar(e.UnicodeChar).ToString()
  58. );
  59. _view.Input(rawTextEvent);
  60. }
  61. if (e.Action == KeyEventActions.Up)
  62. {
  63. //nothing to do here more call base no need of more events
  64. callBase = true;
  65. return null;
  66. }
  67. callBase = false;
  68. return false;
  69. }
  70. private static RawInputModifiers GetModifierKeys(KeyEvent e)
  71. {
  72. var rv = RawInputModifiers.None;
  73. if (e.IsCtrlPressed) rv |= RawInputModifiers.Control;
  74. if (e.IsShiftPressed) rv |= RawInputModifiers.Shift;
  75. return rv;
  76. }
  77. public void Dispose()
  78. {
  79. HandleEvents = false;
  80. }
  81. }
  82. }