WindowsOutput.cs 19 KB

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