2
0

MainLoop.cs 7.1 KB

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