MainLoop.cs 13 KB

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