mainloop.cs 13 KB

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