WindowsOutput.cs 19 KB

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