mainloop.cs 13 KB

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