UnixMainLoop.cs 18 KB

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