UnixMainLoop.cs 6.7 KB

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