AnsiResponseParser.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. // We have found a terminator so bail
  170. State = AnsiResponseParserState.Normal;
  171. // Maybe swallow anyway if user has custom delegate
  172. return ShouldReleaseUnexpectedResponse ();
  173. }
  174. return false; // Continue accumulating
  175. }
  176. /// <summary>
  177. /// <para>
  178. /// When overriden in a derived class, indicates whether the unexpected response
  179. /// currently in <see cref="heldContent"/> should be released or swallowed.
  180. /// Use this to enable default event for escape codes.
  181. /// </para>
  182. ///
  183. /// <remarks>Note this is only called for complete responses.
  184. /// Based on <see cref="_knownTerminators"/></remarks>
  185. /// </summary>
  186. /// <returns></returns>
  187. protected abstract bool ShouldReleaseUnexpectedResponse ();
  188. private bool MatchResponse (string cur, List<AnsiResponseExpectation> collection, bool invokeCallback, bool removeExpectation)
  189. {
  190. // Check for expected responses
  191. var matchingResponse = collection.FirstOrDefault (r => r.Matches (cur));
  192. if (matchingResponse?.Response != null)
  193. {
  194. if (invokeCallback)
  195. {
  196. matchingResponse.Response.Invoke (heldContent);
  197. }
  198. ResetState ();
  199. if (removeExpectation)
  200. {
  201. collection.Remove (matchingResponse);
  202. }
  203. return true;
  204. }
  205. return false;
  206. }
  207. /// <inheritdoc />
  208. public void ExpectResponse (string terminator, Action<string> response, bool persistent)
  209. {
  210. if (persistent)
  211. {
  212. persistentExpectations.Add (new (terminator, (h)=>response.Invoke (h.HeldToString ())));
  213. }
  214. else
  215. {
  216. expectedResponses.Add (new (terminator, (h) => response.Invoke (h.HeldToString ())));
  217. }
  218. }
  219. /// <inheritdoc />
  220. public bool IsExpecting (string terminator)
  221. {
  222. // If any of the new terminator matches any existing terminators characters it's a collision so true.
  223. return expectedResponses.Any (r => r.Terminator.Intersect (terminator).Any ());
  224. }
  225. /// <inheritdoc />
  226. public void StopExpecting (string terminator, bool persistent)
  227. {
  228. if (persistent)
  229. {
  230. persistentExpectations.RemoveAll (r => r.Matches (terminator));
  231. }
  232. else
  233. {
  234. var removed = expectedResponses.Where (r => r.Terminator == terminator).ToArray ();
  235. foreach (var r in removed)
  236. {
  237. expectedResponses.Remove (r);
  238. lateResponses.Add (r);
  239. }
  240. }
  241. }
  242. }
  243. internal class AnsiResponseParser<T> : AnsiResponseParserBase
  244. {
  245. public AnsiResponseParser () : base (new GenericHeld<T> ()) { }
  246. /// <inheritdoc cref="AnsiResponseParser.UnknownResponseHandler"/>
  247. public Func<IEnumerable<Tuple<char, T>>, bool> UnknownResponseHandler { get; set; } = (_) => false;
  248. public IEnumerable<Tuple<char, T>> ProcessInput (params Tuple<char, T> [] input)
  249. {
  250. List<Tuple<char, T>> output = new List<Tuple<char, T>> ();
  251. ProcessInputBase (
  252. i => input [i].Item1,
  253. i => input [i],
  254. c => output.Add ((Tuple<char, T>)c),
  255. input.Length);
  256. return output;
  257. }
  258. public IEnumerable<Tuple<char, T>> Release ()
  259. {
  260. foreach (Tuple<char, T> h in HeldToEnumerable())
  261. {
  262. yield return h;
  263. }
  264. ResetState ();
  265. }
  266. private IEnumerable<Tuple<char, T>> HeldToEnumerable ()
  267. {
  268. return (IEnumerable<Tuple<char, T>>)heldContent.HeldToObjects ();
  269. }
  270. /// <summary>
  271. /// 'Overload' for specifying an expectation that requires the metadata as well as characters. Has
  272. /// a unique name because otherwise most lamdas will give ambiguous overload errors.
  273. /// </summary>
  274. /// <param name="terminator"></param>
  275. /// <param name="response"></param>
  276. /// <param name="persistent"></param>
  277. public void ExpectResponseT (string terminator, Action<IEnumerable<Tuple<char,T>>> response, bool persistent)
  278. {
  279. if (persistent)
  280. {
  281. persistentExpectations.Add (new (terminator, (h) => response.Invoke (HeldToEnumerable ())));
  282. }
  283. else
  284. {
  285. expectedResponses.Add (new (terminator, (h) => response.Invoke (HeldToEnumerable ())));
  286. }
  287. }
  288. /// <inheritdoc />
  289. protected override bool ShouldReleaseUnexpectedResponse ()
  290. {
  291. return !UnknownResponseHandler.Invoke (HeldToEnumerable ());
  292. }
  293. }
  294. internal class AnsiResponseParser : AnsiResponseParserBase
  295. {
  296. /// <summary>
  297. /// <para>
  298. /// Delegate for handling unrecognized escape codes. Default behaviour
  299. /// is to return <see langword="false"/> which simply releases the
  300. /// characters back to input stream for downstream processing.
  301. /// </para>
  302. /// <para>
  303. /// Implement a method to handle if you want and return <see langword="true"/> if you want the
  304. /// keystrokes 'swallowed' (i.e. not returned to input stream).
  305. /// </para>
  306. /// </summary>
  307. public Func<string, bool> UnknownResponseHandler { get; set; } = (_) => false;
  308. public AnsiResponseParser () : base (new StringHeld ()) { }
  309. public string ProcessInput (string input)
  310. {
  311. var output = new StringBuilder ();
  312. ProcessInputBase (
  313. i => input [i],
  314. i => input [i], // For string there is no T so object is same as char
  315. c => output.Append ((char)c),
  316. input.Length);
  317. return output.ToString ();
  318. }
  319. public string Release ()
  320. {
  321. var output = heldContent.HeldToString ();
  322. ResetState ();
  323. return output;
  324. }
  325. /// <inheritdoc />
  326. protected override bool ShouldReleaseUnexpectedResponse ()
  327. {
  328. return !UnknownResponseHandler.Invoke (heldContent.ToString () ?? string.Empty);
  329. }
  330. }