2
0

OutputBase.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. namespace Terminal.Gui.Drivers;
  2. /// <summary>
  3. /// Abstract base class to assist with implementing <see cref="IOutput"/>.
  4. /// </summary>
  5. public abstract class OutputBase
  6. {
  7. private CursorVisibility? _cachedCursorVisibility;
  8. // Last text style used, for updating style with EscSeqUtils.CSI_AppendTextStyleChange().
  9. private TextStyle _redrawTextStyle = TextStyle.None;
  10. /// <summary>
  11. /// Changes the visibility of the cursor in the terminal to the specified <paramref name="visibility"/> e.g.
  12. /// the flashing indicator, invisible, box indicator etc.
  13. /// </summary>
  14. /// <param name="visibility"></param>
  15. public abstract void SetCursorVisibility (CursorVisibility visibility);
  16. /// <inheritdoc cref="IOutput.Write(IOutputBuffer)"/>
  17. public virtual void Write (IOutputBuffer buffer)
  18. {
  19. var top = 0;
  20. var left = 0;
  21. int rows = buffer.Rows;
  22. int cols = buffer.Cols;
  23. var output = new StringBuilder ();
  24. Attribute? redrawAttr = null;
  25. int lastCol = -1;
  26. CursorVisibility? savedVisibility = _cachedCursorVisibility;
  27. SetCursorVisibility (CursorVisibility.Invisible);
  28. for (int row = top; row < rows; row++)
  29. {
  30. if (!SetCursorPositionImpl (0, row))
  31. {
  32. return;
  33. }
  34. output.Clear ();
  35. for (int col = left; col < cols; col++)
  36. {
  37. lastCol = -1;
  38. var outputWidth = 0;
  39. for (; col < cols; col++)
  40. {
  41. if (!buffer.Contents! [row, col].IsDirty)
  42. {
  43. if (output.Length > 0)
  44. {
  45. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  46. }
  47. else if (lastCol == -1)
  48. {
  49. lastCol = col;
  50. }
  51. if (lastCol + 1 < cols)
  52. {
  53. lastCol++;
  54. }
  55. continue;
  56. }
  57. if (lastCol == -1)
  58. {
  59. lastCol = col;
  60. }
  61. Cell cell = buffer.Contents [row, col];
  62. AppendCellAnsi (cell, output, ref redrawAttr, ref _redrawTextStyle, cols, ref col);
  63. outputWidth++;
  64. // Handle special cases that AppendCellAnsi doesn't cover
  65. Rune rune = cell.Rune;
  66. if (cell.CombiningMarks.Count > 0)
  67. {
  68. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  69. // compatible with the driver architecture. Any CMs (except in the first col)
  70. // are correctly combined with the base char, but are ALSO treated as 1 column
  71. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  72. //
  73. // For now, we just ignore the list of CMs.
  74. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  75. // output.Append (combMark);
  76. }
  77. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  78. {
  79. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  80. SetCursorPositionImpl (col - 1, row);
  81. }
  82. buffer.Contents [row, col].IsDirty = false;
  83. }
  84. }
  85. if (output.Length > 0)
  86. {
  87. SetCursorPositionImpl (lastCol, row);
  88. // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
  89. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
  90. Write (processed);
  91. }
  92. }
  93. foreach (SixelToRender s in Application.Sixel)
  94. {
  95. if (!string.IsNullOrWhiteSpace (s.SixelData))
  96. {
  97. SetCursorPositionImpl (s.ScreenPosition.X, s.ScreenPosition.Y);
  98. Console.Out.Write (s.SixelData);
  99. }
  100. }
  101. SetCursorVisibility (savedVisibility ?? CursorVisibility.Default);
  102. _cachedCursorVisibility = savedVisibility;
  103. }
  104. /// <summary>
  105. /// Changes the color and text style of the console to the given <paramref name="attr"/> and
  106. /// <paramref name="redrawTextStyle"/>.
  107. /// If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to
  108. /// <paramref name="output"/>
  109. /// otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
  110. /// </summary>
  111. /// <param name="output"></param>
  112. /// <param name="attr"></param>
  113. /// <param name="redrawTextStyle"></param>
  114. protected abstract void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle);
  115. /// <summary>
  116. /// When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
  117. /// </summary>
  118. /// <param name="screenPositionX">Column to move cursor to</param>
  119. /// <param name="screenPositionY">Row to move cursor to</param>
  120. /// <returns></returns>
  121. protected abstract bool SetCursorPositionImpl (int screenPositionX, int screenPositionY);
  122. /// <summary>
  123. /// Output the contents of the <paramref name="output"/> to the console.
  124. /// </summary>
  125. /// <param name="output"></param>
  126. protected abstract void Write (StringBuilder output);
  127. /// <summary>
  128. /// Builds ANSI escape sequences for the specified rectangular region of the buffer.
  129. /// </summary>
  130. /// <param name="buffer">The output buffer to build ANSI for.</param>
  131. /// <param name="startRow">The starting row (inclusive).</param>
  132. /// <param name="endRow">The ending row (exclusive).</param>
  133. /// <param name="startCol">The starting column (inclusive).</param>
  134. /// <param name="endCol">The ending column (exclusive).</param>
  135. /// <param name="output">The StringBuilder to append ANSI sequences to.</param>
  136. /// <param name="lastAttr">The last attribute used, for optimization.</param>
  137. /// <param name="includeCellPredicate">Predicate to determine which cells to include. If null, includes all cells.</param>
  138. /// <param name="addNewlines">Whether to add newlines between rows.</param>
  139. protected void BuildAnsiForRegion (
  140. IOutputBuffer buffer,
  141. int startRow,
  142. int endRow,
  143. int startCol,
  144. int endCol,
  145. StringBuilder output,
  146. ref Attribute? lastAttr,
  147. Func<int, int, bool>? includeCellPredicate = null,
  148. bool addNewlines = true
  149. )
  150. {
  151. TextStyle redrawTextStyle = TextStyle.None;
  152. for (int row = startRow; row < endRow; row++)
  153. {
  154. for (int col = startCol; col < endCol; col++)
  155. {
  156. if (includeCellPredicate != null && !includeCellPredicate (row, col))
  157. {
  158. continue;
  159. }
  160. Cell cell = buffer.Contents![row, col];
  161. AppendCellAnsi (cell, output, ref lastAttr, ref redrawTextStyle, endCol, ref col);
  162. }
  163. // Add newline at end of row if requested
  164. if (addNewlines)
  165. {
  166. output.AppendLine ();
  167. }
  168. }
  169. }
  170. /// <summary>
  171. /// Appends ANSI sequences for a single cell to the output.
  172. /// </summary>
  173. /// <param name="cell">The cell to append ANSI for.</param>
  174. /// <param name="output">The StringBuilder to append to.</param>
  175. /// <param name="lastAttr">The last attribute used, updated if the cell's attribute is different.</param>
  176. /// <param name="redrawTextStyle">The current text style for optimization.</param>
  177. /// <param name="maxCol">The maximum column, used for wide character handling.</param>
  178. /// <param name="currentCol">The current column, updated for wide characters.</param>
  179. protected void AppendCellAnsi (Cell cell, StringBuilder output, ref Attribute? lastAttr, ref TextStyle redrawTextStyle, int maxCol, ref int currentCol)
  180. {
  181. Attribute? attribute = cell.Attribute;
  182. // Add ANSI escape sequence for attribute change
  183. if (attribute.HasValue && attribute.Value != lastAttr)
  184. {
  185. lastAttr = attribute.Value;
  186. AppendOrWriteAttribute (output, attribute.Value, redrawTextStyle);
  187. redrawTextStyle = attribute.Value.Style;
  188. }
  189. // Add the character
  190. const int MAX_CHARS_PER_RUNE = 2;
  191. Span<char> runeBuffer = stackalloc char [MAX_CHARS_PER_RUNE];
  192. Rune rune = cell.Rune;
  193. int runeCharsWritten = rune.EncodeToUtf16 (runeBuffer);
  194. ReadOnlySpan<char> runeChars = runeBuffer [..runeCharsWritten];
  195. output.Append (runeChars);
  196. // Handle wide characters
  197. if (rune.GetColumns () > 1 && currentCol + 1 < maxCol)
  198. {
  199. currentCol++; // Skip next cell for wide character
  200. }
  201. }
  202. /// <summary>
  203. /// Generates an ANSI escape sequence string representation of the given <paramref name="buffer"/> contents.
  204. /// This is the same output that would be written to the terminal to recreate the current screen contents.
  205. /// </summary>
  206. /// <param name="buffer">The output buffer to convert to ANSI.</param>
  207. /// <returns>A string containing ANSI escape sequences representing the buffer contents.</returns>
  208. public string ToAnsi (IOutputBuffer buffer)
  209. {
  210. var output = new StringBuilder ();
  211. Attribute? lastAttr = null;
  212. BuildAnsiForRegion (buffer, 0, buffer.Rows, 0, buffer.Cols, output, ref lastAttr);
  213. return output.ToString ();
  214. }
  215. private void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  216. {
  217. SetCursorPositionImpl (lastCol, row);
  218. // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
  219. StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
  220. Write (processed);
  221. output.Clear ();
  222. lastCol += outputWidth;
  223. outputWidth = 0;
  224. }
  225. }