MainLoop.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. internal Func<bool> AddIdle (Func<bool> idleHandler)
  92. {
  93. lock (_idleHandlersLock)
  94. {
  95. _idleHandlers.Add (idleHandler);
  96. }
  97. MainLoopDriver.Wakeup ();
  98. return idleHandler;
  99. }
  100. /// <summary>Adds a timeout to the <see cref="MainLoop"/>.</summary>
  101. /// <remarks>
  102. /// When time specified passes, the callback will be invoked. If the callback returns true, the timeout will be
  103. /// reset, repeating the invocation. If it returns false, the timeout will stop and be removed. The returned value is a
  104. /// token that can be used to stop the timeout by calling <see cref="RemoveTimeout(object)"/>.
  105. /// </remarks>
  106. internal object AddTimeout (TimeSpan time, Func<bool> callback)
  107. {
  108. if (callback is null)
  109. {
  110. throw new ArgumentNullException (nameof (callback));
  111. }
  112. var timeout = new Timeout { Span = time, Callback = callback };
  113. AddTimeout (time, timeout);
  114. return timeout;
  115. }
  116. /// <summary>
  117. /// Called from <see cref="IMainLoopDriver.EventsPending"/> to check if there are any outstanding timers or idle
  118. /// handlers.
  119. /// </summary>
  120. /// <param name="waitTimeout">
  121. /// Returns the number of milliseconds remaining in the current timer (if any). Will be -1 if
  122. /// there are no active timers.
  123. /// </param>
  124. /// <returns><see langword="true"/> if there is a timer or idle handler active.</returns>
  125. internal bool CheckTimersAndIdleHandlers (out int waitTimeout)
  126. {
  127. long now = DateTime.UtcNow.Ticks;
  128. waitTimeout = 0;
  129. lock (_timeouts)
  130. {
  131. if (_timeouts.Count > 0)
  132. {
  133. waitTimeout = (int)((_timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  134. if (waitTimeout < 0)
  135. {
  136. // This avoids 'poll' waiting infinitely if 'waitTimeout < 0' until some action is detected
  137. // This can occur after IMainLoopDriver.Wakeup is executed where the pollTimeout is less than 0
  138. // and no event occurred in elapsed time when the 'poll' is start running again.
  139. waitTimeout = 0;
  140. }
  141. return true;
  142. }
  143. // ManualResetEventSlim.Wait, which is called by IMainLoopDriver.EventsPending, will wait indefinitely if
  144. // the timeout is -1.
  145. waitTimeout = -1;
  146. }
  147. // There are no timers set, check if there are any idle handlers
  148. lock (_idleHandlers)
  149. {
  150. return _idleHandlers.Count > 0;
  151. }
  152. }
  153. /// <summary>Determines whether there are pending events to be processed.</summary>
  154. /// <remarks>
  155. /// You can use this method if you want to probe if events are pending. Typically used if you need to flush the
  156. /// input queue while still running some of your own code in your main thread.
  157. /// </remarks>
  158. internal bool EventsPending () { return MainLoopDriver.EventsPending (); }
  159. /// <summary>Removes an idle handler added with <see cref="AddIdle(Func{bool})"/> from processing.</summary>
  160. /// <param name="token">A token returned by <see cref="AddIdle(Func{bool})"/></param>
  161. /// Returns
  162. /// <c>true</c>
  163. /// if the idle handler is successfully removed; otherwise,
  164. /// <c>false</c>
  165. /// .
  166. /// This method also returns
  167. /// <c>false</c>
  168. /// if the idle handler is not found.
  169. internal bool RemoveIdle (Func<bool> token)
  170. {
  171. lock (_idleHandlersLock)
  172. {
  173. return _idleHandlers.Remove (token);
  174. }
  175. }
  176. /// <summary>Removes a previously scheduled timeout</summary>
  177. /// <remarks>The token parameter is the value returned by AddTimeout.</remarks>
  178. /// Returns
  179. /// <c>true</c>
  180. /// if the timeout is successfully removed; otherwise,
  181. /// <c>false</c>
  182. /// .
  183. /// This method also returns
  184. /// <c>false</c>
  185. /// if the timeout is not found.
  186. internal bool RemoveTimeout (object token)
  187. {
  188. lock (_timeoutsLockToken)
  189. {
  190. int idx = _timeouts.IndexOfValue (token as Timeout);
  191. if (idx == -1)
  192. {
  193. return false;
  194. }
  195. _timeouts.RemoveAt (idx);
  196. }
  197. return true;
  198. }
  199. /// <summary>Runs the <see cref="MainLoop"/>. Used only for unit tests.</summary>
  200. internal void Run ()
  201. {
  202. bool prev = Running;
  203. Running = true;
  204. while (Running)
  205. {
  206. EventsPending ();
  207. RunIteration ();
  208. }
  209. Running = prev;
  210. }
  211. /// <summary>Runs one iteration of timers and file watches</summary>
  212. /// <remarks>
  213. /// Use this to process all pending events (timers, idle handlers and file watches).
  214. /// <code>
  215. /// while (main.EventsPending ()) RunIteration ();
  216. /// </code>
  217. /// </remarks>
  218. internal void RunIteration ()
  219. {
  220. lock (_timeouts)
  221. {
  222. if (_timeouts.Count > 0)
  223. {
  224. RunTimers ();
  225. }
  226. }
  227. MainLoopDriver.Iteration ();
  228. var runIdle = false;
  229. lock (_idleHandlersLock)
  230. {
  231. runIdle = _idleHandlers.Count > 0;
  232. }
  233. if (runIdle)
  234. {
  235. RunIdle ();
  236. }
  237. }
  238. /// <summary>Stops the main loop driver and calls <see cref="IMainLoopDriver.Wakeup"/>. Used only for unit tests.</summary>
  239. internal void Stop ()
  240. {
  241. Running = false;
  242. Wakeup ();
  243. }
  244. /// <summary>
  245. /// Invoked when a new timeout is added. To be used in the case when
  246. /// <see cref="Application.EndAfterFirstIteration"/> is <see langword="true"/>.
  247. /// </summary>
  248. internal event EventHandler<TimeoutEventArgs> TimeoutAdded;
  249. /// <summary>Wakes up the <see cref="MainLoop"/> that might be waiting on input.</summary>
  250. internal void Wakeup () { MainLoopDriver?.Wakeup (); }
  251. private void AddTimeout (TimeSpan time, Timeout timeout)
  252. {
  253. lock (_timeoutsLockToken)
  254. {
  255. long k = (DateTime.UtcNow + time).Ticks;
  256. _timeouts.Add (NudgeToUniqueKey (k), timeout);
  257. TimeoutAdded?.Invoke (this, new TimeoutEventArgs (timeout, k));
  258. }
  259. }
  260. /// <summary>
  261. /// Finds the closest number to <paramref name="k"/> that is not present in <see cref="_timeouts"/>
  262. /// (incrementally).
  263. /// </summary>
  264. /// <param name="k"></param>
  265. /// <returns></returns>
  266. private long NudgeToUniqueKey (long k)
  267. {
  268. lock (_timeoutsLockToken)
  269. {
  270. while (_timeouts.ContainsKey (k))
  271. {
  272. k++;
  273. }
  274. }
  275. return k;
  276. }
  277. private void RunIdle ()
  278. {
  279. List<Func<bool>> iterate;
  280. lock (_idleHandlersLock)
  281. {
  282. iterate = _idleHandlers;
  283. _idleHandlers = new List<Func<bool>> ();
  284. }
  285. foreach (Func<bool> idle in iterate)
  286. {
  287. if (idle ())
  288. {
  289. lock (_idleHandlersLock)
  290. {
  291. _idleHandlers.Add (idle);
  292. }
  293. }
  294. }
  295. }
  296. private void RunTimers ()
  297. {
  298. long now = DateTime.UtcNow.Ticks;
  299. SortedList<long, Timeout> copy;
  300. // lock prevents new timeouts being added
  301. // after we have taken the copy but before
  302. // we have allocated a new list (which would
  303. // result in lost timeouts or errors during enumeration)
  304. lock (_timeoutsLockToken)
  305. {
  306. copy = _timeouts;
  307. _timeouts = new SortedList<long, Timeout> ();
  308. }
  309. foreach ((long k, Timeout timeout) in copy)
  310. {
  311. if (k < now)
  312. {
  313. if (timeout.Callback ())
  314. {
  315. AddTimeout (timeout.Span, timeout);
  316. }
  317. }
  318. else
  319. {
  320. lock (_timeoutsLockToken)
  321. {
  322. _timeouts.Add (NudgeToUniqueKey (k), timeout);
  323. }
  324. }
  325. }
  326. }
  327. }