mainloop.cs 9.3 KB

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