UnixMainLoop.cs 18 KB

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