MainLoop.cs 9.3 KB

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