WindowsOutput.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. #nullable enable
  2. using System.ComponentModel;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. using Microsoft.Extensions.Logging;
  6. namespace Terminal.Gui.Drivers;
  7. internal partial class WindowsOutput : OutputBase, IConsoleOutput
  8. {
  9. [LibraryImport ("kernel32.dll", EntryPoint = "WriteConsoleW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
  10. [return: MarshalAs (UnmanagedType.Bool)]
  11. private static partial bool WriteConsole (
  12. nint hConsoleOutput,
  13. ReadOnlySpan<char> lpbufer,
  14. uint numberOfCharsToWriten,
  15. out uint lpNumberOfCharsWritten,
  16. nint lpReserved
  17. );
  18. [LibraryImport ("kernel32.dll", SetLastError = true)]
  19. private static partial nint GetStdHandle (int nStdHandle);
  20. [LibraryImport ("kernel32.dll", SetLastError = true)]
  21. [return: MarshalAs (UnmanagedType.Bool)]
  22. private static partial bool CloseHandle (nint handle);
  23. [LibraryImport ("kernel32.dll", SetLastError = true)]
  24. private static partial nint CreateConsoleScreenBuffer (
  25. DesiredAccess dwDesiredAccess,
  26. ShareMode dwShareMode,
  27. nint secutiryAttributes,
  28. uint flags,
  29. nint screenBufferData
  30. );
  31. [DllImport ("kernel32.dll", SetLastError = true)]
  32. [return: MarshalAs (UnmanagedType.Bool)]
  33. private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  34. [Flags]
  35. private enum ShareMode : uint
  36. {
  37. FileShareRead = 1,
  38. FileShareWrite = 2
  39. }
  40. [Flags]
  41. private enum DesiredAccess : uint
  42. {
  43. GenericRead = 2147483648,
  44. GenericWrite = 1073741824
  45. }
  46. internal static nint INVALID_HANDLE_VALUE = new (-1);
  47. [LibraryImport ("kernel32.dll", SetLastError = true)]
  48. [return: MarshalAs (UnmanagedType.Bool)]
  49. private static partial bool SetConsoleActiveScreenBuffer (nint handle);
  50. [LibraryImport ("kernel32.dll")]
  51. [return: MarshalAs (UnmanagedType.Bool)]
  52. private static partial bool SetConsoleCursorPosition (nint hConsoleOutput, WindowsConsole.Coord dwCursorPosition);
  53. [DllImport ("kernel32.dll", SetLastError = true)]
  54. [return: MarshalAs (UnmanagedType.Bool)]
  55. private static extern bool SetConsoleCursorInfo (nint hConsoleOutput, [In] ref WindowsConsole.ConsoleCursorInfo lpConsoleCursorInfo);
  56. [LibraryImport ("kernel32.dll", SetLastError = true)]
  57. [return: MarshalAs (UnmanagedType.Bool)]
  58. public static partial bool SetConsoleTextAttribute (nint hConsoleOutput, ushort wAttributes);
  59. [LibraryImport ("kernel32.dll")]
  60. [return: MarshalAs (UnmanagedType.Bool)]
  61. private static partial bool GetConsoleMode (nint hConsoleHandle, out uint lpMode);
  62. [LibraryImport ("kernel32.dll")]
  63. [return: MarshalAs (UnmanagedType.Bool)]
  64. private static partial bool SetConsoleMode (nint hConsoleHandle, uint dwMode);
  65. [LibraryImport ("kernel32.dll", SetLastError = true)]
  66. private static partial WindowsConsole.Coord GetLargestConsoleWindowSize (
  67. nint hConsoleOutput
  68. );
  69. [DllImport ("kernel32.dll", SetLastError = true)]
  70. [return: MarshalAs (UnmanagedType.Bool)]
  71. private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX consoleScreenBufferInfo);
  72. [DllImport ("kernel32.dll", SetLastError = true)]
  73. [return: MarshalAs (UnmanagedType.Bool)]
  74. private static extern bool SetConsoleWindowInfo (
  75. nint hConsoleOutput,
  76. bool bAbsolute,
  77. [In] ref WindowsConsole.SmallRect lpConsoleWindow
  78. );
  79. private const int STD_OUTPUT_HANDLE = -11;
  80. private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
  81. private readonly nint _outputHandle;
  82. private nint _screenBuffer;
  83. private readonly bool _isVirtualTerminal;
  84. public WindowsOutput ()
  85. {
  86. Logging.Logger.LogInformation ($"Creating {nameof (WindowsOutput)}");
  87. if (ConsoleDriver.RunningUnitTests)
  88. {
  89. return;
  90. }
  91. // Get the standard output handle which is the current screen buffer.
  92. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  93. GetConsoleMode (_outputHandle, out uint mode);
  94. _isVirtualTerminal = (mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;
  95. if (_isVirtualTerminal)
  96. {
  97. //Enable alternative screen buffer.
  98. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  99. }
  100. else
  101. {
  102. CreateScreenBuffer ();
  103. if (!GetConsoleMode (_screenBuffer, out mode))
  104. {
  105. throw new ApplicationException ($"Failed to get screenBuffer console mode, error code: {Marshal.GetLastWin32Error ()}.");
  106. }
  107. const uint ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002;
  108. mode &= ~ENABLE_WRAP_AT_EOL_OUTPUT; // Disable wrap
  109. if (!SetConsoleMode (_screenBuffer, mode))
  110. {
  111. throw new ApplicationException ($"Failed to set screenBuffer console mode, error code: {Marshal.GetLastWin32Error ()}.");
  112. }
  113. // Force 16 colors if not in virtual terminal mode.
  114. Application.Force16Colors = true;
  115. }
  116. }
  117. private void CreateScreenBuffer ()
  118. {
  119. _screenBuffer = CreateConsoleScreenBuffer (
  120. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  121. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  122. nint.Zero,
  123. 1,
  124. nint.Zero
  125. );
  126. if (_screenBuffer == INVALID_HANDLE_VALUE)
  127. {
  128. int err = Marshal.GetLastWin32Error ();
  129. if (err != 0)
  130. {
  131. throw new Win32Exception (err);
  132. }
  133. }
  134. if (!SetConsoleActiveScreenBuffer (_screenBuffer))
  135. {
  136. throw new Win32Exception (Marshal.GetLastWin32Error ());
  137. }
  138. }
  139. public void Write (ReadOnlySpan<char> str)
  140. {
  141. if (!WriteConsole (_isVirtualTerminal ? _outputHandle : _screenBuffer, str, (uint)str.Length, out uint _, nint.Zero))
  142. {
  143. throw new Win32Exception (Marshal.GetLastWin32Error (), "Failed to write to console screen buffer.");
  144. }
  145. }
  146. public Size ResizeBuffer (Size size)
  147. {
  148. Size newSize = SetConsoleWindow (
  149. (short)Math.Max (size.Width, 0),
  150. (short)Math.Max (size.Height, 0));
  151. return newSize;
  152. }
  153. internal Size SetConsoleWindow (short cols, short rows)
  154. {
  155. var csbi = new WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX ();
  156. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  157. if (!GetConsoleScreenBufferInfoEx (_isVirtualTerminal ? _outputHandle : _screenBuffer, ref csbi))
  158. {
  159. throw new Win32Exception (Marshal.GetLastWin32Error ());
  160. }
  161. WindowsConsole.Coord maxWinSize = GetLargestConsoleWindowSize (_isVirtualTerminal ? _outputHandle : _screenBuffer);
  162. short newCols = Math.Min (cols, maxWinSize.X);
  163. short newRows = Math.Min (rows, maxWinSize.Y);
  164. csbi.dwSize = new (newCols, Math.Max (newRows, (short)1));
  165. csbi.srWindow = new (0, 0, newCols, newRows);
  166. csbi.dwMaximumWindowSize = new (newCols, newRows);
  167. if (!SetConsoleScreenBufferInfoEx (_isVirtualTerminal ? _outputHandle : _screenBuffer, ref csbi))
  168. {
  169. throw new Win32Exception (Marshal.GetLastWin32Error ());
  170. }
  171. var winRect = new WindowsConsole.SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  172. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  173. {
  174. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  175. return new (cols, rows);
  176. }
  177. SetConsoleOutputWindow (csbi);
  178. return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  179. }
  180. private void SetConsoleOutputWindow (WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  181. {
  182. if ((_isVirtualTerminal
  183. ? _outputHandle
  184. : _screenBuffer) != nint.Zero && !SetConsoleScreenBufferInfoEx (_isVirtualTerminal ? _outputHandle : _screenBuffer, ref csbi))
  185. {
  186. throw new Win32Exception (Marshal.GetLastWin32Error ());
  187. }
  188. }
  189. public override void Write (IOutputBuffer outputBuffer)
  190. {
  191. _force16Colors = Application.Driver!.Force16Colors;
  192. _everythingStringBuilder = new StringBuilder ();
  193. // for 16 color mode we will write to a backing buffer then flip it to the active one at the end to avoid jitter.
  194. _consoleBuffer = 0;
  195. if (_force16Colors)
  196. {
  197. if (_isVirtualTerminal)
  198. {
  199. _consoleBuffer = _outputHandle;
  200. }
  201. else
  202. {
  203. _consoleBuffer = _screenBuffer;
  204. }
  205. }
  206. else
  207. {
  208. _consoleBuffer = _outputHandle;
  209. }
  210. base.Write (outputBuffer);
  211. try
  212. {
  213. if (_force16Colors && !_isVirtualTerminal)
  214. {
  215. SetConsoleActiveScreenBuffer (_consoleBuffer);
  216. }
  217. else
  218. {
  219. var span = _everythingStringBuilder.ToString ().AsSpan (); // still allocates the string
  220. var result = WriteConsole (_consoleBuffer, span, (uint)span.Length, out _, nint.Zero);
  221. if (!result)
  222. {
  223. int err = Marshal.GetLastWin32Error ();
  224. if (err != 0)
  225. {
  226. throw new Win32Exception (err);
  227. }
  228. }
  229. }
  230. }
  231. catch (Exception e)
  232. {
  233. Logging.Logger.LogError ($"Error: {e.Message} in {nameof (WindowsOutput)}");
  234. if (!ConsoleDriver.RunningUnitTests)
  235. {
  236. throw;
  237. }
  238. }
  239. }
  240. /// <inheritdoc />
  241. protected override void Write (StringBuilder output)
  242. {
  243. if (output.Length == 0)
  244. {
  245. return;
  246. }
  247. var str = output.ToString ();
  248. if (_force16Colors && !_isVirtualTerminal)
  249. {
  250. var a = str.ToCharArray ();
  251. WriteConsole (_screenBuffer,a ,(uint)a.Length, out _, nint.Zero);
  252. }
  253. else
  254. {
  255. _everythingStringBuilder.Append (str);
  256. }
  257. }
  258. /// <inheritdoc />
  259. protected override void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle)
  260. {
  261. var force16Colors = Application.Force16Colors;
  262. if (force16Colors)
  263. {
  264. if (_isVirtualTerminal)
  265. {
  266. output.Append (EscSeqUtils.CSI_SetForegroundColor (attr.Foreground.GetAnsiColorCode ()));
  267. output.Append (EscSeqUtils.CSI_SetBackgroundColor (attr.Background.GetAnsiColorCode ()));
  268. EscSeqUtils.CSI_AppendTextStyleChange (output, redrawTextStyle, attr.Style);
  269. }
  270. else
  271. {
  272. var as16ColorInt = (ushort)((int)attr.Foreground.GetClosestNamedColor16 () | ((int)attr.Background.GetClosestNamedColor16 () << 4));
  273. SetConsoleTextAttribute (_screenBuffer, as16ColorInt);
  274. }
  275. }
  276. else
  277. {
  278. EscSeqUtils.CSI_AppendForegroundColorRGB (output, attr.Foreground.R, attr.Foreground.G, attr.Foreground.B);
  279. EscSeqUtils.CSI_AppendBackgroundColorRGB (output, attr.Background.R, attr.Background.G, attr.Background.B);
  280. EscSeqUtils.CSI_AppendTextStyleChange (output, redrawTextStyle, attr.Style);
  281. }
  282. }
  283. private Size? _lastSize;
  284. private Size? _lastWindowSizeBeforeMaximized;
  285. private bool _lockResize;
  286. public Size GetWindowSize ()
  287. {
  288. if (_lockResize)
  289. {
  290. return _lastSize!.Value;
  291. }
  292. var newSize = GetWindowSize (out _);
  293. Size largestWindowSize = GetLargestConsoleWindowSize ();
  294. if (_lastWindowSizeBeforeMaximized is null && newSize == largestWindowSize)
  295. {
  296. _lastWindowSizeBeforeMaximized = _lastSize;
  297. }
  298. else if (_lastWindowSizeBeforeMaximized is { } && newSize != largestWindowSize)
  299. {
  300. if (newSize != _lastWindowSizeBeforeMaximized)
  301. {
  302. newSize = _lastWindowSizeBeforeMaximized.Value;
  303. }
  304. _lastWindowSizeBeforeMaximized = null;
  305. }
  306. if (_lastSize == null || _lastSize != newSize)
  307. {
  308. // User is resizing the screen, they can only ever resize the active
  309. // buffer since. We now however have issue because background offscreen
  310. // buffer will be wrong size, recreate it to ensure it doesn't result in
  311. // differing active and back buffer sizes (which causes flickering of window size)
  312. Size? bufSize = null;
  313. while (bufSize != newSize)
  314. {
  315. _lockResize = true;
  316. bufSize = ResizeBuffer (newSize);
  317. }
  318. _lockResize = false;
  319. _lastSize = newSize;
  320. }
  321. return newSize;
  322. }
  323. public Size GetWindowSize (out WindowsConsole.Coord cursorPosition)
  324. {
  325. var csbi = new WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX ();
  326. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  327. if (!GetConsoleScreenBufferInfoEx (_isVirtualTerminal ? _outputHandle : _screenBuffer, ref csbi))
  328. {
  329. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  330. cursorPosition = default;
  331. return Size.Empty;
  332. }
  333. Size sz = new (
  334. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  335. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  336. cursorPosition = csbi.dwCursorPosition;
  337. return sz;
  338. }
  339. private Size GetLargestConsoleWindowSize ()
  340. {
  341. WindowsConsole.Coord maxWinSize = GetLargestConsoleWindowSize (_isVirtualTerminal ? _outputHandle : _screenBuffer);
  342. return new (maxWinSize.X, maxWinSize.Y);
  343. }
  344. /// <inheritdoc />
  345. protected override bool SetCursorPositionImpl (int screenPositionX, int screenPositionY)
  346. {
  347. if (_force16Colors && !_isVirtualTerminal)
  348. {
  349. SetConsoleCursorPosition (_screenBuffer, new ((short)screenPositionX, (short)screenPositionY));
  350. }
  351. else
  352. {
  353. // CSI codes are 1 indexed
  354. _everythingStringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  355. EscSeqUtils.CSI_AppendCursorPosition (_everythingStringBuilder, screenPositionY + 1, screenPositionX + 1);
  356. }
  357. _lastCursorPosition = new (screenPositionX, screenPositionY);
  358. return true;
  359. }
  360. /// <inheritdoc cref="IConsoleOutput.SetCursorVisibility"/>
  361. public override void SetCursorVisibility (CursorVisibility visibility)
  362. {
  363. if (ConsoleDriver.RunningUnitTests)
  364. {
  365. return;
  366. }
  367. if (!_isVirtualTerminal)
  368. {
  369. var info = new WindowsConsole.ConsoleCursorInfo
  370. {
  371. dwSize = (uint)visibility & 0x00FF,
  372. bVisible = ((uint)visibility & 0xFF00) != 0
  373. };
  374. SetConsoleCursorInfo (_screenBuffer, ref info);
  375. }
  376. else
  377. {
  378. string cursorVisibilitySequence = visibility != CursorVisibility.Invisible
  379. ? EscSeqUtils.CSI_ShowCursor
  380. : EscSeqUtils.CSI_HideCursor;
  381. Write (cursorVisibilitySequence);
  382. }
  383. }
  384. private Point? _lastCursorPosition;
  385. /// <inheritdoc/>
  386. public void SetCursorPosition (int col, int row)
  387. {
  388. if (_lastCursorPosition is { } && _lastCursorPosition.Value.X == col && _lastCursorPosition.Value.Y == row)
  389. {
  390. return;
  391. }
  392. _lastCursorPosition = new (col, row);
  393. if (_isVirtualTerminal)
  394. {
  395. var sb = new StringBuilder ();
  396. EscSeqUtils.CSI_AppendCursorPosition (sb, row + 1, col + 1);
  397. Write (sb.ToString ());
  398. }
  399. else
  400. {
  401. SetConsoleCursorPosition (_screenBuffer, new ((short)col, (short)row));
  402. }
  403. }
  404. private bool _isDisposed;
  405. private bool _force16Colors;
  406. private nint _consoleBuffer;
  407. private StringBuilder _everythingStringBuilder;
  408. /// <inheritdoc/>
  409. public void Dispose ()
  410. {
  411. if (_isDisposed)
  412. {
  413. return;
  414. }
  415. if (_isVirtualTerminal)
  416. {
  417. //Disable alternative screen buffer.
  418. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  419. }
  420. else
  421. {
  422. if (_screenBuffer != nint.Zero)
  423. {
  424. CloseHandle (_screenBuffer);
  425. }
  426. _screenBuffer = nint.Zero;
  427. }
  428. _isDisposed = true;
  429. }
  430. }