2
0

OutputBase.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. }
  108. }
  109. // Flush buffered output for row
  110. if (outputStringBuilder.Length > 0)
  111. {
  112. if (IsLegacyConsole)
  113. {
  114. Write (outputStringBuilder);
  115. }
  116. else
  117. {
  118. SetCursorPositionImpl (lastCol, row);
  119. // Wrap URLs with OSC 8 hyperlink sequences
  120. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (outputStringBuilder);
  121. Write (processed);
  122. }
  123. }
  124. }
  125. if (IsLegacyConsole)
  126. {
  127. return;
  128. }
  129. // Render queued sixel images
  130. foreach (SixelToRender s in GetSixels ())
  131. {
  132. if (string.IsNullOrWhiteSpace (s.SixelData))
  133. {
  134. continue;
  135. }
  136. SetCursorPositionImpl (s.ScreenPosition.X, s.ScreenPosition.Y);
  137. Write ((StringBuilder)new (s.SixelData));
  138. }
  139. // Cursor visibility restored by ApplicationMainLoop.SetCursor() to prevent flicker
  140. }
  141. /// <inheritdoc cref="IOutput.GetLastOutput" />
  142. public virtual string GetLastOutput () => _lastOutputStringBuilder.ToString ();
  143. /// <summary>
  144. /// Changes the color and text style of the console to the given <paramref name="attr"/> and
  145. /// <paramref name="redrawTextStyle"/>.
  146. /// If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to
  147. /// <paramref name="output"/>
  148. /// otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
  149. /// </summary>
  150. /// <param name="output"></param>
  151. /// <param name="attr"></param>
  152. /// <param name="redrawTextStyle"></param>
  153. protected abstract void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle);
  154. /// <summary>
  155. /// When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
  156. /// </summary>
  157. /// <param name="screenPositionX">Column to move cursor to</param>
  158. /// <param name="screenPositionY">Row to move cursor to</param>
  159. /// <returns></returns>
  160. protected abstract bool SetCursorPositionImpl (int screenPositionX, int screenPositionY);
  161. /// <summary>
  162. /// Output the contents of the <paramref name="output"/> to the console.
  163. /// </summary>
  164. /// <param name="output"></param>
  165. protected virtual void Write (StringBuilder output)
  166. {
  167. _lastOutputStringBuilder.Append (output);
  168. }
  169. /// <summary>
  170. /// Builds ANSI escape sequences for the specified rectangular region of the buffer.
  171. /// </summary>
  172. /// <param name="buffer">The output buffer to build ANSI for.</param>
  173. /// <param name="startRow">The starting row (inclusive).</param>
  174. /// <param name="endRow">The ending row (exclusive).</param>
  175. /// <param name="startCol">The starting column (inclusive).</param>
  176. /// <param name="endCol">The ending column (exclusive).</param>
  177. /// <param name="output">The StringBuilder to append ANSI sequences to.</param>
  178. /// <param name="lastAttr">The last attribute used, for optimization.</param>
  179. /// <param name="includeCellPredicate">Predicate to determine which cells to include. If null, includes all cells.</param>
  180. /// <param name="addNewlines">Whether to add newlines between rows.</param>
  181. protected void BuildAnsiForRegion (
  182. IOutputBuffer buffer,
  183. int startRow,
  184. int endRow,
  185. int startCol,
  186. int endCol,
  187. StringBuilder output,
  188. ref Attribute? lastAttr,
  189. Func<int, int, bool>? includeCellPredicate = null,
  190. bool addNewlines = true
  191. )
  192. {
  193. TextStyle redrawTextStyle = TextStyle.None;
  194. for (int row = startRow; row < endRow; row++)
  195. {
  196. for (int col = startCol; col < endCol; col++)
  197. {
  198. if (includeCellPredicate != null && !includeCellPredicate (row, col))
  199. {
  200. continue;
  201. }
  202. Cell cell = buffer.Contents! [row, col];
  203. int outputWidth = -1;
  204. AppendCellAnsi (cell, output, ref lastAttr, ref redrawTextStyle, endCol, ref col, ref outputWidth);
  205. }
  206. // Add newline at end of row if requested
  207. if (addNewlines)
  208. {
  209. output.AppendLine ();
  210. }
  211. }
  212. }
  213. /// <summary>
  214. /// Appends ANSI sequences for a single cell to the output.
  215. /// </summary>
  216. /// <param name="cell">The cell to append ANSI for.</param>
  217. /// <param name="output">The StringBuilder to append to.</param>
  218. /// <param name="lastAttr">The last attribute used, updated if the cell's attribute is different.</param>
  219. /// <param name="redrawTextStyle">The current text style for optimization.</param>
  220. /// <param name="maxCol">The maximum column, used for wide character handling.</param>
  221. /// <param name="currentCol">The current column, updated for wide characters.</param>
  222. /// <param name="outputWidth">The current output width, updated for wide characters.</param>
  223. protected void AppendCellAnsi (Cell cell, StringBuilder output, ref Attribute? lastAttr, ref TextStyle redrawTextStyle, int maxCol, ref int currentCol, ref int outputWidth)
  224. {
  225. Attribute? attribute = cell.Attribute;
  226. // Add ANSI escape sequence for attribute change
  227. if (attribute.HasValue && attribute.Value != lastAttr)
  228. {
  229. lastAttr = attribute.Value;
  230. AppendOrWriteAttribute (output, attribute.Value, redrawTextStyle);
  231. redrawTextStyle = attribute.Value.Style;
  232. }
  233. // Add the grapheme
  234. string grapheme = cell.Grapheme;
  235. output.Append (grapheme);
  236. outputWidth++;
  237. // Handle wide grapheme
  238. if (grapheme.GetColumns () > 1 && currentCol + 1 < maxCol)
  239. {
  240. currentCol++; // Skip next cell for wide character
  241. outputWidth++;
  242. }
  243. }
  244. /// <summary>
  245. /// Generates an ANSI escape sequence string representation of the given <paramref name="buffer"/> contents.
  246. /// This is the same output that would be written to the terminal to recreate the current screen contents.
  247. /// </summary>
  248. /// <param name="buffer">The output buffer to convert to ANSI.</param>
  249. /// <returns>A string containing ANSI escape sequences representing the buffer contents.</returns>
  250. public string ToAnsi (IOutputBuffer buffer)
  251. {
  252. StringBuilder output = new ();
  253. Attribute? lastAttr = null;
  254. BuildAnsiForRegion (buffer, 0, buffer.Rows, 0, buffer.Cols, output, ref lastAttr);
  255. return output.ToString ();
  256. }
  257. /// <summary>
  258. /// Writes buffered output to console, wrapping URLs with OSC 8 hyperlinks (non-legacy only),
  259. /// then clears the buffer and advances <paramref name="lastCol"/> by <paramref name="outputWidth"/>.
  260. /// </summary>
  261. private void WriteToConsole (StringBuilder output, ref int lastCol, ref int outputWidth)
  262. {
  263. if (IsLegacyConsole)
  264. {
  265. Write (output);
  266. }
  267. else
  268. {
  269. // Wrap URLs with OSC 8 hyperlink sequences
  270. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
  271. Write (processed);
  272. }
  273. output.Clear ();
  274. lastCol += outputWidth;
  275. outputWidth = 0;
  276. }
  277. }