AnsiResponseParser.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. #nullable enable
  2. using System.Runtime.ConstrainedExecution;
  3. namespace Terminal.Gui;
  4. internal abstract class AnsiResponseParserBase : IAnsiResponseParser
  5. {
  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. // Look for an expected response for what is accumulated so far (since Esc)
  143. if (MatchResponse (cur,
  144. expectedResponses,
  145. invokeCallback: true,
  146. removeExpectation:true))
  147. {
  148. return false;
  149. }
  150. // Also try looking for late requests - in which case we do not invoke but still swallow content to avoid corrupting downstream
  151. if (MatchResponse (cur,
  152. lateResponses,
  153. invokeCallback: false,
  154. removeExpectation:true))
  155. {
  156. return false;
  157. }
  158. // Look for persistent requests
  159. if (MatchResponse (cur,
  160. persistentExpectations,
  161. invokeCallback: true,
  162. removeExpectation:false))
  163. {
  164. return false;
  165. }
  166. // Finally if it is a valid ansi response but not one we are expect (e.g. its mouse activity)
  167. // then we can release it back to input processing stream
  168. if (_knownTerminators.Contains (cur.Last ()) && cur.StartsWith (EscSeqUtils.CSI))
  169. {
  170. // Detected a response that was not expected
  171. return true;
  172. }
  173. return false; // Continue accumulating
  174. }
  175. private bool MatchResponse (string cur, List<AnsiResponseExpectation> collection, bool invokeCallback, bool removeExpectation)
  176. {
  177. // Check for expected responses
  178. var matchingResponse = collection.FirstOrDefault (r => r.Matches(cur));
  179. if (matchingResponse?.Response != null)
  180. {
  181. if (invokeCallback)
  182. {
  183. matchingResponse.Response?.Invoke (heldContent.HeldToString ());
  184. }
  185. ResetState ();
  186. if (removeExpectation)
  187. {
  188. collection.Remove (matchingResponse);
  189. }
  190. return true;
  191. }
  192. return false;
  193. }
  194. /// <inheritdoc />
  195. public void ExpectResponse (string terminator, Action<string> response, bool persistent)
  196. {
  197. if (persistent)
  198. {
  199. persistentExpectations.Add (new (terminator, response));
  200. }
  201. else
  202. {
  203. expectedResponses.Add (new (terminator, response));
  204. }
  205. }
  206. /// <inheritdoc />
  207. public bool IsExpecting (string terminator)
  208. {
  209. // If any of the new terminator matches any existing terminators characters it's a collision so true.
  210. return expectedResponses.Any (r => r.Terminator.Intersect (terminator).Any());
  211. }
  212. /// <inheritdoc />
  213. public void StopExpecting (string terminator, bool persistent)
  214. {
  215. if (persistent)
  216. {
  217. persistentExpectations.RemoveAll (r=>r.Matches (terminator));
  218. }
  219. else
  220. {
  221. var removed = expectedResponses.Where (r => r.Terminator == terminator).ToArray ();
  222. foreach (var r in removed)
  223. {
  224. expectedResponses.Remove (r);
  225. lateResponses.Add (r);
  226. }
  227. }
  228. }
  229. }
  230. internal interface IHeld
  231. {
  232. void ClearHeld ();
  233. string HeldToString ();
  234. IEnumerable<object> HeldToObjects ();
  235. void AddToHeld (object o);
  236. }
  237. internal class StringHeld : IHeld
  238. {
  239. private readonly StringBuilder held = new ();
  240. public void ClearHeld () => held.Clear ();
  241. public string HeldToString () => held.ToString ();
  242. public IEnumerable<object> HeldToObjects () => held.ToString ().Select (c => (object)c);
  243. public void AddToHeld (object o) => held.Append ((char)o);
  244. }
  245. internal class GenericHeld<T> : IHeld
  246. {
  247. private readonly List<Tuple<char, T>> held = new ();
  248. public void ClearHeld () => held.Clear ();
  249. public string HeldToString () => new (held.Select (h => h.Item1).ToArray ());
  250. public IEnumerable<object> HeldToObjects () => held;
  251. public void AddToHeld (object o) => held.Add ((Tuple<char, T>)o);
  252. }
  253. internal class AnsiResponseParser<T> : AnsiResponseParserBase
  254. {
  255. public AnsiResponseParser () : base (new GenericHeld<T> ()) { }
  256. public IEnumerable<Tuple<char, T>> ProcessInput (params Tuple<char, T> [] input)
  257. {
  258. List<Tuple<char, T>> output = new List<Tuple<char, T>> ();
  259. ProcessInputBase (
  260. i => input [i].Item1,
  261. i => input [i],
  262. c => output.Add ((Tuple<char, T>)c),
  263. input.Length);
  264. return output;
  265. }
  266. public IEnumerable<Tuple<char, T>> Release ()
  267. {
  268. foreach (Tuple<char, T> h in (IEnumerable<Tuple<char, T>>)heldContent.HeldToObjects ())
  269. {
  270. yield return h;
  271. }
  272. ResetState ();
  273. }
  274. }
  275. internal class AnsiResponseParser : AnsiResponseParserBase
  276. {
  277. public AnsiResponseParser () : base (new StringHeld ()) { }
  278. public string ProcessInput (string input)
  279. {
  280. var output = new StringBuilder ();
  281. ProcessInputBase (
  282. i => input [i],
  283. i => input [i], // For string there is no T so object is same as char
  284. c => output.Append ((char)c),
  285. input.Length);
  286. return output.ToString ();
  287. }
  288. public string Release ()
  289. {
  290. var output = heldContent.HeldToString ();
  291. ResetState ();
  292. return output;
  293. }
  294. }