UnixMainLoop.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. namespace Terminal.Gui {
  32. /// <summary>
  33. /// Unix main loop, suitable for using on Posix systems
  34. /// </summary>
  35. /// <remarks>
  36. /// In addition to the general functions of the mainloop, the Unix version
  37. /// can watch file descriptors using the AddWatch methods.
  38. /// </remarks>
  39. internal class UnixMainLoop : IMainLoopDriver {
  40. [StructLayout (LayoutKind.Sequential)]
  41. struct Pollfd {
  42. public int fd;
  43. public short events, revents;
  44. }
  45. /// <summary>
  46. /// Condition on which to wake up from file descriptor activity. These match the Linux/BSD poll definitions.
  47. /// </summary>
  48. [Flags]
  49. public enum Condition : short {
  50. /// <summary>
  51. /// There is data to read
  52. /// </summary>
  53. PollIn = 1,
  54. /// <summary>
  55. /// Writing to the specified descriptor will not block
  56. /// </summary>
  57. PollOut = 4,
  58. /// <summary>
  59. /// There is urgent data to read
  60. /// </summary>
  61. PollPri = 2,
  62. /// <summary>
  63. /// Error condition on output
  64. /// </summary>
  65. PollErr = 8,
  66. /// <summary>
  67. /// Hang-up on output
  68. /// </summary>
  69. PollHup = 16,
  70. /// <summary>
  71. /// File descriptor is not open.
  72. /// </summary>
  73. PollNval = 32
  74. }
  75. class Watch {
  76. public int File;
  77. public Condition Condition;
  78. public Func<MainLoop, bool> Callback;
  79. }
  80. Dictionary<int, Watch> descriptorWatchers = new Dictionary<int, Watch> ();
  81. [DllImport ("libc")]
  82. extern static int poll ([In, Out]Pollfd [] ufds, uint nfds, int timeout);
  83. [DllImport ("libc")]
  84. extern static int pipe ([In, Out]int [] pipes);
  85. [DllImport ("libc")]
  86. extern static int read (int fd, IntPtr buf, IntPtr n);
  87. [DllImport ("libc")]
  88. extern static int write (int fd, IntPtr buf, IntPtr n);
  89. Pollfd [] pollmap;
  90. bool poll_dirty = true;
  91. int [] wakeupPipes = new int [2];
  92. static IntPtr ignore = Marshal.AllocHGlobal (1);
  93. MainLoop mainLoop;
  94. void IMainLoopDriver.Wakeup ()
  95. {
  96. write (wakeupPipes [1], ignore, (IntPtr) 1);
  97. }
  98. void IMainLoopDriver.Setup (MainLoop mainLoop) {
  99. this.mainLoop = mainLoop;
  100. pipe (wakeupPipes);
  101. AddWatch (wakeupPipes [0], Condition.PollIn, ml => {
  102. read (wakeupPipes [0], ignore, (IntPtr)1);
  103. return true;
  104. });
  105. }
  106. /// <summary>
  107. /// Removes an active watch from the mainloop.
  108. /// </summary>
  109. /// <remarks>
  110. /// The token parameter is the value returned from AddWatch
  111. /// </remarks>
  112. public void RemoveWatch (object token)
  113. {
  114. var watch = token as Watch;
  115. if (watch == null)
  116. return;
  117. descriptorWatchers.Remove (watch.File);
  118. }
  119. /// <summary>
  120. /// Watches a file descriptor for activity.
  121. /// </summary>
  122. /// <remarks>
  123. /// When the condition is met, the provided callback
  124. /// is invoked. If the callback returns false, the
  125. /// watch is automatically removed.
  126. ///
  127. /// The return value is a token that represents this watch, you can
  128. /// use this token to remove the watch by calling RemoveWatch.
  129. /// </remarks>
  130. public object AddWatch (int fileDescriptor, Condition condition, Func<MainLoop, bool> callback)
  131. {
  132. if (callback == null)
  133. throw new ArgumentNullException (nameof(callback));
  134. var watch = new Watch () { Condition = condition, Callback = callback, File = fileDescriptor };
  135. descriptorWatchers [fileDescriptor] = watch;
  136. poll_dirty = true;
  137. return watch;
  138. }
  139. void UpdatePollMap ()
  140. {
  141. if (!poll_dirty)
  142. return;
  143. poll_dirty = false;
  144. pollmap = new Pollfd [descriptorWatchers.Count];
  145. int i = 0;
  146. foreach (var fd in descriptorWatchers.Keys) {
  147. pollmap [i].fd = fd;
  148. pollmap [i].events = (short)descriptorWatchers [fd].Condition;
  149. i++;
  150. }
  151. }
  152. bool IMainLoopDriver.EventsPending (bool wait)
  153. {
  154. long now = DateTime.UtcNow.Ticks;
  155. int pollTimeout, n;
  156. if (mainLoop.timeouts.Count > 0) {
  157. pollTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  158. if (pollTimeout < 0)
  159. return true;
  160. } else
  161. pollTimeout = -1;
  162. if (!wait)
  163. pollTimeout = 0;
  164. UpdatePollMap ();
  165. while (true) {
  166. if (wait && pollTimeout == -1) {
  167. pollTimeout = 0;
  168. }
  169. n = poll (pollmap, (uint)pollmap.Length, pollTimeout);
  170. if (pollmap != null) {
  171. break;
  172. }
  173. if (mainLoop.timeouts.Count > 0 || mainLoop.idleHandlers.Count > 0) {
  174. return true;
  175. }
  176. }
  177. int ic;
  178. lock (mainLoop.idleHandlers)
  179. ic = mainLoop.idleHandlers.Count;
  180. return n > 0 || mainLoop.timeouts.Count > 0 && ((mainLoop.timeouts.Keys [0] - DateTime.UtcNow.Ticks) < 0) || ic > 0;
  181. }
  182. void IMainLoopDriver.MainIteration ()
  183. {
  184. if (pollmap != null) {
  185. foreach (var p in pollmap) {
  186. Watch watch;
  187. if (p.revents == 0)
  188. continue;
  189. if (!descriptorWatchers.TryGetValue (p.fd, out watch))
  190. continue;
  191. if (!watch.Callback (this.mainLoop))
  192. descriptorWatchers.Remove (p.fd);
  193. }
  194. }
  195. }
  196. }
  197. }