2
0

UnixInput.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. using System.Runtime.InteropServices;
  2. using Microsoft.Extensions.Logging;
  3. namespace Terminal.Gui.Drivers;
  4. internal class UnixInput : ConsoleInput<char>, IUnixInput
  5. {
  6. private const int STDIN_FILENO = 0;
  7. [StructLayout (LayoutKind.Sequential)]
  8. private struct Termios
  9. {
  10. public uint c_iflag;
  11. public uint c_oflag;
  12. public uint c_cflag;
  13. public uint c_lflag;
  14. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 32)]
  15. public byte [] c_cc;
  16. public uint c_ispeed;
  17. public uint c_ospeed;
  18. }
  19. [DllImport ("libc", SetLastError = true)]
  20. private static extern int tcgetattr (int fd, out Termios termios);
  21. [DllImport ("libc", SetLastError = true)]
  22. private static extern int tcsetattr (int fd, int optional_actions, ref Termios termios);
  23. // try cfmakeraw (glibc and macOS usually export it)
  24. [DllImport ("libc", EntryPoint = "cfmakeraw", SetLastError = false)]
  25. private static extern void cfmakeraw_ref (ref Termios termios);
  26. [DllImport ("libc", SetLastError = true)]
  27. private static extern nint strerror (int err);
  28. private const int TCSANOW = 0;
  29. private const ulong BRKINT = 0x00000002;
  30. private const ulong ICRNL = 0x00000100;
  31. private const ulong INPCK = 0x00000010;
  32. private const ulong ISTRIP = 0x00000020;
  33. private const ulong IXON = 0x00000400;
  34. private const ulong OPOST = 0x00000001;
  35. private const ulong ECHO = 0x00000008;
  36. private const ulong ICANON = 0x00000100;
  37. private const ulong IEXTEN = 0x00008000;
  38. private const ulong ISIG = 0x00000001;
  39. private const ulong CS8 = 0x00000030;
  40. private Termios _original;
  41. [StructLayout (LayoutKind.Sequential)]
  42. private struct Pollfd
  43. {
  44. public int fd;
  45. public short events;
  46. public readonly short revents; // readonly signals "don't touch this in managed code"
  47. }
  48. /// <summary>Condition on which to wake up from file descriptor activity. These match the Linux/BSD poll definitions.</summary>
  49. [Flags]
  50. private enum Condition : short
  51. {
  52. /// <summary>There is data to read</summary>
  53. PollIn = 1,
  54. /// <summary>There is urgent data to read</summary>
  55. PollPri = 2,
  56. /// <summary>Writing to the specified descriptor will not block</summary>
  57. PollOut = 4,
  58. /// <summary>Error condition on output</summary>
  59. PollErr = 8,
  60. /// <summary>Hang-up on output</summary>
  61. PollHup = 16,
  62. /// <summary>File descriptor is not open.</summary>
  63. PollNval = 32
  64. }
  65. [DllImport ("libc", SetLastError = true)]
  66. private static extern int poll ([In][Out] Pollfd [] ufds, uint nfds, int timeout);
  67. [DllImport ("libc", SetLastError = true)]
  68. private static extern int read (int fd, byte [] buf, int count);
  69. // File descriptor for stdout
  70. private const int STDOUT_FILENO = 1;
  71. [DllImport ("libc", SetLastError = true)]
  72. private static extern int write (int fd, byte [] buf, int count);
  73. [DllImport ("libc", SetLastError = true)]
  74. private static extern int tcflush (int fd, int queueSelector);
  75. private const int TCIFLUSH = 0; // flush data received but not read
  76. private Pollfd [] _pollMap;
  77. public UnixInput ()
  78. {
  79. Logging.Logger.LogInformation ($"Creating {nameof (UnixInput)}");
  80. if (ConsoleDriver.RunningUnitTests)
  81. {
  82. return;
  83. }
  84. _pollMap = new Pollfd [1];
  85. _pollMap [0].fd = STDIN_FILENO; // stdin
  86. _pollMap [0].events = (short)Condition.PollIn;
  87. EnableRawModeAndTreatControlCAsInput ();
  88. //Enable alternative screen buffer.
  89. WriteRaw (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  90. //Set cursor key to application.
  91. WriteRaw (EscSeqUtils.CSI_HideCursor);
  92. WriteRaw (EscSeqUtils.CSI_EnableMouseEvents);
  93. }
  94. private void EnableRawModeAndTreatControlCAsInput ()
  95. {
  96. if (tcgetattr (STDIN_FILENO, out _original) != 0)
  97. {
  98. var e = Marshal.GetLastWin32Error ();
  99. throw new InvalidOperationException ($"tcgetattr failed errno={e} ({StrError (e)})");
  100. }
  101. var raw = _original;
  102. // Prefer cfmakeraw if available
  103. try
  104. {
  105. cfmakeraw_ref (ref raw);
  106. }
  107. catch (EntryPointNotFoundException)
  108. {
  109. // fallback: roughly cfmakeraw equivalent
  110. raw.c_iflag &= ~((uint)BRKINT | (uint)ICRNL | (uint)INPCK | (uint)ISTRIP | (uint)IXON);
  111. raw.c_oflag &= ~(uint)OPOST;
  112. raw.c_cflag |= (uint)CS8;
  113. raw.c_lflag &= ~((uint)ECHO | (uint)ICANON | (uint)IEXTEN | (uint)ISIG);
  114. }
  115. if (tcsetattr (STDIN_FILENO, TCSANOW, ref raw) != 0)
  116. {
  117. var e = Marshal.GetLastWin32Error ();
  118. throw new InvalidOperationException ($"tcsetattr failed errno={e} ({StrError (e)})");
  119. }
  120. }
  121. private string StrError (int err)
  122. {
  123. var p = strerror (err);
  124. return p == nint.Zero ? $"errno={err}" : Marshal.PtrToStringAnsi (p) ?? $"errno={err}";
  125. }
  126. /// <inheritdoc />
  127. protected override bool Peek ()
  128. {
  129. try
  130. {
  131. if (ConsoleDriver.RunningUnitTests)
  132. {
  133. return false;
  134. }
  135. int n = poll (_pollMap!, (uint)_pollMap!.Length, 0);
  136. if (n != 0)
  137. {
  138. return true;
  139. }
  140. return false;
  141. }
  142. catch (Exception ex)
  143. {
  144. // Optionally log the exception
  145. Logging.Logger.LogError ($"Error in Peek: {ex.Message}");
  146. return false;
  147. }
  148. }
  149. private void WriteRaw (string text)
  150. {
  151. if (!ConsoleDriver.RunningUnitTests)
  152. {
  153. byte [] utf8 = Encoding.UTF8.GetBytes (text);
  154. // Write to stdout (fd 1)
  155. write (STDOUT_FILENO, utf8, utf8.Length);
  156. }
  157. }
  158. /// <inheritdoc/>
  159. protected override IEnumerable<char> Read ()
  160. {
  161. while (poll (_pollMap!, (uint)_pollMap!.Length, 0) != 0)
  162. {
  163. // Check if stdin has data
  164. if ((_pollMap [0].revents & (int)Condition.PollIn) != 0)
  165. {
  166. var buf = new byte [256];
  167. int bytesRead = read (0, buf, buf.Length); // Read from stdin
  168. string input = Encoding.UTF8.GetString (buf, 0, bytesRead);
  169. foreach (char ch in input)
  170. {
  171. yield return ch;
  172. }
  173. }
  174. }
  175. }
  176. private void FlushConsoleInput ()
  177. {
  178. if (!ConsoleDriver.RunningUnitTests)
  179. {
  180. var fds = new Pollfd [1];
  181. fds [0].fd = STDIN_FILENO;
  182. fds [0].events = (short)Condition.PollIn;
  183. var buf = new byte [256];
  184. while (poll (fds, 1, 0) > 0)
  185. {
  186. read (STDIN_FILENO, buf, buf.Length);
  187. }
  188. }
  189. }
  190. /// <inheritdoc />
  191. public override void Dispose ()
  192. {
  193. base.Dispose ();
  194. if (!ConsoleDriver.RunningUnitTests)
  195. {
  196. // Disable mouse events first
  197. WriteRaw (EscSeqUtils.CSI_DisableMouseEvents);
  198. // Drain any pending input already queued by the terminal
  199. FlushConsoleInput ();
  200. // Flush kernel input buffer
  201. tcflush (STDIN_FILENO, TCIFLUSH);
  202. //Disable alternative screen buffer.
  203. WriteRaw (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  204. //Set cursor key to cursor.
  205. WriteRaw (EscSeqUtils.CSI_ShowCursor);
  206. // Restore terminal to original state
  207. tcsetattr (STDIN_FILENO, TCSANOW, ref _original);
  208. }
  209. }
  210. }