UnixMainLoop.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. public UnixMainLoop (ConsoleDriver consoleDriver = null)
  40. {
  41. // UnixDriver doesn't use the consoleDriver parameter, but the WindowsDriver does.
  42. _cursesDriver = (CursesDriver)Application.Driver;
  43. }
  44. void IMainLoopDriver.Wakeup ()
  45. {
  46. if (!ConsoleDriver.RunningUnitTests)
  47. {
  48. write (_wakeUpPipes [1], _ignore, 1);
  49. }
  50. }
  51. void IMainLoopDriver.Setup (MainLoop mainLoop)
  52. {
  53. _mainLoop = mainLoop;
  54. if (ConsoleDriver.RunningUnitTests)
  55. {
  56. return;
  57. }
  58. try
  59. {
  60. pipe (_wakeUpPipes);
  61. AddWatch (
  62. _wakeUpPipes [0],
  63. Condition.PollIn,
  64. ml =>
  65. {
  66. read (_wakeUpPipes [0], _ignore, 1);
  67. return true;
  68. }
  69. );
  70. }
  71. catch (DllNotFoundException e)
  72. {
  73. throw new NotSupportedException ("libc not found", e);
  74. }
  75. }
  76. bool IMainLoopDriver.EventsPending ()
  77. {
  78. UpdatePollMap ();
  79. bool checkTimersResult = _mainLoop.CheckTimersAndIdleHandlers (out int pollTimeout);
  80. int n = poll (_pollMap, (uint)_pollMap.Length, pollTimeout);
  81. if (n == KEY_RESIZE)
  82. {
  83. _winChanged = true;
  84. }
  85. return checkTimersResult || n >= KEY_RESIZE;
  86. }
  87. void IMainLoopDriver.Iteration ()
  88. {
  89. if (_winChanged)
  90. {
  91. _winChanged = false;
  92. _cursesDriver.ProcessInput ();
  93. // This is needed on the mac. See https://github.com/gui-cs/Terminal.Gui/pull/2922#discussion_r1365992426
  94. _cursesDriver.ProcessWinChange ();
  95. }
  96. if (_pollMap is null)
  97. {
  98. return;
  99. }
  100. foreach (Pollfd p in _pollMap)
  101. {
  102. Watch watch;
  103. if (p.revents == 0)
  104. {
  105. continue;
  106. }
  107. if (!_descriptorWatchers.TryGetValue (p.fd, out watch))
  108. {
  109. continue;
  110. }
  111. if (!watch.Callback (_mainLoop))
  112. {
  113. _descriptorWatchers.Remove (p.fd);
  114. }
  115. }
  116. }
  117. void IMainLoopDriver.TearDown ()
  118. {
  119. _descriptorWatchers?.Clear ();
  120. _mainLoop = null;
  121. }
  122. /// <summary>Watches a file descriptor for activity.</summary>
  123. /// <remarks>
  124. /// When the condition is met, the provided callback is invoked. If the callback returns false, the watch is
  125. /// automatically removed. The return value is a token that represents this watch, you can use this token to remove the
  126. /// watch by calling RemoveWatch.
  127. /// </remarks>
  128. internal object AddWatch (int fileDescriptor, Condition condition, Func<MainLoop, bool> callback)
  129. {
  130. if (callback is null)
  131. {
  132. throw new ArgumentNullException (nameof (callback));
  133. }
  134. var watch = new Watch { Condition = condition, Callback = callback, File = fileDescriptor };
  135. _descriptorWatchers [fileDescriptor] = watch;
  136. _pollDirty = true;
  137. return watch;
  138. }
  139. /// <summary>Removes an active watch from the mainloop.</summary>
  140. /// <remarks>The token parameter is the value returned from AddWatch</remarks>
  141. internal void RemoveWatch (object token)
  142. {
  143. if (!ConsoleDriver.RunningUnitTests)
  144. {
  145. if (token is not Watch watch)
  146. {
  147. return;
  148. }
  149. _descriptorWatchers.Remove (watch.File);
  150. }
  151. }
  152. [DllImport ("libc")]
  153. private static extern int pipe ([In] [Out] int [] pipes);
  154. [DllImport ("libc")]
  155. private static extern int poll ([In] [Out] Pollfd [] ufds, uint nfds, int timeout);
  156. [DllImport ("libc")]
  157. private static extern int read (int fd, nint buf, nint n);
  158. private void UpdatePollMap ()
  159. {
  160. if (!_pollDirty)
  161. {
  162. return;
  163. }
  164. _pollDirty = false;
  165. _pollMap = new Pollfd [_descriptorWatchers.Count];
  166. var i = 0;
  167. foreach (int fd in _descriptorWatchers.Keys)
  168. {
  169. _pollMap [i].fd = fd;
  170. _pollMap [i].events = (short)_descriptorWatchers [fd].Condition;
  171. i++;
  172. }
  173. }
  174. [DllImport ("libc")]
  175. private static extern int write (int fd, nint buf, nint n);
  176. [StructLayout (LayoutKind.Sequential)]
  177. private struct Pollfd
  178. {
  179. public int fd;
  180. public short events;
  181. public readonly short revents;
  182. }
  183. private class Watch
  184. {
  185. public Func<MainLoop, bool> Callback;
  186. public Condition Condition;
  187. public int File;
  188. }
  189. }