OutputBase.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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, row, 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. AppendCellAnsi (cell, output, ref redrawAttr, ref _redrawTextStyle, cols, ref col);
  94. outputWidth++;
  95. buffer.Contents [row, col].IsDirty = false;
  96. }
  97. }
  98. if (output.Length > 0)
  99. {
  100. if (IsLegacyConsole)
  101. {
  102. Write (output);
  103. }
  104. else
  105. {
  106. SetCursorPositionImpl (lastCol, row);
  107. // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
  108. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
  109. Write (processed);
  110. }
  111. }
  112. }
  113. if (IsLegacyConsole)
  114. {
  115. return;
  116. }
  117. foreach (SixelToRender s in GetSixels ())
  118. {
  119. if (string.IsNullOrWhiteSpace (s.SixelData))
  120. {
  121. continue;
  122. }
  123. SetCursorPositionImpl (s.ScreenPosition.X, s.ScreenPosition.Y);
  124. Write ((StringBuilder)new (s.SixelData));
  125. }
  126. // DO NOT restore cursor visibility here - let ApplicationMainLoop.SetCursor() handle it
  127. // The old code was saving/restoring visibility which caused flickering because
  128. // it would restore to the old value even if the application wanted it hidden
  129. }
  130. /// <summary>
  131. /// Changes the color and text style of the console to the given <paramref name="attr"/> and
  132. /// <paramref name="redrawTextStyle"/>.
  133. /// If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to
  134. /// <paramref name="output"/>
  135. /// otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
  136. /// </summary>
  137. /// <param name="output"></param>
  138. /// <param name="attr"></param>
  139. /// <param name="redrawTextStyle"></param>
  140. protected abstract void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle);
  141. /// <summary>
  142. /// When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
  143. /// </summary>
  144. /// <param name="screenPositionX">Column to move cursor to</param>
  145. /// <param name="screenPositionY">Row to move cursor to</param>
  146. /// <returns></returns>
  147. protected abstract bool SetCursorPositionImpl (int screenPositionX, int screenPositionY);
  148. /// <summary>
  149. /// Output the contents of the <paramref name="output"/> to the console.
  150. /// </summary>
  151. /// <param name="output"></param>
  152. protected abstract void Write (StringBuilder output);
  153. /// <summary>
  154. /// Builds ANSI escape sequences for the specified rectangular region of the buffer.
  155. /// </summary>
  156. /// <param name="buffer">The output buffer to build ANSI for.</param>
  157. /// <param name="startRow">The starting row (inclusive).</param>
  158. /// <param name="endRow">The ending row (exclusive).</param>
  159. /// <param name="startCol">The starting column (inclusive).</param>
  160. /// <param name="endCol">The ending column (exclusive).</param>
  161. /// <param name="output">The StringBuilder to append ANSI sequences to.</param>
  162. /// <param name="lastAttr">The last attribute used, for optimization.</param>
  163. /// <param name="includeCellPredicate">Predicate to determine which cells to include. If null, includes all cells.</param>
  164. /// <param name="addNewlines">Whether to add newlines between rows.</param>
  165. protected void BuildAnsiForRegion (
  166. IOutputBuffer buffer,
  167. int startRow,
  168. int endRow,
  169. int startCol,
  170. int endCol,
  171. StringBuilder output,
  172. ref Attribute? lastAttr,
  173. Func<int, int, bool>? includeCellPredicate = null,
  174. bool addNewlines = true
  175. )
  176. {
  177. TextStyle redrawTextStyle = TextStyle.None;
  178. for (int row = startRow; row < endRow; row++)
  179. {
  180. for (int col = startCol; col < endCol; col++)
  181. {
  182. if (includeCellPredicate != null && !includeCellPredicate (row, col))
  183. {
  184. continue;
  185. }
  186. Cell cell = buffer.Contents! [row, col];
  187. AppendCellAnsi (cell, output, ref lastAttr, ref redrawTextStyle, endCol, ref col);
  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. protected void AppendCellAnsi (Cell cell, StringBuilder output, ref Attribute? lastAttr, ref TextStyle redrawTextStyle, int maxCol, ref int currentCol)
  206. {
  207. Attribute? attribute = cell.Attribute;
  208. // Add ANSI escape sequence for attribute change
  209. if (attribute.HasValue && attribute.Value != lastAttr)
  210. {
  211. lastAttr = attribute.Value;
  212. AppendOrWriteAttribute (output, attribute.Value, redrawTextStyle);
  213. redrawTextStyle = attribute.Value.Style;
  214. }
  215. // Add the grapheme
  216. string grapheme = cell.Grapheme;
  217. output.Append (grapheme);
  218. // Handle wide grapheme
  219. if (grapheme.GetColumns () > 1 && currentCol + 1 < maxCol)
  220. {
  221. currentCol++; // Skip next cell for wide character
  222. }
  223. }
  224. /// <summary>
  225. /// Generates an ANSI escape sequence string representation of the given <paramref name="buffer"/> contents.
  226. /// This is the same output that would be written to the terminal to recreate the current screen contents.
  227. /// </summary>
  228. /// <param name="buffer">The output buffer to convert to ANSI.</param>
  229. /// <returns>A string containing ANSI escape sequences representing the buffer contents.</returns>
  230. public string ToAnsi (IOutputBuffer buffer)
  231. {
  232. var output = new StringBuilder ();
  233. Attribute? lastAttr = null;
  234. BuildAnsiForRegion (buffer, 0, buffer.Rows, 0, buffer.Cols, output, ref lastAttr);
  235. return output.ToString ();
  236. }
  237. private void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  238. {
  239. if (IsLegacyConsole)
  240. {
  241. Write (output);
  242. }
  243. else
  244. {
  245. // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
  246. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
  247. Write (processed);
  248. }
  249. output.Clear ();
  250. lastCol += outputWidth;
  251. outputWidth = 0;
  252. }
  253. }