WindowsOutput.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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 ConsoleColor _foreground;
  82. private readonly ConsoleColor _background;
  83. public WindowsOutput ()
  84. {
  85. Logging.Information ($"Creating {nameof (WindowsOutput)}");
  86. if (!RuntimeInformation.IsOSPlatform (OSPlatform.Windows))
  87. {
  88. return;
  89. }
  90. // Get the standard output handle which is the current screen buffer.
  91. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  92. GetConsoleMode (_outputHandle, out uint mode);
  93. IsLegacyConsole = (mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) == 0;
  94. if (IsLegacyConsole)
  95. {
  96. CreateScreenBuffer ();
  97. if (!GetConsoleMode (_screenBuffer, out mode))
  98. {
  99. throw new ApplicationException ($"Failed to get screenBuffer console mode, error code: {Marshal.GetLastWin32Error ()}.");
  100. }
  101. const uint ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002;
  102. mode &= ~ENABLE_WRAP_AT_EOL_OUTPUT; // Disable wrap
  103. if (!SetConsoleMode (_screenBuffer, mode))
  104. {
  105. throw new ApplicationException ($"Failed to set screenBuffer console mode, error code: {Marshal.GetLastWin32Error ()}.");
  106. }
  107. }
  108. else
  109. {
  110. if (Environment.GetEnvironmentVariable ("VSAPPIDNAME") is null)
  111. {
  112. //Enable alternative screen buffer.
  113. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  114. }
  115. else
  116. {
  117. _foreground = Console.ForegroundColor;
  118. _background = Console.BackgroundColor;
  119. }
  120. }
  121. GetSize ();
  122. }
  123. private void CreateScreenBuffer ()
  124. {
  125. _screenBuffer = CreateConsoleScreenBuffer (
  126. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  127. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  128. nint.Zero,
  129. 1,
  130. nint.Zero
  131. );
  132. if (_screenBuffer == INVALID_HANDLE_VALUE)
  133. {
  134. int err = Marshal.GetLastWin32Error ();
  135. if (err != 0)
  136. {
  137. throw new Win32Exception (err);
  138. }
  139. }
  140. if (!SetConsoleActiveScreenBuffer (_screenBuffer))
  141. {
  142. throw new Win32Exception (Marshal.GetLastWin32Error ());
  143. }
  144. }
  145. public void Write (ReadOnlySpan<char> str)
  146. {
  147. if (!RuntimeInformation.IsOSPlatform (OSPlatform.Windows))
  148. {
  149. return;
  150. }
  151. if (!WriteConsole (!IsLegacyConsole ? _outputHandle : _screenBuffer, str, (uint)str.Length, out uint _, nint.Zero))
  152. {
  153. // Don't throw in unit tests
  154. // throw new Win32Exception (Marshal.GetLastWin32Error (), "Failed to write to console screen buffer.");
  155. }
  156. }
  157. public Size ResizeBuffer (Size size)
  158. {
  159. Size newSize = size;
  160. try
  161. {
  162. newSize = SetConsoleWindow ((short)Math.Max (size.Width, 0), (short)Math.Max (size.Height, 0));
  163. }
  164. catch
  165. {
  166. // Do nothing; unit tests
  167. }
  168. return newSize;
  169. }
  170. internal Size SetConsoleWindow (short cols, short rows)
  171. {
  172. if (!RuntimeInformation.IsOSPlatform (OSPlatform.Windows))
  173. {
  174. return new (cols, rows);
  175. }
  176. var csbi = new WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX ();
  177. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  178. if (!GetConsoleScreenBufferInfoEx (!IsLegacyConsole ? _outputHandle : _screenBuffer, ref csbi))
  179. {
  180. throw new Win32Exception (Marshal.GetLastWin32Error ());
  181. }
  182. WindowsConsole.Coord maxWinSize = GetLargestConsoleWindowSize (!IsLegacyConsole ? _outputHandle : _screenBuffer);
  183. short newCols = Math.Min (cols, maxWinSize.X);
  184. short newRows = Math.Min (rows, maxWinSize.Y);
  185. csbi.dwSize = new (newCols, Math.Max (newRows, (short)1));
  186. csbi.srWindow = new (0, 0, newCols, newRows);
  187. csbi.dwMaximumWindowSize = new (newCols, newRows);
  188. if (!SetConsoleScreenBufferInfoEx (!IsLegacyConsole ? _outputHandle : _screenBuffer, ref csbi))
  189. {
  190. throw new Win32Exception (Marshal.GetLastWin32Error ());
  191. }
  192. var winRect = new WindowsConsole.SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  193. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  194. {
  195. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  196. return new (cols, rows);
  197. }
  198. SetConsoleOutputWindow (csbi);
  199. return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  200. }
  201. private void SetConsoleOutputWindow (WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  202. {
  203. if ((!IsLegacyConsole
  204. ? _outputHandle
  205. : _screenBuffer)
  206. != nint.Zero
  207. && !SetConsoleScreenBufferInfoEx (!IsLegacyConsole ? _outputHandle : _screenBuffer, ref csbi))
  208. {
  209. throw new Win32Exception (Marshal.GetLastWin32Error ());
  210. }
  211. }
  212. public override void Write (IOutputBuffer outputBuffer)
  213. {
  214. _everythingStringBuilder.Clear ();
  215. // for 16 color mode we will write to a backing buffer, then flip it to the active one at the end to avoid jitter.
  216. _consoleBuffer = 0;
  217. if (Force16Colors)
  218. {
  219. _consoleBuffer = !IsLegacyConsole ? _outputHandle : _screenBuffer;
  220. }
  221. else
  222. {
  223. _consoleBuffer = _outputHandle;
  224. }
  225. try
  226. {
  227. base.Write (outputBuffer);
  228. ReadOnlySpan<char> span = _everythingStringBuilder.ToString ().AsSpan (); // still allocates the string
  229. bool result = WriteConsole (_consoleBuffer, span, (uint)span.Length, out _, nint.Zero);
  230. if (!result)
  231. {
  232. int err = Marshal.GetLastWin32Error ();
  233. if (err == 1)
  234. {
  235. Logging.Error ($"Error: {Marshal.GetLastWin32Error ()} in {nameof (WindowsOutput)}");
  236. return;
  237. }
  238. if (err != 0)
  239. {
  240. throw new Win32Exception (err);
  241. }
  242. }
  243. }
  244. catch (DllNotFoundException)
  245. {
  246. // Running unit tests or in an environment where writing is not possible.
  247. }
  248. catch (Exception e)
  249. {
  250. Logging.Error ($"Error: {e.Message} in {nameof (WindowsOutput)}");
  251. if (RuntimeInformation.IsOSPlatform (OSPlatform.Windows))
  252. {
  253. throw;
  254. }
  255. }
  256. }
  257. /// <inheritdoc/>
  258. protected override void Write (StringBuilder output)
  259. {
  260. if (output.Length == 0)
  261. {
  262. return;
  263. }
  264. base.Write (output);
  265. var str = output.ToString ();
  266. if (Force16Colors && IsLegacyConsole)
  267. {
  268. char [] a = str.ToCharArray ();
  269. WriteConsole (_screenBuffer, a, (uint)a.Length, out _, nint.Zero);
  270. }
  271. else
  272. {
  273. _everythingStringBuilder.Append (str);
  274. }
  275. }
  276. /// <inheritdoc/>
  277. protected override void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle)
  278. {
  279. if (Force16Colors)
  280. {
  281. if (IsLegacyConsole)
  282. {
  283. Write (output);
  284. output.Clear ();
  285. var as16ColorInt = (ushort)((int)attr.Foreground.GetClosestNamedColor16 () | ((int)attr.Background.GetClosestNamedColor16 () << 4));
  286. SetConsoleTextAttribute (_screenBuffer, as16ColorInt);
  287. }
  288. else
  289. {
  290. output.Append (EscSeqUtils.CSI_SetForegroundColor (attr.Foreground.GetAnsiColorCode ()));
  291. output.Append (EscSeqUtils.CSI_SetBackgroundColor (attr.Background.GetAnsiColorCode ()));
  292. EscSeqUtils.CSI_AppendTextStyleChange (output, redrawTextStyle, attr.Style);
  293. }
  294. }
  295. else
  296. {
  297. EscSeqUtils.CSI_AppendForegroundColorRGB (output, attr.Foreground.R, attr.Foreground.G, attr.Foreground.B);
  298. EscSeqUtils.CSI_AppendBackgroundColorRGB (output, attr.Background.R, attr.Background.G, attr.Background.B);
  299. EscSeqUtils.CSI_AppendTextStyleChange (output, redrawTextStyle, attr.Style);
  300. }
  301. }
  302. private Size? _lastSize;
  303. private Size? _lastWindowSizeBeforeMaximized;
  304. private bool _lockResize;
  305. public Size GetSize ()
  306. {
  307. if (_lockResize)
  308. {
  309. return _lastSize!.Value;
  310. }
  311. Size newSize = GetWindowSize (out _);
  312. Size largestWindowSize = GetLargestConsoleWindowSize ();
  313. if (_lastWindowSizeBeforeMaximized is null && newSize == largestWindowSize)
  314. {
  315. _lastWindowSizeBeforeMaximized = _lastSize;
  316. }
  317. else if (_lastWindowSizeBeforeMaximized is { } && newSize != largestWindowSize)
  318. {
  319. if (newSize != _lastWindowSizeBeforeMaximized)
  320. {
  321. newSize = _lastWindowSizeBeforeMaximized.Value;
  322. }
  323. _lastWindowSizeBeforeMaximized = null;
  324. }
  325. if (_lastSize == null || _lastSize != newSize)
  326. {
  327. // User is resizing the screen, they can only ever resize the active
  328. // buffer since. We now however have issue because background offscreen
  329. // buffer will be wrong size, recreate it to ensure it doesn't result in
  330. // differing active and back buffer sizes (which causes flickering of window size)
  331. Size? bufSize = null;
  332. while (bufSize != newSize)
  333. {
  334. _lockResize = true;
  335. bufSize = ResizeBuffer (newSize);
  336. }
  337. _lockResize = false;
  338. _lastSize = newSize;
  339. }
  340. return newSize;
  341. }
  342. public Size GetWindowSize (out WindowsConsole.Coord cursorPosition)
  343. {
  344. try
  345. {
  346. var csbi = new WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX ();
  347. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  348. if (!GetConsoleScreenBufferInfoEx (!IsLegacyConsole ? _outputHandle : _screenBuffer, ref csbi))
  349. {
  350. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  351. cursorPosition = default (WindowsConsole.Coord);
  352. return Size.Empty;
  353. }
  354. Size sz = new (
  355. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  356. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  357. cursorPosition = csbi.dwCursorPosition;
  358. return sz;
  359. }
  360. catch
  361. {
  362. cursorPosition = default (WindowsConsole.Coord);
  363. }
  364. return new (80, 25);
  365. }
  366. private Size GetLargestConsoleWindowSize ()
  367. {
  368. WindowsConsole.Coord maxWinSize;
  369. try
  370. {
  371. maxWinSize = GetLargestConsoleWindowSize (!IsLegacyConsole ? _outputHandle : _screenBuffer);
  372. }
  373. catch
  374. {
  375. maxWinSize = new (80, 25);
  376. }
  377. return new (maxWinSize.X, maxWinSize.Y);
  378. }
  379. /// <inheritdoc/>
  380. protected override bool SetCursorPositionImpl (int screenPositionX, int screenPositionY)
  381. {
  382. if (Force16Colors && IsLegacyConsole)
  383. {
  384. SetConsoleCursorPosition (_screenBuffer, new ((short)screenPositionX, (short)screenPositionY));
  385. }
  386. else
  387. {
  388. // CSI codes are 1 indexed
  389. _everythingStringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  390. EscSeqUtils.CSI_AppendCursorPosition (_everythingStringBuilder, screenPositionY + 1, screenPositionX + 1);
  391. }
  392. _lastCursorPosition = new (screenPositionX, screenPositionY);
  393. return true;
  394. }
  395. /// <inheritdoc cref="IOutput.SetCursorVisibility"/>
  396. public override void SetCursorVisibility (CursorVisibility visibility)
  397. {
  398. if (!RuntimeInformation.IsOSPlatform (OSPlatform.Windows))
  399. {
  400. return;
  401. }
  402. if (IsLegacyConsole)
  403. {
  404. var info = new WindowsConsole.ConsoleCursorInfo
  405. {
  406. dwSize = (uint)visibility & 0x00FF,
  407. bVisible = ((uint)visibility & 0xFF00) != 0
  408. };
  409. SetConsoleCursorInfo (_screenBuffer, ref info);
  410. }
  411. else
  412. {
  413. string cursorVisibilitySequence = visibility != CursorVisibility.Invisible
  414. ? EscSeqUtils.CSI_ShowCursor
  415. : EscSeqUtils.CSI_HideCursor;
  416. Write (cursorVisibilitySequence);
  417. }
  418. }
  419. /// <inheritdoc/>
  420. public Point GetCursorPosition () { return _lastCursorPosition ?? Point.Empty; }
  421. private Point? _lastCursorPosition;
  422. /// <inheritdoc/>
  423. public void SetCursorPosition (int col, int row)
  424. {
  425. if (_lastCursorPosition is { } && _lastCursorPosition.Value.X == col && _lastCursorPosition.Value.Y == row)
  426. {
  427. return;
  428. }
  429. _lastCursorPosition = new (col, row);
  430. if (IsLegacyConsole)
  431. {
  432. SetConsoleCursorPosition (_screenBuffer, new ((short)col, (short)row));
  433. }
  434. else
  435. {
  436. var sb = new StringBuilder ();
  437. EscSeqUtils.CSI_AppendCursorPosition (sb, row + 1, col + 1);
  438. Write (sb.ToString ());
  439. }
  440. }
  441. /// <inheritdoc/>
  442. public void SetSize (int width, int height)
  443. {
  444. // Do Nothing.
  445. }
  446. private bool _isDisposed;
  447. private nint _consoleBuffer;
  448. private readonly StringBuilder _everythingStringBuilder = new ();
  449. /// <inheritdoc/>
  450. public void Dispose ()
  451. {
  452. if (_isDisposed)
  453. {
  454. return;
  455. }
  456. if (IsLegacyConsole)
  457. {
  458. if (_screenBuffer != nint.Zero)
  459. {
  460. CloseHandle (_screenBuffer);
  461. }
  462. _screenBuffer = nint.Zero;
  463. }
  464. else
  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. _isDisposed = true;
  480. }
  481. }