UnixMainLoop.cs 17 KB

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