NetOutput.cs 8.1 KB

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