MainLoop.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 your own platform specific main loop driver.
  13. /// </summary>
  14. public interface IMainLoopDriver {
  15. /// <summary>
  16. /// Initializes the main loop driver, 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 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 MainIteration ();
  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 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 mainloop processing. The handler function will be called once per iteration of the main loop after other events have been handled.
  113. /// </summary>
  114. /// <remarks>
  115. /// <para>
  116. /// Remove an idle hander by calling <see cref="RemoveIdle(Func{bool})"/> with the token this method returns.
  117. /// </para>
  118. /// <para>
  119. /// If the <c>idleHandler</c> returns <c>false</c> it will be removed and not called subsequently.
  120. /// </para>
  121. /// </remarks>
  122. /// <param name="idleHandler">Token that can be used to remove the idle handler with <see cref="RemoveIdle(Func{bool})"/> .</param>
  123. public Func<bool> AddIdle (Func<bool> idleHandler)
  124. {
  125. lock (idleHandlersLock) {
  126. idleHandlers.Add (idleHandler);
  127. }
  128. Driver.Wakeup ();
  129. return idleHandler;
  130. }
  131. /// <summary>
  132. /// Removes an idle handler added with <see cref="AddIdle(Func{bool})"/> from processing.
  133. /// </summary>
  134. /// <param name="token">A token returned by <see cref="AddIdle(Func{bool})"/></param>
  135. /// Returns <c>true</c>if the idle handler is successfully removed; otherwise, <c>false</c>.
  136. /// This method also returns <c>false</c> if the idle handler is not found.
  137. public bool RemoveIdle (Func<bool> token)
  138. {
  139. lock (idleHandlersLock)
  140. return idleHandlers.Remove (token);
  141. }
  142. void AddTimeout (TimeSpan time, Timeout timeout)
  143. {
  144. lock (timeoutsLockToken) {
  145. var k = (DateTime.UtcNow + time).Ticks;
  146. timeouts.Add (NudgeToUniqueKey (k), timeout);
  147. TimeoutAdded?.Invoke (this, new TimeoutEventArgs(timeout, k));
  148. }
  149. }
  150. /// <summary>
  151. /// Adds a timeout to the mainloop.
  152. /// </summary>
  153. /// <remarks>
  154. /// When time specified passes, the callback will be invoked.
  155. /// If the callback returns true, the timeout will be reset, repeating
  156. /// the invocation. If it returns false, the timeout will stop and be removed.
  157. ///
  158. /// The returned value is a token that can be used to stop the timeout
  159. /// by calling <see cref="RemoveTimeout(object)"/>.
  160. /// </remarks>
  161. public object AddTimeout (TimeSpan time, Func<MainLoop, bool> callback)
  162. {
  163. if (callback == null)
  164. throw new ArgumentNullException (nameof (callback));
  165. var timeout = new Timeout () {
  166. Span = time,
  167. Callback = callback
  168. };
  169. AddTimeout (time, timeout);
  170. return timeout;
  171. }
  172. /// <summary>
  173. /// Removes a previously scheduled timeout
  174. /// </summary>
  175. /// <remarks>
  176. /// The token parameter is the value returned by AddTimeout.
  177. /// </remarks>
  178. /// Returns <c>true</c>if the timeout is successfully removed; otherwise, <c>false</c>.
  179. /// This method also returns <c>false</c> if the timeout is not found.
  180. public bool RemoveTimeout (object token)
  181. {
  182. lock (timeoutsLockToken) {
  183. var idx = timeouts.IndexOfValue (token as Timeout);
  184. if (idx == -1)
  185. return false;
  186. timeouts.RemoveAt (idx);
  187. }
  188. return true;
  189. }
  190. void RunTimers ()
  191. {
  192. long now = DateTime.UtcNow.Ticks;
  193. SortedList<long, Timeout> copy;
  194. // lock prevents new timeouts being added
  195. // after we have taken the copy but before
  196. // we have allocated a new list (which would
  197. // result in lost timeouts or errors during enumeration)
  198. lock (timeoutsLockToken) {
  199. copy = timeouts;
  200. timeouts = new SortedList<long, Timeout> ();
  201. }
  202. foreach (var t in copy) {
  203. var k = t.Key;
  204. var timeout = t.Value;
  205. if (k < now) {
  206. if (timeout.Callback (this))
  207. AddTimeout (timeout.Span, timeout);
  208. } else {
  209. lock (timeoutsLockToken) {
  210. timeouts.Add (NudgeToUniqueKey (k), timeout);
  211. }
  212. }
  213. }
  214. }
  215. /// <summary>
  216. /// Finds the closest number to <paramref name="k"/> that is not
  217. /// present in <see cref="timeouts"/> (incrementally).
  218. /// </summary>
  219. /// <param name="k"></param>
  220. /// <returns></returns>
  221. private long NudgeToUniqueKey (long k)
  222. {
  223. lock (timeoutsLockToken) {
  224. while (timeouts.ContainsKey (k)) {
  225. k++;
  226. }
  227. }
  228. return k;
  229. }
  230. void RunIdle ()
  231. {
  232. List<Func<bool>> iterate;
  233. lock (idleHandlersLock) {
  234. iterate = idleHandlers;
  235. idleHandlers = new List<Func<bool>> ();
  236. }
  237. foreach (var idle in iterate) {
  238. if (idle ())
  239. lock (idleHandlersLock)
  240. idleHandlers.Add (idle);
  241. }
  242. }
  243. bool running;
  244. /// <summary>
  245. /// Stops the mainloop.
  246. /// </summary>
  247. public void Stop ()
  248. {
  249. running = false;
  250. Driver.Wakeup ();
  251. }
  252. /// <summary>
  253. /// Determines whether there are pending events to be processed.
  254. /// </summary>
  255. /// <remarks>
  256. /// You can use this method if you want to probe if events are pending.
  257. /// Typically used if you need to flush the input queue while still
  258. /// running some of your own code in your main thread.
  259. /// </remarks>
  260. public bool EventsPending (bool wait = false)
  261. {
  262. return Driver.EventsPending (wait);
  263. }
  264. /// <summary>
  265. /// Runs one iteration of timers and file watches
  266. /// </summary>
  267. /// <remarks>
  268. /// You use this to process all pending events (timers, idle handlers and file watches).
  269. ///
  270. /// You can use it like this:
  271. /// while (main.EvensPending ()) MainIteration ();
  272. /// </remarks>
  273. public void MainIteration ()
  274. {
  275. if (timeouts.Count > 0)
  276. RunTimers ();
  277. Driver.MainIteration ();
  278. bool runIdle = false;
  279. lock (idleHandlersLock) {
  280. runIdle = idleHandlers.Count > 0;
  281. }
  282. if (runIdle) {
  283. RunIdle ();
  284. }
  285. }
  286. /// <summary>
  287. /// Runs the mainloop.
  288. /// </summary>
  289. public void Run ()
  290. {
  291. bool prev = running;
  292. running = true;
  293. while (running) {
  294. EventsPending (true);
  295. MainIteration ();
  296. }
  297. running = prev;
  298. }
  299. }
  300. }