UnixMainLoop.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. #nullable enable
  2. //
  3. // mainloop.cs: Linux/Curses MainLoop implementation.
  4. //
  5. using System.Collections.Concurrent;
  6. using System.Runtime.InteropServices;
  7. namespace Terminal.Gui;
  8. /// <summary>Unix main loop, suitable for using on Posix systems</summary>
  9. /// <remarks>
  10. /// In addition to the general functions of the MainLoop, the Unix version can watch file descriptors using the
  11. /// AddWatch methods.
  12. /// </remarks>
  13. internal class UnixMainLoop (ConsoleDriver consoleDriver) : IMainLoopDriver
  14. {
  15. /// <summary>Condition on which to wake up from file descriptor activity. These match the Linux/BSD poll definitions.</summary>
  16. [Flags]
  17. public enum Condition : short
  18. {
  19. /// <summary>There is data to read</summary>
  20. PollIn = 1,
  21. /// <summary>Writing to the specified descriptor will not block</summary>
  22. PollOut = 4,
  23. /// <summary>There is urgent data to read</summary>
  24. PollPri = 2,
  25. /// <summary>Error condition on output</summary>
  26. PollErr = 8,
  27. /// <summary>Hang-up on output</summary>
  28. PollHup = 16,
  29. /// <summary>File descriptor is not open.</summary>
  30. PollNval = 32
  31. }
  32. private readonly CursesDriver _cursesDriver = (CursesDriver)consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  33. private MainLoop? _mainLoop;
  34. private Pollfd []? _pollMap;
  35. private readonly ConcurrentQueue<PollData> _pollDataQueue = new ();
  36. private readonly ManualResetEventSlim _eventReady = new (false);
  37. ManualResetEventSlim IMainLoopDriver._waitForInput { get; set; } = new (false);
  38. private readonly ManualResetEventSlim _windowSizeChange = new (false);
  39. private readonly CancellationTokenSource _eventReadyTokenSource = new ();
  40. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  41. void IMainLoopDriver.Wakeup () { _eventReady.Set (); }
  42. void IMainLoopDriver.Setup (MainLoop mainLoop)
  43. {
  44. _mainLoop = mainLoop;
  45. if (ConsoleDriver.RunningUnitTests)
  46. {
  47. return;
  48. }
  49. try
  50. {
  51. // Setup poll for stdin (fd 0)
  52. _pollMap = new Pollfd [1];
  53. _pollMap [0].fd = 0; // stdin (file descriptor 0)
  54. _pollMap [0].events = (short)Condition.PollIn; // Monitor input for reading
  55. }
  56. catch (DllNotFoundException e)
  57. {
  58. throw new NotSupportedException ("libc not found", e);
  59. }
  60. AnsiEscapeSequenceRequestUtils.ContinuousButtonPressed += EscSeqUtils_ContinuousButtonPressed;
  61. Task.Run (CursesInputHandler, _inputHandlerTokenSource.Token);
  62. Task.Run (WindowSizeHandler, _inputHandlerTokenSource.Token);
  63. }
  64. private static readonly int TIOCGWINSZ = GetTIOCGWINSZValue ();
  65. private const string PlaceholderLibrary = "compiled-binaries/libGetTIOCGWINSZ"; // Placeholder, won't directly load
  66. [DllImport (PlaceholderLibrary, EntryPoint = "get_tiocgwinsz_value")]
  67. private static extern int GetTIOCGWINSZValueInternal ();
  68. public static int GetTIOCGWINSZValue ()
  69. {
  70. // Determine the correct library path based on the OS
  71. string libraryPath = Path.Combine (
  72. AppContext.BaseDirectory,
  73. "compiled-binaries",
  74. RuntimeInformation.IsOSPlatform (OSPlatform.OSX) ? "libGetTIOCGWINSZ.dylib" : "libGetTIOCGWINSZ.so");
  75. // Load the native library manually
  76. nint handle = NativeLibrary.Load (libraryPath);
  77. // Ensure the handle is valid
  78. if (handle == nint.Zero)
  79. {
  80. throw new DllNotFoundException ($"Unable to load library: {libraryPath}");
  81. }
  82. return GetTIOCGWINSZValueInternal ();
  83. }
  84. private void EscSeqUtils_ContinuousButtonPressed (object? sender, MouseEventArgs e)
  85. {
  86. _pollDataQueue.Enqueue (EnqueueMouseEvent (e.Flags, e.Position));
  87. }
  88. private void WindowSizeHandler ()
  89. {
  90. var ws = new Winsize ();
  91. ioctl (0, TIOCGWINSZ, ref ws);
  92. // Store initial window size
  93. int rows = ws.ws_row;
  94. int cols = ws.ws_col;
  95. while (_inputHandlerTokenSource is { IsCancellationRequested: false })
  96. {
  97. try
  98. {
  99. _windowSizeChange.Wait (_inputHandlerTokenSource.Token);
  100. _windowSizeChange.Reset ();
  101. while (!_inputHandlerTokenSource.IsCancellationRequested)
  102. {
  103. // Wait for a while then check if screen has changed sizes
  104. Task.Delay (500, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token);
  105. ioctl (0, TIOCGWINSZ, ref ws);
  106. if (rows != ws.ws_row || cols != ws.ws_col)
  107. {
  108. rows = ws.ws_row;
  109. cols = ws.ws_col;
  110. _pollDataQueue.Enqueue (EnqueueWindowSizeEvent (rows, cols));
  111. break;
  112. }
  113. }
  114. }
  115. catch (OperationCanceledException)
  116. {
  117. return;
  118. }
  119. _eventReady.Set ();
  120. }
  121. }
  122. bool IMainLoopDriver._forceRead { get; set; }
  123. private int _retries;
  124. private void CursesInputHandler ()
  125. {
  126. while (_mainLoop is { })
  127. {
  128. try
  129. {
  130. if (!_inputHandlerTokenSource.IsCancellationRequested && !((IMainLoopDriver)this)._forceRead)
  131. {
  132. try
  133. {
  134. ((IMainLoopDriver)this)._waitForInput.Wait (_inputHandlerTokenSource.Token);
  135. }
  136. catch (Exception ex)
  137. {
  138. if (ex is OperationCanceledException or ObjectDisposedException)
  139. {
  140. return;
  141. }
  142. throw;
  143. }
  144. ((IMainLoopDriver)this)._waitForInput.Reset ();
  145. }
  146. ProcessInputQueue ();
  147. }
  148. catch (OperationCanceledException)
  149. {
  150. return;
  151. }
  152. }
  153. }
  154. private void ProcessInputQueue ()
  155. {
  156. if (_pollDataQueue.Count == 0 || ((IMainLoopDriver)this)._forceRead)
  157. {
  158. while (!_inputHandlerTokenSource.IsCancellationRequested)
  159. {
  160. try
  161. {
  162. Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token);
  163. }
  164. catch (OperationCanceledException)
  165. {
  166. return;
  167. }
  168. int n = poll (_pollMap!, (uint)_pollMap!.Length, 0);
  169. if (n > 0)
  170. {
  171. // Check if stdin has data
  172. if ((_pollMap [0].revents & (int)Condition.PollIn) != 0)
  173. {
  174. // Allocate memory for the buffer
  175. var buf = new byte [2048];
  176. nint bufPtr = Marshal.AllocHGlobal (buf.Length);
  177. try
  178. {
  179. // Read from the stdin
  180. int bytesRead = read (_pollMap [0].fd, bufPtr, buf.Length);
  181. if (bytesRead > 0)
  182. {
  183. // Copy the data from unmanaged memory to a byte array
  184. var buffer = new byte [bytesRead];
  185. Marshal.Copy (bufPtr, buffer, 0, bytesRead);
  186. // Convert the byte array to a string (assuming UTF-8 encoding)
  187. string data = Encoding.UTF8.GetString (buffer);
  188. if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is { })
  189. {
  190. data = data.Insert (0, AnsiEscapeSequenceRequestUtils.ToString (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos));
  191. AnsiEscapeSequenceRequestUtils.IncompleteCkInfos = null;
  192. }
  193. // Enqueue the data
  194. ProcessEnqueuePollData (data);
  195. }
  196. }
  197. finally
  198. {
  199. // Free the allocated memory
  200. Marshal.FreeHGlobal (bufPtr);
  201. }
  202. }
  203. if (_retries > 0)
  204. {
  205. _retries = 0;
  206. }
  207. break;
  208. }
  209. if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && AnsiEscapeSequenceRequests.Statuses.Count > 0)
  210. {
  211. if (_retries > 1)
  212. {
  213. if (AnsiEscapeSequenceRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? seqReqStatus))
  214. {
  215. lock (seqReqStatus.AnsiRequest._responseLock)
  216. {
  217. AnsiEscapeSequenceRequests.Statuses.TryDequeue (out _);
  218. seqReqStatus.AnsiRequest.RaiseResponseFromInput (null);
  219. }
  220. }
  221. _retries = 0;
  222. }
  223. else
  224. {
  225. _retries++;
  226. }
  227. }
  228. else
  229. {
  230. _retries = 0;
  231. }
  232. }
  233. }
  234. if (_pollDataQueue.Count > 0)
  235. {
  236. _eventReady.Set ();
  237. }
  238. }
  239. private void ProcessEnqueuePollData (string pollData)
  240. {
  241. foreach (string split in AnsiEscapeSequenceRequestUtils.SplitEscapeRawString (pollData))
  242. {
  243. EnqueuePollData (split);
  244. }
  245. }
  246. private void EnqueuePollData (string pollDataPart)
  247. {
  248. ConsoleKeyInfo [] cki = AnsiEscapeSequenceRequestUtils.ToConsoleKeyInfoArray (pollDataPart);
  249. ConsoleKey key = 0;
  250. ConsoleModifiers mod = 0;
  251. ConsoleKeyInfo newConsoleKeyInfo = default;
  252. AnsiEscapeSequenceRequestUtils.DecodeEscSeq (
  253. ref newConsoleKeyInfo,
  254. ref key,
  255. cki,
  256. ref mod,
  257. out string c1Control,
  258. out string code,
  259. out string [] values,
  260. out string terminating,
  261. out bool isMouse,
  262. out List<MouseFlags> mouseFlags,
  263. out Point pos,
  264. out AnsiEscapeSequenceRequestStatus? seqReqStatus,
  265. AnsiEscapeSequenceRequestUtils.ProcessMouseEvent
  266. );
  267. if (isMouse)
  268. {
  269. foreach (MouseFlags mf in mouseFlags)
  270. {
  271. _pollDataQueue.Enqueue (EnqueueMouseEvent (mf, pos));
  272. }
  273. return;
  274. }
  275. if (newConsoleKeyInfo != default)
  276. {
  277. _pollDataQueue.Enqueue (EnqueueKeyboardEvent (newConsoleKeyInfo));
  278. }
  279. }
  280. private PollData EnqueueMouseEvent (MouseFlags mouseFlags, Point pos)
  281. {
  282. var mouseEvent = new MouseEvent { Position = pos, MouseFlags = mouseFlags };
  283. return new () { EventType = EventType.Mouse, MouseEvent = mouseEvent };
  284. }
  285. private PollData EnqueueKeyboardEvent (ConsoleKeyInfo keyInfo)
  286. {
  287. return new () { EventType = EventType.Key, KeyEvent = keyInfo };
  288. }
  289. private PollData EnqueueWindowSizeEvent (int rows, int cols)
  290. {
  291. return new () { EventType = EventType.WindowSize, WindowSizeEvent = new () { Size = new (cols, rows) } };
  292. }
  293. bool IMainLoopDriver.EventsPending ()
  294. {
  295. ((IMainLoopDriver)this)._waitForInput.Set ();
  296. _windowSizeChange.Set ();
  297. if (_mainLoop!.CheckTimersAndIdleHandlers (out int waitTimeout))
  298. {
  299. return true;
  300. }
  301. try
  302. {
  303. if (!_eventReadyTokenSource.IsCancellationRequested)
  304. {
  305. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  306. }
  307. }
  308. catch (OperationCanceledException)
  309. {
  310. return true;
  311. }
  312. finally
  313. {
  314. _eventReady.Reset ();
  315. }
  316. if (!_eventReadyTokenSource.IsCancellationRequested)
  317. {
  318. return _pollDataQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  319. }
  320. return true;
  321. }
  322. void IMainLoopDriver.Iteration ()
  323. {
  324. // Dequeue and process the data
  325. while (_pollDataQueue.TryDequeue (out PollData inputRecords))
  326. {
  327. _cursesDriver.ProcessInput (inputRecords);
  328. }
  329. }
  330. void IMainLoopDriver.TearDown ()
  331. {
  332. AnsiEscapeSequenceRequestUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed;
  333. _inputHandlerTokenSource.Cancel ();
  334. _inputHandlerTokenSource.Dispose ();
  335. ((IMainLoopDriver)this)._waitForInput?.Dispose ();
  336. _windowSizeChange.Dispose();
  337. _pollDataQueue.Clear ();
  338. _eventReadyTokenSource.Cancel ();
  339. _eventReadyTokenSource.Dispose ();
  340. _eventReady.Dispose ();
  341. _mainLoop = null;
  342. }
  343. internal void WriteRaw (string ansiRequest)
  344. {
  345. // Write to stdout (fd 1)
  346. write (STDOUT_FILENO, ansiRequest, ansiRequest.Length);
  347. }
  348. [DllImport ("libc")]
  349. private static extern int poll ([In] [Out] Pollfd [] ufds, uint nfds, int timeout);
  350. [DllImport ("libc")]
  351. private static extern int read (int fd, nint buf, nint n);
  352. // File descriptor for stdout
  353. private const int STDOUT_FILENO = 1;
  354. [DllImport ("libc")]
  355. private static extern int write (int fd, string buf, int n);
  356. [DllImport ("libc", SetLastError = true)]
  357. private static extern int ioctl (int fd, int request, ref Winsize ws);
  358. [StructLayout (LayoutKind.Sequential)]
  359. private struct Pollfd
  360. {
  361. public int fd;
  362. public short events;
  363. public readonly short revents;
  364. }
  365. /// <summary>
  366. /// Window or terminal size structure. This information is stored by the kernel in order to provide a consistent
  367. /// interface, but is not used by the kernel.
  368. /// </summary>
  369. [StructLayout (LayoutKind.Sequential)]
  370. public struct Winsize
  371. {
  372. public ushort ws_row; // Number of rows
  373. public ushort ws_col; // Number of columns
  374. public ushort ws_xpixel; // Width in pixels (unused)
  375. public ushort ws_ypixel; // Height in pixels (unused)
  376. }
  377. #region Events
  378. public enum EventType
  379. {
  380. Key = 1,
  381. Mouse = 2,
  382. WindowSize = 3
  383. }
  384. public struct MouseEvent
  385. {
  386. public Point Position;
  387. public MouseFlags MouseFlags;
  388. }
  389. public struct WindowSizeEvent
  390. {
  391. public Size Size;
  392. }
  393. public struct PollData
  394. {
  395. public EventType EventType;
  396. public ConsoleKeyInfo KeyEvent;
  397. public MouseEvent MouseEvent;
  398. public WindowSizeEvent WindowSizeEvent;
  399. public readonly override string ToString ()
  400. {
  401. return (EventType switch
  402. {
  403. EventType.Key => ToString (KeyEvent),
  404. EventType.Mouse => MouseEvent.ToString (),
  405. EventType.WindowSize => WindowSizeEvent.ToString (),
  406. _ => "Unknown event type: " + EventType
  407. })!;
  408. }
  409. /// <summary>Prints a ConsoleKeyInfoEx structure</summary>
  410. /// <param name="cki"></param>
  411. /// <returns></returns>
  412. public readonly string ToString (ConsoleKeyInfo cki)
  413. {
  414. var ke = new Key ((KeyCode)cki.KeyChar);
  415. var sb = new StringBuilder ();
  416. sb.Append ($"Key: {(KeyCode)cki.Key} ({cki.Key})");
  417. sb.Append ((cki.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  418. sb.Append ((cki.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  419. sb.Append ((cki.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  420. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)cki.KeyChar}) ");
  421. string s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  422. return $"[ConsoleKeyInfo({s})]";
  423. }
  424. }
  425. #endregion
  426. }