MainLoop.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. #nullable enable
  2. //
  3. // MainLoop.cs: IMainLoopDriver and MainLoop for Terminal.Gui
  4. //
  5. // Authors:
  6. // Miguel de Icaza ([email protected])
  7. //
  8. using System.Collections.ObjectModel;
  9. namespace Terminal.Gui;
  10. /// <summary>Interface to create a platform specific <see cref="MainLoop"/> driver.</summary>
  11. internal interface IMainLoopDriver
  12. {
  13. /// <summary>Must report whether there are any events pending, or even block waiting for events.</summary>
  14. /// <returns><c>true</c>, if there were pending events, <c>false</c> otherwise.</returns>
  15. bool EventsPending ();
  16. /// <summary>The iteration function.</summary>
  17. void Iteration ();
  18. /// <summary>Initializes the <see cref="MainLoop"/>, gets the calling main loop for the initialization.</summary>
  19. /// <remarks>Call <see cref="TearDown"/> to release resources.</remarks>
  20. /// <param name="mainLoop">Main loop.</param>
  21. void Setup (MainLoop mainLoop);
  22. /// <summary>Tears down the <see cref="MainLoop"/> driver. Releases resources created in <see cref="Setup"/>.</summary>
  23. void TearDown ();
  24. /// <summary>Wakes up the <see cref="MainLoop"/> that might be waiting on input, must be thread safe.</summary>
  25. void Wakeup ();
  26. }
  27. /// <summary>The MainLoop monitors timers and idle handlers.</summary>
  28. /// <remarks>
  29. /// Monitoring of file descriptors is only available on Unix, there does not seem to be a way of supporting this
  30. /// on Windows.
  31. /// </remarks>
  32. public class MainLoop : IDisposable
  33. {
  34. internal List<Func<bool>> _idleHandlers = new ();
  35. internal SortedList<long, Timeout> _timeouts = new ();
  36. /// <summary>The idle handlers and lock that must be held while manipulating them</summary>
  37. private readonly object _idleHandlersLock = new ();
  38. private readonly object _timeoutsLockToken = new ();
  39. /// <summary>Creates a new MainLoop.</summary>
  40. /// <remarks>Use <see cref="Dispose"/> to release resources.</remarks>
  41. /// <param name="driver">
  42. /// The <see cref="IConsoleDriver"/> instance (one of the implementations FakeMainLoop, UnixMainLoop,
  43. /// NetMainLoop or WindowsMainLoop).
  44. /// </param>
  45. internal MainLoop (IMainLoopDriver driver)
  46. {
  47. MainLoopDriver = driver;
  48. driver.Setup (this);
  49. }
  50. /// <summary>Gets a copy of the list of all idle handlers.</summary>
  51. internal ReadOnlyCollection<Func<bool>> IdleHandlers
  52. {
  53. get
  54. {
  55. lock (_idleHandlersLock)
  56. {
  57. return new List<Func<bool>> (_idleHandlers).AsReadOnly ();
  58. }
  59. }
  60. }
  61. /// <summary>The current <see cref="IMainLoopDriver"/> in use.</summary>
  62. /// <value>The main loop driver.</value>
  63. internal IMainLoopDriver? MainLoopDriver { get; private set; }
  64. /// <summary>Used for unit tests.</summary>
  65. internal bool Running { get; set; }
  66. /// <summary>
  67. /// Gets the list of all timeouts sorted by the <see cref="TimeSpan"/> time ticks. A shorter limit time can be
  68. /// added at the end, but it will be called before an earlier addition that has a longer limit time.
  69. /// </summary>
  70. internal SortedList<long, Timeout> Timeouts => _timeouts;
  71. /// <inheritdoc/>
  72. public void Dispose ()
  73. {
  74. GC.SuppressFinalize (this);
  75. Stop ();
  76. Running = false;
  77. MainLoopDriver?.TearDown ();
  78. MainLoopDriver = null;
  79. }
  80. /// <summary>
  81. /// Adds specified idle handler function to <see cref="MainLoop"/> processing. The handler function will be called
  82. /// once per iteration of the main loop after other events have been handled.
  83. /// </summary>
  84. /// <remarks>
  85. /// <para>Remove an idle handler by calling <see cref="RemoveIdle(Func{bool})"/> with the token this method returns.</para>
  86. /// <para>
  87. /// If the <paramref name="idleHandler"/> returns <see langword="false"/> it will be removed and not called
  88. /// subsequently.
  89. /// </para>
  90. /// </remarks>
  91. /// <param name="idleHandler">Token that can be used to remove the idle handler with <see cref="RemoveIdle(Func{bool})"/> .</param>
  92. // QUESTION: Why are we re-inventing the event wheel here?
  93. // PERF: This is heavy.
  94. // CONCURRENCY: Race conditions exist here.
  95. // CONCURRENCY: null delegates will hose this.
  96. //
  97. internal Func<bool> AddIdle (Func<bool> idleHandler)
  98. {
  99. lock (_idleHandlersLock)
  100. {
  101. _idleHandlers.Add (idleHandler);
  102. }
  103. MainLoopDriver?.Wakeup ();
  104. return idleHandler;
  105. }
  106. /// <summary>Adds a timeout to the <see cref="MainLoop"/>.</summary>
  107. /// <remarks>
  108. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  109. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  110. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  111. /// </remarks>
  112. internal object AddTimeout (TimeSpan time, Func<bool> callback)
  113. {
  114. ArgumentNullException.ThrowIfNull (callback);
  115. var timeout = new Timeout { Span = time, Callback = callback };
  116. AddTimeout (time, timeout);
  117. return timeout;
  118. }
  119. /// <summary>
  120. /// Called from <see cref="IMainLoopDriver.EventsPending"/> to check if there are any outstanding timers or idle
  121. /// handlers.
  122. /// </summary>
  123. /// <param name="waitTimeout">
  124. /// Returns the number of milliseconds remaining in the current timer (if any). Will be -1 if
  125. /// there are no active timers.
  126. /// </param>
  127. /// <returns><see langword="true"/> if there is a timer or idle handler active.</returns>
  128. internal bool CheckTimersAndIdleHandlers (out int waitTimeout)
  129. {
  130. long now = DateTime.UtcNow.Ticks;
  131. waitTimeout = 0;
  132. lock (_timeoutsLockToken)
  133. {
  134. if (_timeouts.Count > 0)
  135. {
  136. waitTimeout = (int)((_timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  137. if (waitTimeout < 0)
  138. {
  139. // This avoids 'poll' waiting infinitely if 'waitTimeout < 0' until some action is detected
  140. // This can occur after IMainLoopDriver.Wakeup is executed where the pollTimeout is less than 0
  141. // and no event occurred in elapsed time when the 'poll' is start running again.
  142. waitTimeout = 0;
  143. }
  144. return true;
  145. }
  146. // ManualResetEventSlim.Wait, which is called by IMainLoopDriver.EventsPending, will wait indefinitely if
  147. // the timeout is -1.
  148. waitTimeout = -1;
  149. }
  150. // There are no timers set, check if there are any idle handlers
  151. lock (_idleHandlers)
  152. {
  153. return _idleHandlers.Count > 0;
  154. }
  155. }
  156. /// <summary>Determines whether there are pending events to be processed.</summary>
  157. /// <remarks>
  158. /// You can use this method if you want to probe if events are pending. Typically used if you need to flush the
  159. /// input queue while still running some of your own code in your main thread.
  160. /// </remarks>
  161. internal bool EventsPending () { return MainLoopDriver!.EventsPending (); }
  162. /// <summary>Removes an idle handler added with <see cref="AddIdle(Func{bool})"/> from processing.</summary>
  163. /// <param name="token">A token returned by <see cref="AddIdle(Func{bool})"/></param>
  164. /// Returns
  165. /// <c>true</c>
  166. /// if the idle handler is successfully removed; otherwise,
  167. /// <c>false</c>
  168. /// .
  169. /// This method also returns
  170. /// <c>false</c>
  171. /// if the idle handler is not found.
  172. internal bool RemoveIdle (Func<bool> token)
  173. {
  174. lock (_idleHandlersLock)
  175. {
  176. return _idleHandlers.Remove (token);
  177. }
  178. }
  179. /// <summary>Removes a previously scheduled timeout</summary>
  180. /// <remarks>The token parameter is the value returned by AddTimeout.</remarks>
  181. /// Returns
  182. /// <c>true</c>
  183. /// if the timeout is successfully removed; otherwise,
  184. /// <c>false</c>
  185. /// .
  186. /// This method also returns
  187. /// <c>false</c>
  188. /// if the timeout is not found.
  189. internal bool RemoveTimeout (object token)
  190. {
  191. lock (_timeoutsLockToken)
  192. {
  193. int idx = _timeouts.IndexOfValue ((token as Timeout)!);
  194. if (idx == -1)
  195. {
  196. return false;
  197. }
  198. _timeouts.RemoveAt (idx);
  199. }
  200. return true;
  201. }
  202. /// <summary>Runs the <see cref="MainLoop"/>. Used only for unit tests.</summary>
  203. internal void Run ()
  204. {
  205. bool prev = Running;
  206. Running = true;
  207. while (Running)
  208. {
  209. EventsPending ();
  210. RunIteration ();
  211. }
  212. Running = prev;
  213. }
  214. /// <summary>Runs one iteration of timers and file watches</summary>
  215. /// <remarks>
  216. /// Use this to process all pending events (timers, idle handlers and file watches).
  217. /// <code>
  218. /// while (main.EventsPending ()) RunIteration ();
  219. /// </code>
  220. /// </remarks>
  221. internal void RunIteration ()
  222. {
  223. lock (_timeoutsLockToken)
  224. {
  225. if (_timeouts.Count > 0)
  226. {
  227. RunTimers ();
  228. }
  229. }
  230. RunAnsiScheduler ();
  231. MainLoopDriver?.Iteration ();
  232. bool runIdle;
  233. lock (_idleHandlersLock)
  234. {
  235. runIdle = _idleHandlers.Count > 0;
  236. }
  237. if (runIdle)
  238. {
  239. RunIdle ();
  240. }
  241. }
  242. private void RunAnsiScheduler ()
  243. {
  244. Application.Driver?.GetRequestScheduler ().RunSchedule ();
  245. }
  246. /// <summary>Stops the main loop driver and calls <see cref="IMainLoopDriver.Wakeup"/>. Used only for unit tests.</summary>
  247. internal void Stop ()
  248. {
  249. Running = false;
  250. Wakeup ();
  251. }
  252. /// <summary>
  253. /// Invoked when a new timeout is added. To be used in the case when
  254. /// <see cref="Application.EndAfterFirstIteration"/> is <see langword="true"/>.
  255. /// </summary>
  256. internal event EventHandler<TimeoutEventArgs>? TimeoutAdded;
  257. /// <summary>Wakes up the <see cref="MainLoop"/> that might be waiting on input.</summary>
  258. internal void Wakeup () { MainLoopDriver?.Wakeup (); }
  259. private void AddTimeout (TimeSpan time, Timeout timeout)
  260. {
  261. lock (_timeoutsLockToken)
  262. {
  263. long k = (DateTime.UtcNow + time).Ticks;
  264. _timeouts.Add (NudgeToUniqueKey (k), timeout);
  265. TimeoutAdded?.Invoke (this, new TimeoutEventArgs (timeout, k));
  266. }
  267. }
  268. /// <summary>
  269. /// Finds the closest number to <paramref name="k"/> that is not present in <see cref="_timeouts"/>
  270. /// (incrementally).
  271. /// </summary>
  272. /// <param name="k"></param>
  273. /// <returns></returns>
  274. private long NudgeToUniqueKey (long k)
  275. {
  276. lock (_timeoutsLockToken)
  277. {
  278. while (_timeouts.ContainsKey (k))
  279. {
  280. k++;
  281. }
  282. }
  283. return k;
  284. }
  285. // PERF: This is heavier than it looks.
  286. // CONCURRENCY: Potential deadlock city here.
  287. // CONCURRENCY: Multiple concurrency pitfalls on the delegates themselves.
  288. // INTENT: It looks like the general architecture here is trying to be a form of publisher/consumer pattern.
  289. private void RunIdle ()
  290. {
  291. List<Func<bool>> iterate;
  292. lock (_idleHandlersLock)
  293. {
  294. iterate = _idleHandlers;
  295. _idleHandlers = new List<Func<bool>> ();
  296. }
  297. foreach (Func<bool> idle in iterate)
  298. {
  299. if (idle ())
  300. {
  301. lock (_idleHandlersLock)
  302. {
  303. _idleHandlers.Add (idle);
  304. }
  305. }
  306. }
  307. }
  308. private void RunTimers ()
  309. {
  310. long now = DateTime.UtcNow.Ticks;
  311. SortedList<long, Timeout> copy;
  312. // lock prevents new timeouts being added
  313. // after we have taken the copy but before
  314. // we have allocated a new list (which would
  315. // result in lost timeouts or errors during enumeration)
  316. lock (_timeoutsLockToken)
  317. {
  318. copy = _timeouts;
  319. _timeouts = new SortedList<long, Timeout> ();
  320. }
  321. foreach ((long k, Timeout timeout) in copy)
  322. {
  323. if (k < now)
  324. {
  325. if (timeout.Callback ())
  326. {
  327. AddTimeout (timeout.Span, timeout);
  328. }
  329. }
  330. else
  331. {
  332. lock (_timeoutsLockToken)
  333. {
  334. _timeouts.Add (NudgeToUniqueKey (k), timeout);
  335. }
  336. }
  337. }
  338. }
  339. }