mainloop.cs 13 KB

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