UnixMainLoop.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. //
  2. // mainloop.cs: Simple managed mainloop implementation.
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. // Copyright (C) 2011 Novell (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Runtime.InteropServices;
  31. namespace Terminal.Gui {
  32. /// <summary>
  33. /// Unix main loop, suitable for using on Posix systems
  34. /// </summary>
  35. /// <remarks>
  36. /// In addition to the general functions of the mainloop, the Unix version
  37. /// can watch file descriptors using the AddWatch methods.
  38. /// </remarks>
  39. internal class UnixMainLoop : IMainLoopDriver {
  40. public UnixMainLoop (ConsoleDriver consoleDriver = null)
  41. {
  42. // UnixDriver doesn't use the consoleDriver parameter, but the WindowsDriver does.
  43. }
  44. public const int KEY_RESIZE = unchecked((int)0xffffffffffffffff);
  45. [StructLayout (LayoutKind.Sequential)]
  46. struct Pollfd {
  47. public int fd;
  48. public short events, revents;
  49. }
  50. /// <summary>
  51. /// Condition on which to wake up from file descriptor activity. These match the Linux/BSD poll definitions.
  52. /// </summary>
  53. [Flags]
  54. public enum Condition : short {
  55. /// <summary>
  56. /// There is data to read
  57. /// </summary>
  58. PollIn = 1,
  59. /// <summary>
  60. /// Writing to the specified descriptor will not block
  61. /// </summary>
  62. PollOut = 4,
  63. /// <summary>
  64. /// There is urgent data to read
  65. /// </summary>
  66. PollPri = 2,
  67. /// <summary>
  68. /// Error condition on output
  69. /// </summary>
  70. PollErr = 8,
  71. /// <summary>
  72. /// Hang-up on output
  73. /// </summary>
  74. PollHup = 16,
  75. /// <summary>
  76. /// File descriptor is not open.
  77. /// </summary>
  78. PollNval = 32
  79. }
  80. class Watch {
  81. public int File;
  82. public Condition Condition;
  83. public Func<MainLoop, bool> Callback;
  84. }
  85. Dictionary<int, Watch> descriptorWatchers = new Dictionary<int, Watch> ();
  86. [DllImport ("libc")]
  87. extern static int poll ([In, Out] Pollfd [] ufds, uint nfds, int timeout);
  88. [DllImport ("libc")]
  89. extern static int pipe ([In, Out] int [] pipes);
  90. [DllImport ("libc")]
  91. extern static int read (int fd, IntPtr buf, IntPtr n);
  92. [DllImport ("libc")]
  93. extern static int write (int fd, IntPtr buf, IntPtr n);
  94. Pollfd [] pollmap;
  95. bool poll_dirty = true;
  96. int [] wakeupPipes = new int [2];
  97. static IntPtr ignore = Marshal.AllocHGlobal (1);
  98. MainLoop mainLoop;
  99. bool winChanged;
  100. public Action WinChanged;
  101. void IMainLoopDriver.Wakeup ()
  102. {
  103. write (wakeupPipes [1], ignore, (IntPtr)1);
  104. }
  105. void IMainLoopDriver.Setup (MainLoop mainLoop)
  106. {
  107. this.mainLoop = mainLoop;
  108. pipe (wakeupPipes);
  109. AddWatch (wakeupPipes [0], Condition.PollIn, ml => {
  110. read (wakeupPipes [0], ignore, (IntPtr)1);
  111. return true;
  112. });
  113. }
  114. /// <summary>
  115. /// Removes an active watch from the mainloop.
  116. /// </summary>
  117. /// <remarks>
  118. /// The token parameter is the value returned from AddWatch
  119. /// </remarks>
  120. public void RemoveWatch (object token)
  121. {
  122. var watch = token as Watch;
  123. if (watch == null)
  124. return;
  125. descriptorWatchers.Remove (watch.File);
  126. }
  127. /// <summary>
  128. /// Watches a file descriptor for activity.
  129. /// </summary>
  130. /// <remarks>
  131. /// When the condition is met, the provided callback
  132. /// is invoked. If the callback returns false, the
  133. /// watch is automatically removed.
  134. ///
  135. /// The return value is a token that represents this watch, you can
  136. /// use this token to remove the watch by calling RemoveWatch.
  137. /// </remarks>
  138. public object AddWatch (int fileDescriptor, Condition condition, Func<MainLoop, bool> callback)
  139. {
  140. if (callback == null)
  141. throw new ArgumentNullException (nameof (callback));
  142. var watch = new Watch () { Condition = condition, Callback = callback, File = fileDescriptor };
  143. descriptorWatchers [fileDescriptor] = watch;
  144. poll_dirty = true;
  145. return watch;
  146. }
  147. void UpdatePollMap ()
  148. {
  149. if (!poll_dirty)
  150. return;
  151. poll_dirty = false;
  152. pollmap = new Pollfd [descriptorWatchers.Count];
  153. int i = 0;
  154. foreach (var fd in descriptorWatchers.Keys) {
  155. pollmap [i].fd = fd;
  156. pollmap [i].events = (short)descriptorWatchers [fd].Condition;
  157. i++;
  158. }
  159. }
  160. bool IMainLoopDriver.EventsPending (bool wait)
  161. {
  162. UpdatePollMap ();
  163. bool checkTimersResult = CheckTimers (wait, out var pollTimeout);
  164. var n = poll (pollmap, (uint)pollmap.Length, pollTimeout);
  165. if (n == KEY_RESIZE) {
  166. winChanged = true;
  167. }
  168. return checkTimersResult || n >= KEY_RESIZE;
  169. }
  170. bool CheckTimers (bool wait, out int pollTimeout)
  171. {
  172. long now = DateTime.UtcNow.Ticks;
  173. if (mainLoop.timeouts.Count > 0) {
  174. pollTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  175. if (pollTimeout < 0) {
  176. return true;
  177. }
  178. } else
  179. pollTimeout = -1;
  180. if (!wait)
  181. pollTimeout = 0;
  182. int ic;
  183. lock (mainLoop.idleHandlers) {
  184. ic = mainLoop.idleHandlers.Count;
  185. }
  186. return ic > 0;
  187. }
  188. void IMainLoopDriver.MainIteration ()
  189. {
  190. if (winChanged) {
  191. winChanged = false;
  192. WinChanged?.Invoke ();
  193. }
  194. if (pollmap != null) {
  195. foreach (var p in pollmap) {
  196. Watch watch;
  197. if (p.revents == 0)
  198. continue;
  199. if (!descriptorWatchers.TryGetValue (p.fd, out watch))
  200. continue;
  201. if (!watch.Callback (this.mainLoop))
  202. descriptorWatchers.Remove (p.fd);
  203. }
  204. }
  205. }
  206. }
  207. }