UnixInput.cs 7.9 KB

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