NetOutput.cs 8.4 KB

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