UnixMainLoop.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. MainLoop mainLoop;
  75. bool winChanged;
  76. public Action WinChanged;
  77. void IMainLoopDriver.Wakeup ()
  78. {
  79. write (wakeupPipes [1], ignore, (IntPtr)1);
  80. }
  81. void IMainLoopDriver.Setup (MainLoop mainLoop)
  82. {
  83. this.mainLoop = mainLoop;
  84. pipe (wakeupPipes);
  85. AddWatch (wakeupPipes [0], Condition.PollIn, ml => {
  86. read (wakeupPipes [0], ignore, (IntPtr)1);
  87. return true;
  88. });
  89. }
  90. /// <summary>
  91. /// Removes an active watch from the mainloop.
  92. /// </summary>
  93. /// <remarks>
  94. /// The token parameter is the value returned from AddWatch
  95. /// </remarks>
  96. public void RemoveWatch (object token)
  97. {
  98. var watch = token as Watch;
  99. if (watch == null)
  100. return;
  101. descriptorWatchers.Remove (watch.File);
  102. }
  103. /// <summary>
  104. /// Watches a file descriptor for activity.
  105. /// </summary>
  106. /// <remarks>
  107. /// When the condition is met, the provided callback
  108. /// is invoked. If the callback returns false, the
  109. /// watch is automatically removed.
  110. ///
  111. /// The return value is a token that represents this watch, you can
  112. /// use this token to remove the watch by calling RemoveWatch.
  113. /// </remarks>
  114. public object AddWatch (int fileDescriptor, Condition condition, Func<MainLoop, bool> callback)
  115. {
  116. if (callback == null)
  117. throw new ArgumentNullException (nameof (callback));
  118. var watch = new Watch () { Condition = condition, Callback = callback, File = fileDescriptor };
  119. descriptorWatchers [fileDescriptor] = watch;
  120. poll_dirty = true;
  121. return watch;
  122. }
  123. void UpdatePollMap ()
  124. {
  125. if (!poll_dirty)
  126. return;
  127. poll_dirty = false;
  128. pollmap = new Pollfd [descriptorWatchers.Count];
  129. int i = 0;
  130. foreach (var fd in descriptorWatchers.Keys) {
  131. pollmap [i].fd = fd;
  132. pollmap [i].events = (short)descriptorWatchers [fd].Condition;
  133. i++;
  134. }
  135. }
  136. bool IMainLoopDriver.EventsPending (bool wait)
  137. {
  138. UpdatePollMap ();
  139. bool checkTimersResult = CheckTimers (wait, out var pollTimeout);
  140. var n = poll (pollmap, (uint)pollmap.Length, pollTimeout);
  141. if (n == KEY_RESIZE) {
  142. winChanged = true;
  143. }
  144. return checkTimersResult || n >= KEY_RESIZE;
  145. }
  146. bool CheckTimers (bool wait, out int pollTimeout)
  147. {
  148. long now = DateTime.UtcNow.Ticks;
  149. if (mainLoop.timeouts.Count > 0) {
  150. pollTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  151. if (pollTimeout < 0) {
  152. // This avoids 'poll' waiting infinitely if 'pollTimeout < 0' until some action is detected
  153. // This can occur after IMainLoopDriver.Wakeup is executed where the pollTimeout is less than 0
  154. // and no event occurred in elapsed time when the 'poll' is start running again.
  155. /*
  156. The 'poll' function in the C standard library uses a signed integer as the timeout argument, where:
  157. - A positive value specifies a timeout in milliseconds.
  158. - A value of 0 means the poll function will return immediately, checking for events and not waiting.
  159. - A value of -1 means the poll function will wait indefinitely until an event occurs or an error occurs.
  160. - A negative value other than -1 typically indicates an error.
  161. */
  162. pollTimeout = 0;
  163. return true;
  164. }
  165. } else
  166. pollTimeout = -1;
  167. if (!wait)
  168. pollTimeout = 0;
  169. int ic;
  170. lock (mainLoop.idleHandlers) {
  171. ic = mainLoop.idleHandlers.Count;
  172. }
  173. return ic > 0;
  174. }
  175. void IMainLoopDriver.MainIteration ()
  176. {
  177. if (winChanged) {
  178. winChanged = false;
  179. WinChanged?.Invoke ();
  180. }
  181. if (pollmap != null) {
  182. foreach (var p in pollmap) {
  183. Watch watch;
  184. if (p.revents == 0)
  185. continue;
  186. if (!descriptorWatchers.TryGetValue (p.fd, out watch))
  187. continue;
  188. if (!watch.Callback (this.mainLoop))
  189. descriptorWatchers.Remove (p.fd);
  190. }
  191. }
  192. }
  193. }
  194. }