WindowsOutput.cs 12 KB

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