UnixMainLoop.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 (OperationCanceledException)
  137. {
  138. return;
  139. }
  140. ((IMainLoopDriver)this)._waitForInput.Reset ();
  141. ProcessInputQueue ();
  142. }
  143. }
  144. catch (OperationCanceledException)
  145. {
  146. return;
  147. }
  148. _eventReady.Set ();
  149. }
  150. }
  151. private void ProcessInputQueue ()
  152. {
  153. if (_pollDataQueue.Count == 0 || ((IMainLoopDriver)this)._forceRead)
  154. {
  155. while (!_inputHandlerTokenSource.IsCancellationRequested)
  156. {
  157. try
  158. {
  159. Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token);
  160. }
  161. catch (OperationCanceledException)
  162. {
  163. return;
  164. }
  165. int n = poll (_pollMap!, (uint)_pollMap!.Length, 0);
  166. if (n > 0)
  167. {
  168. // Check if stdin has data
  169. if ((_pollMap [0].revents & (int)Condition.PollIn) != 0)
  170. {
  171. // Allocate memory for the buffer
  172. var buf = new byte [2048];
  173. nint bufPtr = Marshal.AllocHGlobal (buf.Length);
  174. try
  175. {
  176. // Read from the stdin
  177. int bytesRead = read (_pollMap [0].fd, bufPtr, buf.Length);
  178. if (bytesRead > 0)
  179. {
  180. // Copy the data from unmanaged memory to a byte array
  181. var buffer = new byte [bytesRead];
  182. Marshal.Copy (bufPtr, buffer, 0, bytesRead);
  183. // Convert the byte array to a string (assuming UTF-8 encoding)
  184. string data = Encoding.UTF8.GetString (buffer);
  185. if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is { })
  186. {
  187. data = data.Insert (0, AnsiEscapeSequenceRequestUtils.ToString (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos));
  188. AnsiEscapeSequenceRequestUtils.IncompleteCkInfos = null;
  189. }
  190. // Enqueue the data
  191. ProcessEnqueuePollData (data);
  192. }
  193. }
  194. finally
  195. {
  196. // Free the allocated memory
  197. Marshal.FreeHGlobal (bufPtr);
  198. }
  199. }
  200. if (_retries > 0)
  201. {
  202. _retries = 0;
  203. }
  204. break;
  205. }
  206. if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && AnsiEscapeSequenceRequests.Statuses.Count > 0)
  207. {
  208. if (_retries > 1)
  209. {
  210. if (AnsiEscapeSequenceRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? seqReqStatus))
  211. {
  212. lock (seqReqStatus.AnsiRequest._responseLock)
  213. {
  214. AnsiEscapeSequenceRequests.Statuses.TryDequeue (out _);
  215. seqReqStatus.AnsiRequest.RaiseResponseFromInput (null);
  216. }
  217. }
  218. _retries = 0;
  219. }
  220. else
  221. {
  222. _retries++;
  223. }
  224. }
  225. else
  226. {
  227. _retries = 0;
  228. }
  229. }
  230. }
  231. }
  232. private void ProcessEnqueuePollData (string pollData)
  233. {
  234. foreach (string split in AnsiEscapeSequenceRequestUtils.SplitEscapeRawString (pollData))
  235. {
  236. EnqueuePollData (split);
  237. }
  238. }
  239. private void EnqueuePollData (string pollDataPart)
  240. {
  241. ConsoleKeyInfo [] cki = AnsiEscapeSequenceRequestUtils.ToConsoleKeyInfoArray (pollDataPart);
  242. ConsoleKey key = 0;
  243. ConsoleModifiers mod = 0;
  244. ConsoleKeyInfo newConsoleKeyInfo = default;
  245. AnsiEscapeSequenceRequestUtils.DecodeEscSeq (
  246. ref newConsoleKeyInfo,
  247. ref key,
  248. cki,
  249. ref mod,
  250. out string c1Control,
  251. out string code,
  252. out string [] values,
  253. out string terminating,
  254. out bool isMouse,
  255. out List<MouseFlags> mouseFlags,
  256. out Point pos,
  257. out AnsiEscapeSequenceRequestStatus? seqReqStatus,
  258. AnsiEscapeSequenceRequestUtils.ProcessMouseEvent
  259. );
  260. if (isMouse)
  261. {
  262. foreach (MouseFlags mf in mouseFlags)
  263. {
  264. _pollDataQueue.Enqueue (EnqueueMouseEvent (mf, pos));
  265. }
  266. return;
  267. }
  268. if (newConsoleKeyInfo != default)
  269. {
  270. _pollDataQueue.Enqueue (EnqueueKeyboardEvent (newConsoleKeyInfo));
  271. }
  272. }
  273. private PollData EnqueueMouseEvent (MouseFlags mouseFlags, Point pos)
  274. {
  275. var mouseEvent = new MouseEvent { Position = pos, MouseFlags = mouseFlags };
  276. return new () { EventType = EventType.Mouse, MouseEvent = mouseEvent };
  277. }
  278. private PollData EnqueueKeyboardEvent (ConsoleKeyInfo keyInfo)
  279. {
  280. return new () { EventType = EventType.Key, KeyEvent = keyInfo };
  281. }
  282. private PollData EnqueueWindowSizeEvent (int rows, int cols)
  283. {
  284. return new () { EventType = EventType.WindowSize, WindowSizeEvent = new () { Size = new (cols, rows) } };
  285. }
  286. bool IMainLoopDriver.EventsPending ()
  287. {
  288. ((IMainLoopDriver)this)._waitForInput.Set ();
  289. _windowSizeChange.Set ();
  290. if (_mainLoop!.CheckTimersAndIdleHandlers (out int waitTimeout))
  291. {
  292. return true;
  293. }
  294. try
  295. {
  296. if (!_eventReadyTokenSource.IsCancellationRequested)
  297. {
  298. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  299. }
  300. }
  301. catch (OperationCanceledException)
  302. {
  303. return true;
  304. }
  305. finally
  306. {
  307. _eventReady.Reset ();
  308. }
  309. if (!_eventReadyTokenSource.IsCancellationRequested)
  310. {
  311. return _pollDataQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  312. }
  313. return true;
  314. }
  315. void IMainLoopDriver.Iteration ()
  316. {
  317. // Dequeue and process the data
  318. while (_pollDataQueue.TryDequeue (out PollData inputRecords))
  319. {
  320. _cursesDriver.ProcessInput (inputRecords);
  321. }
  322. }
  323. void IMainLoopDriver.TearDown ()
  324. {
  325. AnsiEscapeSequenceRequestUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed;
  326. _inputHandlerTokenSource.Cancel ();
  327. _inputHandlerTokenSource.Dispose ();
  328. ((IMainLoopDriver)this)._waitForInput?.Dispose ();
  329. _windowSizeChange.Dispose();
  330. _pollDataQueue.Clear ();
  331. _eventReadyTokenSource.Cancel ();
  332. _eventReadyTokenSource.Dispose ();
  333. _eventReady.Dispose ();
  334. _mainLoop = null;
  335. }
  336. internal void WriteRaw (string ansiRequest)
  337. {
  338. // Write to stdout (fd 1)
  339. write (STDOUT_FILENO, ansiRequest, ansiRequest.Length);
  340. }
  341. [DllImport ("libc")]
  342. private static extern int poll ([In] [Out] Pollfd [] ufds, uint nfds, int timeout);
  343. [DllImport ("libc")]
  344. private static extern int read (int fd, nint buf, nint n);
  345. // File descriptor for stdout
  346. private const int STDOUT_FILENO = 1;
  347. [DllImport ("libc")]
  348. private static extern int write (int fd, string buf, int n);
  349. [DllImport ("libc", SetLastError = true)]
  350. private static extern int ioctl (int fd, int request, ref Winsize ws);
  351. [StructLayout (LayoutKind.Sequential)]
  352. private struct Pollfd
  353. {
  354. public int fd;
  355. public short events;
  356. public readonly short revents;
  357. }
  358. /// <summary>
  359. /// Window or terminal size structure. This information is stored by the kernel in order to provide a consistent
  360. /// interface, but is not used by the kernel.
  361. /// </summary>
  362. [StructLayout (LayoutKind.Sequential)]
  363. public struct Winsize
  364. {
  365. public ushort ws_row; // Number of rows
  366. public ushort ws_col; // Number of columns
  367. public ushort ws_xpixel; // Width in pixels (unused)
  368. public ushort ws_ypixel; // Height in pixels (unused)
  369. }
  370. #region Events
  371. public enum EventType
  372. {
  373. Key = 1,
  374. Mouse = 2,
  375. WindowSize = 3
  376. }
  377. public struct MouseEvent
  378. {
  379. public Point Position;
  380. public MouseFlags MouseFlags;
  381. }
  382. public struct WindowSizeEvent
  383. {
  384. public Size Size;
  385. }
  386. public struct PollData
  387. {
  388. public EventType EventType;
  389. public ConsoleKeyInfo KeyEvent;
  390. public MouseEvent MouseEvent;
  391. public WindowSizeEvent WindowSizeEvent;
  392. public readonly override string ToString ()
  393. {
  394. return (EventType switch
  395. {
  396. EventType.Key => ToString (KeyEvent),
  397. EventType.Mouse => MouseEvent.ToString (),
  398. EventType.WindowSize => WindowSizeEvent.ToString (),
  399. _ => "Unknown event type: " + EventType
  400. })!;
  401. }
  402. /// <summary>Prints a ConsoleKeyInfoEx structure</summary>
  403. /// <param name="cki"></param>
  404. /// <returns></returns>
  405. public readonly string ToString (ConsoleKeyInfo cki)
  406. {
  407. var ke = new Key ((KeyCode)cki.KeyChar);
  408. var sb = new StringBuilder ();
  409. sb.Append ($"Key: {(KeyCode)cki.Key} ({cki.Key})");
  410. sb.Append ((cki.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  411. sb.Append ((cki.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  412. sb.Append ((cki.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  413. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)cki.KeyChar}) ");
  414. string s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  415. return $"[ConsoleKeyInfo({s})]";
  416. }
  417. }
  418. #endregion
  419. }