mainloop.cs 11 KB

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