mainloop.cs 12 KB

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