AnsiResponseParser.cs 11 KB

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