AnsiResponseParser.cs 15 KB

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