UnixMainLoop.cs 5.3 KB

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