MainLoop.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. MainLoopDriver?.Iteration ();
  231. bool runIdle;
  232. lock (_idleHandlersLock)
  233. {
  234. runIdle = _idleHandlers.Count > 0;
  235. }
  236. if (runIdle)
  237. {
  238. RunIdle ();
  239. }
  240. }
  241. /// <summary>Stops the main loop driver and calls <see cref="IMainLoopDriver.Wakeup"/>. Used only for unit tests.</summary>
  242. internal void Stop ()
  243. {
  244. Running = false;
  245. Wakeup ();
  246. }
  247. /// <summary>
  248. /// Invoked when a new timeout is added. To be used in the case when
  249. /// <see cref="Application.EndAfterFirstIteration"/> is <see langword="true"/>.
  250. /// </summary>
  251. internal event EventHandler<TimeoutEventArgs>? TimeoutAdded;
  252. /// <summary>Wakes up the <see cref="MainLoop"/> that might be waiting on input.</summary>
  253. internal void Wakeup () { MainLoopDriver?.Wakeup (); }
  254. private void AddTimeout (TimeSpan time, Timeout timeout)
  255. {
  256. lock (_timeoutsLockToken)
  257. {
  258. long k = (DateTime.UtcNow + time).Ticks;
  259. _timeouts.Add (NudgeToUniqueKey (k), timeout);
  260. TimeoutAdded?.Invoke (this, new TimeoutEventArgs (timeout, k));
  261. }
  262. }
  263. /// <summary>
  264. /// Finds the closest number to <paramref name="k"/> that is not present in <see cref="_timeouts"/>
  265. /// (incrementally).
  266. /// </summary>
  267. /// <param name="k"></param>
  268. /// <returns></returns>
  269. private long NudgeToUniqueKey (long k)
  270. {
  271. lock (_timeoutsLockToken)
  272. {
  273. while (_timeouts.ContainsKey (k))
  274. {
  275. k++;
  276. }
  277. }
  278. return k;
  279. }
  280. // PERF: This is heavier than it looks.
  281. // CONCURRENCY: Potential deadlock city here.
  282. // CONCURRENCY: Multiple concurrency pitfalls on the delegates themselves.
  283. // INTENT: It looks like the general architecture here is trying to be a form of publisher/consumer pattern.
  284. private void RunIdle ()
  285. {
  286. List<Func<bool>> iterate;
  287. lock (_idleHandlersLock)
  288. {
  289. iterate = _idleHandlers;
  290. _idleHandlers = new List<Func<bool>> ();
  291. }
  292. foreach (Func<bool> idle in iterate)
  293. {
  294. if (idle ())
  295. {
  296. lock (_idleHandlersLock)
  297. {
  298. _idleHandlers.Add (idle);
  299. }
  300. }
  301. }
  302. }
  303. private void RunTimers ()
  304. {
  305. long now = DateTime.UtcNow.Ticks;
  306. SortedList<long, Timeout> copy;
  307. // lock prevents new timeouts being added
  308. // after we have taken the copy but before
  309. // we have allocated a new list (which would
  310. // result in lost timeouts or errors during enumeration)
  311. lock (_timeoutsLockToken)
  312. {
  313. copy = _timeouts;
  314. _timeouts = new SortedList<long, Timeout> ();
  315. }
  316. foreach ((long k, Timeout timeout) in copy)
  317. {
  318. if (k < now)
  319. {
  320. if (timeout.Callback ())
  321. {
  322. AddTimeout (timeout.Span, timeout);
  323. }
  324. }
  325. else
  326. {
  327. lock (_timeoutsLockToken)
  328. {
  329. _timeouts.Add (NudgeToUniqueKey (k), timeout);
  330. }
  331. }
  332. }
  333. }
  334. }