AnsiResponseParser.cs 15 KB

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