CsiCursorPattern.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #nullable enable
  2. using System.Text.RegularExpressions;
  3. namespace Terminal.Gui.Drivers;
  4. /// <summary>
  5. /// Detects ansi escape sequences in strings that have been read from
  6. /// the terminal (see <see cref="IAnsiResponseParser"/>).
  7. /// Handles navigation CSI key parsing such as <c>\x1b[A</c> (Cursor up)
  8. /// and <c>\x1b[1;5A</c> (Cursor/Function with modifier(s))
  9. /// </summary>
  10. public class CsiCursorPattern : AnsiKeyboardParserPattern
  11. {
  12. private readonly Regex _pattern = new (@"^\u001b\[(?:1;(\d+))?([A-DFHPQRS])$");
  13. private readonly Dictionary<char, Key> _cursorMap = new ()
  14. {
  15. { 'A', Key.CursorUp },
  16. { 'B', Key.CursorDown },
  17. { 'C', Key.CursorRight },
  18. { 'D', Key.CursorLeft },
  19. { 'H', Key.Home },
  20. { 'F', Key.End },
  21. // F1–F4 as per xterm VT100-style CSI sequences
  22. { 'P', Key.F1 },
  23. { 'Q', Key.F2 },
  24. { 'R', Key.F3 },
  25. { 'S', Key.F4 }
  26. };
  27. /// <inheritdoc/>
  28. public override bool IsMatch (string? input) { return _pattern.IsMatch (input!); }
  29. /// <summary>
  30. /// Called by the base class to determine the key that matches the input.
  31. /// </summary>
  32. /// <param name="input"></param>
  33. /// <returns></returns>
  34. protected override Key? GetKeyImpl (string? input)
  35. {
  36. Match match = _pattern.Match (input!);
  37. if (!match.Success)
  38. {
  39. return null;
  40. }
  41. string modifierGroup = match.Groups [1].Value;
  42. char terminator = match.Groups [2].Value [0];
  43. if (!_cursorMap.TryGetValue (terminator, out Key? key))
  44. {
  45. return null;
  46. }
  47. if (string.IsNullOrEmpty (modifierGroup))
  48. {
  49. return key;
  50. }
  51. if (int.TryParse (modifierGroup, out int modifier))
  52. {
  53. key = modifier switch
  54. {
  55. 2 => key.WithShift,
  56. 3 => key.WithAlt,
  57. 4 => key.WithAlt.WithShift,
  58. 5 => key.WithCtrl,
  59. 6 => key.WithCtrl.WithShift,
  60. 7 => key.WithCtrl.WithAlt,
  61. 8 => key.WithCtrl.WithAlt.WithShift,
  62. _ => key
  63. };
  64. }
  65. return key;
  66. }
  67. }