AnsiResponseParser.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. #nullable enable
  2. using System.Runtime.ConstrainedExecution;
  3. namespace Terminal.Gui;
  4. internal abstract class AnsiResponseParserBase : IAnsiResponseParser
  5. {
  6. protected readonly List<(string terminator, Action<string> response)> expectedResponses = new ();
  7. private AnsiResponseParserState _state = AnsiResponseParserState.Normal;
  8. // Current state of the parser
  9. public AnsiResponseParserState State
  10. {
  11. get => _state;
  12. protected set
  13. {
  14. StateChangedAt = DateTime.Now;
  15. _state = value;
  16. }
  17. }
  18. /// <summary>
  19. /// When <see cref="State"/> was last changed.
  20. /// </summary>
  21. public DateTime StateChangedAt { get; private set; } = DateTime.Now;
  22. protected readonly HashSet<char> _knownTerminators = new ();
  23. public AnsiResponseParserBase ()
  24. {
  25. // These all are valid terminators on ansi responses,
  26. // see CSI in https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s
  27. _knownTerminators.Add ('@');
  28. _knownTerminators.Add ('A');
  29. _knownTerminators.Add ('B');
  30. _knownTerminators.Add ('C');
  31. _knownTerminators.Add ('D');
  32. _knownTerminators.Add ('E');
  33. _knownTerminators.Add ('F');
  34. _knownTerminators.Add ('G');
  35. _knownTerminators.Add ('G');
  36. _knownTerminators.Add ('H');
  37. _knownTerminators.Add ('I');
  38. _knownTerminators.Add ('J');
  39. _knownTerminators.Add ('K');
  40. _knownTerminators.Add ('L');
  41. _knownTerminators.Add ('M');
  42. // No - N or O
  43. _knownTerminators.Add ('P');
  44. _knownTerminators.Add ('Q');
  45. _knownTerminators.Add ('R');
  46. _knownTerminators.Add ('S');
  47. _knownTerminators.Add ('T');
  48. _knownTerminators.Add ('W');
  49. _knownTerminators.Add ('X');
  50. _knownTerminators.Add ('Z');
  51. _knownTerminators.Add ('^');
  52. _knownTerminators.Add ('`');
  53. _knownTerminators.Add ('~');
  54. _knownTerminators.Add ('a');
  55. _knownTerminators.Add ('b');
  56. _knownTerminators.Add ('c');
  57. _knownTerminators.Add ('d');
  58. _knownTerminators.Add ('e');
  59. _knownTerminators.Add ('f');
  60. _knownTerminators.Add ('g');
  61. _knownTerminators.Add ('h');
  62. _knownTerminators.Add ('i');
  63. _knownTerminators.Add ('l');
  64. _knownTerminators.Add ('m');
  65. _knownTerminators.Add ('n');
  66. _knownTerminators.Add ('p');
  67. _knownTerminators.Add ('q');
  68. _knownTerminators.Add ('r');
  69. _knownTerminators.Add ('s');
  70. _knownTerminators.Add ('t');
  71. _knownTerminators.Add ('u');
  72. _knownTerminators.Add ('v');
  73. _knownTerminators.Add ('w');
  74. _knownTerminators.Add ('x');
  75. _knownTerminators.Add ('y');
  76. _knownTerminators.Add ('z');
  77. }
  78. protected void ResetState ()
  79. {
  80. State = AnsiResponseParserState.Normal;
  81. ClearHeld ();
  82. }
  83. public abstract void ClearHeld ();
  84. protected abstract string HeldToString ();
  85. protected abstract IEnumerable<object> HeldToObjects ();
  86. protected abstract void AddToHeld (object o);
  87. /// <summary>
  88. /// Processes an input collection of objects <paramref name="inputLength"/> long.
  89. /// You must provide the indexers to return the objects and the action to append
  90. /// to output stream.
  91. /// </summary>
  92. /// <param name="getCharAtIndex">The character representation of element i of your input collection</param>
  93. /// <param name="getObjectAtIndex">The actual element in the collection (e.g. char or Tuple&lt;char,T&gt;)</param>
  94. /// <param name="appendOutput">
  95. /// Action to invoke when parser confirms an element of the current collection or a previous
  96. /// call's collection should be appended to the current output (i.e. append to your output List/StringBuilder).
  97. /// </param>
  98. /// <param name="inputLength">The total number of elements in your collection</param>
  99. protected void ProcessInputBase (
  100. Func<int, char> getCharAtIndex,
  101. Func<int, object> getObjectAtIndex,
  102. Action<object> appendOutput,
  103. int inputLength
  104. )
  105. {
  106. var index = 0; // Tracks position in the input string
  107. while (index < inputLength)
  108. {
  109. char currentChar = getCharAtIndex (index);
  110. object currentObj = getObjectAtIndex (index);
  111. bool isEscape = currentChar == '\x1B';
  112. switch (State)
  113. {
  114. case AnsiResponseParserState.Normal:
  115. if (isEscape)
  116. {
  117. // Escape character detected, move to ExpectingBracket state
  118. State = AnsiResponseParserState.ExpectingBracket;
  119. AddToHeld (currentObj); // Hold the escape character
  120. }
  121. else
  122. {
  123. // Normal character, append to output
  124. appendOutput (currentObj);
  125. }
  126. break;
  127. case AnsiResponseParserState.ExpectingBracket:
  128. if (isEscape)
  129. {
  130. // Second escape so we must release first
  131. ReleaseHeld (appendOutput, AnsiResponseParserState.ExpectingBracket);
  132. AddToHeld (currentObj); // Hold the new escape
  133. }
  134. else if (currentChar == '[')
  135. {
  136. // Detected '[', transition to InResponse state
  137. State = AnsiResponseParserState.InResponse;
  138. AddToHeld (currentObj); // Hold the '['
  139. }
  140. else
  141. {
  142. // Invalid sequence, release held characters and reset to Normal
  143. ReleaseHeld (appendOutput);
  144. appendOutput (currentObj); // Add current character
  145. }
  146. break;
  147. case AnsiResponseParserState.InResponse:
  148. AddToHeld (currentObj);
  149. // Check if the held content should be released
  150. if (ShouldReleaseHeldContent ())
  151. {
  152. ReleaseHeld (appendOutput);
  153. }
  154. break;
  155. }
  156. index++;
  157. }
  158. }
  159. private void ReleaseHeld (Action<object> appendOutput, AnsiResponseParserState newState = AnsiResponseParserState.Normal)
  160. {
  161. foreach (object o in HeldToObjects ())
  162. {
  163. appendOutput (o);
  164. }
  165. State = newState;
  166. ClearHeld ();
  167. }
  168. // Common response handler logic
  169. protected bool ShouldReleaseHeldContent ()
  170. {
  171. string cur = HeldToString ();
  172. // Check for expected responses
  173. (string terminator, Action<string> response) matchingResponse = expectedResponses.FirstOrDefault (r => cur.EndsWith (r.terminator));
  174. if (matchingResponse.response != null)
  175. {
  176. DispatchResponse (matchingResponse.response);
  177. expectedResponses.Remove (matchingResponse);
  178. return false;
  179. }
  180. if (_knownTerminators.Contains (cur.Last ()) && cur.StartsWith (EscSeqUtils.CSI))
  181. {
  182. // Detected a response that was not expected
  183. return true;
  184. }
  185. return false; // Continue accumulating
  186. }
  187. protected void DispatchResponse (Action<string> response)
  188. {
  189. response?.Invoke (HeldToString ());
  190. ResetState ();
  191. }
  192. /// <summary>
  193. /// Registers a new expected ANSI response with a specific terminator and a callback for when the response is
  194. /// completed.
  195. /// </summary>
  196. public void ExpectResponse (string terminator, Action<string> response) { expectedResponses.Add ((terminator, response)); }
  197. /// <inheritdoc />
  198. public bool IsExpecting (string requestTerminator)
  199. {
  200. // If any of the new terminator matches any existing terminators characters it's a collision so true.
  201. return expectedResponses.Any (r => r.terminator.Intersect (requestTerminator).Any());
  202. }
  203. }
  204. internal class AnsiResponseParser<T> : AnsiResponseParserBase
  205. {
  206. private readonly List<Tuple<char, T>> held = new ();
  207. public IEnumerable<Tuple<char, T>> ProcessInput (params Tuple<char, T> [] input)
  208. {
  209. List<Tuple<char, T>> output = new List<Tuple<char, T>> ();
  210. ProcessInputBase (
  211. i => input [i].Item1,
  212. i => input [i],
  213. c => output.Add ((Tuple<char, T>)c),
  214. input.Length);
  215. return output;
  216. }
  217. public IEnumerable<Tuple<char, T>> Release ()
  218. {
  219. foreach (Tuple<char, T> h in held.ToArray ())
  220. {
  221. yield return h;
  222. }
  223. ResetState ();
  224. }
  225. public override void ClearHeld () { held.Clear (); }
  226. protected override string HeldToString () { return new (held.Select (h => h.Item1).ToArray ()); }
  227. protected override IEnumerable<object> HeldToObjects () { return held; }
  228. protected override void AddToHeld (object o) { held.Add ((Tuple<char, T>)o); }
  229. }
  230. internal class AnsiResponseParser : AnsiResponseParserBase
  231. {
  232. private readonly StringBuilder held = new ();
  233. public string ProcessInput (string input)
  234. {
  235. var output = new StringBuilder ();
  236. ProcessInputBase (
  237. i => input [i],
  238. i => input [i], // For string there is no T so object is same as char
  239. c => output.Append ((char)c),
  240. input.Length);
  241. return output.ToString ();
  242. }
  243. public string Release ()
  244. {
  245. var output = held.ToString ();
  246. ResetState ();
  247. return output;
  248. }
  249. public override void ClearHeld () { held.Clear (); }
  250. protected override string HeldToString () { return held.ToString (); }
  251. protected override IEnumerable<object> HeldToObjects () { return held.ToString ().Select (c => (object)c).ToArray (); }
  252. protected override void AddToHeld (object o) { held.Append ((char)o); }
  253. }
  254. /// <summary>
  255. /// Describes an ongoing ANSI request sent to the console.
  256. /// Use <see cref="ResponseReceived"/> to handle the response
  257. /// when console answers the request.
  258. /// </summary>
  259. public class AnsiEscapeSequenceRequest
  260. {
  261. /// <summary>
  262. /// Request to send e.g. see
  263. /// <see>
  264. /// <cref>EscSeqUtils.CSI_SendDeviceAttributes.Request</cref>
  265. /// </see>
  266. /// </summary>
  267. public required string Request { get; init; }
  268. /// <summary>
  269. /// Invoked when the console responds with an ANSI response code that matches the
  270. /// <see cref="Terminator"/>
  271. /// </summary>
  272. public Action<string> ResponseReceived;
  273. /// <summary>
  274. /// <para>
  275. /// The terminator that uniquely identifies the type of response as responded
  276. /// by the console. e.g. for
  277. /// <see>
  278. /// <cref>EscSeqUtils.CSI_SendDeviceAttributes.Request</cref>
  279. /// </see>
  280. /// the terminator is
  281. /// <see>
  282. /// <cref>EscSeqUtils.CSI_SendDeviceAttributes.Terminator</cref>
  283. /// </see>
  284. /// .
  285. /// </para>
  286. /// <para>
  287. /// After sending a request, the first response with matching terminator will be matched
  288. /// to the oldest outstanding request.
  289. /// </para>
  290. /// </summary>
  291. public required string Terminator { get; init; }
  292. /// <summary>
  293. /// Sends the <see cref="Request"/> to the raw output stream of the current <see cref="ConsoleDriver"/>.
  294. /// Only call this method from the main UI thread. You should use <see cref="AnsiRequestScheduler"/> if
  295. /// sending many requests.
  296. /// </summary>
  297. public void Send ()
  298. {
  299. Application.Driver?.RawWrite (Request);
  300. }
  301. }