WindowsOutput.cs 19 KB

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