WindowsDriverKeyPairer.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using static Terminal.Gui.WindowsConsole;
  2. namespace Terminal.Gui.ConsoleDrivers;
  3. class WindowsDriverKeyPairer
  4. {
  5. private InputRecord? _heldDownEvent = null; // To hold the "down" event
  6. // Process a single input record at a time
  7. public IEnumerable<InputRecord []> ProcessInput (InputRecord record)
  8. {
  9. // If it's a "down" event, store it as a held event
  10. if (IsKeyDown (record))
  11. {
  12. return HandleKeyDown (record);
  13. }
  14. // If it's an "up" event, try to match it with the held "down" event
  15. else if (IsKeyUp (record))
  16. {
  17. return HandleKeyUp (record);
  18. }
  19. else
  20. {
  21. // If it's not a key event, just pass it through
  22. return new [] { new [] { record } };
  23. }
  24. }
  25. private IEnumerable<InputRecord []> HandleKeyDown (InputRecord record)
  26. {
  27. // If we already have a held "down" event, release it (unmatched)
  28. if (_heldDownEvent != null)
  29. {
  30. // Release the previous "down" event since there's a new "down"
  31. var previousDown = _heldDownEvent.Value;
  32. _heldDownEvent = record; // Hold the new "down" event
  33. return new [] { new [] { previousDown } };
  34. }
  35. // Hold the new "down" event
  36. _heldDownEvent = record;
  37. return Enumerable.Empty<InputRecord []> ();
  38. }
  39. private IEnumerable<InputRecord []> HandleKeyUp (InputRecord record)
  40. {
  41. // If we have a held "down" event that matches this "up" event, release both
  42. if (_heldDownEvent != null && IsMatchingKey (record, _heldDownEvent.Value))
  43. {
  44. var downEvent = _heldDownEvent.Value;
  45. _heldDownEvent = null; // Clear the held event
  46. return new [] { new [] { downEvent, record } };
  47. }
  48. else
  49. {
  50. // No match, release the "up" event by itself
  51. return new [] { new [] { record } };
  52. }
  53. }
  54. private bool IsKeyDown (InputRecord record)
  55. {
  56. return record.KeyEvent.bKeyDown;
  57. }
  58. private bool IsKeyUp (InputRecord record)
  59. {
  60. return !record.KeyEvent.bKeyDown;
  61. }
  62. private bool IsMatchingKey (InputRecord upEvent, InputRecord downEvent)
  63. {
  64. return upEvent.KeyEvent.UnicodeChar == downEvent.KeyEvent.UnicodeChar;
  65. }
  66. }