AnsiResponseParser.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. using System.Runtime.ConstrainedExecution;
  4. namespace Terminal.Gui;
  5. public class AnsiRequestScheduler(IAnsiResponseParser parser)
  6. {
  7. public static int sent = 0;
  8. public List<AnsiEscapeSequenceRequest> Requests = new ();
  9. private ConcurrentDictionary<string, DateTime> _lastSend = new ();
  10. private TimeSpan _throttle = TimeSpan.FromMilliseconds (100);
  11. private TimeSpan _runScheduleThrottle = TimeSpan.FromMilliseconds (100);
  12. /// <summary>
  13. /// Sends the <paramref name="request"/> immediately or queues it if there is already
  14. /// an outstanding request for the given <see cref="AnsiEscapeSequenceRequest.Terminator"/>.
  15. /// </summary>
  16. /// <param name="request"></param>
  17. /// <returns><see langword="true"/> if request was sent immediately. <see langword="false"/> if it was queued.</returns>
  18. public bool SendOrSchedule (AnsiEscapeSequenceRequest request )
  19. {
  20. if (CanSend(request))
  21. {
  22. Send (request);
  23. return true;
  24. }
  25. else
  26. {
  27. Requests.Add (request);
  28. return false;
  29. }
  30. }
  31. private DateTime _lastRun = DateTime.Now;
  32. /// <summary>
  33. /// Identifies and runs any <see cref="Requests"/> that can be sent based on the
  34. /// current outstanding requests of the parser.
  35. /// </summary>
  36. /// <param name="force">Repeated requests to run the schedule over short period of time will be ignored.
  37. /// Pass <see langword="true"/> to override this behaviour and force evaluation of outstanding requests.</param>
  38. /// <returns><see langword="true"/> if a request was found and run. <see langword="false"/>
  39. /// if no outstanding requests or all have existing outstanding requests underway in parser.</returns>
  40. public bool RunSchedule (bool force = false)
  41. {
  42. if (!force && DateTime.Now - _lastRun < _runScheduleThrottle)
  43. {
  44. return false;
  45. }
  46. var opportunity = Requests.FirstOrDefault (CanSend);
  47. if (opportunity != null)
  48. {
  49. Requests.Remove (opportunity);
  50. Send (opportunity);
  51. return true;
  52. }
  53. return false;
  54. }
  55. private void Send (AnsiEscapeSequenceRequest r)
  56. {
  57. Interlocked.Increment(ref sent);
  58. _lastSend.AddOrUpdate (r.Terminator,(s)=>DateTime.Now,(s,v)=>DateTime.Now);
  59. parser.ExpectResponse (r.Terminator,r.ResponseReceived);
  60. r.Send ();
  61. }
  62. public bool CanSend (AnsiEscapeSequenceRequest r)
  63. {
  64. if (ShouldThrottle (r))
  65. {
  66. return false;
  67. }
  68. return !parser.IsExpecting (r.Terminator);
  69. }
  70. private bool ShouldThrottle (AnsiEscapeSequenceRequest r)
  71. {
  72. if (_lastSend.TryGetValue (r.Terminator, out DateTime value))
  73. {
  74. return DateTime.Now - value < _throttle;
  75. }
  76. return false;
  77. }
  78. }
  79. internal abstract class AnsiResponseParserBase : IAnsiResponseParser
  80. {
  81. protected readonly List<(string terminator, Action<string> response)> expectedResponses = new ();
  82. private AnsiResponseParserState _state = AnsiResponseParserState.Normal;
  83. // Current state of the parser
  84. public AnsiResponseParserState State
  85. {
  86. get => _state;
  87. protected set
  88. {
  89. StateChangedAt = DateTime.Now;
  90. _state = value;
  91. }
  92. }
  93. /// <summary>
  94. /// When <see cref="State"/> was last changed.
  95. /// </summary>
  96. public DateTime StateChangedAt { get; private set; } = DateTime.Now;
  97. protected readonly HashSet<char> _knownTerminators = new ();
  98. public AnsiResponseParserBase ()
  99. {
  100. // These all are valid terminators on ansi responses,
  101. // see CSI in https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s
  102. _knownTerminators.Add ('@');
  103. _knownTerminators.Add ('A');
  104. _knownTerminators.Add ('B');
  105. _knownTerminators.Add ('C');
  106. _knownTerminators.Add ('D');
  107. _knownTerminators.Add ('E');
  108. _knownTerminators.Add ('F');
  109. _knownTerminators.Add ('G');
  110. _knownTerminators.Add ('G');
  111. _knownTerminators.Add ('H');
  112. _knownTerminators.Add ('I');
  113. _knownTerminators.Add ('J');
  114. _knownTerminators.Add ('K');
  115. _knownTerminators.Add ('L');
  116. _knownTerminators.Add ('M');
  117. // No - N or O
  118. _knownTerminators.Add ('P');
  119. _knownTerminators.Add ('Q');
  120. _knownTerminators.Add ('R');
  121. _knownTerminators.Add ('S');
  122. _knownTerminators.Add ('T');
  123. _knownTerminators.Add ('W');
  124. _knownTerminators.Add ('X');
  125. _knownTerminators.Add ('Z');
  126. _knownTerminators.Add ('^');
  127. _knownTerminators.Add ('`');
  128. _knownTerminators.Add ('~');
  129. _knownTerminators.Add ('a');
  130. _knownTerminators.Add ('b');
  131. _knownTerminators.Add ('c');
  132. _knownTerminators.Add ('d');
  133. _knownTerminators.Add ('e');
  134. _knownTerminators.Add ('f');
  135. _knownTerminators.Add ('g');
  136. _knownTerminators.Add ('h');
  137. _knownTerminators.Add ('i');
  138. _knownTerminators.Add ('l');
  139. _knownTerminators.Add ('m');
  140. _knownTerminators.Add ('n');
  141. _knownTerminators.Add ('p');
  142. _knownTerminators.Add ('q');
  143. _knownTerminators.Add ('r');
  144. _knownTerminators.Add ('s');
  145. _knownTerminators.Add ('t');
  146. _knownTerminators.Add ('u');
  147. _knownTerminators.Add ('v');
  148. _knownTerminators.Add ('w');
  149. _knownTerminators.Add ('x');
  150. _knownTerminators.Add ('y');
  151. _knownTerminators.Add ('z');
  152. }
  153. protected void ResetState ()
  154. {
  155. State = AnsiResponseParserState.Normal;
  156. ClearHeld ();
  157. }
  158. public abstract void ClearHeld ();
  159. protected abstract string HeldToString ();
  160. protected abstract IEnumerable<object> HeldToObjects ();
  161. protected abstract void AddToHeld (object o);
  162. /// <summary>
  163. /// Processes an input collection of objects <paramref name="inputLength"/> long.
  164. /// You must provide the indexers to return the objects and the action to append
  165. /// to output stream.
  166. /// </summary>
  167. /// <param name="getCharAtIndex">The character representation of element i of your input collection</param>
  168. /// <param name="getObjectAtIndex">The actual element in the collection (e.g. char or Tuple&lt;char,T&gt;)</param>
  169. /// <param name="appendOutput">
  170. /// Action to invoke when parser confirms an element of the current collection or a previous
  171. /// call's collection should be appended to the current output (i.e. append to your output List/StringBuilder).
  172. /// </param>
  173. /// <param name="inputLength">The total number of elements in your collection</param>
  174. protected void ProcessInputBase (
  175. Func<int, char> getCharAtIndex,
  176. Func<int, object> getObjectAtIndex,
  177. Action<object> appendOutput,
  178. int inputLength
  179. )
  180. {
  181. var index = 0; // Tracks position in the input string
  182. while (index < inputLength)
  183. {
  184. char currentChar = getCharAtIndex (index);
  185. object currentObj = getObjectAtIndex (index);
  186. bool isEscape = currentChar == '\x1B';
  187. switch (State)
  188. {
  189. case AnsiResponseParserState.Normal:
  190. if (isEscape)
  191. {
  192. // Escape character detected, move to ExpectingBracket state
  193. State = AnsiResponseParserState.ExpectingBracket;
  194. AddToHeld (currentObj); // Hold the escape character
  195. }
  196. else
  197. {
  198. // Normal character, append to output
  199. appendOutput (currentObj);
  200. }
  201. break;
  202. case AnsiResponseParserState.ExpectingBracket:
  203. if (isEscape)
  204. {
  205. // Second escape so we must release first
  206. ReleaseHeld (appendOutput, AnsiResponseParserState.ExpectingBracket);
  207. AddToHeld (currentObj); // Hold the new escape
  208. }
  209. else if (currentChar == '[')
  210. {
  211. // Detected '[', transition to InResponse state
  212. State = AnsiResponseParserState.InResponse;
  213. AddToHeld (currentObj); // Hold the '['
  214. }
  215. else
  216. {
  217. // Invalid sequence, release held characters and reset to Normal
  218. ReleaseHeld (appendOutput);
  219. appendOutput (currentObj); // Add current character
  220. }
  221. break;
  222. case AnsiResponseParserState.InResponse:
  223. AddToHeld (currentObj);
  224. // Check if the held content should be released
  225. if (ShouldReleaseHeldContent ())
  226. {
  227. ReleaseHeld (appendOutput);
  228. }
  229. break;
  230. }
  231. index++;
  232. }
  233. }
  234. private void ReleaseHeld (Action<object> appendOutput, AnsiResponseParserState newState = AnsiResponseParserState.Normal)
  235. {
  236. foreach (object o in HeldToObjects ())
  237. {
  238. appendOutput (o);
  239. }
  240. State = newState;
  241. ClearHeld ();
  242. }
  243. // Common response handler logic
  244. protected bool ShouldReleaseHeldContent ()
  245. {
  246. string cur = HeldToString ();
  247. // Check for expected responses
  248. (string terminator, Action<string> response) matchingResponse = expectedResponses.FirstOrDefault (r => cur.EndsWith (r.terminator));
  249. if (matchingResponse.response != null)
  250. {
  251. DispatchResponse (matchingResponse.response);
  252. expectedResponses.Remove (matchingResponse);
  253. return false;
  254. }
  255. if (_knownTerminators.Contains (cur.Last ()) && cur.StartsWith (EscSeqUtils.CSI))
  256. {
  257. // Detected a response that was not expected
  258. return true;
  259. }
  260. return false; // Continue accumulating
  261. }
  262. protected void DispatchResponse (Action<string> response)
  263. {
  264. response?.Invoke (HeldToString ());
  265. ResetState ();
  266. }
  267. /// <summary>
  268. /// Registers a new expected ANSI response with a specific terminator and a callback for when the response is
  269. /// completed.
  270. /// </summary>
  271. public void ExpectResponse (string terminator, Action<string> response) { expectedResponses.Add ((terminator, response)); }
  272. /// <inheritdoc />
  273. public bool IsExpecting (string requestTerminator)
  274. {
  275. // If any of the new terminator matches any existing terminators characters it's a collision so true.
  276. return expectedResponses.Any (r => r.terminator.Intersect (requestTerminator).Any());
  277. }
  278. }
  279. internal class AnsiResponseParser<T> : AnsiResponseParserBase
  280. {
  281. private readonly List<Tuple<char, T>> held = new ();
  282. public IEnumerable<Tuple<char, T>> ProcessInput (params Tuple<char, T> [] input)
  283. {
  284. List<Tuple<char, T>> output = new List<Tuple<char, T>> ();
  285. ProcessInputBase (
  286. i => input [i].Item1,
  287. i => input [i],
  288. c => output.Add ((Tuple<char, T>)c),
  289. input.Length);
  290. return output;
  291. }
  292. public IEnumerable<Tuple<char, T>> Release ()
  293. {
  294. foreach (Tuple<char, T> h in held.ToArray ())
  295. {
  296. yield return h;
  297. }
  298. ResetState ();
  299. }
  300. public override void ClearHeld () { held.Clear (); }
  301. protected override string HeldToString () { return new (held.Select (h => h.Item1).ToArray ()); }
  302. protected override IEnumerable<object> HeldToObjects () { return held; }
  303. protected override void AddToHeld (object o) { held.Add ((Tuple<char, T>)o); }
  304. }
  305. internal class AnsiResponseParser : AnsiResponseParserBase
  306. {
  307. private readonly StringBuilder held = new ();
  308. public string ProcessInput (string input)
  309. {
  310. var output = new StringBuilder ();
  311. ProcessInputBase (
  312. i => input [i],
  313. i => input [i], // For string there is no T so object is same as char
  314. c => output.Append ((char)c),
  315. input.Length);
  316. return output.ToString ();
  317. }
  318. public string Release ()
  319. {
  320. var output = held.ToString ();
  321. ResetState ();
  322. return output;
  323. }
  324. public override void ClearHeld () { held.Clear (); }
  325. protected override string HeldToString () { return held.ToString (); }
  326. protected override IEnumerable<object> HeldToObjects () { return held.ToString ().Select (c => (object)c).ToArray (); }
  327. protected override void AddToHeld (object o) { held.Append ((char)o); }
  328. }
  329. /// <summary>
  330. /// Describes an ongoing ANSI request sent to the console.
  331. /// Use <see cref="ResponseReceived"/> to handle the response
  332. /// when console answers the request.
  333. /// </summary>
  334. public class AnsiEscapeSequenceRequest
  335. {
  336. /// <summary>
  337. /// Request to send e.g. see
  338. /// <see>
  339. /// <cref>EscSeqUtils.CSI_SendDeviceAttributes.Request</cref>
  340. /// </see>
  341. /// </summary>
  342. public required string Request { get; init; }
  343. /// <summary>
  344. /// Invoked when the console responds with an ANSI response code that matches the
  345. /// <see cref="Terminator"/>
  346. /// </summary>
  347. public Action<string> ResponseReceived;
  348. /// <summary>
  349. /// <para>
  350. /// The terminator that uniquely identifies the type of response as responded
  351. /// by the console. e.g. for
  352. /// <see>
  353. /// <cref>EscSeqUtils.CSI_SendDeviceAttributes.Request</cref>
  354. /// </see>
  355. /// the terminator is
  356. /// <see>
  357. /// <cref>EscSeqUtils.CSI_SendDeviceAttributes.Terminator</cref>
  358. /// </see>
  359. /// .
  360. /// </para>
  361. /// <para>
  362. /// After sending a request, the first response with matching terminator will be matched
  363. /// to the oldest outstanding request.
  364. /// </para>
  365. /// </summary>
  366. public required string Terminator { get; init; }
  367. /// <summary>
  368. /// Sends the <see cref="Request"/> to the raw output stream of the current <see cref="ConsoleDriver"/>.
  369. /// Only call this method from the main UI thread. You should use <see cref="AnsiRequestScheduler"/> if
  370. /// sending many requests.
  371. /// </summary>
  372. public void Send ()
  373. {
  374. Application.Driver?.RawWrite (Request);
  375. }
  376. }