AnsiResponseParser.cs 14 KB

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