UnixMainLoop.cs 5.0 KB

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