UnixMainLoop.cs 5.4 KB

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