OutputBase.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. using System.Collections.Concurrent;
  2. namespace Terminal.Gui.Drivers;
  3. /// <summary>
  4. /// Abstract base class to assist with implementing <see cref="IOutput"/>.
  5. /// </summary>
  6. public abstract class OutputBase
  7. {
  8. private bool _force16Colors;
  9. /// <inheritdoc cref="IOutput.Force16Colors"/>
  10. public bool Force16Colors
  11. {
  12. get => _force16Colors;
  13. set
  14. {
  15. if (IsLegacyConsole && !value)
  16. {
  17. return;
  18. }
  19. _force16Colors = value;
  20. }
  21. }
  22. private bool _isLegacyConsole;
  23. /// <inheritdoc cref="IOutput.IsLegacyConsole"/>
  24. public bool IsLegacyConsole
  25. {
  26. get => _isLegacyConsole;
  27. set
  28. {
  29. _isLegacyConsole = value;
  30. if (value) // If legacy console (true), force 16 colors
  31. {
  32. Force16Colors = true;
  33. }
  34. }
  35. }
  36. private readonly ConcurrentQueue<SixelToRender> _sixels = [];
  37. /// <inheritdoc cref="IOutput.GetSixels"/>>
  38. public ConcurrentQueue<SixelToRender> GetSixels () => _sixels;
  39. // Last text style used, for updating style with EscSeqUtils.CSI_AppendTextStyleChange().
  40. private TextStyle _redrawTextStyle = TextStyle.None;
  41. /// <summary>
  42. /// Changes the visibility of the cursor in the terminal to the specified <paramref name="visibility"/> e.g.
  43. /// the flashing indicator, invisible, box indicator etc.
  44. /// </summary>
  45. /// <param name="visibility"></param>
  46. public abstract void SetCursorVisibility (CursorVisibility visibility);
  47. /// <inheritdoc cref="IOutput.Write(IOutputBuffer)"/>
  48. public virtual void Write (IOutputBuffer buffer)
  49. {
  50. var top = 0;
  51. var left = 0;
  52. int rows = buffer.Rows;
  53. int cols = buffer.Cols;
  54. var output = new StringBuilder ();
  55. Attribute? redrawAttr = null;
  56. int lastCol = -1;
  57. SetCursorVisibility (CursorVisibility.Invisible);
  58. for (int row = top; row < rows; row++)
  59. {
  60. if (!SetCursorPositionImpl (0, row))
  61. {
  62. return;
  63. }
  64. output.Clear ();
  65. for (int col = left; col < cols; col++)
  66. {
  67. lastCol = -1;
  68. var outputWidth = 0;
  69. for (; col < cols; col++)
  70. {
  71. if (!buffer.Contents! [row, col].IsDirty)
  72. {
  73. if (output.Length > 0)
  74. {
  75. WriteToConsole (output, ref lastCol, ref outputWidth);
  76. }
  77. else if (lastCol == -1)
  78. {
  79. lastCol = col;
  80. }
  81. if (lastCol + 1 < cols)
  82. {
  83. lastCol++;
  84. }
  85. SetCursorPositionImpl (lastCol, row);
  86. continue;
  87. }
  88. if (lastCol == -1)
  89. {
  90. lastCol = col;
  91. }
  92. Cell cell = buffer.Contents [row, col];
  93. buffer.Contents [row, col].IsDirty = false;
  94. AppendCellAnsi (cell, output, ref redrawAttr, ref _redrawTextStyle, cols, ref col, ref outputWidth);
  95. }
  96. }
  97. if (output.Length > 0)
  98. {
  99. if (IsLegacyConsole)
  100. {
  101. Write (output);
  102. }
  103. else
  104. {
  105. SetCursorPositionImpl (lastCol, row);
  106. // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
  107. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
  108. Write (processed);
  109. }
  110. }
  111. }
  112. if (IsLegacyConsole)
  113. {
  114. return;
  115. }
  116. foreach (SixelToRender s in GetSixels ())
  117. {
  118. if (string.IsNullOrWhiteSpace (s.SixelData))
  119. {
  120. continue;
  121. }
  122. SetCursorPositionImpl (s.ScreenPosition.X, s.ScreenPosition.Y);
  123. Write ((StringBuilder)new (s.SixelData));
  124. }
  125. // DO NOT restore cursor visibility here - let ApplicationMainLoop.SetCursor() handle it
  126. // The old code was saving/restoring visibility which caused flickering because
  127. // it would restore to the old value even if the application wanted it hidden
  128. }
  129. /// <summary>
  130. /// Changes the color and text style of the console to the given <paramref name="attr"/> and
  131. /// <paramref name="redrawTextStyle"/>.
  132. /// If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to
  133. /// <paramref name="output"/>
  134. /// otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
  135. /// </summary>
  136. /// <param name="output"></param>
  137. /// <param name="attr"></param>
  138. /// <param name="redrawTextStyle"></param>
  139. protected abstract void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle);
  140. /// <summary>
  141. /// When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
  142. /// </summary>
  143. /// <param name="screenPositionX">Column to move cursor to</param>
  144. /// <param name="screenPositionY">Row to move cursor to</param>
  145. /// <returns></returns>
  146. protected abstract bool SetCursorPositionImpl (int screenPositionX, int screenPositionY);
  147. /// <summary>
  148. /// Output the contents of the <paramref name="output"/> to the console.
  149. /// </summary>
  150. /// <param name="output"></param>
  151. protected abstract void Write (StringBuilder output);
  152. /// <summary>
  153. /// Builds ANSI escape sequences for the specified rectangular region of the buffer.
  154. /// </summary>
  155. /// <param name="buffer">The output buffer to build ANSI for.</param>
  156. /// <param name="startRow">The starting row (inclusive).</param>
  157. /// <param name="endRow">The ending row (exclusive).</param>
  158. /// <param name="startCol">The starting column (inclusive).</param>
  159. /// <param name="endCol">The ending column (exclusive).</param>
  160. /// <param name="output">The StringBuilder to append ANSI sequences to.</param>
  161. /// <param name="lastAttr">The last attribute used, for optimization.</param>
  162. /// <param name="includeCellPredicate">Predicate to determine which cells to include. If null, includes all cells.</param>
  163. /// <param name="addNewlines">Whether to add newlines between rows.</param>
  164. protected void BuildAnsiForRegion (
  165. IOutputBuffer buffer,
  166. int startRow,
  167. int endRow,
  168. int startCol,
  169. int endCol,
  170. StringBuilder output,
  171. ref Attribute? lastAttr,
  172. Func<int, int, bool>? includeCellPredicate = null,
  173. bool addNewlines = true
  174. )
  175. {
  176. TextStyle redrawTextStyle = TextStyle.None;
  177. for (int row = startRow; row < endRow; row++)
  178. {
  179. for (int col = startCol; col < endCol; col++)
  180. {
  181. if (includeCellPredicate != null && !includeCellPredicate (row, col))
  182. {
  183. continue;
  184. }
  185. Cell cell = buffer.Contents! [row, col];
  186. int outputWidth = -1;
  187. AppendCellAnsi (cell, output, ref lastAttr, ref redrawTextStyle, endCol, ref col, ref outputWidth);
  188. }
  189. // Add newline at end of row if requested
  190. if (addNewlines)
  191. {
  192. output.AppendLine ();
  193. }
  194. }
  195. }
  196. /// <summary>
  197. /// Appends ANSI sequences for a single cell to the output.
  198. /// </summary>
  199. /// <param name="cell">The cell to append ANSI for.</param>
  200. /// <param name="output">The StringBuilder to append to.</param>
  201. /// <param name="lastAttr">The last attribute used, updated if the cell's attribute is different.</param>
  202. /// <param name="redrawTextStyle">The current text style for optimization.</param>
  203. /// <param name="maxCol">The maximum column, used for wide character handling.</param>
  204. /// <param name="currentCol">The current column, updated for wide characters.</param>
  205. /// <param name="outputWidth">The current output width, updated for wide characters.</param>
  206. protected void AppendCellAnsi (Cell cell, StringBuilder output, ref Attribute? lastAttr, ref TextStyle redrawTextStyle, int maxCol, ref int currentCol, ref int outputWidth)
  207. {
  208. Attribute? attribute = cell.Attribute;
  209. // Add ANSI escape sequence for attribute change
  210. if (attribute.HasValue && attribute.Value != lastAttr)
  211. {
  212. lastAttr = attribute.Value;
  213. AppendOrWriteAttribute (output, attribute.Value, redrawTextStyle);
  214. redrawTextStyle = attribute.Value.Style;
  215. }
  216. // Add the grapheme
  217. string grapheme = cell.Grapheme;
  218. output.Append (grapheme);
  219. outputWidth++;
  220. // Handle wide grapheme
  221. if (grapheme.GetColumns () > 1 && currentCol + 1 < maxCol)
  222. {
  223. currentCol++; // Skip next cell for wide character
  224. outputWidth++;
  225. }
  226. }
  227. /// <summary>
  228. /// Generates an ANSI escape sequence string representation of the given <paramref name="buffer"/> contents.
  229. /// This is the same output that would be written to the terminal to recreate the current screen contents.
  230. /// </summary>
  231. /// <param name="buffer">The output buffer to convert to ANSI.</param>
  232. /// <returns>A string containing ANSI escape sequences representing the buffer contents.</returns>
  233. public string ToAnsi (IOutputBuffer buffer)
  234. {
  235. var output = new StringBuilder ();
  236. Attribute? lastAttr = null;
  237. BuildAnsiForRegion (buffer, 0, buffer.Rows, 0, buffer.Cols, output, ref lastAttr);
  238. return output.ToString ();
  239. }
  240. private void WriteToConsole (StringBuilder output, ref int lastCol, ref int outputWidth)
  241. {
  242. if (IsLegacyConsole)
  243. {
  244. Write (output);
  245. }
  246. else
  247. {
  248. // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
  249. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
  250. Write (processed);
  251. }
  252. output.Clear ();
  253. lastCol += outputWidth;
  254. outputWidth = 0;
  255. }
  256. }