WindowsOutput.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. #nullable enable
  2. using System.Buffers;
  3. using System.ComponentModel;
  4. using System.Runtime.InteropServices;
  5. using Microsoft.Extensions.Logging;
  6. using static Terminal.Gui.Drivers.WindowsConsole;
  7. namespace Terminal.Gui.Drivers;
  8. internal partial class WindowsOutput : IConsoleOutput
  9. {
  10. [LibraryImport ("kernel32.dll", EntryPoint = "WriteConsoleW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
  11. [return: MarshalAs (UnmanagedType.Bool)]
  12. private static partial bool WriteConsole (
  13. nint hConsoleOutput,
  14. ReadOnlySpan<char> lpbufer,
  15. uint numberOfCharsToWriten,
  16. out uint lpNumberOfCharsWritten,
  17. nint lpReserved
  18. );
  19. [DllImport ("kernel32.dll", SetLastError = true)]
  20. private static extern bool CloseHandle (nint handle);
  21. [DllImport ("kernel32.dll", SetLastError = true)]
  22. private static extern nint CreateConsoleScreenBuffer (
  23. DesiredAccess dwDesiredAccess,
  24. ShareMode dwShareMode,
  25. nint secutiryAttributes,
  26. uint flags,
  27. nint screenBufferData
  28. );
  29. [DllImport ("kernel32.dll", SetLastError = true)]
  30. private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  31. [Flags]
  32. private enum ShareMode : uint
  33. {
  34. FileShareRead = 1,
  35. FileShareWrite = 2
  36. }
  37. [Flags]
  38. private enum DesiredAccess : uint
  39. {
  40. GenericRead = 2147483648,
  41. GenericWrite = 1073741824
  42. }
  43. internal static nint INVALID_HANDLE_VALUE = new (-1);
  44. [DllImport ("kernel32.dll", SetLastError = true)]
  45. private static extern bool SetConsoleActiveScreenBuffer (nint handle);
  46. [DllImport ("kernel32.dll")]
  47. private static extern bool SetConsoleCursorPosition (nint hConsoleOutput, WindowsConsole.Coord dwCursorPosition);
  48. [DllImport ("kernel32.dll", SetLastError = true)]
  49. private static extern bool SetConsoleCursorInfo (nint hConsoleOutput, [In] ref WindowsConsole.ConsoleCursorInfo lpConsoleCursorInfo);
  50. private readonly nint _screenBuffer;
  51. // Last text style used, for updating style with EscSeqUtils.CSI_AppendTextStyleChange().
  52. private TextStyle _redrawTextStyle = TextStyle.None;
  53. public WindowsOutput ()
  54. {
  55. Logging.Logger.LogInformation ($"Creating {nameof (WindowsOutput)}");
  56. if (ConsoleDriver.RunningUnitTests)
  57. {
  58. return;
  59. }
  60. _screenBuffer = CreateConsoleScreenBuffer (
  61. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  62. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  63. nint.Zero,
  64. 1,
  65. nint.Zero
  66. );
  67. if (_screenBuffer == INVALID_HANDLE_VALUE)
  68. {
  69. int err = Marshal.GetLastWin32Error ();
  70. if (err != 0)
  71. {
  72. throw new Win32Exception (err);
  73. }
  74. }
  75. if (!SetConsoleActiveScreenBuffer (_screenBuffer))
  76. {
  77. throw new Win32Exception (Marshal.GetLastWin32Error ());
  78. }
  79. }
  80. public void Write (ReadOnlySpan<char> str)
  81. {
  82. if (!WriteConsole (_screenBuffer, str, (uint)str.Length, out uint _, nint.Zero))
  83. {
  84. throw new Win32Exception (Marshal.GetLastWin32Error (), "Failed to write to console screen buffer.");
  85. }
  86. }
  87. public void Write (IOutputBuffer buffer)
  88. {
  89. WindowsConsole.ExtendedCharInfo [] outputBuffer = new WindowsConsole.ExtendedCharInfo [buffer.Rows * buffer.Cols];
  90. // TODO: probably do need this right?
  91. /*
  92. if (!windowSize.IsEmpty && (windowSize.Width != buffer.Cols || windowSize.Height != buffer.Rows))
  93. {
  94. return;
  95. }*/
  96. var bufferCoords = new WindowsConsole.Coord
  97. {
  98. X = (short)buffer.Cols, //Clip.Width,
  99. Y = (short)buffer.Rows //Clip.Height
  100. };
  101. for (var row = 0; row < buffer.Rows; row++)
  102. {
  103. if (!buffer.DirtyLines [row])
  104. {
  105. continue;
  106. }
  107. buffer.DirtyLines [row] = false;
  108. for (var col = 0; col < buffer.Cols; col++)
  109. {
  110. int position = row * buffer.Cols + col;
  111. outputBuffer [position].Attribute = buffer.Contents [row, col].Attribute.GetValueOrDefault ();
  112. if (buffer.Contents [row, col].IsDirty == false)
  113. {
  114. outputBuffer [position].Empty = true;
  115. outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  116. continue;
  117. }
  118. outputBuffer [position].Empty = false;
  119. if (buffer.Contents [row, col].Rune.IsBmp)
  120. {
  121. outputBuffer [position].Char = (char)buffer.Contents [row, col].Rune.Value;
  122. }
  123. else
  124. {
  125. //outputBuffer [position].Empty = true;
  126. outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  127. if (buffer.Contents [row, col].Rune.GetColumns () > 1 && col + 1 < buffer.Cols)
  128. {
  129. // TODO: This is a hack to deal with non-BMP and wide characters.
  130. col++;
  131. position = row * buffer.Cols + col;
  132. outputBuffer [position].Empty = false;
  133. outputBuffer [position].Char = ' ';
  134. }
  135. }
  136. }
  137. }
  138. var damageRegion = new WindowsConsole.SmallRect
  139. {
  140. Top = 0,
  141. Left = 0,
  142. Bottom = (short)buffer.Rows,
  143. Right = (short)buffer.Cols
  144. };
  145. //size, ExtendedCharInfo [] charInfoBuffer, Coord , SmallRect window,
  146. if (!ConsoleDriver.RunningUnitTests
  147. && !WriteToConsole (
  148. new (buffer.Cols, buffer.Rows),
  149. outputBuffer,
  150. bufferCoords,
  151. damageRegion,
  152. Application.Driver!.Force16Colors))
  153. {
  154. int err = Marshal.GetLastWin32Error ();
  155. if (err != 0)
  156. {
  157. throw new Win32Exception (err);
  158. }
  159. }
  160. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  161. }
  162. public bool WriteToConsole (Size size, WindowsConsole.ExtendedCharInfo [] charInfoBuffer, WindowsConsole.Coord bufferSize, WindowsConsole.SmallRect window, bool force16Colors)
  163. {
  164. //Debug.WriteLine ("WriteToConsole");
  165. //if (_screenBuffer == nint.Zero)
  166. //{
  167. // ReadFromConsoleOutput (size, bufferSize, ref window);
  168. //}
  169. var result = false;
  170. if (force16Colors)
  171. {
  172. var i = 0;
  173. WindowsConsole.CharInfo [] ci = new WindowsConsole.CharInfo [charInfoBuffer.Length];
  174. foreach (WindowsConsole.ExtendedCharInfo info in charInfoBuffer)
  175. {
  176. ci [i++] = new ()
  177. {
  178. Char = new () { UnicodeChar = info.Char },
  179. Attributes =
  180. (ushort)((int)info.Attribute.Foreground.GetClosestNamedColor16 () | ((int)info.Attribute.Background.GetClosestNamedColor16 () << 4))
  181. };
  182. }
  183. result = WriteConsoleOutput (_screenBuffer, ci, bufferSize, new () { X = window.Left, Y = window.Top }, ref window);
  184. }
  185. else
  186. {
  187. StringBuilder stringBuilder = new();
  188. stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  189. EscSeqUtils.CSI_AppendCursorPosition (stringBuilder, 0, 0);
  190. Attribute? prev = null;
  191. foreach (WindowsConsole.ExtendedCharInfo info in charInfoBuffer)
  192. {
  193. Attribute attr = info.Attribute;
  194. if (attr != prev)
  195. {
  196. prev = attr;
  197. EscSeqUtils.CSI_AppendForegroundColorRGB (stringBuilder, attr.Foreground.R, attr.Foreground.G, attr.Foreground.B);
  198. EscSeqUtils.CSI_AppendBackgroundColorRGB (stringBuilder, attr.Background.R, attr.Background.G, attr.Background.B);
  199. EscSeqUtils.CSI_AppendTextStyleChange (stringBuilder, _redrawTextStyle, attr.Style);
  200. _redrawTextStyle = attr.Style;
  201. }
  202. if (info.Char != '\x1b')
  203. {
  204. if (!info.Empty)
  205. {
  206. stringBuilder.Append (info.Char);
  207. }
  208. }
  209. else
  210. {
  211. stringBuilder.Append (' ');
  212. }
  213. }
  214. stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition);
  215. stringBuilder.Append (EscSeqUtils.CSI_HideCursor);
  216. // TODO: Potentially could stackalloc whenever reasonably small (<= 8 kB?) write buffer is needed.
  217. char [] rentedWriteArray = ArrayPool<char>.Shared.Rent (minimumLength: stringBuilder.Length);
  218. try
  219. {
  220. Span<char> writeBuffer = rentedWriteArray.AsSpan(0, stringBuilder.Length);
  221. stringBuilder.CopyTo (0, writeBuffer, stringBuilder.Length);
  222. // Supply console with the new content.
  223. result = WriteConsole (_screenBuffer, writeBuffer, (uint)writeBuffer.Length, out uint _, nint.Zero);
  224. }
  225. finally
  226. {
  227. ArrayPool<char>.Shared.Return (rentedWriteArray);
  228. }
  229. foreach (SixelToRender sixel in Application.Sixel)
  230. {
  231. SetCursorPosition ((short)sixel.ScreenPosition.X, (short)sixel.ScreenPosition.Y);
  232. WriteConsole (_screenBuffer, sixel.SixelData, (uint)sixel.SixelData.Length, out uint _, nint.Zero);
  233. }
  234. }
  235. if (!result)
  236. {
  237. int err = Marshal.GetLastWin32Error ();
  238. if (err != 0)
  239. {
  240. throw new Win32Exception (err);
  241. }
  242. }
  243. return result;
  244. }
  245. public Size GetWindowSize ()
  246. {
  247. var csbi = new WindowsConsole.CONSOLE_SCREEN_BUFFER_INFOEX ();
  248. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  249. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  250. {
  251. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  252. return Size.Empty;
  253. }
  254. Size sz = new (
  255. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  256. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  257. return sz;
  258. }
  259. /// <inheritdoc/>
  260. public void SetCursorVisibility (CursorVisibility visibility)
  261. {
  262. if (ConsoleDriver.RunningUnitTests)
  263. {
  264. return;
  265. }
  266. if (Application.Driver!.Force16Colors)
  267. {
  268. var info = new WindowsConsole.ConsoleCursorInfo
  269. {
  270. dwSize = (uint)visibility & 0x00FF,
  271. bVisible = ((uint)visibility & 0xFF00) != 0
  272. };
  273. SetConsoleCursorInfo (_screenBuffer, ref info);
  274. }
  275. else
  276. {
  277. string cursorVisibilitySequence = visibility != CursorVisibility.Invisible
  278. ? EscSeqUtils.CSI_ShowCursor
  279. : EscSeqUtils.CSI_HideCursor;
  280. Write (cursorVisibilitySequence);
  281. }
  282. }
  283. private Point _lastCursorPosition;
  284. /// <inheritdoc/>
  285. public void SetCursorPosition (int col, int row)
  286. {
  287. if (_lastCursorPosition.X == col && _lastCursorPosition.Y == row)
  288. {
  289. return;
  290. }
  291. _lastCursorPosition = new (col, row);
  292. SetConsoleCursorPosition (_screenBuffer, new ((short)col, (short)row));
  293. }
  294. private bool _isDisposed;
  295. /// <inheritdoc/>
  296. public void Dispose ()
  297. {
  298. if (_isDisposed)
  299. {
  300. return;
  301. }
  302. if (_screenBuffer != nint.Zero)
  303. {
  304. try
  305. {
  306. CloseHandle (_screenBuffer);
  307. }
  308. catch (Exception e)
  309. {
  310. Logging.Logger.LogError (e, "Error trying to close screen buffer handle in WindowsOutput via interop method");
  311. }
  312. }
  313. _isDisposed = true;
  314. }
  315. }