WindowsOutput.cs 18 KB

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