WindowsOutput.cs 17 KB

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