UnixMainLoop.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. //
  2. // mainloop.cs: Linux/Curses MainLoop implementation.
  3. //
  4. using System.Runtime.InteropServices;
  5. namespace Terminal.Gui;
  6. /// <summary>Unix main loop, suitable for using on Posix systems</summary>
  7. /// <remarks>
  8. /// In addition to the general functions of the MainLoop, the Unix version can watch file descriptors using the
  9. /// AddWatch methods.
  10. /// </remarks>
  11. internal class UnixMainLoop : IMainLoopDriver
  12. {
  13. /// <summary>Condition on which to wake up from file descriptor activity. These match the Linux/BSD poll definitions.</summary>
  14. [Flags]
  15. public enum Condition : short
  16. {
  17. /// <summary>There is data to read</summary>
  18. PollIn = 1,
  19. /// <summary>Writing to the specified descriptor will not block</summary>
  20. PollOut = 4,
  21. /// <summary>There is urgent data to read</summary>
  22. PollPri = 2,
  23. /// <summary>Error condition on output</summary>
  24. PollErr = 8,
  25. /// <summary>Hang-up on output</summary>
  26. PollHup = 16,
  27. /// <summary>File descriptor is not open.</summary>
  28. PollNval = 32
  29. }
  30. public const int KEY_RESIZE = unchecked ((int)0xffffffffffffffff);
  31. private static readonly nint _ignore = Marshal.AllocHGlobal (1);
  32. private readonly CursesDriver _cursesDriver;
  33. private readonly Dictionary<int, Watch> _descriptorWatchers = new ();
  34. private readonly int [] _wakeUpPipes = new int [2];
  35. private MainLoop _mainLoop;
  36. private bool _pollDirty = true;
  37. private Pollfd [] _pollMap;
  38. private bool _winChanged;
  39. private readonly ManualResetEventSlim _eventReady = new (false);
  40. internal readonly ManualResetEventSlim _waitForInput = new (false);
  41. private readonly CancellationTokenSource _eventReadyTokenSource = new ();
  42. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  43. public UnixMainLoop (ConsoleDriver consoleDriver = null)
  44. {
  45. // UnixDriver doesn't use the consoleDriver parameter, but the WindowsDriver does.
  46. _cursesDriver = (CursesDriver)Application.Driver;
  47. }
  48. void IMainLoopDriver.Wakeup ()
  49. {
  50. if (!ConsoleDriver.RunningUnitTests)
  51. {
  52. write (_wakeUpPipes [1], _ignore, 1);
  53. }
  54. }
  55. void IMainLoopDriver.Setup (MainLoop mainLoop)
  56. {
  57. _mainLoop = mainLoop;
  58. if (ConsoleDriver.RunningUnitTests)
  59. {
  60. return;
  61. }
  62. try
  63. {
  64. pipe (_wakeUpPipes);
  65. AddWatch (
  66. _wakeUpPipes [0],
  67. Condition.PollIn,
  68. ml =>
  69. {
  70. read (_wakeUpPipes [0], _ignore, 1);
  71. return true;
  72. }
  73. );
  74. }
  75. catch (DllNotFoundException e)
  76. {
  77. throw new NotSupportedException ("libc not found", e);
  78. }
  79. Task.Run (CursesInputHandler, _inputHandlerTokenSource.Token);
  80. }
  81. internal bool _forceRead;
  82. internal bool _suspendRead;
  83. private int n;
  84. private void CursesInputHandler ()
  85. {
  86. while (_mainLoop is { })
  87. {
  88. try
  89. {
  90. UpdatePollMap ();
  91. if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead)
  92. {
  93. _waitForInput.Wait (_inputHandlerTokenSource.Token);
  94. }
  95. }
  96. catch (OperationCanceledException)
  97. {
  98. return;
  99. }
  100. finally
  101. {
  102. if (!_inputHandlerTokenSource.IsCancellationRequested)
  103. {
  104. _waitForInput.Reset ();
  105. }
  106. }
  107. while (!_inputHandlerTokenSource.IsCancellationRequested)
  108. {
  109. if (!_suspendRead)
  110. {
  111. n = poll (_pollMap, (uint)_pollMap.Length, 0);
  112. if (n == KEY_RESIZE)
  113. {
  114. _winChanged = true;
  115. break;
  116. }
  117. if (n > 0)
  118. {
  119. break;
  120. }
  121. }
  122. if (!_forceRead)
  123. {
  124. Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token);
  125. }
  126. }
  127. _eventReady.Set ();
  128. }
  129. }
  130. bool IMainLoopDriver.EventsPending ()
  131. {
  132. _waitForInput.Set ();
  133. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout))
  134. {
  135. return true;
  136. }
  137. try
  138. {
  139. if (!_eventReadyTokenSource.IsCancellationRequested)
  140. {
  141. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  142. }
  143. }
  144. catch (OperationCanceledException)
  145. {
  146. return true;
  147. }
  148. finally
  149. {
  150. _eventReady.Reset ();
  151. }
  152. if (!_eventReadyTokenSource.IsCancellationRequested)
  153. {
  154. return n > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  155. }
  156. return true;
  157. }
  158. void IMainLoopDriver.Iteration ()
  159. {
  160. if (_winChanged)
  161. {
  162. _winChanged = false;
  163. _cursesDriver.ProcessInput ();
  164. // This is needed on the mac. See https://github.com/gui-cs/Terminal.Gui/pull/2922#discussion_r1365992426
  165. _cursesDriver.ProcessWinChange ();
  166. }
  167. n = 0;
  168. if (_pollMap is null)
  169. {
  170. return;
  171. }
  172. foreach (Pollfd p in _pollMap)
  173. {
  174. Watch watch;
  175. if (p.revents == 0)
  176. {
  177. continue;
  178. }
  179. if (!_descriptorWatchers.TryGetValue (p.fd, out watch))
  180. {
  181. continue;
  182. }
  183. if (!watch.Callback (_mainLoop))
  184. {
  185. _descriptorWatchers.Remove (p.fd);
  186. }
  187. }
  188. }
  189. void IMainLoopDriver.TearDown ()
  190. {
  191. _descriptorWatchers?.Clear ();
  192. _inputHandlerTokenSource?.Cancel ();
  193. _inputHandlerTokenSource?.Dispose ();
  194. _waitForInput?.Dispose ();
  195. _eventReadyTokenSource?.Cancel ();
  196. _eventReadyTokenSource?.Dispose ();
  197. _eventReady?.Dispose ();
  198. _mainLoop = null;
  199. }
  200. /// <summary>Watches a file descriptor for activity.</summary>
  201. /// <remarks>
  202. /// When the condition is met, the provided callback is invoked. If the callback returns false, the watch is
  203. /// automatically removed. The return value is a token that represents this watch, you can use this token to remove the
  204. /// watch by calling RemoveWatch.
  205. /// </remarks>
  206. internal object AddWatch (int fileDescriptor, Condition condition, Func<MainLoop, bool> callback)
  207. {
  208. if (callback is null)
  209. {
  210. throw new ArgumentNullException (nameof (callback));
  211. }
  212. var watch = new Watch { Condition = condition, Callback = callback, File = fileDescriptor };
  213. _descriptorWatchers [fileDescriptor] = watch;
  214. _pollDirty = true;
  215. return watch;
  216. }
  217. /// <summary>Removes an active watch from the mainloop.</summary>
  218. /// <remarks>The token parameter is the value returned from AddWatch</remarks>
  219. internal void RemoveWatch (object token)
  220. {
  221. if (!ConsoleDriver.RunningUnitTests)
  222. {
  223. if (token is not Watch watch)
  224. {
  225. return;
  226. }
  227. _descriptorWatchers.Remove (watch.File);
  228. }
  229. }
  230. [DllImport ("libc")]
  231. private static extern int pipe ([In] [Out] int [] pipes);
  232. [DllImport ("libc")]
  233. private static extern int poll ([In] [Out] Pollfd [] ufds, uint nfds, int timeout);
  234. [DllImport ("libc")]
  235. private static extern int read (int fd, nint buf, nint n);
  236. private void UpdatePollMap ()
  237. {
  238. if (!_pollDirty)
  239. {
  240. return;
  241. }
  242. _pollDirty = false;
  243. _pollMap = new Pollfd [_descriptorWatchers.Count];
  244. var i = 0;
  245. foreach (int fd in _descriptorWatchers.Keys)
  246. {
  247. _pollMap [i].fd = fd;
  248. _pollMap [i].events = (short)_descriptorWatchers [fd].Condition;
  249. i++;
  250. }
  251. }
  252. [DllImport ("libc")]
  253. private static extern int write (int fd, nint buf, nint n);
  254. [StructLayout (LayoutKind.Sequential)]
  255. private struct Pollfd
  256. {
  257. public int fd;
  258. public short events;
  259. public readonly short revents;
  260. }
  261. private class Watch
  262. {
  263. public Func<MainLoop, bool> Callback;
  264. public Condition Condition;
  265. public int File;
  266. }
  267. }