MainLoop.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. bool _forceRead { get; set; }
  26. ManualResetEventSlim _waitForInput { get; set; }
  27. }
  28. /// <summary>The MainLoop monitors timers and idle handlers.</summary>
  29. /// <remarks>
  30. /// Monitoring of file descriptors is only available on Unix, there does not seem to be a way of supporting this
  31. /// on Windows.
  32. /// </remarks>
  33. public class MainLoop : IDisposable
  34. {
  35. internal List<Func<bool>> _idleHandlers = new ();
  36. internal SortedList<long, Timeout> _timeouts = new ();
  37. /// <summary>The idle handlers and lock that must be held while manipulating them</summary>
  38. private readonly object _idleHandlersLock = new ();
  39. private readonly object _timeoutsLockToken = new ();
  40. /// <summary>Creates a new MainLoop.</summary>
  41. /// <remarks>Use <see cref="Dispose"/> to release resources.</remarks>
  42. /// <param name="driver">
  43. /// The <see cref="ConsoleDriver"/> instance (one of the implementations FakeMainLoop, UnixMainLoop,
  44. /// NetMainLoop or WindowsMainLoop).
  45. /// </param>
  46. internal MainLoop (IMainLoopDriver driver)
  47. {
  48. MainLoopDriver = driver;
  49. driver.Setup (this);
  50. }
  51. /// <summary>Gets a copy of the list of all idle handlers.</summary>
  52. internal ReadOnlyCollection<Func<bool>> IdleHandlers
  53. {
  54. get
  55. {
  56. lock (_idleHandlersLock)
  57. {
  58. return new List<Func<bool>> (_idleHandlers).AsReadOnly ();
  59. }
  60. }
  61. }
  62. /// <summary>The current <see cref="IMainLoopDriver"/> in use.</summary>
  63. /// <value>The main loop driver.</value>
  64. public IMainLoopDriver MainLoopDriver { get; private set; }
  65. /// <summary>Used for unit tests.</summary>
  66. internal bool Running { get; set; }
  67. /// <summary>
  68. /// Gets the list of all timeouts sorted by the <see cref="TimeSpan"/> time ticks. A shorter limit time can be
  69. /// added at the end, but it will be called before an earlier addition that has a longer limit time.
  70. /// </summary>
  71. internal SortedList<long, Timeout> Timeouts => _timeouts;
  72. /// <inheritdoc/>
  73. public void Dispose ()
  74. {
  75. GC.SuppressFinalize (this);
  76. Stop ();
  77. Running = false;
  78. MainLoopDriver?.TearDown ();
  79. MainLoopDriver = null;
  80. }
  81. /// <summary>
  82. /// Adds specified idle handler function to <see cref="MainLoop"/> processing. The handler function will be called
  83. /// once per iteration of the main loop after other events have been handled.
  84. /// </summary>
  85. /// <remarks>
  86. /// <para>Remove an idle handler by calling <see cref="RemoveIdle(Func{bool})"/> with the token this method returns.</para>
  87. /// <para>
  88. /// If the <paramref name="idleHandler"/> returns <see langword="false"/> it will be removed and not called
  89. /// subsequently.
  90. /// </para>
  91. /// </remarks>
  92. /// <param name="idleHandler">Token that can be used to remove the idle handler with <see cref="RemoveIdle(Func{bool})"/> .</param>
  93. // QUESTION: Why are we re-inventing the event wheel here?
  94. // PERF: This is heavy.
  95. // CONCURRENCY: Race conditions exist here.
  96. // CONCURRENCY: null delegates will hose this.
  97. //
  98. internal Func<bool> AddIdle (Func<bool> idleHandler)
  99. {
  100. lock (_idleHandlersLock)
  101. {
  102. _idleHandlers.Add (idleHandler);
  103. }
  104. MainLoopDriver.Wakeup ();
  105. return idleHandler;
  106. }
  107. /// <summary>Adds a timeout to the <see cref="MainLoop"/>.</summary>
  108. /// <remarks>
  109. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  110. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  111. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  112. /// </remarks>
  113. internal object AddTimeout (TimeSpan time, Func<bool> callback)
  114. {
  115. if (callback is null)
  116. {
  117. throw new ArgumentNullException (nameof (callback));
  118. }
  119. var timeout = new Timeout { Span = time, Callback = callback };
  120. AddTimeout (time, timeout);
  121. return timeout;
  122. }
  123. /// <summary>
  124. /// Called from <see cref="IMainLoopDriver.EventsPending"/> to check if there are any outstanding timers or idle
  125. /// handlers.
  126. /// </summary>
  127. /// <param name="waitTimeout">
  128. /// Returns the number of milliseconds remaining in the current timer (if any). Will be -1 if
  129. /// there are no active timers.
  130. /// </param>
  131. /// <returns><see langword="true"/> if there is a timer or idle handler active.</returns>
  132. internal bool CheckTimersAndIdleHandlers (out int waitTimeout)
  133. {
  134. long now = DateTime.UtcNow.Ticks;
  135. waitTimeout = 0;
  136. lock (_timeouts)
  137. {
  138. if (_timeouts.Count > 0)
  139. {
  140. waitTimeout = (int)((_timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  141. if (waitTimeout < 0)
  142. {
  143. // This avoids 'poll' waiting infinitely if 'waitTimeout < 0' until some action is detected
  144. // This can occur after IMainLoopDriver.Wakeup is executed where the pollTimeout is less than 0
  145. // and no event occurred in elapsed time when the 'poll' is start running again.
  146. waitTimeout = 0;
  147. }
  148. return true;
  149. }
  150. // ManualResetEventSlim.Wait, which is called by IMainLoopDriver.EventsPending, will wait indefinitely if
  151. // the timeout is -1.
  152. waitTimeout = -1;
  153. }
  154. // There are no timers set, check if there are any idle handlers
  155. lock (_idleHandlers)
  156. {
  157. return _idleHandlers.Count > 0;
  158. }
  159. }
  160. /// <summary>Determines whether there are pending events to be processed.</summary>
  161. /// <remarks>
  162. /// You can use this method if you want to probe if events are pending. Typically used if you need to flush the
  163. /// input queue while still running some of your own code in your main thread.
  164. /// </remarks>
  165. internal bool EventsPending () { return MainLoopDriver.EventsPending (); }
  166. /// <summary>Removes an idle handler added with <see cref="AddIdle(Func{bool})"/> from processing.</summary>
  167. /// <param name="token">A token returned by <see cref="AddIdle(Func{bool})"/></param>
  168. /// Returns
  169. /// <c>true</c>
  170. /// if the idle handler is successfully removed; otherwise,
  171. /// <c>false</c>
  172. /// .
  173. /// This method also returns
  174. /// <c>false</c>
  175. /// if the idle handler is not found.
  176. internal bool RemoveIdle (Func<bool> token)
  177. {
  178. lock (_idleHandlersLock)
  179. {
  180. return _idleHandlers.Remove (token);
  181. }
  182. }
  183. /// <summary>Removes a previously scheduled timeout</summary>
  184. /// <remarks>The token parameter is the value returned by AddTimeout.</remarks>
  185. /// Returns
  186. /// <c>true</c>
  187. /// if the timeout is successfully removed; otherwise,
  188. /// <c>false</c>
  189. /// .
  190. /// This method also returns
  191. /// <c>false</c>
  192. /// if the timeout is not found.
  193. internal bool RemoveTimeout (object token)
  194. {
  195. lock (_timeoutsLockToken)
  196. {
  197. int idx = _timeouts.IndexOfValue (token as Timeout);
  198. if (idx == -1)
  199. {
  200. return false;
  201. }
  202. _timeouts.RemoveAt (idx);
  203. }
  204. return true;
  205. }
  206. /// <summary>Runs the <see cref="MainLoop"/>. Used only for unit tests.</summary>
  207. internal void Run ()
  208. {
  209. bool prev = Running;
  210. Running = true;
  211. while (Running)
  212. {
  213. EventsPending ();
  214. RunIteration ();
  215. }
  216. Running = prev;
  217. }
  218. /// <summary>Runs one iteration of timers and file watches</summary>
  219. /// <remarks>
  220. /// Use this to process all pending events (timers, idle handlers and file watches).
  221. /// <code>
  222. /// while (main.EventsPending ()) RunIteration ();
  223. /// </code>
  224. /// </remarks>
  225. internal void RunIteration ()
  226. {
  227. lock (_timeouts)
  228. {
  229. if (_timeouts.Count > 0)
  230. {
  231. RunTimers ();
  232. }
  233. }
  234. MainLoopDriver.Iteration ();
  235. var runIdle = false;
  236. lock (_idleHandlersLock)
  237. {
  238. runIdle = _idleHandlers.Count > 0;
  239. }
  240. if (runIdle)
  241. {
  242. RunIdle ();
  243. }
  244. }
  245. /// <summary>Stops the main loop driver and calls <see cref="IMainLoopDriver.Wakeup"/>. Used only for unit tests.</summary>
  246. internal void Stop ()
  247. {
  248. Running = false;
  249. Wakeup ();
  250. }
  251. /// <summary>
  252. /// Invoked when a new timeout is added. To be used in the case when
  253. /// <see cref="Application.EndAfterFirstIteration"/> is <see langword="true"/>.
  254. /// </summary>
  255. [CanBeNull]
  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. }