NetOutput.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 (Console.WindowHeight < 1
  39. || buffer.Contents.Length != buffer.Rows * buffer.Cols
  40. || buffer.Rows != Console.WindowHeight)
  41. {
  42. // return;
  43. }
  44. var top = 0;
  45. var left = 0;
  46. int rows = buffer.Rows;
  47. int cols = buffer.Cols;
  48. var output = new StringBuilder ();
  49. Attribute? redrawAttr = null;
  50. int lastCol = -1;
  51. CursorVisibility? savedVisibility = _cachedCursorVisibility;
  52. SetCursorVisibility (CursorVisibility.Invisible);
  53. const int maxCharsPerRune = 2;
  54. Span<char> runeBuffer = stackalloc char[maxCharsPerRune];
  55. for (int row = top; row < rows; row++)
  56. {
  57. if (Console.WindowHeight < 1)
  58. {
  59. return;
  60. }
  61. if (!buffer.DirtyLines [row])
  62. {
  63. continue;
  64. }
  65. if (!SetCursorPositionImpl (0, row))
  66. {
  67. return;
  68. }
  69. buffer.DirtyLines [row] = false;
  70. output.Clear ();
  71. for (int col = left; col < cols; col++)
  72. {
  73. lastCol = -1;
  74. var outputWidth = 0;
  75. for (; col < cols; col++)
  76. {
  77. if (!buffer.Contents [row, col].IsDirty)
  78. {
  79. if (output.Length > 0)
  80. {
  81. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  82. }
  83. else if (lastCol == -1)
  84. {
  85. lastCol = col;
  86. }
  87. if (lastCol + 1 < cols)
  88. {
  89. lastCol++;
  90. }
  91. continue;
  92. }
  93. if (lastCol == -1)
  94. {
  95. lastCol = col;
  96. }
  97. Attribute attr = buffer.Contents [row, col].Attribute.Value;
  98. // Performance: Only send the escape sequence if the attribute has changed.
  99. if (attr != redrawAttr)
  100. {
  101. redrawAttr = attr;
  102. EscSeqUtils.CSI_AppendForegroundColorRGB (
  103. output,
  104. attr.Foreground.R,
  105. attr.Foreground.G,
  106. attr.Foreground.B
  107. );
  108. EscSeqUtils.CSI_AppendBackgroundColorRGB (
  109. output,
  110. attr.Background.R,
  111. attr.Background.G,
  112. attr.Background.B
  113. );
  114. EscSeqUtils.CSI_AppendTextStyleChange (output, _redrawTextStyle, attr.Style);
  115. _redrawTextStyle = attr.Style;
  116. }
  117. outputWidth++;
  118. // Avoid Rune.ToString() by appending the rune chars.
  119. Rune rune = buffer.Contents [row, col].Rune;
  120. int runeCharsWritten = rune.EncodeToUtf16 (runeBuffer);
  121. ReadOnlySpan<char> runeChars = runeBuffer[..runeCharsWritten];
  122. output.Append (runeChars);
  123. if (buffer.Contents [row, col].CombiningMarks.Count > 0)
  124. {
  125. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  126. // compatible with the driver architecture. Any CMs (except in the first col)
  127. // are correctly combined with the base char, but are ALSO treated as 1 column
  128. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  129. //
  130. // For now, we just ignore the list of CMs.
  131. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  132. // output.Append (combMark);
  133. //}
  134. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  135. }
  136. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  137. {
  138. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  139. SetCursorPositionImpl (col - 1, row);
  140. }
  141. buffer.Contents [row, col].IsDirty = false;
  142. }
  143. }
  144. if (output.Length > 0)
  145. {
  146. SetCursorPositionImpl (lastCol, row);
  147. Console.Out.Write (output);
  148. }
  149. }
  150. foreach (SixelToRender s in Application.Sixel)
  151. {
  152. if (!string.IsNullOrWhiteSpace (s.SixelData))
  153. {
  154. SetCursorPositionImpl (s.ScreenPosition.X, s.ScreenPosition.Y);
  155. Console.Out.Write (s.SixelData);
  156. }
  157. }
  158. SetCursorVisibility (savedVisibility ?? CursorVisibility.Default);
  159. _cachedCursorVisibility = savedVisibility;
  160. }
  161. /// <inheritdoc/>
  162. public Size GetWindowSize () { return new (Console.WindowWidth, Console.WindowHeight); }
  163. private void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  164. {
  165. SetCursorPositionImpl (lastCol, row);
  166. Console.Out.Write (output);
  167. output.Clear ();
  168. lastCol += outputWidth;
  169. outputWidth = 0;
  170. }
  171. /// <inheritdoc/>
  172. public void SetCursorPosition (int col, int row) { SetCursorPositionImpl (col, row); }
  173. private Point _lastCursorPosition;
  174. private bool SetCursorPositionImpl (int col, int row)
  175. {
  176. if (_lastCursorPosition.X == col && _lastCursorPosition.Y == row)
  177. {
  178. return true;
  179. }
  180. _lastCursorPosition = new (col, row);
  181. if (_isWinPlatform)
  182. {
  183. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  184. try
  185. {
  186. Console.SetCursorPosition (col, row);
  187. return true;
  188. }
  189. catch (Exception)
  190. {
  191. return false;
  192. }
  193. }
  194. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  195. // Console.CursorTop/CursorLeft isn't reliable.
  196. EscSeqUtils.CSI_WriteCursorPosition (Console.Out, row + 1, col + 1);
  197. return true;
  198. }
  199. /// <inheritdoc/>
  200. public void Dispose ()
  201. {
  202. Console.ResetColor ();
  203. //Disable alternative screen buffer.
  204. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  205. //Set cursor key to cursor.
  206. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  207. Console.Out.Close ();
  208. }
  209. /// <inheritdoc/>
  210. public void SetCursorVisibility (CursorVisibility visibility)
  211. {
  212. Console.Out.Write (visibility == CursorVisibility.Default ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  213. }
  214. }