MainLoop.cs 5.9 KB

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