MainLoop.cs 11 KB

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