MainLoop.cs 11 KB

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