MainLoop.cs 10 KB

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