using System.Collections.Concurrent;
namespace Terminal.Gui.Drivers;
///
/// Abstract base class to assist with implementing .
///
public abstract class OutputBase
{
private bool _force16Colors;
///
public bool Force16Colors
{
get => _force16Colors;
set
{
if (IsLegacyConsole && !value)
{
return;
}
_force16Colors = value;
}
}
private bool _isLegacyConsole;
///
public bool IsLegacyConsole
{
get => _isLegacyConsole;
set
{
_isLegacyConsole = value;
if (value) // If legacy console (true), force 16 colors
{
Force16Colors = true;
}
}
}
private readonly ConcurrentQueue _sixels = [];
/// >
public ConcurrentQueue GetSixels () => _sixels;
// Last text style used, for updating style with EscSeqUtils.CSI_AppendTextStyleChange().
private TextStyle _redrawTextStyle = TextStyle.None;
///
/// Changes the visibility of the cursor in the terminal to the specified e.g.
/// the flashing indicator, invisible, box indicator etc.
///
///
public abstract void SetCursorVisibility (CursorVisibility visibility);
StringBuilder _lastOutputStringBuilder = new ();
///
/// Writes dirty cells from the buffer to the console. Hides cursor, iterates rows/cols,
/// skips clean cells, batches dirty cells into ANSI sequences, wraps URLs with OSC 8,
/// then renders sixel images. Cursor visibility is managed by ApplicationMainLoop.SetCursor().
///
public virtual void Write (IOutputBuffer buffer)
{
StringBuilder outputStringBuilder = new ();
int top = 0;
int left = 0;
int rows = buffer.Rows;
int cols = buffer.Cols;
Attribute? redrawAttr = null;
int lastCol = -1;
// Hide cursor during rendering to prevent flicker
SetCursorVisibility (CursorVisibility.Invisible);
// Process each row
for (int row = top; row < rows; row++)
{
if (!SetCursorPositionImpl (0, row))
{
return;
}
outputStringBuilder.Clear ();
// Process columns in row
for (int col = left; col < cols; col++)
{
lastCol = -1;
var outputWidth = 0;
// Batch consecutive dirty cells
for (; col < cols; col++)
{
// Skip clean cells - position cursor and continue
if (!buffer.Contents! [row, col].IsDirty)
{
if (outputStringBuilder.Length > 0)
{
// This clears outputStringBuilder
WriteToConsole (outputStringBuilder, ref lastCol, ref outputWidth);
}
else if (lastCol == -1)
{
lastCol = col;
}
if (lastCol + 1 < cols)
{
lastCol++;
}
SetCursorPositionImpl (lastCol, row);
continue;
}
if (lastCol == -1)
{
lastCol = col;
}
// Append dirty cell as ANSI and mark clean
Cell cell = buffer.Contents [row, col];
buffer.Contents [row, col].IsDirty = false;
AppendCellAnsi (cell, outputStringBuilder, ref redrawAttr, ref _redrawTextStyle, cols, ref col, ref outputWidth);
}
}
// Flush buffered output for row
if (outputStringBuilder.Length > 0)
{
if (IsLegacyConsole)
{
Write (outputStringBuilder);
}
else
{
SetCursorPositionImpl (lastCol, row);
// Wrap URLs with OSC 8 hyperlink sequences
StringBuilder processed = Osc8UrlLinker.WrapOsc8 (outputStringBuilder);
Write (processed);
}
}
}
if (IsLegacyConsole)
{
return;
}
// Render queued sixel images
foreach (SixelToRender s in GetSixels ())
{
if (string.IsNullOrWhiteSpace (s.SixelData))
{
continue;
}
SetCursorPositionImpl (s.ScreenPosition.X, s.ScreenPosition.Y);
Write ((StringBuilder)new (s.SixelData));
}
// Cursor visibility restored by ApplicationMainLoop.SetCursor() to prevent flicker
}
///
public virtual string GetLastOutput () => _lastOutputStringBuilder.ToString ();
///
/// Changes the color and text style of the console to the given and
/// .
/// If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to
///
/// otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
///
///
///
///
protected abstract void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle);
///
/// When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
///
/// Column to move cursor to
/// Row to move cursor to
///
protected abstract bool SetCursorPositionImpl (int screenPositionX, int screenPositionY);
///
/// Output the contents of the to the console.
///
///
protected virtual void Write (StringBuilder output)
{
_lastOutputStringBuilder.Append (output);
}
///
/// Builds ANSI escape sequences for the specified rectangular region of the buffer.
///
/// The output buffer to build ANSI for.
/// The starting row (inclusive).
/// The ending row (exclusive).
/// The starting column (inclusive).
/// The ending column (exclusive).
/// The StringBuilder to append ANSI sequences to.
/// The last attribute used, for optimization.
/// Predicate to determine which cells to include. If null, includes all cells.
/// Whether to add newlines between rows.
protected void BuildAnsiForRegion (
IOutputBuffer buffer,
int startRow,
int endRow,
int startCol,
int endCol,
StringBuilder output,
ref Attribute? lastAttr,
Func? includeCellPredicate = null,
bool addNewlines = true
)
{
TextStyle redrawTextStyle = TextStyle.None;
for (int row = startRow; row < endRow; row++)
{
for (int col = startCol; col < endCol; col++)
{
if (includeCellPredicate != null && !includeCellPredicate (row, col))
{
continue;
}
Cell cell = buffer.Contents! [row, col];
int outputWidth = -1;
AppendCellAnsi (cell, output, ref lastAttr, ref redrawTextStyle, endCol, ref col, ref outputWidth);
}
// Add newline at end of row if requested
if (addNewlines)
{
output.AppendLine ();
}
}
}
///
/// Appends ANSI sequences for a single cell to the output.
///
/// The cell to append ANSI for.
/// The StringBuilder to append to.
/// The last attribute used, updated if the cell's attribute is different.
/// The current text style for optimization.
/// The maximum column, used for wide character handling.
/// The current column, updated for wide characters.
/// The current output width, updated for wide characters.
protected void AppendCellAnsi (Cell cell, StringBuilder output, ref Attribute? lastAttr, ref TextStyle redrawTextStyle, int maxCol, ref int currentCol, ref int outputWidth)
{
Attribute? attribute = cell.Attribute;
// Add ANSI escape sequence for attribute change
if (attribute.HasValue && attribute.Value != lastAttr)
{
lastAttr = attribute.Value;
AppendOrWriteAttribute (output, attribute.Value, redrawTextStyle);
redrawTextStyle = attribute.Value.Style;
}
// Add the grapheme
string grapheme = cell.Grapheme;
output.Append (grapheme);
outputWidth++;
// Handle wide grapheme
if (grapheme.GetColumns () > 1 && currentCol + 1 < maxCol)
{
currentCol++; // Skip next cell for wide character
outputWidth++;
}
}
///
/// Generates an ANSI escape sequence string representation of the given contents.
/// This is the same output that would be written to the terminal to recreate the current screen contents.
///
/// The output buffer to convert to ANSI.
/// A string containing ANSI escape sequences representing the buffer contents.
public string ToAnsi (IOutputBuffer buffer)
{
StringBuilder output = new ();
Attribute? lastAttr = null;
BuildAnsiForRegion (buffer, 0, buffer.Rows, 0, buffer.Cols, output, ref lastAttr);
return output.ToString ();
}
///
/// Writes buffered output to console, wrapping URLs with OSC 8 hyperlinks (non-legacy only),
/// then clears the buffer and advances by .
///
private void WriteToConsole (StringBuilder output, ref int lastCol, ref int outputWidth)
{
if (IsLegacyConsole)
{
Write (output);
}
else
{
// Wrap URLs with OSC 8 hyperlink sequences
StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
Write (processed);
}
output.Clear ();
lastCol += outputWidth;
outputWidth = 0;
}
}