UnixMainLoop.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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 const int KEY_RESIZE = unchecked((int)0xffffffffffffffff);
  41. [StructLayout (LayoutKind.Sequential)]
  42. struct Pollfd {
  43. public int fd;
  44. public short events, revents;
  45. }
  46. /// <summary>
  47. /// Condition on which to wake up from file descriptor activity. These match the Linux/BSD poll definitions.
  48. /// </summary>
  49. [Flags]
  50. public enum Condition : short {
  51. /// <summary>
  52. /// There is data to read
  53. /// </summary>
  54. PollIn = 1,
  55. /// <summary>
  56. /// Writing to the specified descriptor will not block
  57. /// </summary>
  58. PollOut = 4,
  59. /// <summary>
  60. /// There is urgent data to read
  61. /// </summary>
  62. PollPri = 2,
  63. /// <summary>
  64. /// Error condition on output
  65. /// </summary>
  66. PollErr = 8,
  67. /// <summary>
  68. /// Hang-up on output
  69. /// </summary>
  70. PollHup = 16,
  71. /// <summary>
  72. /// File descriptor is not open.
  73. /// </summary>
  74. PollNval = 32
  75. }
  76. class Watch {
  77. public int File;
  78. public Condition Condition;
  79. public Func<MainLoop, bool> Callback;
  80. }
  81. Dictionary<int, Watch> descriptorWatchers = new Dictionary<int, Watch> ();
  82. [DllImport ("libc")]
  83. extern static int poll ([In, Out] Pollfd [] ufds, uint nfds, int timeout);
  84. [DllImport ("libc")]
  85. extern static int pipe ([In, Out] int [] pipes);
  86. [DllImport ("libc")]
  87. extern static int read (int fd, IntPtr buf, IntPtr n);
  88. [DllImport ("libc")]
  89. extern static int write (int fd, IntPtr buf, IntPtr n);
  90. Pollfd [] pollmap;
  91. bool poll_dirty = true;
  92. int [] wakeupPipes = new int [2];
  93. static IntPtr ignore = Marshal.AllocHGlobal (1);
  94. MainLoop mainLoop;
  95. bool winChanged;
  96. public Action WinChanged;
  97. void IMainLoopDriver.Wakeup ()
  98. {
  99. write (wakeupPipes [1], ignore, (IntPtr)1);
  100. }
  101. void IMainLoopDriver.Setup (MainLoop mainLoop)
  102. {
  103. this.mainLoop = mainLoop;
  104. pipe (wakeupPipes);
  105. AddWatch (wakeupPipes [0], Condition.PollIn, ml => {
  106. read (wakeupPipes [0], ignore, (IntPtr)1);
  107. return true;
  108. });
  109. }
  110. /// <summary>
  111. /// Removes an active watch from the mainloop.
  112. /// </summary>
  113. /// <remarks>
  114. /// The token parameter is the value returned from AddWatch
  115. /// </remarks>
  116. public void RemoveWatch (object token)
  117. {
  118. var watch = token as Watch;
  119. if (watch == null)
  120. return;
  121. descriptorWatchers.Remove (watch.File);
  122. }
  123. /// <summary>
  124. /// Watches a file descriptor for activity.
  125. /// </summary>
  126. /// <remarks>
  127. /// When the condition is met, the provided callback
  128. /// is invoked. If the callback returns false, the
  129. /// watch is automatically removed.
  130. ///
  131. /// The return value is a token that represents this watch, you can
  132. /// use this token to remove the watch by calling RemoveWatch.
  133. /// </remarks>
  134. public object AddWatch (int fileDescriptor, Condition condition, Func<MainLoop, bool> callback)
  135. {
  136. if (callback == null)
  137. throw new ArgumentNullException (nameof (callback));
  138. var watch = new Watch () { Condition = condition, Callback = callback, File = fileDescriptor };
  139. descriptorWatchers [fileDescriptor] = watch;
  140. poll_dirty = true;
  141. return watch;
  142. }
  143. void UpdatePollMap ()
  144. {
  145. if (!poll_dirty)
  146. return;
  147. poll_dirty = false;
  148. pollmap = new Pollfd [descriptorWatchers.Count];
  149. int i = 0;
  150. foreach (var fd in descriptorWatchers.Keys) {
  151. pollmap [i].fd = fd;
  152. pollmap [i].events = (short)descriptorWatchers [fd].Condition;
  153. i++;
  154. }
  155. }
  156. bool IMainLoopDriver.EventsPending (bool wait)
  157. {
  158. UpdatePollMap ();
  159. bool checkTimersResult = CheckTimers (wait, out var pollTimeout);
  160. var n = poll (pollmap, (uint)pollmap.Length, pollTimeout);
  161. if (n == KEY_RESIZE) {
  162. winChanged = true;
  163. }
  164. return checkTimersResult || n >= KEY_RESIZE;
  165. }
  166. bool CheckTimers (bool wait, out int pollTimeout)
  167. {
  168. long now = DateTime.UtcNow.Ticks;
  169. if (mainLoop.timeouts.Count > 0) {
  170. pollTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  171. if (pollTimeout < 0) {
  172. return true;
  173. }
  174. } else
  175. pollTimeout = -1;
  176. if (!wait)
  177. pollTimeout = 0;
  178. int ic;
  179. lock (mainLoop.idleHandlers) {
  180. ic = mainLoop.idleHandlers.Count;
  181. }
  182. return ic > 0;
  183. }
  184. void IMainLoopDriver.MainIteration ()
  185. {
  186. if (winChanged) {
  187. winChanged = false;
  188. WinChanged?.Invoke ();
  189. }
  190. if (pollmap != null) {
  191. foreach (var p in pollmap) {
  192. Watch watch;
  193. if (p.revents == 0)
  194. continue;
  195. if (!descriptorWatchers.TryGetValue (p.fd, out watch))
  196. continue;
  197. if (!watch.Callback (this.mainLoop))
  198. descriptorWatchers.Remove (p.fd);
  199. }
  200. }
  201. }
  202. }
  203. }