OutputBase.cs 11 KB

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