MainLoop.cs 9.2 KB

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