mainloop.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 Mono.Unix.Native;
  29. using System.Collections.Generic;
  30. using System;
  31. using System.Runtime.InteropServices;
  32. namespace Mono.Terminal {
  33. /// <summary>
  34. /// Simple main loop implementation that can be used to monitor
  35. /// file descriptor, run timers and idle handlers.
  36. /// </summary>
  37. public class MainLoop {
  38. /// <summary>
  39. /// Condition on which to wake up from file descriptor activity
  40. /// </summary>
  41. [Flags]
  42. public enum Condition {
  43. /// <summary>
  44. /// There is data to read
  45. /// </summary>
  46. PollIn = 1,
  47. /// <summary>
  48. /// Writing to the specified descriptor will not block
  49. /// </summary>
  50. PollOut = 2,
  51. /// <summary>
  52. /// There is urgent data to read
  53. /// </summary>
  54. PollPri = 4,
  55. /// <summary>
  56. /// Error condition on output
  57. /// </summary>
  58. PollErr = 8,
  59. /// <summary>
  60. /// Hang-up on output
  61. /// </summary>
  62. PollHup = 16,
  63. /// <summary>
  64. /// File descriptor is not open.
  65. /// </summary>
  66. PollNval = 32
  67. }
  68. class Watch {
  69. public int File;
  70. public Condition Condition;
  71. public Func<MainLoop,bool> Callback;
  72. }
  73. class Timeout {
  74. public TimeSpan Span;
  75. public Func<MainLoop,bool> Callback;
  76. }
  77. Dictionary <int, Watch> descriptorWatchers = new Dictionary<int,Watch>();
  78. SortedList <double, Timeout> timeouts = new SortedList<double,Timeout> ();
  79. List<Func<bool>> idleHandlers = new List<Func<bool>> ();
  80. Pollfd [] pollmap;
  81. bool poll_dirty = true;
  82. int [] wakeupPipes = new int [2];
  83. static IntPtr ignore = Marshal.AllocHGlobal (1);
  84. /// <summary>
  85. /// Default constructor
  86. /// </summary>
  87. public MainLoop ()
  88. {
  89. Syscall.pipe (wakeupPipes);
  90. AddWatch (wakeupPipes [0], Condition.PollIn, ml => {
  91. Syscall.read (wakeupPipes [0], ignore, 1);
  92. return true;
  93. });
  94. }
  95. void Wakeup ()
  96. {
  97. Syscall.write (wakeupPipes [1], ignore, 1);
  98. }
  99. /// <summary>
  100. /// Runs @action on the thread that is processing events
  101. /// </summary>
  102. public void Invoke (Action action)
  103. {
  104. AddIdle (()=> {
  105. action ();
  106. return false;
  107. });
  108. Wakeup ();
  109. }
  110. /// <summary>
  111. /// Executes the specified @idleHandler on the idle loop. The return value is a token to remove it.
  112. /// </summary>
  113. public Func<bool> AddIdle (Func<bool> idleHandler)
  114. {
  115. lock (idleHandlers)
  116. idleHandlers.Add (idleHandler);
  117. return idleHandler;
  118. }
  119. /// <summary>
  120. /// Removes the specified idleHandler from processing.
  121. /// </summary>
  122. public void RemoveIdle (Func<bool> idleHandler)
  123. {
  124. lock (idleHandler)
  125. idleHandlers.Remove (idleHandler);
  126. }
  127. /// <summary>
  128. /// Watches a file descriptor for activity.
  129. /// </summary>
  130. /// <remarks>
  131. /// When the condition is met, the provided callback
  132. /// is invoked. If the callback returns false, the
  133. /// watch is automatically removed.
  134. ///
  135. /// The return value is a token that represents this watch, you can
  136. /// use this token to remove the watch by calling RemoveWatch.
  137. /// </remarks>
  138. public object AddWatch (int fileDescriptor, Condition condition, Func<MainLoop,bool> callback)
  139. {
  140. if (callback == null)
  141. throw new ArgumentNullException ("callback");
  142. var watch = new Watch () { Condition = condition, Callback = callback, File = fileDescriptor };
  143. descriptorWatchers [fileDescriptor] = watch;
  144. poll_dirty = true;
  145. return watch;
  146. }
  147. /// <summary>
  148. /// Removes an active watch from the mainloop.
  149. /// </summary>
  150. /// <remarks>
  151. /// The token parameter is the value returned from AddWatch
  152. /// </remarks>
  153. public void RemoveWatch (object token)
  154. {
  155. var watch = token as Watch;
  156. if (watch == null)
  157. return;
  158. descriptorWatchers.Remove (watch.File);
  159. }
  160. void AddTimeout (TimeSpan time, Timeout timeout)
  161. {
  162. timeouts.Add ((DateTime.UtcNow + time).Ticks, timeout);
  163. }
  164. /// <summary>
  165. /// Adds a timeout to the mainloop.
  166. /// </summary>
  167. /// <remarks>
  168. /// When time time specified passes, the callback will be invoked.
  169. /// If the callback returns true, the timeout will be reset, repeating
  170. /// the invocation. If it returns false, the timeout will stop.
  171. ///
  172. /// The returned value is a token that can be used to stop the timeout
  173. /// by calling RemoveTimeout.
  174. /// </remarks>
  175. public object AddTimeout (TimeSpan time, Func<MainLoop,bool> callback)
  176. {
  177. if (callback == null)
  178. throw new ArgumentNullException ("callback");
  179. var timeout = new Timeout () {
  180. Span = time,
  181. Callback = callback
  182. };
  183. AddTimeout (time, timeout);
  184. return timeout;
  185. }
  186. /// <summary>
  187. /// Removes a previously scheduled timeout
  188. /// </summary>
  189. /// <remarks>
  190. /// The token parameter is the value returned by AddTimeout.
  191. /// </remarks>
  192. public void RemoveTimeout (object token)
  193. {
  194. var idx = timeouts.IndexOfValue (token as Timeout);
  195. if (idx == -1)
  196. return;
  197. timeouts.RemoveAt (idx);
  198. }
  199. static PollEvents MapCondition (Condition condition)
  200. {
  201. PollEvents ret = 0;
  202. if ((condition & Condition.PollIn) != 0)
  203. ret |= PollEvents.POLLIN;
  204. if ((condition & Condition.PollOut) != 0)
  205. ret |= PollEvents.POLLOUT;
  206. if ((condition & Condition.PollPri) != 0)
  207. ret |= PollEvents.POLLPRI;
  208. if ((condition & Condition.PollErr) != 0)
  209. ret |= PollEvents.POLLERR;
  210. if ((condition & Condition.PollHup) != 0)
  211. ret |= PollEvents.POLLHUP;
  212. if ((condition & Condition.PollNval) != 0)
  213. ret |= PollEvents.POLLNVAL;
  214. return ret;
  215. }
  216. void UpdatePollMap ()
  217. {
  218. if (!poll_dirty)
  219. return;
  220. poll_dirty = false;
  221. pollmap = new Pollfd [descriptorWatchers.Count];
  222. int i = 0;
  223. foreach (var fd in descriptorWatchers.Keys){
  224. pollmap [i].fd = fd;
  225. pollmap [i].events = MapCondition (descriptorWatchers [fd].Condition);
  226. i++;
  227. }
  228. }
  229. void RunTimers ()
  230. {
  231. long now = DateTime.UtcNow.Ticks;
  232. var copy = timeouts;
  233. timeouts = new SortedList<double,Timeout> ();
  234. foreach (var k in copy.Keys){
  235. var timeout = copy [k];
  236. if (k < now) {
  237. if (timeout.Callback (this))
  238. AddTimeout (timeout.Span, timeout);
  239. } else
  240. timeouts.Add (k, timeout);
  241. }
  242. }
  243. void RunIdle ()
  244. {
  245. List<Func<bool>> iterate;
  246. lock (idleHandlers){
  247. iterate = idleHandlers;
  248. idleHandlers = new List<Func<bool>> ();
  249. }
  250. foreach (var idle in iterate){
  251. if (idle ())
  252. lock (idleHandlers)
  253. idleHandlers.Add (idle);
  254. }
  255. }
  256. bool running;
  257. /// <summary>
  258. /// Stops the mainloop.
  259. /// </summary>
  260. public void Stop ()
  261. {
  262. running = false;
  263. Wakeup ();
  264. }
  265. /// <summary>
  266. /// Determines whether there are pending events to be processed.
  267. /// </summary>
  268. /// <remarks>
  269. /// You can use this method if you want to probe if events are pending.
  270. /// Typically used if you need to flush the input queue while still
  271. /// running some of your own code in your main thread.
  272. /// </remarks>
  273. public bool EventsPending (bool wait = false)
  274. {
  275. long now = DateTime.UtcNow.Ticks;
  276. int pollTimeout, n;
  277. if (timeouts.Count > 0)
  278. pollTimeout = (int) ((timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  279. else
  280. pollTimeout = -1;
  281. if (!wait)
  282. pollTimeout = 0;
  283. UpdatePollMap ();
  284. n = Syscall.poll (pollmap, (uint) pollmap.Length, pollTimeout);
  285. int ic;
  286. lock (idleHandlers)
  287. ic = idleHandlers.Count;
  288. return n > 0 || timeouts.Count > 0 && ((timeouts.Keys [0] - DateTime.UtcNow.Ticks) < 0) || ic > 0;
  289. }
  290. /// <summary>
  291. /// Runs one iteration of timers and file watches
  292. /// </summary>
  293. /// <remarks>
  294. /// You use this to process all pending events (timers, idle handlers and file watches).
  295. ///
  296. /// You can use it like this:
  297. /// while (main.EvensPending ()) MainIteration ();
  298. /// </remarks>
  299. public void MainIteration ()
  300. {
  301. if (timeouts.Count > 0)
  302. RunTimers ();
  303. foreach (var p in pollmap){
  304. Watch watch;
  305. if (p.revents == 0)
  306. continue;
  307. if (!descriptorWatchers.TryGetValue (p.fd, out watch))
  308. continue;
  309. if (!watch.Callback (this))
  310. descriptorWatchers.Remove (p.fd);
  311. }
  312. if (idleHandlers.Count > 0)
  313. RunIdle ();
  314. }
  315. /// <summary>
  316. /// Runs the mainloop.
  317. /// </summary>
  318. public void Run ()
  319. {
  320. bool prev = running;
  321. running = true;
  322. while (running){
  323. EventsPending (true);
  324. MainIteration ();
  325. }
  326. running = prev;
  327. }
  328. }
  329. }