WindowsOutput.cs 11 KB

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