UnixMainLoop.cs 17 KB

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