UnixMainLoop.cs 5.1 KB

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