MainLoop.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. namespace Terminal.Gui {
  10. /// <summary>
  11. /// Public interface to create your own platform specific main loop driver.
  12. /// </summary>
  13. public interface IMainLoopDriver {
  14. /// <summary>
  15. /// Initializes the main loop driver, gets the calling main loop for the initialization.
  16. /// </summary>
  17. /// <param name="mainLoop">Main loop.</param>
  18. void Setup (MainLoop mainLoop);
  19. /// <summary>
  20. /// Wakes up the mainloop that might be waiting on input, must be thread safe.
  21. /// </summary>
  22. void Wakeup ();
  23. /// <summary>
  24. /// Must report whether there are any events pending, or even block waiting for events.
  25. /// </summary>
  26. /// <returns><c>true</c>, if there were pending events, <c>false</c> otherwise.</returns>
  27. /// <param name="wait">If set to <c>true</c> wait until an event is available, otherwise return immediately.</param>
  28. bool EventsPending (bool wait);
  29. /// <summary>
  30. /// The iteration function.
  31. /// </summary>
  32. void MainIteration ();
  33. }
  34. /// <summary>
  35. /// Simple main loop implementation that can be used to monitor
  36. /// file descriptor, run timers and idle handlers.
  37. /// </summary>
  38. /// <remarks>
  39. /// Monitoring of file descriptors is only available on Unix, there
  40. /// does not seem to be a way of supporting this on Windows.
  41. /// </remarks>
  42. public class MainLoop {
  43. /// <summary>
  44. /// Provides data for timers running manipulation.
  45. /// </summary>
  46. public sealed class Timeout {
  47. /// <summary>
  48. /// Time to wait before invoke the callback.
  49. /// </summary>
  50. public TimeSpan Span;
  51. /// <summary>
  52. /// The function that will be invoked.
  53. /// </summary>
  54. public Func<MainLoop, bool> Callback;
  55. }
  56. internal SortedList<long, Timeout> timeouts = new SortedList<long, Timeout> ();
  57. object timeoutsLockToken = new object ();
  58. internal List<Func<bool>> idleHandlers = new List<Func<bool>> ();
  59. /// <summary>
  60. /// Gets the list of all timeouts sorted by the <see cref="TimeSpan"/> time ticks./>.
  61. /// A shorter limit time can be added at the end, but it will be called before an
  62. /// earlier addition that has a longer limit time.
  63. /// </summary>
  64. public SortedList<long, Timeout> Timeouts => timeouts;
  65. /// <summary>
  66. /// Gets the list of all idle handlers.
  67. /// </summary>
  68. public List<Func<bool>> IdleHandlers => idleHandlers;
  69. /// <summary>
  70. /// The current IMainLoopDriver in use.
  71. /// </summary>
  72. /// <value>The driver.</value>
  73. public IMainLoopDriver Driver { get; }
  74. /// <summary>
  75. /// Invoked when a new timeout is added to be used on the case
  76. /// if <see cref="Application.ExitRunLoopAfterFirstIteration"/> is true,
  77. /// </summary>
  78. public event Action<long> TimeoutAdded;
  79. /// <summary>
  80. /// Creates a new Mainloop.
  81. /// </summary>
  82. /// <param name="driver">Should match the <see cref="ConsoleDriver"/> (one of the implementations UnixMainLoop, NetMainLoop or WindowsMainLoop).</param>
  83. public MainLoop (IMainLoopDriver driver)
  84. {
  85. Driver = driver;
  86. driver.Setup (this);
  87. }
  88. /// <summary>
  89. /// Runs <c>action</c> on the thread that is processing events
  90. /// </summary>
  91. /// <param name="action">the action to be invoked on the main processing thread.</param>
  92. public void Invoke (Action action)
  93. {
  94. AddIdle (() => {
  95. action ();
  96. return false;
  97. });
  98. }
  99. /// <summary>
  100. /// Adds specified idle handler function to mainloop processing. 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 (idleHandlers) {
  114. idleHandlers.Add (idleHandler);
  115. }
  116. Driver.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 (token)
  128. return idleHandlers.Remove (token);
  129. }
  130. void AddTimeout (TimeSpan time, Timeout timeout)
  131. {
  132. lock (timeoutsLockToken) {
  133. var k = (DateTime.UtcNow + time).Ticks;
  134. timeouts.Add (NudgeToUniqueKey (k), timeout);
  135. TimeoutAdded?.Invoke (k);
  136. }
  137. }
  138. /// <summary>
  139. /// Adds a timeout to the mainloop.
  140. /// </summary>
  141. /// <remarks>
  142. /// When time specified passes, the callback will be invoked.
  143. /// If the callback returns true, the timeout will be reset, repeating
  144. /// the invocation. If it returns false, the timeout will stop and be removed.
  145. ///
  146. /// The returned value is a token that can be used to stop the timeout
  147. /// by calling <see cref="RemoveTimeout(object)"/>.
  148. /// </remarks>
  149. public object AddTimeout (TimeSpan time, Func<MainLoop, bool> callback)
  150. {
  151. if (callback == null)
  152. throw new ArgumentNullException (nameof (callback));
  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. timeouts.RemoveAt (idx);
  175. }
  176. return true;
  177. }
  178. void RunTimers ()
  179. {
  180. long 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 t in copy) {
  191. var k = t.Key;
  192. var timeout = t.Value;
  193. if (k < now) {
  194. if (timeout.Callback (this))
  195. AddTimeout (timeout.Span, timeout);
  196. } else {
  197. lock (timeoutsLockToken) {
  198. timeouts.Add (NudgeToUniqueKey (k), timeout);
  199. }
  200. }
  201. }
  202. }
  203. /// <summary>
  204. /// Finds the closest number to <paramref name="k"/> that is not
  205. /// present in <see cref="timeouts"/> (incrementally).
  206. /// </summary>
  207. /// <param name="k"></param>
  208. /// <returns></returns>
  209. private long NudgeToUniqueKey (long k)
  210. {
  211. lock (timeoutsLockToken) {
  212. while (timeouts.ContainsKey (k)) {
  213. k++;
  214. }
  215. }
  216. return k;
  217. }
  218. void RunIdle ()
  219. {
  220. List<Func<bool>> iterate;
  221. lock (idleHandlers) {
  222. iterate = idleHandlers;
  223. idleHandlers = new List<Func<bool>> ();
  224. }
  225. foreach (var idle in iterate) {
  226. if (idle ())
  227. lock (idleHandlers)
  228. idleHandlers.Add (idle);
  229. }
  230. }
  231. bool running;
  232. /// <summary>
  233. /// Stops the mainloop.
  234. /// </summary>
  235. public void Stop ()
  236. {
  237. running = false;
  238. Driver.Wakeup ();
  239. }
  240. /// <summary>
  241. /// Determines whether there are pending events to be processed.
  242. /// </summary>
  243. /// <remarks>
  244. /// You can use this method if you want to probe if events are pending.
  245. /// Typically used if you need to flush the input queue while still
  246. /// running some of your own code in your main thread.
  247. /// </remarks>
  248. public bool EventsPending (bool wait = false)
  249. {
  250. return Driver.EventsPending (wait);
  251. }
  252. /// <summary>
  253. /// Runs one iteration of timers and file watches
  254. /// </summary>
  255. /// <remarks>
  256. /// You use this to process all pending events (timers, idle handlers and file watches).
  257. ///
  258. /// You can use it like this:
  259. /// while (main.EvensPending ()) MainIteration ();
  260. /// </remarks>
  261. public void MainIteration ()
  262. {
  263. if (timeouts.Count > 0)
  264. RunTimers ();
  265. Driver.MainIteration ();
  266. lock (idleHandlers) {
  267. if (idleHandlers.Count > 0)
  268. RunIdle ();
  269. }
  270. }
  271. /// <summary>
  272. /// Runs the mainloop.
  273. /// </summary>
  274. public void Run ()
  275. {
  276. bool prev = running;
  277. running = true;
  278. while (running) {
  279. EventsPending (true);
  280. MainIteration ();
  281. }
  282. running = prev;
  283. }
  284. }
  285. }