#nullable enable using System.Runtime.InteropServices; namespace Terminal.Gui.Drivers; /// /// Provides the main implementation of the driver abstraction layer for Terminal.Gui. /// This implementation of coordinates the interaction between input processing, output /// rendering, /// screen size monitoring, and ANSI escape sequence handling. /// /// /// /// implements , /// serving as the central coordination point for console I/O operations. It delegates functionality /// to specialized components: /// /// /// - Processes keyboard and mouse input /// - Manages the screen buffer state /// - Handles actual console output rendering /// - Manages ANSI escape sequence requests /// - Monitors terminal size changes /// /// /// This class is internal and should not be used directly by application code. /// Applications interact with drivers through the class. /// /// internal class DriverImpl : IDriver { private readonly IOutput _output; private readonly AnsiRequestScheduler _ansiRequestScheduler; private CursorVisibility _lastCursor = CursorVisibility.Default; /// /// Initializes a new instance of the class. /// /// The input processor for handling keyboard and mouse events. /// The output buffer for managing screen state. /// The output interface for rendering to the console. /// The scheduler for managing ANSI escape sequence requests. /// The monitor for tracking terminal size changes. public DriverImpl ( IInputProcessor inputProcessor, IOutputBuffer outputBuffer, IOutput output, AnsiRequestScheduler ansiRequestScheduler, ISizeMonitor sizeMonitor ) { InputProcessor = inputProcessor; _output = output; OutputBuffer = outputBuffer; _ansiRequestScheduler = ansiRequestScheduler; InputProcessor.KeyDown += (s, e) => KeyDown?.Invoke (s, e); InputProcessor.KeyUp += (s, e) => KeyUp?.Invoke (s, e); InputProcessor.MouseEvent += (s, e) => { //Logging.Logger.LogTrace ($"Mouse {e.Flags} at x={e.ScreenPosition.X} y={e.ScreenPosition.Y}"); MouseEvent?.Invoke (s, e); }; SizeMonitor = sizeMonitor; sizeMonitor.SizeChanged += (_, e) => { SetScreenSize (e.Size!.Value.Width, e.Size.Value.Height); //SizeChanged?.Invoke (this, e); }; CreateClipboard (); } /// /// The event fired when the screen changes (size, position, etc.). /// public event EventHandler? SizeChanged; /// public IInputProcessor InputProcessor { get; } /// public IOutputBuffer OutputBuffer { get; } /// public ISizeMonitor SizeMonitor { get; } private void CreateClipboard () { if (InputProcessor.DriverName is { } && InputProcessor.DriverName.Contains ("fake")) { if (Clipboard is null) { Clipboard = new FakeClipboard (); } return; } PlatformID p = Environment.OSVersion.Platform; if (p is PlatformID.Win32NT or PlatformID.Win32S or PlatformID.Win32Windows) { Clipboard = new WindowsClipboard (); } else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) { Clipboard = new MacOSXClipboard (); } else if (PlatformDetection.IsWSLPlatform ()) { Clipboard = new WSLClipboard (); } // Clipboard is set to FakeClipboard at initialization } /// Gets the location and size of the terminal screen. public Rectangle Screen { get { //if (Application.RunningUnitTests && _output is WindowsConsoleOutput or NetOutput) //{ // // In unit tests, we don't have a real output, so we return an empty rectangle. // return Rectangle.Empty; //} return new (0, 0, OutputBuffer.Cols, OutputBuffer.Rows); } } /// /// Sets the screen size for testing purposes. Only supported by FakeDriver. /// /// The new width in columns. /// The new height in rows. /// Thrown when called on non-FakeDriver instances. public virtual void SetScreenSize (int width, int height) { OutputBuffer.SetSize (width, height); _output.SetSize (width, height); SizeChanged?.Invoke (this, new (new (width, height))); } /// /// Gets or sets the clip rectangle that and are subject /// to. /// /// The rectangle describing the of region. public Region? Clip { get => OutputBuffer.Clip; set => OutputBuffer.Clip = value; } /// Get the operating system clipboard. public IClipboard? Clipboard { get; private set; } = new FakeClipboard (); /// /// Gets the column last set by . and are used by /// and to determine where to add content. /// public int Col => OutputBuffer.Col; /// The number of columns visible in the terminal. public int Cols { get => OutputBuffer.Cols; set => OutputBuffer.Cols = value; } /// /// The contents of the application output. The driver outputs this buffer to the terminal. /// The format of the array is rows, columns. The first index is the row, the second index is the column. /// public Cell [,]? Contents { get => OutputBuffer.Contents; set => OutputBuffer.Contents = value; } /// The leftmost column in the terminal. public int Left { get => OutputBuffer.Left; set => OutputBuffer.Left = value; } /// /// Gets the row last set by . and are used by /// and to determine where to add content. /// public int Row => OutputBuffer.Row; /// The number of rows visible in the terminal. public int Rows { get => OutputBuffer.Rows; set => OutputBuffer.Rows = value; } /// The topmost row in the terminal. public int Top { get => OutputBuffer.Top; set => OutputBuffer.Top = value; } // TODO: Probably not everyone right? /// Gets whether the supports TrueColor output. public bool SupportsTrueColor => true; // TODO: Currently ignored /// /// 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. /// /// public bool Force16Colors { get => Application.Force16Colors || !SupportsTrueColor; set => Application.Force16Colors = value || !SupportsTrueColor; } /// /// The that will be used for the next or /// /// call. /// public Attribute CurrentAttribute { get => OutputBuffer.CurrentAttribute; set => OutputBuffer.CurrentAttribute = 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) { OutputBuffer.AddRune (rune); } /// /// 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) { OutputBuffer.AddRune (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) { OutputBuffer.AddStr (str); } /// Clears the of the driver. public void ClearContents () { OutputBuffer.ClearContents (); ClearedContents?.Invoke (this, new MouseEventArgs ()); } /// /// Raised each time is called. For benchmarking. /// public event EventHandler? ClearedContents; /// /// 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) { OutputBuffer.FillRect (rect, rune); } /// /// Fills the specified rectangle with the specified . This method is a convenience method /// that calls . /// /// /// public void FillRect (Rectangle rect, char c) { OutputBuffer.FillRect (rect, c); } /// public virtual string GetVersionInfo () { string type = InputProcessor.DriverName ?? throw new ArgumentNullException (nameof (InputProcessor.DriverName)); return type; } /// 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 bool IsRuneSupported (Rune rune) { return Rune.IsValid (rune.Value); } /// Tests whether the specified coordinate are valid for drawing the specified Rune. /// Used to determine if one or two columns are required. /// The column. /// The row. /// /// if the coordinate is outside the screen bounds or outside of /// . /// otherwise. /// public bool IsValidLocation (Rune rune, int col, int row) { return OutputBuffer.IsValidLocation (rune, 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 void Move (int col, int row) { OutputBuffer.Move (col, row); } // TODO: Probably part of output /// Sets the terminal cursor visibility. /// The wished /// upon success public bool SetCursorVisibility (CursorVisibility visibility) { _lastCursor = visibility; _output.SetCursorVisibility (visibility); return true; } /// public bool GetCursorVisibility (out CursorVisibility current) { current = _lastCursor; return true; } /// public void Suspend () { // BUGBUG: This is all platform-specific and should not be implemented here. // BUGBUG: This needs to be in each platform's driver implementation. if (Environment.OSVersion.Platform != PlatformID.Unix) { return; } Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); try { Console.ResetColor (); Console.Clear (); //Disable alternative screen buffer. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll); //Set cursor key to cursor. Console.Out.Write (EscSeqUtils.CSI_ShowCursor); Platform.Suspend (); //Enable alternative screen buffer. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll); } catch (Exception ex) { Logging.Error ($"Error suspending terminal: {ex.Message}"); } Application.LayoutAndDraw (); Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); } /// /// Sets the position of the terminal cursor to and /// . /// public void UpdateCursor () { _output.SetCursorPosition (Col, Row); } /// Initializes the driver public void Init () { throw new NotSupportedException (); } /// Ends the execution of the console driver. public void End () { // TODO: Nope } /// Selects the specified attribute as the attribute to use for future calls to AddRune and AddString. /// Implementations should call base.SetAttribute(c). /// C. /// The previously set Attribute. public Attribute SetAttribute (Attribute newAttribute) { Attribute currentAttribute = OutputBuffer.CurrentAttribute; OutputBuffer.CurrentAttribute = newAttribute; return currentAttribute; } /// Gets the current . /// The current attribute. public Attribute GetAttribute () { return OutputBuffer.CurrentAttribute; } /// Event fired when a key is pressed down. This is a precursor to . public event EventHandler? KeyDown; /// 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; /// Event fired when a mouse event occurs. public event EventHandler? MouseEvent; /// /// Provide proper writing to send escape sequence recognized by the . /// /// public void WriteRaw (string ansi) { _output.Write (ansi); } /// public void EnqueueKeyEvent (Key key) { InputProcessor.EnqueueKeyDownEvent (key); } /// /// Queues the specified ANSI escape sequence request for execution. /// /// The ANSI request to queue. /// /// The request is sent immediately if possible, or queued for later execution /// by the to prevent overwhelming the console. /// public void QueueAnsiRequest (AnsiEscapeSequenceRequest request) { _ansiRequestScheduler.SendOrSchedule (request); } /// /// Gets the instance used by this driver. /// /// The ANSI request scheduler. public AnsiRequestScheduler GetRequestScheduler () { return _ansiRequestScheduler; } /// public void Refresh () { // No need we will always draw when dirty } public string? GetName () { return InputProcessor.DriverName?.ToLowerInvariant (); } }