MainLoop.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. while (timeouts.ContainsKey (k)) {
  111. k = (DateTime.UtcNow + time).Ticks;
  112. }
  113. timeouts.Add (k, timeout);
  114. }
  115. }
  116. /// <summary>
  117. /// Adds a timeout to the mainloop.
  118. /// </summary>
  119. /// <remarks>
  120. /// When time specified passes, the callback will be invoked.
  121. /// If the callback returns true, the timeout will be reset, repeating
  122. /// the invocation. If it returns false, the timeout will stop and be removed.
  123. ///
  124. /// The returned value is a token that can be used to stop the timeout
  125. /// by calling <see cref="RemoveTimeout(object)"/>.
  126. /// </remarks>
  127. public object AddTimeout (TimeSpan time, Func<MainLoop, bool> callback)
  128. {
  129. if (callback == null)
  130. throw new ArgumentNullException (nameof (callback));
  131. var timeout = new Timeout () {
  132. Span = time,
  133. Callback = callback
  134. };
  135. AddTimeout (time, timeout);
  136. return timeout;
  137. }
  138. /// <summary>
  139. /// Removes a previously scheduled timeout
  140. /// </summary>
  141. /// <remarks>
  142. /// The token parameter is the value returned by AddTimeout.
  143. /// </remarks>
  144. /// Returns <c>true</c>if the timeout is successfully removed; otherwise, <c>false</c>.
  145. /// This method also returns <c>false</c> if the timeout is not found.
  146. public bool RemoveTimeout (object token)
  147. {
  148. lock (timeoutsLockToken) {
  149. var idx = timeouts.IndexOfValue (token as Timeout);
  150. if (idx == -1)
  151. return false;
  152. timeouts.RemoveAt (idx);
  153. }
  154. return true;
  155. }
  156. void RunTimers ()
  157. {
  158. long now = DateTime.UtcNow.Ticks;
  159. SortedList<long, Timeout> copy;
  160. // lock prevents new timeouts being added
  161. // after we have taken the copy but before
  162. // we have allocated a new list (which would
  163. // result in lost timeouts or errors during enumeration)
  164. lock (timeoutsLockToken) {
  165. copy = timeouts;
  166. timeouts = new SortedList<long, Timeout> ();
  167. }
  168. foreach (var t in copy) {
  169. var k = t.Key;
  170. var timeout = t.Value;
  171. if (k < now) {
  172. if (timeout.Callback (this))
  173. AddTimeout (timeout.Span, timeout);
  174. } else {
  175. lock (timeoutsLockToken) {
  176. timeouts.Add (k, timeout);
  177. }
  178. }
  179. }
  180. }
  181. void RunIdle ()
  182. {
  183. List<Func<bool>> iterate;
  184. lock (idleHandlers) {
  185. iterate = idleHandlers;
  186. idleHandlers = new List<Func<bool>> ();
  187. }
  188. foreach (var idle in iterate) {
  189. if (idle ())
  190. lock (idleHandlers)
  191. idleHandlers.Add (idle);
  192. }
  193. }
  194. bool running;
  195. /// <summary>
  196. /// Stops the mainloop.
  197. /// </summary>
  198. public void Stop ()
  199. {
  200. running = false;
  201. Driver.Wakeup ();
  202. }
  203. /// <summary>
  204. /// Determines whether there are pending events to be processed.
  205. /// </summary>
  206. /// <remarks>
  207. /// You can use this method if you want to probe if events are pending.
  208. /// Typically used if you need to flush the input queue while still
  209. /// running some of your own code in your main thread.
  210. /// </remarks>
  211. public bool EventsPending (bool wait = false)
  212. {
  213. return Driver.EventsPending (wait);
  214. }
  215. /// <summary>
  216. /// Runs one iteration of timers and file watches
  217. /// </summary>
  218. /// <remarks>
  219. /// You use this to process all pending events (timers, idle handlers and file watches).
  220. ///
  221. /// You can use it like this:
  222. /// while (main.EvensPending ()) MainIteration ();
  223. /// </remarks>
  224. public void MainIteration ()
  225. {
  226. if (timeouts.Count > 0)
  227. RunTimers ();
  228. Driver.MainIteration ();
  229. lock (idleHandlers) {
  230. if (idleHandlers.Count > 0)
  231. RunIdle ();
  232. }
  233. }
  234. /// <summary>
  235. /// Runs the mainloop.
  236. /// </summary>
  237. public void Run ()
  238. {
  239. bool prev = running;
  240. running = true;
  241. while (running) {
  242. EventsPending (true);
  243. MainIteration ();
  244. }
  245. running = prev;
  246. }
  247. }
  248. }