MainLoop.cs 13 KB

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