CsiCursorPattern.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #nullable enable
  2. using System.Text.RegularExpressions;
  3. namespace Terminal.Gui;
  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 up with Ctrl)
  9. /// </summary>
  10. public class CsiCursorPattern : AnsiKeyboardParserPattern
  11. {
  12. private readonly Regex _pattern = new (@"^\u001b\[(?:1;(\d+))?([A-DHF])$");
  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. };
  22. /// <inheritdoc/>
  23. public override bool IsMatch (string? input) { return _pattern.IsMatch (input!); }
  24. /// <summary>
  25. /// Called by the base class to determine the key that matches the input.
  26. /// </summary>
  27. /// <param name="input"></param>
  28. /// <returns></returns>
  29. protected override Key? GetKeyImpl (string? input)
  30. {
  31. Match match = _pattern.Match (input!);
  32. if (!match.Success)
  33. {
  34. return null;
  35. }
  36. string modifierGroup = match.Groups [1].Value;
  37. char terminator = match.Groups [2].Value [0];
  38. if (!_cursorMap.TryGetValue (terminator, out Key? key))
  39. {
  40. return null;
  41. }
  42. if (string.IsNullOrEmpty (modifierGroup))
  43. {
  44. return key;
  45. }
  46. if (int.TryParse (modifierGroup, out int modifier))
  47. {
  48. key = modifier switch
  49. {
  50. 2 => key.WithShift,
  51. 3 => key.WithAlt,
  52. 4 => key.WithAlt.WithShift,
  53. 5 => key.WithCtrl,
  54. 6 => key.WithCtrl.WithShift,
  55. 7 => key.WithCtrl.WithAlt,
  56. 8 => key.WithCtrl.WithAlt.WithShift,
  57. _ => key
  58. };
  59. }
  60. return key;
  61. }
  62. }