MainLoop.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 interation 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. return idleHandler;
  91. }
  92. /// <summary>
  93. /// Removes an idle handler added with <see cref="AddIdle(Func{bool})"/> from processing.
  94. /// </summary>
  95. /// <param name="token">A token returned by <see cref="AddIdle(Func{bool})"/></param>
  96. public void RemoveIdle (Func<bool> token)
  97. {
  98. lock (token)
  99. idleHandlers.Remove (token);
  100. }
  101. void AddTimeout (TimeSpan time, Timeout timeout)
  102. {
  103. timeouts.Add ((DateTime.UtcNow + time).Ticks, timeout);
  104. }
  105. /// <summary>
  106. /// Adds a timeout to the mainloop.
  107. /// </summary>
  108. /// <remarks>
  109. /// When time time specified passes, the callback will be invoked.
  110. /// If the callback returns true, the timeout will be reset, repeating
  111. /// the invocation. If it returns false, the timeout will stop and be removed.
  112. ///
  113. /// The returned value is a token that can be used to stop the timeout
  114. /// by calling <see cref="RemoveTimeout(object)"/>.
  115. /// </remarks>
  116. public object AddTimeout (TimeSpan time, Func<MainLoop, bool> callback)
  117. {
  118. if (callback == null)
  119. throw new ArgumentNullException (nameof (callback));
  120. var timeout = new Timeout () {
  121. Span = time,
  122. Callback = callback
  123. };
  124. AddTimeout (time, timeout);
  125. return timeout;
  126. }
  127. /// <summary>
  128. /// Removes a previously scheduled timeout
  129. /// </summary>
  130. /// <remarks>
  131. /// The token parameter is the value returned by AddTimeout.
  132. /// </remarks>
  133. public void RemoveTimeout (object token)
  134. {
  135. var idx = timeouts.IndexOfValue (token as Timeout);
  136. if (idx == -1)
  137. return;
  138. timeouts.RemoveAt (idx);
  139. }
  140. void RunTimers ()
  141. {
  142. long now = DateTime.UtcNow.Ticks;
  143. var copy = timeouts;
  144. timeouts = new SortedList<long, Timeout> ();
  145. foreach (var k in copy.Keys) {
  146. var timeout = copy [k];
  147. if (k < now) {
  148. if (timeout.Callback (this))
  149. AddTimeout (timeout.Span, timeout);
  150. } else
  151. timeouts.Add (k, timeout);
  152. }
  153. }
  154. void RunIdle ()
  155. {
  156. List<Func<bool>> iterate;
  157. lock (idleHandlers) {
  158. iterate = idleHandlers;
  159. idleHandlers = new List<Func<bool>> ();
  160. }
  161. foreach (var idle in iterate) {
  162. if (idle ())
  163. lock (idleHandlers)
  164. idleHandlers.Add (idle);
  165. }
  166. }
  167. bool running;
  168. /// <summary>
  169. /// Stops the mainloop.
  170. /// </summary>
  171. public void Stop ()
  172. {
  173. running = false;
  174. Driver.Wakeup ();
  175. }
  176. /// <summary>
  177. /// Determines whether there are pending events to be processed.
  178. /// </summary>
  179. /// <remarks>
  180. /// You can use this method if you want to probe if events are pending.
  181. /// Typically used if you need to flush the input queue while still
  182. /// running some of your own code in your main thread.
  183. /// </remarks>
  184. public bool EventsPending (bool wait = false)
  185. {
  186. return Driver.EventsPending (wait);
  187. }
  188. /// <summary>
  189. /// Runs one iteration of timers and file watches
  190. /// </summary>
  191. /// <remarks>
  192. /// You use this to process all pending events (timers, idle handlers and file watches).
  193. ///
  194. /// You can use it like this:
  195. /// while (main.EvensPending ()) MainIteration ();
  196. /// </remarks>
  197. public void MainIteration ()
  198. {
  199. if (timeouts.Count > 0)
  200. RunTimers ();
  201. Driver.MainIteration ();
  202. lock (idleHandlers) {
  203. if (idleHandlers.Count > 0)
  204. RunIdle ();
  205. }
  206. }
  207. /// <summary>
  208. /// Runs the mainloop.
  209. /// </summary>
  210. public void Run ()
  211. {
  212. bool prev = running;
  213. running = true;
  214. while (running) {
  215. EventsPending (true);
  216. MainIteration ();
  217. }
  218. running = prev;
  219. }
  220. }
  221. }