AnsiResponseParser.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. #nullable enable
  2. namespace Terminal.Gui;
  3. internal abstract class AnsiResponseParserBase : IAnsiResponseParser
  4. {
  5. protected object lockExpectedResponses = new object();
  6. protected object lockState = new object ();
  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. // Current state of the parser
  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 (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)
  50. {
  51. this.heldContent = heldContent;
  52. }
  53. protected void ResetState ()
  54. {
  55. State = AnsiResponseParserState.Normal;
  56. heldContent.ClearHeld ();
  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. string cur = heldContent.HeldToString ();
  155. lock (lockExpectedResponses)
  156. {
  157. // Look for an expected response for what is accumulated so far (since Esc)
  158. if (MatchResponse (
  159. cur,
  160. expectedResponses,
  161. invokeCallback: true,
  162. removeExpectation: true))
  163. {
  164. return false;
  165. }
  166. // Also try looking for late requests - in which case we do not invoke but still swallow content to avoid corrupting downstream
  167. if (MatchResponse (
  168. cur,
  169. lateResponses,
  170. invokeCallback: false,
  171. removeExpectation: true))
  172. {
  173. return false;
  174. }
  175. // Look for persistent requests
  176. if (MatchResponse (
  177. cur,
  178. persistentExpectations,
  179. invokeCallback: true,
  180. removeExpectation: false))
  181. {
  182. return false;
  183. }
  184. }
  185. // Finally if it is a valid ansi response but not one we are expect (e.g. its mouse activity)
  186. // then we can release it back to input processing stream
  187. if (_knownTerminators.Contains (cur.Last ()) && cur.StartsWith (EscSeqUtils.CSI))
  188. {
  189. // We have found a terminator so bail
  190. State = AnsiResponseParserState.Normal;
  191. // Maybe swallow anyway if user has custom delegate
  192. var swallow = ShouldSwallowUnexpectedResponse ();
  193. if (swallow)
  194. {
  195. heldContent.ClearHeld ();
  196. // Do not send back to input stream
  197. return false;
  198. }
  199. // Do release back to input stream
  200. return true;
  201. }
  202. return false; // Continue accumulating
  203. }
  204. /// <summary>
  205. /// <para>
  206. /// When overriden in a derived class, indicates whether the unexpected response
  207. /// currently in <see cref="heldContent"/> should be released or swallowed.
  208. /// Use this to enable default event for escape codes.
  209. /// </para>
  210. ///
  211. /// <remarks>Note this is only called for complete responses.
  212. /// Based on <see cref="_knownTerminators"/></remarks>
  213. /// </summary>
  214. /// <returns></returns>
  215. protected abstract bool ShouldSwallowUnexpectedResponse ();
  216. private bool MatchResponse (string cur, List<AnsiResponseExpectation> collection, bool invokeCallback, bool removeExpectation)
  217. {
  218. // Check for expected responses
  219. var matchingResponse = collection.FirstOrDefault (r => r.Matches (cur));
  220. if (matchingResponse?.Response != null)
  221. {
  222. if (invokeCallback)
  223. {
  224. matchingResponse.Response.Invoke (heldContent);
  225. }
  226. ResetState ();
  227. if (removeExpectation)
  228. {
  229. collection.Remove (matchingResponse);
  230. }
  231. return true;
  232. }
  233. return false;
  234. }
  235. /// <inheritdoc />
  236. public void ExpectResponse (string terminator, Action<string> response, bool persistent)
  237. {
  238. lock (lockExpectedResponses)
  239. {
  240. if (persistent)
  241. {
  242. persistentExpectations.Add (new (terminator, (h) => response.Invoke (h.HeldToString ())));
  243. }
  244. else
  245. {
  246. expectedResponses.Add (new (terminator, (h) => response.Invoke (h.HeldToString ())));
  247. }
  248. }
  249. }
  250. /// <inheritdoc />
  251. public bool IsExpecting (string terminator)
  252. {
  253. lock (lockExpectedResponses)
  254. {
  255. // If any of the new terminator matches any existing terminators characters it's a collision so true.
  256. return expectedResponses.Any (r => r.Terminator.Intersect (terminator).Any ());
  257. }
  258. }
  259. /// <inheritdoc />
  260. public void StopExpecting (string terminator, bool persistent)
  261. {
  262. lock (lockExpectedResponses)
  263. {
  264. if (persistent)
  265. {
  266. persistentExpectations.RemoveAll (r => r.Matches (terminator));
  267. }
  268. else
  269. {
  270. var removed = expectedResponses.Where (r => r.Terminator == terminator).ToArray ();
  271. foreach (var r in removed)
  272. {
  273. expectedResponses.Remove (r);
  274. lateResponses.Add (r);
  275. }
  276. }
  277. }
  278. }
  279. }
  280. internal class AnsiResponseParser<T> : AnsiResponseParserBase
  281. {
  282. public AnsiResponseParser () : base (new GenericHeld<T> ()) { }
  283. /// <inheritdoc cref="AnsiResponseParser.UnknownResponseHandler"/>
  284. public Func<IEnumerable<Tuple<char, T>>, bool> UnexpectedResponseHandler { get; set; } = (_) => false;
  285. public IEnumerable<Tuple<char, T>> ProcessInput (params Tuple<char, T> [] input)
  286. {
  287. List<Tuple<char, T>> output = new List<Tuple<char, T>> ();
  288. ProcessInputBase (
  289. i => input [i].Item1,
  290. i => input [i],
  291. c => output.Add ((Tuple<char, T>)c),
  292. input.Length);
  293. return output;
  294. }
  295. public IEnumerable<Tuple<char, T>> Release ()
  296. {
  297. // Lock in case Release is called from different Thread from parse
  298. lock (lockState)
  299. {
  300. foreach (Tuple<char, T> h in HeldToEnumerable())
  301. {
  302. yield return h;
  303. }
  304. ResetState ();
  305. }
  306. }
  307. private IEnumerable<Tuple<char, T>> HeldToEnumerable ()
  308. {
  309. return (IEnumerable<Tuple<char, T>>)heldContent.HeldToObjects ();
  310. }
  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="persistent"></param>
  318. public void ExpectResponseT (string terminator, Action<IEnumerable<Tuple<char,T>>> response, bool persistent)
  319. {
  320. lock (lockExpectedResponses)
  321. {
  322. if (persistent)
  323. {
  324. persistentExpectations.Add (new (terminator, (h) => response.Invoke (HeldToEnumerable ())));
  325. }
  326. else
  327. {
  328. expectedResponses.Add (new (terminator, (h) => response.Invoke (HeldToEnumerable ())));
  329. }
  330. }
  331. }
  332. /// <inheritdoc />
  333. protected override bool ShouldSwallowUnexpectedResponse ()
  334. {
  335. return UnexpectedResponseHandler.Invoke (HeldToEnumerable ());
  336. }
  337. }
  338. internal class AnsiResponseParser : AnsiResponseParserBase
  339. {
  340. /// <summary>
  341. /// <para>
  342. /// Delegate for handling unrecognized escape codes. Default behaviour
  343. /// is to return <see langword="false"/> which simply releases the
  344. /// characters back to input stream for downstream processing.
  345. /// </para>
  346. /// <para>
  347. /// Implement a method to handle if you want and return <see langword="true"/> if you want the
  348. /// keystrokes 'swallowed' (i.e. not returned to input stream).
  349. /// </para>
  350. /// </summary>
  351. public Func<string, bool> UnknownResponseHandler { get; set; } = (_) => false;
  352. public AnsiResponseParser () : base (new StringHeld ()) { }
  353. public string ProcessInput (string input)
  354. {
  355. var output = new StringBuilder ();
  356. ProcessInputBase (
  357. i => input [i],
  358. i => input [i], // For string there is no T so object is same as char
  359. c => output.Append ((char)c),
  360. input.Length);
  361. return output.ToString ();
  362. }
  363. public string Release ()
  364. {
  365. lock (lockState)
  366. {
  367. var output = heldContent.HeldToString ();
  368. ResetState ();
  369. return output;
  370. }
  371. }
  372. /// <inheritdoc />
  373. protected override bool ShouldSwallowUnexpectedResponse ()
  374. {
  375. return UnknownResponseHandler.Invoke (heldContent.HeldToString ());
  376. }
  377. }