MainLoop.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. using System.Collections.ObjectModel;
  10. namespace Terminal.Gui {
  11. /// <summary>
  12. /// Public interface to create a platform specific <see cref="MainLoop"/> driver.
  13. /// </summary>
  14. public interface IMainLoopDriver {
  15. /// <summary>
  16. /// Initializes the <see cref="MainLoop"/>, gets the calling main loop for the initialization.
  17. /// </summary>
  18. /// <param name="mainLoop">Main loop.</param>
  19. void Setup (MainLoop mainLoop);
  20. /// <summary>
  21. /// Wakes up the <see cref="MainLoop"/> that might be waiting on input, must be thread safe.
  22. /// </summary>
  23. void Wakeup ();
  24. /// <summary>
  25. /// Must report whether there are any events pending, or even block waiting for events.
  26. /// </summary>
  27. /// <returns><c>true</c>, if there were pending events, <c>false</c> otherwise.</returns>
  28. /// <param name="wait">If set to <c>true</c> wait until an event is available, otherwise return immediately.</param>
  29. bool EventsPending (bool wait);
  30. /// <summary>
  31. /// The iteration function.
  32. /// </summary>
  33. void Iteration ();
  34. }
  35. /// <summary>
  36. /// Simple main loop implementation that can be used to monitor
  37. /// file descriptor, run timers and idle handlers.
  38. /// </summary>
  39. /// <remarks>
  40. /// Monitoring of file descriptors is only available on Unix, there
  41. /// does not seem to be a way of supporting this on Windows.
  42. /// </remarks>
  43. public class MainLoop {
  44. internal SortedList<long, Timeout> timeouts = new SortedList<long, Timeout> ();
  45. object _timeoutsLockToken = new object ();
  46. /// <summary>
  47. /// The idle handlers and lock that must be held while manipulating them
  48. /// </summary>
  49. object _idleHandlersLock = new object ();
  50. internal List<Func<bool>> idleHandlers = new List<Func<bool>> ();
  51. /// <summary>
  52. /// Gets the list of all timeouts sorted by the <see cref="TimeSpan"/> time ticks./>.
  53. /// A shorter limit time can be added at the end, but it will be called before an
  54. /// earlier addition that has a longer limit time.
  55. /// </summary>
  56. public SortedList<long, Timeout> Timeouts => timeouts;
  57. /// <summary>
  58. /// Gets a copy of the list of all idle handlers.
  59. /// </summary>
  60. public ReadOnlyCollection<Func<bool>> IdleHandlers {
  61. get {
  62. lock (_idleHandlersLock) {
  63. return new List<Func<bool>> (idleHandlers).AsReadOnly ();
  64. }
  65. }
  66. }
  67. /// <summary>
  68. /// The current <see cref="IMainLoopDriver"/> in use.
  69. /// </summary>
  70. /// <value>The driver.</value>
  71. public IMainLoopDriver Driver { get; }
  72. /// <summary>
  73. /// Invoked when a new timeout is added. To be used in the case
  74. /// when <see cref="Application.ExitRunLoopAfterFirstIteration"/> is <see langword="true"/>.
  75. /// </summary>
  76. public event EventHandler<TimeoutEventArgs> TimeoutAdded;
  77. /// <summary>
  78. /// Creates a new Mainloop.
  79. /// </summary>
  80. /// <param name="driver">Should match the <see cref="ConsoleDriver"/>
  81. /// (one of the implementations FakeMainLoop, UnixMainLoop, NetMainLoop or WindowsMainLoop).</param>
  82. public MainLoop (IMainLoopDriver driver)
  83. {
  84. Driver = driver;
  85. driver.Setup (this);
  86. }
  87. /// <summary>
  88. /// Runs <c>action</c> on the thread that is processing events
  89. /// </summary>
  90. /// <param name="action">the action to be invoked on the main processing thread.</param>
  91. public void Invoke (Action action)
  92. {
  93. AddIdle (() => {
  94. action ();
  95. return false;
  96. });
  97. }
  98. /// <summary>
  99. /// Adds specified idle handler function to <see cref="MainLoop"/> processing.
  100. /// The handler function will be called once per iteration of the main loop after other events have been handled.
  101. /// </summary>
  102. /// <remarks>
  103. /// <para>
  104. /// Remove an idle hander by calling <see cref="RemoveIdle(Func{bool})"/> with the token this method returns.
  105. /// </para>
  106. /// <para>
  107. /// If the <c>idleHandler</c> returns <c>false</c> it will be removed and not called subsequently.
  108. /// </para>
  109. /// </remarks>
  110. /// <param name="idleHandler">Token that can be used to remove the idle handler with <see cref="RemoveIdle(Func{bool})"/> .</param>
  111. public Func<bool> AddIdle (Func<bool> idleHandler)
  112. {
  113. lock (_idleHandlersLock) {
  114. idleHandlers.Add (idleHandler);
  115. }
  116. Driver.Wakeup ();
  117. return idleHandler;
  118. }
  119. /// <summary>
  120. /// Removes an idle handler added with <see cref="AddIdle(Func{bool})"/> from processing.
  121. /// </summary>
  122. /// <param name="token">A token returned by <see cref="AddIdle(Func{bool})"/></param>
  123. /// Returns <c>true</c>if the idle handler is successfully removed; otherwise, <c>false</c>.
  124. /// This method also returns <c>false</c> if the idle handler is not found.
  125. public bool RemoveIdle (Func<bool> token)
  126. {
  127. lock (_idleHandlersLock)
  128. return idleHandlers.Remove (token);
  129. }
  130. void AddTimeout (TimeSpan time, Timeout timeout)
  131. {
  132. lock (_timeoutsLockToken) {
  133. var k = (DateTime.UtcNow + time).Ticks;
  134. timeouts.Add (NudgeToUniqueKey (k), timeout);
  135. TimeoutAdded?.Invoke (this, new TimeoutEventArgs(timeout, k));
  136. }
  137. }
  138. /// <summary>
  139. /// Adds a timeout to the <see cref="MainLoop"/>.
  140. /// </summary>
  141. /// <remarks>
  142. /// When time specified passes, the callback will be invoked.
  143. /// If the callback returns true, the timeout will be reset, repeating
  144. /// the invocation. If it returns false, the timeout will stop and be removed.
  145. ///
  146. /// The returned value is a token that can be used to stop the timeout
  147. /// by calling <see cref="RemoveTimeout(object)"/>.
  148. /// </remarks>
  149. public object AddTimeout (TimeSpan time, Func<MainLoop, bool> callback)
  150. {
  151. if (callback == null)
  152. throw new ArgumentNullException (nameof (callback));
  153. var timeout = new Timeout () {
  154. Span = time,
  155. Callback = callback
  156. };
  157. AddTimeout (time, timeout);
  158. return timeout;
  159. }
  160. /// <summary>
  161. /// Removes a previously scheduled timeout
  162. /// </summary>
  163. /// <remarks>
  164. /// The token parameter is the value returned by AddTimeout.
  165. /// </remarks>
  166. /// Returns <c>true</c>if the timeout is successfully removed; otherwise, <c>false</c>.
  167. /// This method also returns <c>false</c> if the timeout is not found.
  168. public bool RemoveTimeout (object token)
  169. {
  170. lock (_timeoutsLockToken) {
  171. var idx = timeouts.IndexOfValue (token as Timeout);
  172. if (idx == -1)
  173. return false;
  174. timeouts.RemoveAt (idx);
  175. }
  176. return true;
  177. }
  178. void RunTimers ()
  179. {
  180. long now = DateTime.UtcNow.Ticks;
  181. SortedList<long, Timeout> copy;
  182. // lock prevents new timeouts being added
  183. // after we have taken the copy but before
  184. // we have allocated a new list (which would
  185. // result in lost timeouts or errors during enumeration)
  186. lock (_timeoutsLockToken) {
  187. copy = timeouts;
  188. timeouts = new SortedList<long, Timeout> ();
  189. }
  190. foreach (var t in copy) {
  191. var k = t.Key;
  192. var timeout = t.Value;
  193. if (k < now) {
  194. if (timeout.Callback (this))
  195. AddTimeout (timeout.Span, timeout);
  196. } else {
  197. lock (_timeoutsLockToken) {
  198. timeouts.Add (NudgeToUniqueKey (k), timeout);
  199. }
  200. }
  201. }
  202. }
  203. /// <summary>
  204. /// Finds the closest number to <paramref name="k"/> that is not
  205. /// present in <see cref="timeouts"/> (incrementally).
  206. /// </summary>
  207. /// <param name="k"></param>
  208. /// <returns></returns>
  209. private long NudgeToUniqueKey (long k)
  210. {
  211. lock (_timeoutsLockToken) {
  212. while (timeouts.ContainsKey (k)) {
  213. k++;
  214. }
  215. }
  216. return k;
  217. }
  218. void RunIdle ()
  219. {
  220. List<Func<bool>> iterate;
  221. lock (_idleHandlersLock) {
  222. iterate = idleHandlers;
  223. idleHandlers = new List<Func<bool>> ();
  224. }
  225. foreach (var idle in iterate) {
  226. if (idle ())
  227. lock (_idleHandlersLock)
  228. idleHandlers.Add (idle);
  229. }
  230. }
  231. bool _running;
  232. /// <summary>
  233. /// Stops the mainloop.
  234. /// </summary>
  235. public void Stop ()
  236. {
  237. _running = false;
  238. Driver.Wakeup ();
  239. }
  240. /// <summary>
  241. /// Determines whether there are pending events to be processed.
  242. /// </summary>
  243. /// <remarks>
  244. /// You can use this method if you want to probe if events are pending.
  245. /// Typically used if you need to flush the input queue while still
  246. /// running some of your own code in your main thread.
  247. /// </remarks>
  248. public bool EventsPending (bool wait = false)
  249. {
  250. return Driver.EventsPending (wait);
  251. }
  252. /// <summary>
  253. /// Runs one iteration of timers and file watches
  254. /// </summary>
  255. /// <remarks>
  256. /// Use this to process all pending events (timers, idle handlers and file watches).
  257. ///
  258. /// <code>
  259. /// while (main.EvenstPending ()) RunIteration ();
  260. /// </code>
  261. /// </remarks>
  262. public void RunIteration ()
  263. {
  264. if (timeouts.Count > 0)
  265. RunTimers ();
  266. Driver.Iteration ();
  267. bool runIdle = false;
  268. lock (_idleHandlersLock) {
  269. runIdle = idleHandlers.Count > 0;
  270. }
  271. if (runIdle) {
  272. RunIdle ();
  273. }
  274. }
  275. /// <summary>
  276. /// Runs the <see cref="MainLoop"/>.
  277. /// </summary>
  278. public void Run ()
  279. {
  280. bool prev = _running;
  281. _running = true;
  282. while (_running) {
  283. EventsPending (true);
  284. RunIteration ();
  285. }
  286. _running = prev;
  287. }
  288. }
  289. }