UnixMainLoop.cs 18 KB

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