NetOutput.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. using Microsoft.Extensions.Logging;
  2. namespace Terminal.Gui.Drivers;
  3. /// <summary>
  4. /// Implementation of <see cref="IConsoleOutput"/> that uses native dotnet
  5. /// methods e.g. <see cref="System.Console"/>
  6. /// </summary>
  7. public class NetOutput : IConsoleOutput
  8. {
  9. private readonly bool _isWinPlatform;
  10. private CursorVisibility? _cachedCursorVisibility;
  11. // Last text style used, for updating style with EscSeqUtils.CSI_AppendTextStyleChange().
  12. private TextStyle _redrawTextStyle = TextStyle.None;
  13. /// <summary>
  14. /// Creates a new instance of the <see cref="NetOutput"/> class.
  15. /// </summary>
  16. public NetOutput ()
  17. {
  18. Logging.Logger.LogInformation ($"Creating {nameof (NetOutput)}");
  19. Console.OutputEncoding = Encoding.UTF8;
  20. PlatformID p = Environment.OSVersion.Platform;
  21. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  22. {
  23. _isWinPlatform = true;
  24. }
  25. //Enable alternative screen buffer.
  26. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  27. //Set cursor key to application.
  28. Console.Out.Write (EscSeqUtils.CSI_HideCursor);
  29. }
  30. /// <inheritdoc/>
  31. public void Write (ReadOnlySpan<char> text)
  32. {
  33. Console.Out.Write (text);
  34. }
  35. /// <inheritdoc/>
  36. public void Write (IOutputBuffer buffer)
  37. {
  38. if (ConsoleDriver.RunningUnitTests)
  39. {
  40. return;
  41. }
  42. if (Console.WindowHeight < 1
  43. || buffer.Contents.Length != buffer.Rows * buffer.Cols
  44. || buffer.Rows != Console.WindowHeight)
  45. {
  46. // return;
  47. }
  48. var top = 0;
  49. var left = 0;
  50. int rows = buffer.Rows;
  51. int cols = buffer.Cols;
  52. var output = new StringBuilder ();
  53. Attribute? redrawAttr = null;
  54. int lastCol = -1;
  55. CursorVisibility? savedVisibility = _cachedCursorVisibility;
  56. SetCursorVisibility (CursorVisibility.Invisible);
  57. const int maxCharsPerRune = 2;
  58. Span<char> runeBuffer = stackalloc char[maxCharsPerRune];
  59. for (int row = top; row < rows; row++)
  60. {
  61. if (Console.WindowHeight < 1)
  62. {
  63. return;
  64. }
  65. if (!buffer.DirtyLines [row])
  66. {
  67. continue;
  68. }
  69. if (!SetCursorPositionImpl (0, row))
  70. {
  71. return;
  72. }
  73. buffer.DirtyLines [row] = false;
  74. output.Clear ();
  75. for (int col = left; col < cols; col++)
  76. {
  77. lastCol = -1;
  78. var outputWidth = 0;
  79. for (; col < cols; col++)
  80. {
  81. if (!buffer.Contents [row, col].IsDirty)
  82. {
  83. if (output.Length > 0)
  84. {
  85. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  86. }
  87. else if (lastCol == -1)
  88. {
  89. lastCol = col;
  90. }
  91. if (lastCol + 1 < cols)
  92. {
  93. lastCol++;
  94. }
  95. continue;
  96. }
  97. if (lastCol == -1)
  98. {
  99. lastCol = col;
  100. }
  101. Attribute attr = buffer.Contents [row, col].Attribute.Value;
  102. // Performance: Only send the escape sequence if the attribute has changed.
  103. if (attr != redrawAttr)
  104. {
  105. redrawAttr = attr;
  106. EscSeqUtils.CSI_AppendForegroundColorRGB (
  107. output,
  108. attr.Foreground.R,
  109. attr.Foreground.G,
  110. attr.Foreground.B
  111. );
  112. EscSeqUtils.CSI_AppendBackgroundColorRGB (
  113. output,
  114. attr.Background.R,
  115. attr.Background.G,
  116. attr.Background.B
  117. );
  118. EscSeqUtils.CSI_AppendTextStyleChange (output, _redrawTextStyle, attr.Style);
  119. _redrawTextStyle = attr.Style;
  120. }
  121. outputWidth++;
  122. // Avoid Rune.ToString() by appending the rune chars.
  123. Rune rune = buffer.Contents [row, col].Rune;
  124. int runeCharsWritten = rune.EncodeToUtf16 (runeBuffer);
  125. ReadOnlySpan<char> runeChars = runeBuffer[..runeCharsWritten];
  126. output.Append (runeChars);
  127. if (buffer.Contents [row, col].CombiningMarks.Count > 0)
  128. {
  129. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  130. // compatible with the driver architecture. Any CMs (except in the first col)
  131. // are correctly combined with the base char, but are ALSO treated as 1 column
  132. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  133. //
  134. // For now, we just ignore the list of CMs.
  135. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  136. // output.Append (combMark);
  137. //}
  138. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  139. }
  140. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  141. {
  142. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  143. SetCursorPositionImpl (col - 1, row);
  144. }
  145. buffer.Contents [row, col].IsDirty = false;
  146. }
  147. }
  148. if (output.Length > 0)
  149. {
  150. SetCursorPositionImpl (lastCol, row);
  151. Console.Out.Write (output);
  152. }
  153. }
  154. foreach (SixelToRender s in Application.Sixel)
  155. {
  156. if (!string.IsNullOrWhiteSpace (s.SixelData))
  157. {
  158. SetCursorPositionImpl (s.ScreenPosition.X, s.ScreenPosition.Y);
  159. Console.Out.Write (s.SixelData);
  160. }
  161. }
  162. SetCursorVisibility (savedVisibility ?? CursorVisibility.Default);
  163. _cachedCursorVisibility = savedVisibility;
  164. }
  165. /// <inheritdoc/>
  166. public Size GetWindowSize ()
  167. {
  168. if (ConsoleDriver.RunningUnitTests)
  169. {
  170. // For unit tests, we return a default size.
  171. return Size.Empty;
  172. }
  173. return new (Console.WindowWidth, Console.WindowHeight);
  174. }
  175. private void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  176. {
  177. SetCursorPositionImpl (lastCol, row);
  178. Console.Out.Write (output);
  179. output.Clear ();
  180. lastCol += outputWidth;
  181. outputWidth = 0;
  182. }
  183. /// <inheritdoc/>
  184. public void SetCursorPosition (int col, int row) { SetCursorPositionImpl (col, row); }
  185. private Point _lastCursorPosition;
  186. private bool SetCursorPositionImpl (int col, int row)
  187. {
  188. if (_lastCursorPosition.X == col && _lastCursorPosition.Y == row)
  189. {
  190. return true;
  191. }
  192. _lastCursorPosition = new (col, row);
  193. if (_isWinPlatform)
  194. {
  195. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  196. try
  197. {
  198. Console.SetCursorPosition (col, row);
  199. return true;
  200. }
  201. catch (Exception)
  202. {
  203. return false;
  204. }
  205. }
  206. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  207. // Console.CursorTop/CursorLeft isn't reliable.
  208. EscSeqUtils.CSI_WriteCursorPosition (Console.Out, row + 1, col + 1);
  209. return true;
  210. }
  211. /// <inheritdoc/>
  212. public void Dispose ()
  213. {
  214. Console.ResetColor ();
  215. //Disable alternative screen buffer.
  216. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  217. //Set cursor key to cursor.
  218. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  219. Console.Out.Close ();
  220. }
  221. /// <inheritdoc/>
  222. public void SetCursorVisibility (CursorVisibility visibility)
  223. {
  224. Console.Out.Write (visibility == CursorVisibility.Default ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  225. }
  226. }