mainloop.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. while (true) {
  191. if (wait && pollTimeout == -1) {
  192. pollTimeout = 0;
  193. }
  194. n = poll (pollmap, (uint)pollmap.Length, pollTimeout);
  195. if (pollmap != null) {
  196. break;
  197. }
  198. if (mainLoop.timeouts.Count > 0 || mainLoop.idleHandlers.Count > 0) {
  199. return true;
  200. }
  201. }
  202. int ic;
  203. lock (mainLoop.idleHandlers)
  204. ic = mainLoop.idleHandlers.Count;
  205. return n > 0 || mainLoop.timeouts.Count > 0 && ((mainLoop.timeouts.Keys [0] - DateTime.UtcNow.Ticks) < 0) || ic > 0;
  206. }
  207. void IMainLoopDriver.MainIteration ()
  208. {
  209. if (pollmap != null) {
  210. foreach (var p in pollmap) {
  211. Watch watch;
  212. if (p.revents == 0)
  213. continue;
  214. if (!descriptorWatchers.TryGetValue (p.fd, out watch))
  215. continue;
  216. if (!watch.Callback (this.mainLoop))
  217. descriptorWatchers.Remove (p.fd);
  218. }
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// Mainloop intended to be used with the .NET System.Console API, and can
  224. /// be used on Windows and Unix, it is cross platform but lacks things like
  225. /// file descriptor monitoring.
  226. /// </summary>
  227. class NetMainLoop : IMainLoopDriver {
  228. AutoResetEvent keyReady = new AutoResetEvent (false);
  229. AutoResetEvent waitForProbe = new AutoResetEvent (false);
  230. ConsoleKeyInfo? windowsKeyResult = null;
  231. public Action<ConsoleKeyInfo> WindowsKeyPressed;
  232. MainLoop mainLoop;
  233. public NetMainLoop ()
  234. {
  235. }
  236. void WindowsKeyReader ()
  237. {
  238. while (true) {
  239. waitForProbe.WaitOne ();
  240. windowsKeyResult = Console.ReadKey (true);
  241. keyReady.Set ();
  242. }
  243. }
  244. void IMainLoopDriver.Setup (MainLoop mainLoop)
  245. {
  246. this.mainLoop = mainLoop;
  247. Thread readThread = new Thread (WindowsKeyReader);
  248. readThread.Start ();
  249. }
  250. void IMainLoopDriver.Wakeup ()
  251. {
  252. }
  253. bool IMainLoopDriver.EventsPending (bool wait)
  254. {
  255. long now = DateTime.UtcNow.Ticks;
  256. int waitTimeout;
  257. if (mainLoop.timeouts.Count > 0) {
  258. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  259. if (waitTimeout < 0)
  260. return true;
  261. } else
  262. waitTimeout = -1;
  263. if (!wait)
  264. waitTimeout = 0;
  265. windowsKeyResult = null;
  266. waitForProbe.Set ();
  267. keyReady.WaitOne (waitTimeout);
  268. return windowsKeyResult.HasValue;
  269. }
  270. void IMainLoopDriver.MainIteration ()
  271. {
  272. if (windowsKeyResult.HasValue) {
  273. if (WindowsKeyPressed!= null)
  274. WindowsKeyPressed (windowsKeyResult.Value);
  275. windowsKeyResult = null;
  276. }
  277. }
  278. }
  279. /// <summary>
  280. /// Simple main loop implementation that can be used to monitor
  281. /// file descriptor, run timers and idle handlers.
  282. /// </summary>
  283. /// <remarks>
  284. /// Monitoring of file descriptors is only available on Unix, there
  285. /// does not seem to be a way of supporting this on Windows.
  286. /// </remarks>
  287. public class MainLoop {
  288. internal class Timeout {
  289. public TimeSpan Span;
  290. public Func<MainLoop,bool> Callback;
  291. }
  292. internal SortedList <long, Timeout> timeouts = new SortedList<long,Timeout> ();
  293. internal List<Func<bool>> idleHandlers = new List<Func<bool>> ();
  294. IMainLoopDriver driver;
  295. /// <summary>
  296. /// The current IMainLoopDriver in use.
  297. /// </summary>
  298. /// <value>The driver.</value>
  299. public IMainLoopDriver Driver => driver;
  300. /// <summary>
  301. /// Creates a new Mainloop, to run it you must provide a driver, and choose
  302. /// one of the implementations UnixMainLoop, NetMainLoop or WindowsMainLoop.
  303. /// </summary>
  304. public MainLoop (IMainLoopDriver driver)
  305. {
  306. this.driver = driver;
  307. driver.Setup (this);
  308. }
  309. /// <summary>
  310. /// Runs @action on the thread that is processing events
  311. /// </summary>
  312. public void Invoke (Action action)
  313. {
  314. AddIdle (()=> {
  315. action ();
  316. return false;
  317. });
  318. }
  319. /// <summary>
  320. /// Executes the specified @idleHandler on the idle loop. The return value is a token to remove it.
  321. /// </summary>
  322. public Func<bool> AddIdle (Func<bool> idleHandler)
  323. {
  324. lock (idleHandlers)
  325. idleHandlers.Add (idleHandler);
  326. return idleHandler;
  327. }
  328. /// <summary>
  329. /// Removes the specified idleHandler from processing.
  330. /// </summary>
  331. public void RemoveIdle (Func<bool> idleHandler)
  332. {
  333. lock (idleHandler)
  334. idleHandlers.Remove (idleHandler);
  335. }
  336. void AddTimeout (TimeSpan time, Timeout timeout)
  337. {
  338. timeouts.Add ((DateTime.UtcNow + time).Ticks, timeout);
  339. }
  340. /// <summary>
  341. /// Adds a timeout to the mainloop.
  342. /// </summary>
  343. /// <remarks>
  344. /// When time time specified passes, the callback will be invoked.
  345. /// If the callback returns true, the timeout will be reset, repeating
  346. /// the invocation. If it returns false, the timeout will stop.
  347. ///
  348. /// The returned value is a token that can be used to stop the timeout
  349. /// by calling RemoveTimeout.
  350. /// </remarks>
  351. public object AddTimeout (TimeSpan time, Func<MainLoop,bool> callback)
  352. {
  353. if (callback == null)
  354. throw new ArgumentNullException (nameof (callback));
  355. var timeout = new Timeout () {
  356. Span = time,
  357. Callback = callback
  358. };
  359. AddTimeout (time, timeout);
  360. return timeout;
  361. }
  362. /// <summary>
  363. /// Removes a previously scheduled timeout
  364. /// </summary>
  365. /// <remarks>
  366. /// The token parameter is the value returned by AddTimeout.
  367. /// </remarks>
  368. public void RemoveTimeout (object token)
  369. {
  370. var idx = timeouts.IndexOfValue (token as Timeout);
  371. if (idx == -1)
  372. return;
  373. timeouts.RemoveAt (idx);
  374. }
  375. void RunTimers ()
  376. {
  377. long now = DateTime.UtcNow.Ticks;
  378. var copy = timeouts;
  379. timeouts = new SortedList<long,Timeout> ();
  380. foreach (var k in copy.Keys){
  381. var timeout = copy [k];
  382. if (k < now) {
  383. if (timeout.Callback (this))
  384. AddTimeout (timeout.Span, timeout);
  385. } else
  386. timeouts.Add (k, timeout);
  387. }
  388. }
  389. void RunIdle ()
  390. {
  391. List<Func<bool>> iterate;
  392. lock (idleHandlers){
  393. iterate = idleHandlers;
  394. idleHandlers = new List<Func<bool>> ();
  395. }
  396. foreach (var idle in iterate){
  397. if (idle ())
  398. lock (idleHandlers)
  399. idleHandlers.Add (idle);
  400. }
  401. }
  402. bool running;
  403. /// <summary>
  404. /// Stops the mainloop.
  405. /// </summary>
  406. public void Stop ()
  407. {
  408. running = false;
  409. driver.Wakeup ();
  410. }
  411. /// <summary>
  412. /// Determines whether there are pending events to be processed.
  413. /// </summary>
  414. /// <remarks>
  415. /// You can use this method if you want to probe if events are pending.
  416. /// Typically used if you need to flush the input queue while still
  417. /// running some of your own code in your main thread.
  418. /// </remarks>
  419. public bool EventsPending (bool wait = false)
  420. {
  421. return driver.EventsPending (wait);
  422. }
  423. /// <summary>
  424. /// Runs one iteration of timers and file watches
  425. /// </summary>
  426. /// <remarks>
  427. /// You use this to process all pending events (timers, idle handlers and file watches).
  428. ///
  429. /// You can use it like this:
  430. /// while (main.EvensPending ()) MainIteration ();
  431. /// </remarks>
  432. public void MainIteration ()
  433. {
  434. if (timeouts.Count > 0)
  435. RunTimers ();
  436. driver.MainIteration ();
  437. lock (idleHandlers){
  438. if (idleHandlers.Count > 0)
  439. RunIdle();
  440. }
  441. }
  442. /// <summary>
  443. /// Runs the mainloop.
  444. /// </summary>
  445. public void Run ()
  446. {
  447. bool prev = running;
  448. running = true;
  449. while (running){
  450. EventsPending (true);
  451. MainIteration ();
  452. }
  453. running = prev;
  454. }
  455. }
  456. }