OutputBase.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. StringBuilder _lastOutputStringBuilder = new ();
  48. /// <summary>
  49. /// Writes dirty cells from the buffer to the console. Hides cursor, iterates rows/cols,
  50. /// skips clean cells, batches dirty cells into ANSI sequences, wraps URLs with OSC 8,
  51. /// then renders sixel images. Cursor visibility is managed by <c>ApplicationMainLoop.SetCursor()</c>.
  52. /// </summary>
  53. public virtual void Write (IOutputBuffer buffer)
  54. {
  55. StringBuilder outputStringBuilder = new ();
  56. int top = 0;
  57. int left = 0;
  58. int rows = buffer.Rows;
  59. int cols = buffer.Cols;
  60. Attribute? redrawAttr = null;
  61. int lastCol = -1;
  62. // Hide cursor during rendering to prevent flicker
  63. SetCursorVisibility (CursorVisibility.Invisible);
  64. // Process each row
  65. for (int row = top; row < rows; row++)
  66. {
  67. if (!SetCursorPositionImpl (0, row))
  68. {
  69. return;
  70. }
  71. outputStringBuilder.Clear ();
  72. // Process columns in row
  73. for (int col = left; col < cols; col++)
  74. {
  75. lastCol = -1;
  76. var outputWidth = 0;
  77. // Batch consecutive dirty cells
  78. for (; col < cols; col++)
  79. {
  80. // Skip clean cells - position cursor and continue
  81. if (!buffer.Contents! [row, col].IsDirty)
  82. {
  83. if (outputStringBuilder.Length > 0)
  84. {
  85. // This clears outputStringBuilder
  86. WriteToConsole (outputStringBuilder, ref lastCol, ref outputWidth);
  87. }
  88. else if (lastCol == -1)
  89. {
  90. lastCol = col;
  91. }
  92. if (lastCol + 1 < cols)
  93. {
  94. lastCol++;
  95. }
  96. SetCursorPositionImpl (lastCol, row);
  97. continue;
  98. }
  99. if (lastCol == -1)
  100. {
  101. lastCol = col;
  102. }
  103. // Append dirty cell as ANSI and mark clean
  104. Cell cell = buffer.Contents [row, col];
  105. buffer.Contents [row, col].IsDirty = false;
  106. AppendCellAnsi (cell, outputStringBuilder, ref redrawAttr, ref _redrawTextStyle, cols, ref col, ref outputWidth);
  107. if (col != lastCol)
  108. {
  109. // Was a wide grapheme so mark clean next cell
  110. // See https://github.com/gui-cs/Terminal.Gui/issues/4466
  111. buffer.Contents [row, col].IsDirty = false;
  112. }
  113. }
  114. }
  115. // Flush buffered output for row
  116. if (outputStringBuilder.Length > 0)
  117. {
  118. if (IsLegacyConsole)
  119. {
  120. Write (outputStringBuilder);
  121. }
  122. else
  123. {
  124. SetCursorPositionImpl (lastCol, row);
  125. // Wrap URLs with OSC 8 hyperlink sequences
  126. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (outputStringBuilder);
  127. Write (processed);
  128. }
  129. }
  130. }
  131. if (IsLegacyConsole)
  132. {
  133. return;
  134. }
  135. // Render queued sixel images
  136. foreach (SixelToRender s in GetSixels ())
  137. {
  138. if (string.IsNullOrWhiteSpace (s.SixelData))
  139. {
  140. continue;
  141. }
  142. SetCursorPositionImpl (s.ScreenPosition.X, s.ScreenPosition.Y);
  143. Write ((StringBuilder)new (s.SixelData));
  144. }
  145. // Cursor visibility restored by ApplicationMainLoop.SetCursor() to prevent flicker
  146. }
  147. /// <inheritdoc cref="IOutput.GetLastOutput" />
  148. public virtual string GetLastOutput () => _lastOutputStringBuilder.ToString ();
  149. /// <summary>
  150. /// Changes the color and text style of the console to the given <paramref name="attr"/> and
  151. /// <paramref name="redrawTextStyle"/>.
  152. /// If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to
  153. /// <paramref name="output"/>
  154. /// otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
  155. /// </summary>
  156. /// <param name="output"></param>
  157. /// <param name="attr"></param>
  158. /// <param name="redrawTextStyle"></param>
  159. protected abstract void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle);
  160. /// <summary>
  161. /// When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
  162. /// </summary>
  163. /// <param name="screenPositionX">Column to move cursor to</param>
  164. /// <param name="screenPositionY">Row to move cursor to</param>
  165. /// <returns></returns>
  166. protected abstract bool SetCursorPositionImpl (int screenPositionX, int screenPositionY);
  167. /// <summary>
  168. /// Output the contents of the <paramref name="output"/> to the console.
  169. /// </summary>
  170. /// <param name="output"></param>
  171. protected virtual void Write (StringBuilder output)
  172. {
  173. _lastOutputStringBuilder.Append (output);
  174. }
  175. /// <summary>
  176. /// Builds ANSI escape sequences for the specified rectangular region of the buffer.
  177. /// </summary>
  178. /// <param name="buffer">The output buffer to build ANSI for.</param>
  179. /// <param name="startRow">The starting row (inclusive).</param>
  180. /// <param name="endRow">The ending row (exclusive).</param>
  181. /// <param name="startCol">The starting column (inclusive).</param>
  182. /// <param name="endCol">The ending column (exclusive).</param>
  183. /// <param name="output">The StringBuilder to append ANSI sequences to.</param>
  184. /// <param name="lastAttr">The last attribute used, for optimization.</param>
  185. /// <param name="includeCellPredicate">Predicate to determine which cells to include. If null, includes all cells.</param>
  186. /// <param name="addNewlines">Whether to add newlines between rows.</param>
  187. protected void BuildAnsiForRegion (
  188. IOutputBuffer buffer,
  189. int startRow,
  190. int endRow,
  191. int startCol,
  192. int endCol,
  193. StringBuilder output,
  194. ref Attribute? lastAttr,
  195. Func<int, int, bool>? includeCellPredicate = null,
  196. bool addNewlines = true
  197. )
  198. {
  199. TextStyle redrawTextStyle = TextStyle.None;
  200. for (int row = startRow; row < endRow; row++)
  201. {
  202. for (int col = startCol; col < endCol; col++)
  203. {
  204. if (includeCellPredicate != null && !includeCellPredicate (row, col))
  205. {
  206. continue;
  207. }
  208. Cell cell = buffer.Contents! [row, col];
  209. int outputWidth = -1;
  210. AppendCellAnsi (cell, output, ref lastAttr, ref redrawTextStyle, endCol, ref col, ref outputWidth);
  211. }
  212. // Add newline at end of row if requested
  213. if (addNewlines)
  214. {
  215. output.AppendLine ();
  216. }
  217. }
  218. }
  219. /// <summary>
  220. /// Appends ANSI sequences for a single cell to the output.
  221. /// </summary>
  222. /// <param name="cell">The cell to append ANSI for.</param>
  223. /// <param name="output">The StringBuilder to append to.</param>
  224. /// <param name="lastAttr">The last attribute used, updated if the cell's attribute is different.</param>
  225. /// <param name="redrawTextStyle">The current text style for optimization.</param>
  226. /// <param name="maxCol">The maximum column, used for wide character handling.</param>
  227. /// <param name="currentCol">The current column, updated for wide characters.</param>
  228. /// <param name="outputWidth">The current output width, updated for wide characters.</param>
  229. protected void AppendCellAnsi (Cell cell, StringBuilder output, ref Attribute? lastAttr, ref TextStyle redrawTextStyle, int maxCol, ref int currentCol, ref int outputWidth)
  230. {
  231. Attribute? attribute = cell.Attribute;
  232. // Add ANSI escape sequence for attribute change
  233. if (attribute.HasValue && attribute.Value != lastAttr)
  234. {
  235. lastAttr = attribute.Value;
  236. AppendOrWriteAttribute (output, attribute.Value, redrawTextStyle);
  237. redrawTextStyle = attribute.Value.Style;
  238. }
  239. // Add the grapheme
  240. string grapheme = cell.Grapheme;
  241. output.Append (grapheme);
  242. outputWidth++;
  243. // Handle wide grapheme
  244. if (grapheme.GetColumns () > 1 && currentCol + 1 < maxCol)
  245. {
  246. currentCol++; // Skip next cell for wide character
  247. outputWidth++;
  248. }
  249. }
  250. /// <summary>
  251. /// Generates an ANSI escape sequence string representation of the given <paramref name="buffer"/> contents.
  252. /// This is the same output that would be written to the terminal to recreate the current screen contents.
  253. /// </summary>
  254. /// <param name="buffer">The output buffer to convert to ANSI.</param>
  255. /// <returns>A string containing ANSI escape sequences representing the buffer contents.</returns>
  256. public string ToAnsi (IOutputBuffer buffer)
  257. {
  258. StringBuilder output = new ();
  259. Attribute? lastAttr = null;
  260. BuildAnsiForRegion (buffer, 0, buffer.Rows, 0, buffer.Cols, output, ref lastAttr);
  261. return output.ToString ();
  262. }
  263. /// <summary>
  264. /// Writes buffered output to console, wrapping URLs with OSC 8 hyperlinks (non-legacy only),
  265. /// then clears the buffer and advances <paramref name="lastCol"/> by <paramref name="outputWidth"/>.
  266. /// </summary>
  267. private void WriteToConsole (StringBuilder output, ref int lastCol, ref int outputWidth)
  268. {
  269. if (IsLegacyConsole)
  270. {
  271. Write (output);
  272. }
  273. else
  274. {
  275. // Wrap URLs with OSC 8 hyperlink sequences
  276. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
  277. Write (processed);
  278. }
  279. output.Clear ();
  280. lastCol += outputWidth;
  281. outputWidth = 0;
  282. }
  283. }