UnixInput.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using System.Runtime.InteropServices;
  2. // ReSharper disable IdentifierTypo
  3. // ReSharper disable InconsistentNaming
  4. // ReSharper disable StringLiteralTypo
  5. // ReSharper disable CommentTypo
  6. namespace Terminal.Gui.Drivers;
  7. internal class UnixInput : InputImpl<char>, IUnixInput
  8. {
  9. private const int STDIN_FILENO = 0;
  10. [StructLayout (LayoutKind.Sequential)]
  11. private struct Termios
  12. {
  13. public uint c_iflag;
  14. public uint c_oflag;
  15. public uint c_cflag;
  16. public uint c_lflag;
  17. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 32)]
  18. public byte [] c_cc;
  19. public uint c_ispeed;
  20. public uint c_ospeed;
  21. }
  22. [DllImport ("libc", SetLastError = true)]
  23. private static extern int tcgetattr (int fd, out Termios termios);
  24. [DllImport ("libc", SetLastError = true)]
  25. private static extern int tcsetattr (int fd, int optional_actions, ref Termios termios);
  26. // try cfmakeraw (glibc and macOS usually export it)
  27. [DllImport ("libc", EntryPoint = "cfmakeraw", SetLastError = false)]
  28. private static extern void cfmakeraw_ref (ref Termios termios);
  29. [DllImport ("libc", SetLastError = true)]
  30. private static extern nint strerror (int err);
  31. private const int TCSANOW = 0;
  32. private const ulong BRKINT = 0x00000002;
  33. private const ulong ICRNL = 0x00000100;
  34. private const ulong INPCK = 0x00000010;
  35. private const ulong ISTRIP = 0x00000020;
  36. private const ulong IXON = 0x00000400;
  37. private const ulong OPOST = 0x00000001;
  38. private const ulong ECHO = 0x00000008;
  39. private const ulong ICANON = 0x00000100;
  40. private const ulong IEXTEN = 0x00008000;
  41. private const ulong ISIG = 0x00000001;
  42. private const ulong CS8 = 0x00000030;
  43. private Termios _original;
  44. private bool _terminalInitialized;
  45. [StructLayout (LayoutKind.Sequential)]
  46. private struct Pollfd
  47. {
  48. public int fd;
  49. public short events;
  50. public readonly short revents;
  51. }
  52. [Flags]
  53. private enum Condition : short
  54. {
  55. PollIn = 1,
  56. PollPri = 2,
  57. PollOut = 4,
  58. PollErr = 8,
  59. PollHup = 16,
  60. PollNval = 32
  61. }
  62. [DllImport ("libc", SetLastError = true)]
  63. private static extern int poll ([In] [Out] Pollfd [] ufds, uint nfds, int timeout);
  64. [DllImport ("libc", SetLastError = true)]
  65. private static extern int read (int fd, byte [] buf, int count);
  66. private const int STDOUT_FILENO = 1;
  67. [DllImport ("libc", SetLastError = true)]
  68. private static extern int write (int fd, byte [] buf, int count);
  69. [DllImport ("libc", SetLastError = true)]
  70. private static extern int tcflush (int fd, int queueSelector);
  71. private const int TCIFLUSH = 0;
  72. private Pollfd []? _pollMap;
  73. public UnixInput ()
  74. {
  75. Logging.Information ($"Creating {nameof (UnixInput)}");
  76. try
  77. {
  78. _pollMap = new Pollfd [1];
  79. _pollMap [0].fd = STDIN_FILENO;
  80. _pollMap [0].events = (short)Condition.PollIn;
  81. EnableRawModeAndTreatControlCAsInput ();
  82. if (_terminalInitialized)
  83. {
  84. WriteRaw (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  85. WriteRaw (EscSeqUtils.CSI_HideCursor);
  86. WriteRaw (EscSeqUtils.CSI_EnableMouseEvents);
  87. }
  88. }
  89. catch (DllNotFoundException ex)
  90. {
  91. Logging.Warning ($"UnixInput: libc not available: {ex.Message}. Running in degraded mode.");
  92. _terminalInitialized = false;
  93. }
  94. catch (Exception ex)
  95. {
  96. Logging.Warning ($"UnixInput: Failed to initialize terminal: {ex.Message}. Running in degraded mode.");
  97. _terminalInitialized = false;
  98. }
  99. }
  100. private void EnableRawModeAndTreatControlCAsInput ()
  101. {
  102. try
  103. {
  104. int result = tcgetattr (STDIN_FILENO, out _original);
  105. if (result != 0)
  106. {
  107. int e = Marshal.GetLastWin32Error ();
  108. Logging.Warning ($"tcgetattr failed errno={e} ({StrError (e)}). Running without TTY support.");
  109. return;
  110. }
  111. Termios raw = _original;
  112. try
  113. {
  114. cfmakeraw_ref (ref raw);
  115. }
  116. catch (EntryPointNotFoundException)
  117. {
  118. raw.c_iflag &= ~((uint)BRKINT | (uint)ICRNL | (uint)INPCK | (uint)ISTRIP | (uint)IXON);
  119. raw.c_oflag &= ~(uint)OPOST;
  120. raw.c_cflag |= (uint)CS8;
  121. raw.c_lflag &= ~((uint)ECHO | (uint)ICANON | (uint)IEXTEN | (uint)ISIG);
  122. }
  123. result = tcsetattr (STDIN_FILENO, TCSANOW, ref raw);
  124. if (result != 0)
  125. {
  126. int e = Marshal.GetLastWin32Error ();
  127. Logging.Warning ($"tcsetattr failed errno={e} ({StrError (e)}). Running without TTY support.");
  128. return;
  129. }
  130. _terminalInitialized = true;
  131. }
  132. catch (DllNotFoundException)
  133. {
  134. throw; // Re-throw to be caught by constructor
  135. }
  136. }
  137. private string StrError (int err)
  138. {
  139. try
  140. {
  141. nint p = strerror (err);
  142. return p == nint.Zero ? $"errno={err}" : Marshal.PtrToStringAnsi (p) ?? $"errno={err}";
  143. }
  144. catch
  145. {
  146. return $"errno={err}";
  147. }
  148. }
  149. /// <inheritdoc/>
  150. public override bool Peek ()
  151. {
  152. if (!_terminalInitialized || _pollMap is null)
  153. {
  154. return false;
  155. }
  156. try
  157. {
  158. int n = poll (_pollMap, (uint)_pollMap.Length, 0);
  159. return n != 0;
  160. }
  161. catch (Exception ex)
  162. {
  163. Logging.Error ($"Error in Peek: {ex.Message}");
  164. return false;
  165. }
  166. }
  167. private void WriteRaw (string text)
  168. {
  169. if (!_terminalInitialized)
  170. {
  171. return;
  172. }
  173. try
  174. {
  175. byte [] utf8 = Encoding.UTF8.GetBytes (text);
  176. write (STDOUT_FILENO, utf8, utf8.Length);
  177. }
  178. catch
  179. {
  180. // ignore exceptions during write
  181. }
  182. }
  183. /// <inheritdoc/>
  184. public override IEnumerable<char> Read ()
  185. {
  186. if (!_terminalInitialized || _pollMap is null)
  187. {
  188. yield break;
  189. }
  190. while (poll (_pollMap, (uint)_pollMap.Length, 0) != 0)
  191. {
  192. if ((_pollMap [0].revents & (int)Condition.PollIn) != 0)
  193. {
  194. var buf = new byte [256];
  195. int bytesRead = read (0, buf, buf.Length);
  196. string input = Encoding.UTF8.GetString (buf, 0, bytesRead);
  197. foreach (char ch in input)
  198. {
  199. yield return ch;
  200. }
  201. }
  202. }
  203. }
  204. private void FlushConsoleInput ()
  205. {
  206. if (!_terminalInitialized)
  207. {
  208. return;
  209. }
  210. try
  211. {
  212. Pollfd [] fds = new Pollfd [1];
  213. fds [0].fd = STDIN_FILENO;
  214. fds [0].events = (short)Condition.PollIn;
  215. var buf = new byte [256];
  216. while (poll (fds, 1, 0) > 0)
  217. {
  218. read (STDIN_FILENO, buf, buf.Length);
  219. }
  220. }
  221. catch
  222. {
  223. // ignore
  224. }
  225. }
  226. /// <inheritdoc/>
  227. public override void Dispose ()
  228. {
  229. base.Dispose ();
  230. if (!_terminalInitialized)
  231. {
  232. return;
  233. }
  234. try
  235. {
  236. WriteRaw (EscSeqUtils.CSI_DisableMouseEvents);
  237. FlushConsoleInput ();
  238. tcflush (STDIN_FILENO, TCIFLUSH);
  239. WriteRaw (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  240. WriteRaw (EscSeqUtils.CSI_ShowCursor);
  241. tcsetattr (STDIN_FILENO, TCSANOW, ref _original);
  242. }
  243. catch
  244. {
  245. // ignore exceptions during disposal
  246. }
  247. }
  248. }