2
0

UnixMainLoop.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 Terminal.Gui {
  33. /// <summary>
  34. /// Unix main loop, suitable for using on Posix systems
  35. /// </summary>
  36. /// <remarks>
  37. /// In addition to the general functions of the mainloop, the Unix version
  38. /// can watch file descriptors using the AddWatch methods.
  39. /// </remarks>
  40. public class UnixMainLoop : IMainLoopDriver {
  41. [StructLayout (LayoutKind.Sequential)]
  42. struct Pollfd {
  43. public int fd;
  44. public short events, revents;
  45. }
  46. /// <summary>
  47. /// Condition on which to wake up from file descriptor activity. These match the Linux/BSD poll definitions.
  48. /// </summary>
  49. [Flags]
  50. public enum Condition : short {
  51. /// <summary>
  52. /// There is data to read
  53. /// </summary>
  54. PollIn = 1,
  55. /// <summary>
  56. /// Writing to the specified descriptor will not block
  57. /// </summary>
  58. PollOut = 4,
  59. /// <summary>
  60. /// There is urgent data to read
  61. /// </summary>
  62. PollPri = 2,
  63. /// <summary>
  64. /// Error condition on output
  65. /// </summary>
  66. PollErr = 8,
  67. /// <summary>
  68. /// Hang-up on output
  69. /// </summary>
  70. PollHup = 16,
  71. /// <summary>
  72. /// File descriptor is not open.
  73. /// </summary>
  74. PollNval = 32
  75. }
  76. class Watch {
  77. public int File;
  78. public Condition Condition;
  79. public Func<MainLoop, bool> Callback;
  80. }
  81. Dictionary<int, Watch> descriptorWatchers = new Dictionary<int, Watch> ();
  82. [DllImport ("libc")]
  83. extern static int poll ([In, Out]Pollfd [] ufds, uint nfds, int timeout);
  84. [DllImport ("libc")]
  85. extern static int pipe ([In, Out]int [] pipes);
  86. [DllImport ("libc")]
  87. extern static int read (int fd, IntPtr buf, IntPtr n);
  88. [DllImport ("libc")]
  89. extern static int write (int fd, IntPtr buf, IntPtr n);
  90. Pollfd [] pollmap;
  91. bool poll_dirty = true;
  92. int [] wakeupPipes = new int [2];
  93. static IntPtr ignore = Marshal.AllocHGlobal (1);
  94. MainLoop mainLoop;
  95. void IMainLoopDriver.Wakeup ()
  96. {
  97. write (wakeupPipes [1], ignore, (IntPtr) 1);
  98. }
  99. void IMainLoopDriver.Setup (MainLoop mainLoop) {
  100. this.mainLoop = mainLoop;
  101. pipe (wakeupPipes);
  102. AddWatch (wakeupPipes [0], Condition.PollIn, ml => {
  103. read (wakeupPipes [0], ignore, (IntPtr)1);
  104. return true;
  105. });
  106. }
  107. /// <summary>
  108. /// Removes an active watch from the mainloop.
  109. /// </summary>
  110. /// <remarks>
  111. /// The token parameter is the value returned from AddWatch
  112. /// </remarks>
  113. public void RemoveWatch (object token)
  114. {
  115. var watch = token as Watch;
  116. if (watch == null)
  117. return;
  118. descriptorWatchers.Remove (watch.File);
  119. }
  120. /// <summary>
  121. /// Watches a file descriptor for activity.
  122. /// </summary>
  123. /// <remarks>
  124. /// When the condition is met, the provided callback
  125. /// is invoked. If the callback returns false, the
  126. /// watch is automatically removed.
  127. ///
  128. /// The return value is a token that represents this watch, you can
  129. /// use this token to remove the watch by calling RemoveWatch.
  130. /// </remarks>
  131. public object AddWatch (int fileDescriptor, Condition condition, Func<MainLoop, bool> callback)
  132. {
  133. if (callback == null)
  134. throw new ArgumentNullException (nameof(callback));
  135. var watch = new Watch () { Condition = condition, Callback = callback, File = fileDescriptor };
  136. descriptorWatchers [fileDescriptor] = watch;
  137. poll_dirty = true;
  138. return watch;
  139. }
  140. void UpdatePollMap ()
  141. {
  142. if (!poll_dirty)
  143. return;
  144. poll_dirty = false;
  145. pollmap = new Pollfd [descriptorWatchers.Count];
  146. int i = 0;
  147. foreach (var fd in descriptorWatchers.Keys) {
  148. pollmap [i].fd = fd;
  149. pollmap [i].events = (short)descriptorWatchers [fd].Condition;
  150. i++;
  151. }
  152. }
  153. bool IMainLoopDriver.EventsPending (bool wait)
  154. {
  155. int pollTimeout = 0;
  156. int n;
  157. if (CkeckTimeout (wait, ref pollTimeout))
  158. return true;
  159. UpdatePollMap ();
  160. while (true) {
  161. n = poll (pollmap, (uint)pollmap.Length, 0);
  162. if (pollmap != null) {
  163. break;
  164. }
  165. if (mainLoop.idleHandlers.Count > 0 || CkeckTimeout (wait, ref pollTimeout)) {
  166. return true;
  167. }
  168. }
  169. int ic;
  170. lock (mainLoop.idleHandlers)
  171. ic = mainLoop.idleHandlers.Count;
  172. return n > 0 || mainLoop.timeouts.Count > 0 && ((mainLoop.timeouts.Keys [0] - DateTime.UtcNow.Ticks) < 0) || ic > 0;
  173. }
  174. bool CkeckTimeout (bool wait, ref int pollTimeout)
  175. {
  176. long now = DateTime.UtcNow.Ticks;
  177. if (mainLoop.timeouts.Count > 0) {
  178. pollTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  179. if (pollTimeout < 0)
  180. return true;
  181. } else
  182. pollTimeout = -1;
  183. if (!wait)
  184. pollTimeout = 0;
  185. return false;
  186. }
  187. void IMainLoopDriver.MainIteration ()
  188. {
  189. if (pollmap != null) {
  190. foreach (var p in pollmap) {
  191. Watch watch;
  192. if (p.revents == 0)
  193. continue;
  194. if (!descriptorWatchers.TryGetValue (p.fd, out watch))
  195. continue;
  196. if (!watch.Callback (this.mainLoop))
  197. descriptorWatchers.Remove (p.fd);
  198. }
  199. }
  200. }
  201. }
  202. /// <summary>
  203. /// Mainloop intended to be used with the .NET System.Console API, and can
  204. /// be used on Windows and Unix, it is cross platform but lacks things like
  205. /// file descriptor monitoring.
  206. /// </summary>
  207. class NetMainLoop : IMainLoopDriver {
  208. AutoResetEvent keyReady = new AutoResetEvent (false);
  209. AutoResetEvent waitForProbe = new AutoResetEvent (false);
  210. ConsoleKeyInfo? windowsKeyResult = null;
  211. public Action<ConsoleKeyInfo> WindowsKeyPressed;
  212. MainLoop mainLoop;
  213. public NetMainLoop ()
  214. {
  215. }
  216. void WindowsKeyReader ()
  217. {
  218. while (true) {
  219. waitForProbe.WaitOne ();
  220. windowsKeyResult = Console.ReadKey (true);
  221. keyReady.Set ();
  222. }
  223. }
  224. void IMainLoopDriver.Setup (MainLoop mainLoop)
  225. {
  226. this.mainLoop = mainLoop;
  227. Thread readThread = new Thread (WindowsKeyReader);
  228. readThread.Start ();
  229. }
  230. void IMainLoopDriver.Wakeup ()
  231. {
  232. }
  233. bool IMainLoopDriver.EventsPending (bool wait)
  234. {
  235. long now = DateTime.UtcNow.Ticks;
  236. int waitTimeout;
  237. if (mainLoop.timeouts.Count > 0) {
  238. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  239. if (waitTimeout < 0)
  240. return true;
  241. } else
  242. waitTimeout = -1;
  243. if (!wait)
  244. waitTimeout = 0;
  245. windowsKeyResult = null;
  246. waitForProbe.Set ();
  247. keyReady.WaitOne (waitTimeout);
  248. return windowsKeyResult.HasValue;
  249. }
  250. void IMainLoopDriver.MainIteration ()
  251. {
  252. if (windowsKeyResult.HasValue) {
  253. if (WindowsKeyPressed!= null)
  254. WindowsKeyPressed (windowsKeyResult.Value);
  255. windowsKeyResult = null;
  256. }
  257. }
  258. }
  259. }