MainLoop.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. internal class Timeout {
  44. public TimeSpan Span;
  45. public Func<MainLoop, bool> Callback;
  46. }
  47. internal SortedList<long, Timeout> timeouts = new SortedList<long, Timeout> ();
  48. object timeoutsLockToken = new object ();
  49. internal List<Func<bool>> idleHandlers = new List<Func<bool>> ();
  50. /// <summary>
  51. /// The current IMainLoopDriver in use.
  52. /// </summary>
  53. /// <value>The driver.</value>
  54. public IMainLoopDriver Driver { get; }
  55. /// <summary>
  56. /// Creates a new Mainloop.
  57. /// </summary>
  58. /// <param name="driver">Should match the <see cref="ConsoleDriver"/> (one of the implementations UnixMainLoop, NetMainLoop or WindowsMainLoop).</param>
  59. public MainLoop (IMainLoopDriver driver)
  60. {
  61. Driver = driver;
  62. driver.Setup (this);
  63. }
  64. /// <summary>
  65. /// Runs <c>action</c> on the thread that is processing events
  66. /// </summary>
  67. /// <param name="action">the action to be invoked on the main processing thread.</param>
  68. public void Invoke (Action action)
  69. {
  70. AddIdle (() => {
  71. action ();
  72. return false;
  73. });
  74. }
  75. /// <summary>
  76. /// 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.
  77. /// </summary>
  78. /// <remarks>
  79. /// <para>
  80. /// Remove an idle hander by calling <see cref="RemoveIdle(Func{bool})"/> with the token this method returns.
  81. /// </para>
  82. /// <para>
  83. /// If the <c>idleHandler</c> returns <c>false</c> it will be removed and not called subsequently.
  84. /// </para>
  85. /// </remarks>
  86. /// <param name="idleHandler">Token that can be used to remove the idle handler with <see cref="RemoveIdle(Func{bool})"/> .</param>
  87. public Func<bool> AddIdle (Func<bool> idleHandler)
  88. {
  89. lock (idleHandlers) {
  90. idleHandlers.Add (idleHandler);
  91. }
  92. Driver.Wakeup ();
  93. return idleHandler;
  94. }
  95. /// <summary>
  96. /// Removes an idle handler added with <see cref="AddIdle(Func{bool})"/> from processing.
  97. /// </summary>
  98. /// <param name="token">A token returned by <see cref="AddIdle(Func{bool})"/></param>
  99. /// Returns <c>true</c>if the idle handler is successfully removed; otherwise, <c>false</c>.
  100. /// This method also returns <c>false</c> if the idle handler is not found.
  101. public bool RemoveIdle (Func<bool> token)
  102. {
  103. lock (token)
  104. return idleHandlers.Remove (token);
  105. }
  106. void AddTimeout (TimeSpan time, Timeout timeout)
  107. {
  108. lock (timeoutsLockToken) {
  109. var k = (DateTime.UtcNow + time).Ticks;
  110. timeouts.Add (NudgeToUniqueKey(k), timeout);
  111. }
  112. }
  113. /// <summary>
  114. /// Adds a timeout to the mainloop.
  115. /// </summary>
  116. /// <remarks>
  117. /// When time specified passes, the callback will be invoked.
  118. /// If the callback returns true, the timeout will be reset, repeating
  119. /// the invocation. If it returns false, the timeout will stop and be removed.
  120. ///
  121. /// The returned value is a token that can be used to stop the timeout
  122. /// by calling <see cref="RemoveTimeout(object)"/>.
  123. /// </remarks>
  124. public object AddTimeout (TimeSpan time, Func<MainLoop, bool> callback)
  125. {
  126. if (callback == null)
  127. throw new ArgumentNullException (nameof (callback));
  128. var timeout = new Timeout () {
  129. Span = time,
  130. Callback = callback
  131. };
  132. AddTimeout (time, timeout);
  133. return timeout;
  134. }
  135. /// <summary>
  136. /// Removes a previously scheduled timeout
  137. /// </summary>
  138. /// <remarks>
  139. /// The token parameter is the value returned by AddTimeout.
  140. /// </remarks>
  141. /// Returns <c>true</c>if the timeout is successfully removed; otherwise, <c>false</c>.
  142. /// This method also returns <c>false</c> if the timeout is not found.
  143. public bool RemoveTimeout (object token)
  144. {
  145. lock (timeoutsLockToken) {
  146. var idx = timeouts.IndexOfValue (token as Timeout);
  147. if (idx == -1)
  148. return false;
  149. timeouts.RemoveAt (idx);
  150. }
  151. return true;
  152. }
  153. void RunTimers ()
  154. {
  155. long now = DateTime.UtcNow.Ticks;
  156. SortedList<long, Timeout> copy;
  157. // lock prevents new timeouts being added
  158. // after we have taken the copy but before
  159. // we have allocated a new list (which would
  160. // result in lost timeouts or errors during enumeration)
  161. lock (timeoutsLockToken) {
  162. copy = timeouts;
  163. timeouts = new SortedList<long, Timeout> ();
  164. }
  165. foreach (var t in copy) {
  166. var k = t.Key;
  167. var timeout = t.Value;
  168. if (k < now) {
  169. if (timeout.Callback (this))
  170. AddTimeout (timeout.Span, timeout);
  171. } else {
  172. lock (timeoutsLockToken) {
  173. timeouts.Add (NudgeToUniqueKey(k), timeout);
  174. }
  175. }
  176. }
  177. }
  178. /// <summary>
  179. /// Finds the closest number to <paramref name="k"/> that is not
  180. /// present in <see cref="timeouts"/> (incrementally).
  181. /// </summary>
  182. /// <param name="k"></param>
  183. /// <returns></returns>
  184. private long NudgeToUniqueKey (long k)
  185. {
  186. lock(timeoutsLockToken) {
  187. while (timeouts.ContainsKey (k)) {
  188. k++;
  189. }
  190. }
  191. return k;
  192. }
  193. void RunIdle ()
  194. {
  195. List<Func<bool>> iterate;
  196. lock (idleHandlers) {
  197. iterate = idleHandlers;
  198. idleHandlers = new List<Func<bool>> ();
  199. }
  200. foreach (var idle in iterate) {
  201. if (idle ())
  202. lock (idleHandlers)
  203. idleHandlers.Add (idle);
  204. }
  205. }
  206. bool running;
  207. /// <summary>
  208. /// Stops the mainloop.
  209. /// </summary>
  210. public void Stop ()
  211. {
  212. running = false;
  213. Driver.Wakeup ();
  214. }
  215. /// <summary>
  216. /// Determines whether there are pending events to be processed.
  217. /// </summary>
  218. /// <remarks>
  219. /// You can use this method if you want to probe if events are pending.
  220. /// Typically used if you need to flush the input queue while still
  221. /// running some of your own code in your main thread.
  222. /// </remarks>
  223. public bool EventsPending (bool wait = false)
  224. {
  225. return Driver.EventsPending (wait);
  226. }
  227. /// <summary>
  228. /// Runs one iteration of timers and file watches
  229. /// </summary>
  230. /// <remarks>
  231. /// You use this to process all pending events (timers, idle handlers and file watches).
  232. ///
  233. /// You can use it like this:
  234. /// while (main.EvensPending ()) MainIteration ();
  235. /// </remarks>
  236. public void MainIteration ()
  237. {
  238. if (timeouts.Count > 0)
  239. RunTimers ();
  240. Driver.MainIteration ();
  241. lock (idleHandlers) {
  242. if (idleHandlers.Count > 0)
  243. RunIdle ();
  244. }
  245. }
  246. /// <summary>
  247. /// Runs the mainloop.
  248. /// </summary>
  249. public void Run ()
  250. {
  251. bool prev = running;
  252. running = true;
  253. while (running) {
  254. EventsPending (true);
  255. MainIteration ();
  256. }
  257. running = prev;
  258. }
  259. }
  260. }