WindowsOutput.cs 18 KB

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