MainLoop.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. //
  2. // MainLoop.cs: Simple managed mainloop implementation.
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. // Copyright (C) 2011 Novell (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System.Collections.Generic;
  29. using System;
  30. namespace Terminal.Gui {
  31. /// <summary>
  32. /// Interface to create platform specific main loop drivers.
  33. /// </summary>
  34. public interface IMainLoopDriver {
  35. /// <summary>
  36. /// Initializes the main loop driver, gets the calling main loop for the initialization.
  37. /// </summary>
  38. /// <param name="mainLoop">Main loop.</param>
  39. void Setup (MainLoop mainLoop);
  40. /// <summary>
  41. /// Wakes up the mainloop that might be waiting on input, must be thread safe.
  42. /// </summary>
  43. void Wakeup ();
  44. /// <summary>
  45. /// Must report whether there are any events pending, or even block waiting for events.
  46. /// </summary>
  47. /// <returns><c>true</c>, if there were pending events, <c>false</c> otherwise.</returns>
  48. /// <param name="wait">If set to <c>true</c> wait until an event is available, otherwise return immediately.</param>
  49. bool EventsPending (bool wait);
  50. /// <summary>
  51. /// The interation function.
  52. /// </summary>
  53. void MainIteration ();
  54. }
  55. /// <summary>
  56. /// Simple main loop implementation that can be used to monitor
  57. /// file descriptor, run timers and idle handlers.
  58. /// </summary>
  59. /// <remarks>
  60. /// Monitoring of file descriptors is only available on Unix, there
  61. /// does not seem to be a way of supporting this on Windows.
  62. /// </remarks>
  63. public class MainLoop {
  64. internal class Timeout {
  65. public TimeSpan Span;
  66. public Func<MainLoop, bool> Callback;
  67. }
  68. internal SortedList<long, Timeout> timeouts = new SortedList<long, Timeout> ();
  69. internal List<Func<bool>> idleHandlers = new List<Func<bool>> ();
  70. IMainLoopDriver driver;
  71. /// <summary>
  72. /// The current IMainLoopDriver in use.
  73. /// </summary>
  74. /// <value>The driver.</value>
  75. public IMainLoopDriver Driver => driver;
  76. /// <summary>
  77. /// Creates a new Mainloop, to run it you must provide a driver, and choose
  78. /// one of the implementations UnixMainLoop, NetMainLoop or WindowsMainLoop.
  79. /// </summary>
  80. public MainLoop (IMainLoopDriver driver)
  81. {
  82. this.driver = driver;
  83. driver.Setup (this);
  84. }
  85. /// <summary>
  86. /// Runs @action on the thread that is processing events
  87. /// </summary>
  88. public void Invoke (Action action)
  89. {
  90. AddIdle (() => {
  91. action ();
  92. return false;
  93. });
  94. }
  95. /// <summary>
  96. /// Executes the specified @idleHandler on the idle loop. The return value is a token to remove it.
  97. /// </summary>
  98. public Func<bool> AddIdle (Func<bool> idleHandler)
  99. {
  100. lock (idleHandlers)
  101. idleHandlers.Add (idleHandler);
  102. return idleHandler;
  103. }
  104. /// <summary>
  105. /// Removes the specified idleHandler from processing.
  106. /// </summary>
  107. public void RemoveIdle (Func<bool> idleHandler)
  108. {
  109. lock (idleHandler)
  110. idleHandlers.Remove (idleHandler);
  111. }
  112. void AddTimeout (TimeSpan time, Timeout timeout)
  113. {
  114. timeouts.Add ((DateTime.UtcNow + time).Ticks, timeout);
  115. }
  116. /// <summary>
  117. /// Adds a timeout to the mainloop.
  118. /// </summary>
  119. /// <remarks>
  120. /// When time 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.
  123. ///
  124. /// The returned value is a token that can be used to stop the timeout
  125. /// by calling RemoveTimeout.
  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. public void RemoveTimeout (object token)
  145. {
  146. var idx = timeouts.IndexOfValue (token as Timeout);
  147. if (idx == -1)
  148. return;
  149. timeouts.RemoveAt (idx);
  150. }
  151. void RunTimers ()
  152. {
  153. long now = DateTime.UtcNow.Ticks;
  154. var copy = timeouts;
  155. timeouts = new SortedList<long, Timeout> ();
  156. foreach (var k in copy.Keys) {
  157. var timeout = copy [k];
  158. if (k < now) {
  159. if (timeout.Callback (this))
  160. AddTimeout (timeout.Span, timeout);
  161. } else
  162. timeouts.Add (k, timeout);
  163. }
  164. }
  165. void RunIdle ()
  166. {
  167. List<Func<bool>> iterate;
  168. lock (idleHandlers) {
  169. iterate = idleHandlers;
  170. idleHandlers = new List<Func<bool>> ();
  171. }
  172. foreach (var idle in iterate) {
  173. if (idle ())
  174. lock (idleHandlers)
  175. idleHandlers.Add (idle);
  176. }
  177. }
  178. bool running;
  179. /// <summary>
  180. /// Stops the mainloop.
  181. /// </summary>
  182. public void Stop ()
  183. {
  184. running = false;
  185. driver.Wakeup ();
  186. }
  187. /// <summary>
  188. /// Determines whether there are pending events to be processed.
  189. /// </summary>
  190. /// <remarks>
  191. /// You can use this method if you want to probe if events are pending.
  192. /// Typically used if you need to flush the input queue while still
  193. /// running some of your own code in your main thread.
  194. /// </remarks>
  195. public bool EventsPending (bool wait = false)
  196. {
  197. return driver.EventsPending (wait);
  198. }
  199. /// <summary>
  200. /// Runs one iteration of timers and file watches
  201. /// </summary>
  202. /// <remarks>
  203. /// You use this to process all pending events (timers, idle handlers and file watches).
  204. ///
  205. /// You can use it like this:
  206. /// while (main.EvensPending ()) MainIteration ();
  207. /// </remarks>
  208. public void MainIteration ()
  209. {
  210. if (timeouts.Count > 0)
  211. RunTimers ();
  212. driver.MainIteration ();
  213. lock (idleHandlers) {
  214. if (idleHandlers.Count > 0)
  215. RunIdle ();
  216. }
  217. }
  218. /// <summary>
  219. /// Runs the mainloop.
  220. /// </summary>
  221. public void Run ()
  222. {
  223. bool prev = running;
  224. running = true;
  225. while (running) {
  226. EventsPending (true);
  227. MainIteration ();
  228. }
  229. running = prev;
  230. }
  231. }
  232. }