WindowsOutput.cs 12 KB

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