AnsiResponseParser.cs 14 KB

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