#nullable enable
using System.Diagnostics;
namespace Terminal.Gui;
/// Base class for Terminal.Gui ConsoleDriver implementations.
///
/// There are currently four implementations: - (for Unix and Mac) -
/// - that uses the .NET Console API -
/// for unit testing.
///
public abstract class ConsoleDriver
{
///
/// Set this to true in any unit tests that attempt to test drivers other than FakeDriver.
///
/// public ColorTests ()
/// {
/// ConsoleDriver.RunningUnitTests = true;
/// }
///
///
internal static bool RunningUnitTests { get; set; }
/// Get the operating system clipboard.
public IClipboard? Clipboard { get; internal set; }
/// Returns the name of the driver and relevant library version information.
///
public virtual string GetVersionInfo () { return GetType ().Name; }
/// Suspends the application (e.g. on Linux via SIGTSTP) and upon resume, resets the console driver.
/// This is only implemented in .
public abstract void Suspend ();
#region ANSI Esc Sequence Handling
// QUESTION: Should this be virtual with a default implementation that does the common stuff?
// QUESTION: Looking at the implementations of this method, there is TONs of duplicated code.
// QUESTION: We should figure out how to find just the things that are unique to each driver and
// QUESTION: create more fine-grained APIs to handle those.
///
/// Provide handling for the terminal write ANSI escape sequence request.
///
/// The object.
/// The request response.
public abstract bool TryWriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest);
// QUESTION: This appears to be an API to help in debugging. It's only implemented in CursesDriver and WindowsDriver.
// QUESTION: Can it be factored such that it does not contaminate the ConsoleDriver API?
///
/// Provide proper writing to send escape sequence recognized by the .
///
///
internal abstract void WriteRaw (string ansi);
#endregion ANSI Esc Sequence Handling
#region Screen and Contents
// As performance is a concern, we keep track of the dirty lines and only refresh those.
// This is in addition to the dirty flag on each cell.
internal bool []? _dirtyLines;
// QUESTION: When non-full screen apps are supported, will this represent the app size, or will that be in Application?
/// Gets the location and size of the terminal screen.
internal Rectangle Screen => new (0, 0, Cols, Rows);
/// Redraws the physical screen with the contents that have been queued up via any of the printing commands.
public abstract void UpdateScreen ();
/// Called when the terminal size changes. Fires the event.
///
public void OnSizeChanged (SizeChangedEventArgs args) { SizeChanged?.Invoke (this, args); }
/// The event fired when the terminal is resized.
public event EventHandler? SizeChanged;
/// Updates the screen to reflect all the changes that have been done to the display buffer
public abstract void Refresh ();
///
/// Gets the column last set by . and are used by
/// and to determine where to add content.
///
public int Col { get; internal set; }
/// The number of columns visible in the terminal.
public virtual int Cols
{
get => _cols;
internal set
{
_cols = value;
ClearContents ();
}
}
///
/// The contents of the application output. The driver outputs this buffer to the terminal when
/// is called.
/// The format of the array is rows, columns. The first index is the row, the second index is the column.
///
public Cell [,]? Contents { get; internal set; }
/// The leftmost column in the terminal.
public virtual int Left { get; internal set; } = 0;
/// Tests if the specified rune is supported by the driver.
///
///
/// if the rune can be properly presented; if the driver does not
/// support displaying this rune.
///
public virtual bool IsRuneSupported (Rune rune) { return Rune.IsValid (rune.Value); }
/// Tests whether the specified coordinate are valid for drawing.
/// The column.
/// The row.
///
/// if the coordinate is outside the screen bounds or outside of .
/// otherwise.
///
public bool IsValidLocation (int col, int row) { return col >= 0 && row >= 0 && col < Cols && row < Rows && Clip.Contains (col, row); }
///
/// Updates and to the specified column and row in .
/// Used by and to determine where to add content.
///
///
/// This does not move the cursor on the screen, it only updates the internal state of the driver.
///
/// If or are negative or beyond and
/// , the method still sets those properties.
///
///
/// Column to move to.
/// Row to move to.
public virtual void Move (int col, int row)
{
//Debug.Assert (col >= 0 && row >= 0 && col < Contents.GetLength(1) && row < Contents.GetLength(0));
Col = col;
Row = row;
}
///
/// Gets the row last set by . and are used by
/// and to determine where to add content.
///
public int Row { get; internal set; }
/// The number of rows visible in the terminal.
public virtual int Rows
{
get => _rows;
internal set
{
_rows = value;
ClearContents ();
}
}
/// The topmost row in the terminal.
public virtual int Top { get; internal set; } = 0;
private Rectangle _clip;
///
/// Gets or sets the clip rectangle that and are subject
/// to.
///
/// The rectangle describing the of region.
public Rectangle Clip
{
get => _clip;
set
{
if (_clip == value)
{
return;
}
// Don't ever let Clip be bigger than Screen
_clip = Rectangle.Intersect (Screen, value);
}
}
/// Adds the specified rune to the display at the current cursor position.
///
///
/// When the method returns, will be incremented by the number of columns
/// required, even if the new column value is outside of the or screen
/// dimensions defined by .
///
///
/// If requires more than one column, and plus the number of columns
/// needed exceeds the or screen dimensions, the default Unicode replacement character (U+FFFD)
/// will be added instead.
///
///
/// Rune to add.
public void AddRune (Rune rune)
{
int runeWidth = -1;
bool validLocation = IsValidLocation (Col, Row);
if (Contents is null)
{
return;
}
if (validLocation)
{
rune = rune.MakePrintable ();
runeWidth = rune.GetColumns ();
lock (Contents)
{
if (runeWidth == 0 && rune.IsCombiningMark ())
{
// AtlasEngine does not support NON-NORMALIZED combining marks in a way
// compatible with the driver architecture. Any CMs (except in the first col)
// are correctly combined with the base char, but are ALSO treated as 1 column
// width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
//
// Until this is addressed (see Issue #), we do our best by
// a) Attempting to normalize any CM with the base char to it's left
// b) Ignoring any CMs that don't normalize
if (Col > 0)
{
if (Contents [Row, Col - 1].CombiningMarks.Count > 0)
{
// Just add this mark to the list
Contents [Row, Col - 1].CombiningMarks.Add (rune);
// Ignore. Don't move to next column (let the driver figure out what to do).
}
else
{
// Attempt to normalize the cell to our left combined with this mark
string combined = Contents [Row, Col - 1].Rune + rune.ToString ();
// Normalize to Form C (Canonical Composition)
string normalized = combined.Normalize (NormalizationForm.FormC);
if (normalized.Length == 1)
{
// It normalized! We can just set the Cell to the left with the
// normalized codepoint
Contents [Row, Col - 1].Rune = (Rune)normalized [0];
// Ignore. Don't move to next column because we're already there
}
else
{
// It didn't normalize. Add it to the Cell to left's CM list
Contents [Row, Col - 1].CombiningMarks.Add (rune);
// Ignore. Don't move to next column (let the driver figure out what to do).
}
}
Contents [Row, Col - 1].Attribute = CurrentAttribute;
Contents [Row, Col - 1].IsDirty = true;
}
else
{
// Most drivers will render a combining mark at col 0 as the mark
Contents [Row, Col].Rune = rune;
Contents [Row, Col].Attribute = CurrentAttribute;
Contents [Row, Col].IsDirty = true;
Col++;
}
}
else
{
Contents [Row, Col].Attribute = CurrentAttribute;
Contents [Row, Col].IsDirty = true;
if (Col > 0)
{
// Check if cell to left has a wide glyph
if (Contents [Row, Col - 1].Rune.GetColumns () > 1)
{
// Invalidate cell to left
Contents [Row, Col - 1].Rune = Rune.ReplacementChar;
Contents [Row, Col - 1].IsDirty = true;
}
}
if (runeWidth < 1)
{
Contents [Row, Col].Rune = Rune.ReplacementChar;
}
else if (runeWidth == 1)
{
Contents [Row, Col].Rune = rune;
if (Col < Clip.Right - 1)
{
Contents [Row, Col + 1].IsDirty = true;
}
}
else if (runeWidth == 2)
{
if (Col == Clip.Right - 1)
{
// We're at the right edge of the clip, so we can't display a wide character.
// TODO: Figure out if it is better to show a replacement character or ' '
Contents [Row, Col].Rune = Rune.ReplacementChar;
}
else
{
Contents [Row, Col].Rune = rune;
if (Col < Clip.Right - 1)
{
// Invalidate cell to right so that it doesn't get drawn
// TODO: Figure out if it is better to show a replacement character or ' '
Contents [Row, Col + 1].Rune = Rune.ReplacementChar;
Contents [Row, Col + 1].IsDirty = true;
}
}
}
else
{
// This is a non-spacing character, so we don't need to do anything
Contents [Row, Col].Rune = (Rune)' ';
Contents [Row, Col].IsDirty = false;
}
_dirtyLines! [Row] = true;
}
}
}
if (runeWidth is < 0 or > 0)
{
Col++;
}
if (runeWidth > 1)
{
Debug.Assert (runeWidth <= 2);
if (validLocation && Col < Clip.Right)
{
lock (Contents!)
{
// This is a double-width character, and we are not at the end of the line.
// Col now points to the second column of the character. Ensure it doesn't
// Get rendered.
Contents [Row, Col].IsDirty = false;
Contents [Row, Col].Attribute = CurrentAttribute;
// TODO: Determine if we should wipe this out (for now now)
//Contents [Row, Col].Rune = (Rune)' ';
}
}
Col++;
}
}
///
/// Adds the specified to the display at the current cursor position. This method is a
/// convenience method that calls with the constructor.
///
/// Character to add.
public void AddRune (char c) { AddRune (new Rune (c)); }
/// Adds the to the display at the cursor position.
///
///
/// When the method returns, will be incremented by the number of columns
/// required, unless the new column value is outside of the or screen
/// dimensions defined by .
///
/// If requires more columns than are available, the output will be clipped.
///
/// String.
public void AddStr (string str)
{
List runes = str.EnumerateRunes ().ToList ();
for (var i = 0; i < runes.Count; i++)
{
AddRune (runes [i]);
}
}
/// Fills the specified rectangle with the specified rune, using
///
/// The value of is honored. Any parts of the rectangle not in the clip will not be drawn.
///
/// The Screen-relative rectangle.
/// The Rune used to fill the rectangle
public void FillRect (Rectangle rect, Rune rune = default)
{
rect = Rectangle.Intersect (rect, Clip);
lock (Contents!)
{
for (int r = rect.Y; r < rect.Y + rect.Height; r++)
{
for (int c = rect.X; c < rect.X + rect.Width; c++)
{
Contents [r, c] = new ()
{
Rune = rune != default (Rune) ? rune : (Rune)' ',
Attribute = CurrentAttribute, IsDirty = true
};
_dirtyLines! [r] = true;
}
}
}
}
/// Clears the of the driver.
public void ClearContents ()
{
Contents = new Cell [Rows, Cols];
//CONCURRENCY: Unsynchronized access to Clip isn't safe.
// TODO: ClearContents should not clear the clip; it should only clear the contents. Move clearing it elsewhere.
Clip = Screen;
_dirtyLines = new bool [Rows];
lock (Contents)
{
for (var row = 0; row < Rows; row++)
{
for (var c = 0; c < Cols; c++)
{
Contents [row, c] = new ()
{
Rune = (Rune)' ',
Attribute = new Attribute (Color.White, Color.Black),
IsDirty = true
};
}
_dirtyLines [row] = true;
}
}
}
///
/// Sets as dirty for situations where views
/// don't need layout and redrawing, but just refresh the screen.
///
public void SetContentsAsDirty ()
{
lock (Contents!)
{
for (var row = 0; row < Rows; row++)
{
for (var c = 0; c < Cols; c++)
{
Contents [row, c].IsDirty = true;
}
_dirtyLines! [row] = true;
}
}
}
///
/// Fills the specified rectangle with the specified . This method is a convenience method
/// that calls .
///
///
///
public void FillRect (Rectangle rect, char c) { FillRect (rect, new Rune (c)); }
#endregion Screen and Contents
#region Cursor Handling
/// Determines if the terminal cursor should be visible or not and sets it accordingly.
/// upon success
public abstract bool EnsureCursorVisibility ();
/// Gets the terminal cursor visibility.
/// The current
/// upon success
public abstract bool GetCursorVisibility (out CursorVisibility visibility);
/// Sets the position of the terminal cursor to and .
public abstract void UpdateCursor ();
/// Sets the terminal cursor visibility.
/// The wished
/// upon success
public abstract bool SetCursorVisibility (CursorVisibility visibility);
#endregion Cursor Handling
#region Setup & Teardown
/// Initializes the driver
/// Returns an instance of using the for the driver.
internal abstract MainLoop Init ();
/// Ends the execution of the console driver.
internal abstract void End ();
#endregion
#region Color Handling
/// Gets whether the supports TrueColor output.
public virtual bool SupportsTrueColor => true;
// TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
// BUGBUG: Application.Force16Colors should be bool? so if SupportsTrueColor and Application.Force16Colors == false, this doesn't override
///
/// Gets or sets whether the should use 16 colors instead of the default TrueColors.
/// See to change this setting via .
///
///
///
/// Will be forced to if is
/// , indicating that the cannot support TrueColor.
///
///
internal virtual bool Force16Colors
{
get => Application.Force16Colors || !SupportsTrueColor;
set => Application.Force16Colors = value || !SupportsTrueColor;
}
private Attribute _currentAttribute;
private int _cols;
private int _rows;
///
/// The that will be used for the next or
/// call.
///
public Attribute CurrentAttribute
{
get => _currentAttribute;
set
{
// TODO: This makes ConsoleDriver dependent on Application, which is not ideal. Once Attribute.PlatformColor is removed, this can be fixed.
if (Application.Driver is { })
{
_currentAttribute = new (value.Foreground, value.Background);
return;
}
_currentAttribute = value;
}
}
/// Selects the specified attribute as the attribute to use for future calls to AddRune and AddString.
/// Implementations should call base.SetAttribute(c).
/// C.
public Attribute SetAttribute (Attribute c)
{
Attribute prevAttribute = CurrentAttribute;
CurrentAttribute = c;
return prevAttribute;
}
/// Gets the current .
/// The current attribute.
public Attribute GetAttribute () { return CurrentAttribute; }
// TODO: This is only overridden by CursesDriver. Once CursesDriver supports 24-bit color, this virtual method can be
// removed (and Attribute can lose the platformColor property).
/// Makes an .
/// The foreground color.
/// The background color.
/// The attribute for the foreground and background colors.
public virtual Attribute MakeColor (in Color foreground, in Color background)
{
// Encode the colors into the int value.
return new (
-1, // only used by cursesdriver!
foreground,
background
);
}
#endregion Color Handling
#region Mouse Handling
/// Event fired when a mouse event occurs.
public event EventHandler? MouseEvent;
/// Called when a mouse event occurs. Fires the event.
///
public void OnMouseEvent (MouseEventArgs a)
{
// Ensure ScreenPosition is set
a.ScreenPosition = a.Position;
MouseEvent?.Invoke (this, a);
}
#endregion Mouse Handling
#region Keyboard Handling
/// Event fired when a key is pressed down. This is a precursor to .
public event EventHandler? KeyDown;
///
/// Called when a key is pressed down. Fires the event. This is a precursor to
/// .
///
///
public void OnKeyDown (Key a) { KeyDown?.Invoke (this, a); }
/// Event fired when a key is released.
///
/// Drivers that do not support key release events will fire this event after processing is
/// complete.
///
public event EventHandler? KeyUp;
/// Called when a key is released. Fires the event.
///
/// Drivers that do not support key release events will call this method after processing
/// is complete.
///
///
public void OnKeyUp (Key a) { KeyUp?.Invoke (this, a); }
// TODO: Remove this API - it was needed when we didn't have a reliable way to simulate key presses.
// TODO: We now do: Applicaiton.RaiseKeyDown and Application.RaiseKeyUp
/// Simulates a key press.
/// The key character.
/// The key.
/// If simulates the Shift key being pressed.
/// If simulates the Alt key being pressed.
/// If simulates the Ctrl key being pressed.
public abstract void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool ctrl);
#endregion Keyboard Handling
}