UnixMainLoop.cs 6.6 KB

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