MainLoop.cs 9.3 KB

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