UnixMainLoop.cs 17 KB

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