CsiCursorPattern.cs 2.2 KB

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