From 9de21e066d0b4566785f3ca70233a1aee8a9eae0 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 30 Sep 2024 01:37:13 +0100 Subject: [PATCH 01/89] Fixes #3767. Allowing any driver to request ANSI escape sequence with immediate response. --- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 1eb63e34aa..17589d101c 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -304,6 +304,91 @@ Action continuousButtonPressedHandler } #nullable enable + /// + /// Execute an ANSI escape sequence escape which may return a response or error. + /// + /// The ANSI escape sequence to request. + /// A tuple with the response and error. + public static (string response, string error) ExecuteAnsiRequest (string ansiRequest) + { + var response = new StringBuilder (); + var error = new StringBuilder (); + var foundEscapeSequence = false; + + try + { + switch (Application.Driver) + { + case NetDriver netDriver: + netDriver.StopReportingMouseMoves (); + + break; + case CursesDriver cursesDriver: + cursesDriver.StopReportingMouseMoves (); + + break; + } + + Thread.Sleep (100); // Allow time for mouse stopping + + // Flush the input buffer to avoid reading stale input + while (Console.KeyAvailable) + { + Console.ReadKey (true); + } + + // Send the ANSI escape sequence + Console.Write (ansiRequest); + Console.Out.Flush (); // Ensure the request is sent + + // Read the response from stdin (response should come back as input) + Thread.Sleep (100); // Allow time for the terminal to respond + + // Read input until no more characters are available or another \u001B is encountered + while (Console.KeyAvailable) + { + // Peek the next key + ConsoleKeyInfo keyInfo = Console.ReadKey (true); // true to not display on the console + + if (keyInfo.KeyChar == '\u001B') // Check if the key is Escape (ANSI escape sequence starts) + { + if (foundEscapeSequence) + { + // If we already found one \u001B, break out of the loop when another is found + break; + } + else + { + foundEscapeSequence = true; // Mark that we've encountered the first escape sequence + } + } + + // Append the current key to the response + response.Append (keyInfo.KeyChar); + } + } + catch (Exception ex) + { + error.AppendLine ($"Error executing ANSI request: {ex.Message}"); + } + finally + { + switch (Application.Driver) + { + case NetDriver netDriver: + netDriver.StartReportingMouseMoves (); + + break; + case CursesDriver cursesDriver: + cursesDriver.StartReportingMouseMoves (); + + break; + } + } + + return (response.ToString (), error.ToString ()); + } + /// /// Gets the c1Control used in the called escape sequence. /// From 0b3d2199611fcdc90300a91fa8028bbae2e491c4 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 30 Sep 2024 01:41:46 +0100 Subject: [PATCH 02/89] Using a more appropriate request for cursor position. --- Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 17589d101c..8348d031ad 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -1399,10 +1399,10 @@ public enum DECSCUSR_Style #region Requests /// - /// ESC [ ? 6 n - Request Cursor Position Report (?) (DECXCPR) - /// https://terminalguide.namepad.de/seq/csi_sn__p-6/ + /// ESC [ 6 n - Request Cursor Position Report (CPR) + /// https://terminalguide.namepad.de/seq/csi_sn-6/ /// - public static readonly string CSI_RequestCursorPositionReport = CSI + "?6n"; + public static readonly string CSI_RequestCursorPositionReport = CSI + "6n"; /// /// The terminal reply to . ESC [ ? (y) ; (x) R From c89a9c8dfb98b3685b22c11fc3416c8e43092995 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 30 Sep 2024 18:53:02 +0100 Subject: [PATCH 03/89] Add AnsiEscapeSequenceRequest and AnsiEscapeSequenceResponse classes. --- .../AnsiEscapeSequenceRequest.cs | 163 ++++++++++++++++++ .../AnsiEscapeSequenceResponse.cs | 53 ++++++ .../CursesDriver/CursesDriver.cs | 6 + .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 119 +------------ Terminal.Gui/ConsoleDrivers/NetDriver.cs | 86 ++++----- 5 files changed, 275 insertions(+), 152 deletions(-) create mode 100644 Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs create mode 100644 Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs new file mode 100644 index 0000000000..30546501be --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -0,0 +1,163 @@ +#nullable enable +namespace Terminal.Gui; + +/// +/// Describes an ongoing ANSI request sent to the console. +/// Use to handle the response +/// when console answers the request. +/// +public class AnsiEscapeSequenceRequest +{ + /// + /// Execute an ANSI escape sequence escape which may return a response or error. + /// + /// The ANSI escape sequence to request. + /// A with the response, error, terminator and value. + public static AnsiEscapeSequenceResponse ExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) + { + var response = new StringBuilder (); + var error = new StringBuilder (); + var savedIsReportingMouseMoves = false; + + try + { + switch (Application.Driver) + { + case NetDriver netDriver: + savedIsReportingMouseMoves = netDriver.IsReportingMouseMoves; + + if (savedIsReportingMouseMoves) + { + netDriver.StopReportingMouseMoves (); + } + + break; + case CursesDriver cursesDriver: + savedIsReportingMouseMoves = cursesDriver.IsReportingMouseMoves; + + if (savedIsReportingMouseMoves) + { + cursesDriver.StopReportingMouseMoves (); + } + + break; + } + + Thread.Sleep (100); // Allow time for mouse stopping and to flush the input buffer + + // Flush the input buffer to avoid reading stale input + while (Console.KeyAvailable) + { + Console.ReadKey (true); + } + + // Send the ANSI escape sequence + Console.Write (ansiRequest.Request); + Console.Out.Flush (); // Ensure the request is sent + + // Read the response from stdin (response should come back as input) + Thread.Sleep (100); // Allow time for the terminal to respond + + // Read input until no more characters are available or the terminator is encountered + while (Console.KeyAvailable) + { + // Peek the next key + ConsoleKeyInfo keyInfo = Console.ReadKey (true); // true to not display on the console + + // Append the current key to the response + response.Append (keyInfo.KeyChar); + + if (keyInfo.KeyChar == ansiRequest.Terminator [^1]) // Check if the key is terminator (ANSI escape sequence ends) + { + // Break out of the loop when terminator is found + break; + } + } + + if (!response.ToString ().EndsWith (ansiRequest.Terminator [^1])) + { + throw new InvalidOperationException ($"Terminator doesn't ends with: {ansiRequest.Terminator [^1]}"); + } + } + catch (Exception ex) + { + error.AppendLine ($"Error executing ANSI request: {ex.Message}"); + } + finally + { + if (savedIsReportingMouseMoves) + { + switch (Application.Driver) + { + case NetDriver netDriver: + netDriver.StartReportingMouseMoves (); + + break; + case CursesDriver cursesDriver: + cursesDriver.StartReportingMouseMoves (); + + break; + } + } + } + + var values = new string? [] { null }; + + if (string.IsNullOrEmpty (error.ToString ())) + { + (string? c1Control, string? code, values, string? terminator) = EscSeqUtils.GetEscapeResult (response.ToString ().ToCharArray ()); + } + + AnsiEscapeSequenceResponse ansiResponse = new () + { Response = response.ToString (), Error = error.ToString (), Terminator = response.ToString () [^1].ToString (), Value = values [0] }; + + // Invoke the event if it's subscribed + ansiRequest.ResponseReceived?.Invoke (ansiRequest, ansiResponse); + + return ansiResponse; + } + + /// + /// Request to send e.g. see + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Request + /// + /// + public required string Request { get; init; } + + /// + /// Invoked when the console responds with an ANSI response code that matches the + /// + /// + public event EventHandler? ResponseReceived; + + /// + /// + /// The terminator that uniquely identifies the type of response as responded + /// by the console. e.g. for + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Request + /// + /// the terminator is + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Terminator + /// + /// . + /// + /// + /// After sending a request, the first response with matching terminator will be matched + /// to the oldest outstanding request. + /// + /// + public required string Terminator { get; init; } + + /// + /// The value expected in the response e.g. + /// + /// EscSeqUtils.CSI_ReportTerminalSizeInChars.Value + /// + /// which will have a 't' as terminator but also other different request may return the same terminator with a + /// different value. + /// + public string? Value { get; init; } +} diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs new file mode 100644 index 0000000000..df98511558 --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs @@ -0,0 +1,53 @@ +#nullable enable +namespace Terminal.Gui; + +/// +/// Describes a finished ANSI received from the console. +/// +public class AnsiEscapeSequenceResponse +{ + /// + /// Error received from e.g. see + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Request + /// + /// + public required string Error { get; init; } + + /// + /// Response received from e.g. see + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Request + /// + /// . + /// + public required string Response { get; init; } + + /// + /// + /// The terminator that uniquely identifies the type of response as responded + /// by the console. e.g. for + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Request + /// + /// the terminator is + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Terminator + /// + /// + /// + /// The received terminator must match to the terminator sent by the request. + /// + /// + public required string Terminator { get; init; } + + /// + /// The value expected in the response e.g. + /// + /// EscSeqUtils.CSI_ReportTerminalSizeInChars.Value + /// + /// which will have a 't' as terminator but also other different request may return the same terminator with a + /// different value. + /// + public string? Value { get; init; } +} diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index b806457d46..ff4f95bdb6 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -177,11 +177,15 @@ public override bool SetCursorVisibility (CursorVisibility visibility) return true; } + public bool IsReportingMouseMoves { get; private set; } + public void StartReportingMouseMoves () { if (!RunningUnitTests) { Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); + + IsReportingMouseMoves = true; } } @@ -190,6 +194,8 @@ public void StopReportingMouseMoves () if (!RunningUnitTests) { Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); + + IsReportingMouseMoves = false; } } diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 8348d031ad..d32a8e01fe 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -304,91 +304,6 @@ Action continuousButtonPressedHandler } #nullable enable - /// - /// Execute an ANSI escape sequence escape which may return a response or error. - /// - /// The ANSI escape sequence to request. - /// A tuple with the response and error. - public static (string response, string error) ExecuteAnsiRequest (string ansiRequest) - { - var response = new StringBuilder (); - var error = new StringBuilder (); - var foundEscapeSequence = false; - - try - { - switch (Application.Driver) - { - case NetDriver netDriver: - netDriver.StopReportingMouseMoves (); - - break; - case CursesDriver cursesDriver: - cursesDriver.StopReportingMouseMoves (); - - break; - } - - Thread.Sleep (100); // Allow time for mouse stopping - - // Flush the input buffer to avoid reading stale input - while (Console.KeyAvailable) - { - Console.ReadKey (true); - } - - // Send the ANSI escape sequence - Console.Write (ansiRequest); - Console.Out.Flush (); // Ensure the request is sent - - // Read the response from stdin (response should come back as input) - Thread.Sleep (100); // Allow time for the terminal to respond - - // Read input until no more characters are available or another \u001B is encountered - while (Console.KeyAvailable) - { - // Peek the next key - ConsoleKeyInfo keyInfo = Console.ReadKey (true); // true to not display on the console - - if (keyInfo.KeyChar == '\u001B') // Check if the key is Escape (ANSI escape sequence starts) - { - if (foundEscapeSequence) - { - // If we already found one \u001B, break out of the loop when another is found - break; - } - else - { - foundEscapeSequence = true; // Mark that we've encountered the first escape sequence - } - } - - // Append the current key to the response - response.Append (keyInfo.KeyChar); - } - } - catch (Exception ex) - { - error.AppendLine ($"Error executing ANSI request: {ex.Message}"); - } - finally - { - switch (Application.Driver) - { - case NetDriver netDriver: - netDriver.StartReportingMouseMoves (); - - break; - case CursesDriver cursesDriver: - cursesDriver.StartReportingMouseMoves (); - - break; - } - } - - return (response.ToString (), error.ToString ()); - } - /// /// Gets the c1Control used in the called escape sequence. /// @@ -1399,15 +1314,11 @@ public enum DECSCUSR_Style #region Requests /// - /// ESC [ 6 n - Request Cursor Position Report (CPR) - /// https://terminalguide.namepad.de/seq/csi_sn-6/ + /// ESC [ ? 6 n - Request Cursor Position Report (?) (DECXCPR) + /// https://terminalguide.namepad.de/seq/csi_sn__p-6/ + /// The terminal reply to . ESC [ ? (y) ; (x) ; 1 R /// - public static readonly string CSI_RequestCursorPositionReport = CSI + "6n"; - - /// - /// The terminal reply to . ESC [ ? (y) ; (x) R - /// - public const string CSI_RequestCursorPositionReport_Terminator = "R"; + public static readonly AnsiEscapeSequenceRequest CSI_RequestCursorPositionReport = new () { Request = CSI + "?6n", Terminator = "R" }; /// /// ESC [ 0 c - Send Device Attributes (Primary DA) @@ -1426,37 +1337,25 @@ public enum DECSCUSR_Style /// 28 = Rectangular area operations /// 32 = Text macros /// 42 = ISO Latin-2 character set + /// The terminator indicating a reply to or + /// /// - public static readonly string CSI_SendDeviceAttributes = CSI + "0c"; + public static readonly AnsiEscapeSequenceRequest CSI_SendDeviceAttributes = new () { Request = CSI + "0c", Terminator = "c" }; /// /// ESC [ > 0 c - Send Device Attributes (Secondary DA) /// Windows Terminal v1.18+ emits: "\x1b[>0;10;1c" (vt100, firmware version 1.0, vt220) - /// - public static readonly string CSI_SendDeviceAttributes2 = CSI + ">0c"; - - /// /// The terminator indicating a reply to or /// /// - public const string CSI_ReportDeviceAttributes_Terminator = "c"; + public static readonly AnsiEscapeSequenceRequest CSI_SendDeviceAttributes2 = new () { Request = CSI + ">0c", Terminator = "c" }; /// /// CSI 1 8 t | yes | yes | yes | report window size in chars /// https://terminalguide.namepad.de/seq/csi_st-18/ - /// - public static readonly string CSI_ReportTerminalSizeInChars = CSI + "18t"; - - /// /// The terminator indicating a reply to : ESC [ 8 ; height ; width t /// - public const string CSI_ReportTerminalSizeInChars_Terminator = "t"; - - /// - /// The value of the response to indicating value 1 and 2 are the terminal - /// size in chars. - /// - public const string CSI_ReportTerminalSizeInChars_ResponseValue = "8"; + public static readonly AnsiEscapeSequenceRequest CSI_ReportTerminalSizeInChars = new () { Request = CSI + "18t", Terminator = "t", Value = "8" }; #endregion } diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 8aaddc3215..79ddbcde2d 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -591,52 +591,48 @@ private MouseButtonState MapMouseFlags (MouseFlags mouseFlags) private void HandleRequestResponseEvent (string c1Control, string code, string [] values, string terminating) { - switch (terminating) - { - // BUGBUG: I can't find where we send a request for cursor position (ESC[?6n), so I'm not sure if this is needed. - case EscSeqUtils.CSI_RequestCursorPositionReport_Terminator: - var point = new Point { X = int.Parse (values [1]) - 1, Y = int.Parse (values [0]) - 1 }; - - if (_lastCursorPosition.Y != point.Y) - { - _lastCursorPosition = point; - var eventType = EventType.WindowPosition; - var winPositionEv = new WindowPositionEvent { CursorPosition = point }; + if (terminating == - _inputQueue.Enqueue ( - new InputResult { EventType = eventType, WindowPositionEvent = winPositionEv } - ); - } - else - { - return; - } - - break; - - case EscSeqUtils.CSI_ReportTerminalSizeInChars_Terminator: - switch (values [0]) - { - case EscSeqUtils.CSI_ReportTerminalSizeInChars_ResponseValue: - EnqueueWindowSizeEvent ( - Math.Max (int.Parse (values [1]), 0), - Math.Max (int.Parse (values [2]), 0), - Math.Max (int.Parse (values [1]), 0), - Math.Max (int.Parse (values [2]), 0) - ); - - break; - default: - EnqueueRequestResponseEvent (c1Control, code, values, terminating); + // BUGBUG: I can't find where we send a request for cursor position (ESC[?6n), so I'm not sure if this is needed. + // The observation is correct because the response isn't immediate and this is useless + EscSeqUtils.CSI_RequestCursorPositionReport.Terminator) + { + var point = new Point { X = int.Parse (values [1]) - 1, Y = int.Parse (values [0]) - 1 }; - break; - } + if (_lastCursorPosition.Y != point.Y) + { + _lastCursorPosition = point; + var eventType = EventType.WindowPosition; + var winPositionEv = new WindowPositionEvent { CursorPosition = point }; - break; - default: + _inputQueue.Enqueue ( + new InputResult { EventType = eventType, WindowPositionEvent = winPositionEv } + ); + } + else + { + return; + } + } + else if (terminating == EscSeqUtils.CSI_ReportTerminalSizeInChars.Terminator) + { + if (values [0] == EscSeqUtils.CSI_ReportTerminalSizeInChars.Value) + { + EnqueueWindowSizeEvent ( + Math.Max (int.Parse (values [1]), 0), + Math.Max (int.Parse (values [2]), 0), + Math.Max (int.Parse (values [1]), 0), + Math.Max (int.Parse (values [2]), 0) + ); + } + else + { EnqueueRequestResponseEvent (c1Control, code, values, terminating); - - break; + } + } + else + { + EnqueueRequestResponseEvent (c1Control, code, values, terminating); } _inputReady.Set (); @@ -1377,11 +1373,15 @@ public override bool EnsureCursorVisibility () #region Mouse Handling + public bool IsReportingMouseMoves { get; private set; } + public void StartReportingMouseMoves () { if (!RunningUnitTests) { Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); + + IsReportingMouseMoves = true; } } @@ -1390,6 +1390,8 @@ public void StopReportingMouseMoves () if (!RunningUnitTests) { Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); + + IsReportingMouseMoves = false; } } From 21c31557c0cd175ccf5a7bdc4c65ef959f7af123 Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 1 Oct 2024 17:31:08 +0100 Subject: [PATCH 04/89] Prevents empty response error. --- .../AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 30546501be..ca11e8a912 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -76,7 +76,7 @@ public static AnsiEscapeSequenceResponse ExecuteAnsiRequest (AnsiEscapeSequenceR if (!response.ToString ().EndsWith (ansiRequest.Terminator [^1])) { - throw new InvalidOperationException ($"Terminator doesn't ends with: {ansiRequest.Terminator [^1]}"); + throw new InvalidOperationException ($"Terminator doesn't ends with: '{ansiRequest.Terminator [^1]}'"); } } catch (Exception ex) @@ -109,7 +109,10 @@ public static AnsiEscapeSequenceResponse ExecuteAnsiRequest (AnsiEscapeSequenceR } AnsiEscapeSequenceResponse ansiResponse = new () - { Response = response.ToString (), Error = error.ToString (), Terminator = response.ToString () [^1].ToString (), Value = values [0] }; + { + Response = response.ToString (), Error = error.ToString (), + Terminator = string.IsNullOrEmpty (response.ToString ()) ? "" : response.ToString () [^1].ToString (), Value = values [0] + }; // Invoke the event if it's subscribed ansiRequest.ResponseReceived?.Invoke (ansiRequest, ansiResponse); From 7142a0489f3f1eded35ede0664c7cb0b4a23cf25 Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 1 Oct 2024 17:34:41 +0100 Subject: [PATCH 05/89] Add AnsiEscapeSequenceRequests scenario. --- .../Scenarios/AnsiEscapeSequenceRequest.cs | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs new file mode 100644 index 0000000000..7882c44490 --- /dev/null +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Terminal.Gui; + +namespace UICatalog.Scenarios; + +[ScenarioMetadata ("AnsiEscapeSequenceRequest", "Ansi Escape Sequence Request")] +[ScenarioCategory ("Controls")] +public sealed class AnsiEscapeSequenceRequests : Scenario +{ + public override void Main () + { + // Init + Application.Init (); + + // Setup - Create a top-level application window and configure it. + Window appWindow = new () + { + Title = GetQuitKeyAndName (), + }; + appWindow.Padding.Thickness = new (1); + + var scrRequests = new List + { + "CSI_SendDeviceAttributes", + "CSI_ReportTerminalSizeInChars", + "CSI_RequestCursorPositionReport", + "CSI_SendDeviceAttributes2" + }; + + var cbRequests = new ComboBox () { Width = 40, Height = 5, ReadOnly = true, Source = new ListWrapper (new (scrRequests)) }; + appWindow.Add (cbRequests); + + var label = new Label { Y = Pos.Bottom (cbRequests) + 1, Text = "Request:"}; + var tfRequest = new TextField { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 20 }; + appWindow.Add (label, tfRequest); + + label = new Label { X = Pos.Right (tfRequest) + 1, Y = Pos.Top (tfRequest), Text = "Value:" }; + var tfValue = new TextField { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 6 }; + appWindow.Add (label, tfValue); + + label = new Label { X = Pos.Right (tfValue) + 1, Y = Pos.Top (tfValue), Text = "Terminator:" }; + var tfTerminator = new TextField { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 4 }; + appWindow.Add (label, tfTerminator); + + cbRequests.SelectedItemChanged += (s, e) => + { + var selAnsiEscapeSequenceRequestName = scrRequests [cbRequests.SelectedItem]; + AnsiEscapeSequenceRequest selAnsiEscapeSequenceRequest = null; + switch (selAnsiEscapeSequenceRequestName) + { + case "CSI_SendDeviceAttributes": + selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_SendDeviceAttributes; + break; + case "CSI_ReportTerminalSizeInChars": + selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_ReportTerminalSizeInChars; + break; + case "CSI_RequestCursorPositionReport": + selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_RequestCursorPositionReport; + break; + case "CSI_SendDeviceAttributes2": + selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_SendDeviceAttributes2; + break; + } + + tfRequest.Text = selAnsiEscapeSequenceRequest is { } ? selAnsiEscapeSequenceRequest.Request : ""; + tfValue.Text = selAnsiEscapeSequenceRequest is { } ? selAnsiEscapeSequenceRequest.Value ?? "" : ""; + tfTerminator.Text = selAnsiEscapeSequenceRequest is { } ? selAnsiEscapeSequenceRequest.Terminator : ""; + }; + // Forces raise cbRequests.SelectedItemChanged to update TextFields + cbRequests.SelectedItem = 0; + + label = new Label { Y = Pos.Bottom (tfRequest) + 2, Text = "Response:" }; + var tvResponse = new TextView { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 30, Height = 4, ReadOnly = true }; + appWindow.Add (label, tvResponse); + + label = new Label { X = Pos.Right (tvResponse) + 1, Y = Pos.Top (tvResponse), Text = "Error:" }; + var tvError = new TextView { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 20, Height = 4, ReadOnly = true }; + appWindow.Add (label, tvError); + + label = new Label { X = Pos.Right (tvError) + 1, Y = Pos.Top (tvError), Text = "Value:" }; + var tvValue = new TextView { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 6, Height = 4, ReadOnly = true }; + appWindow.Add (label, tvValue); + + label = new Label { X = Pos.Right (tvValue) + 1, Y = Pos.Top (tvValue), Text = "Terminator:" }; + var tvTerminator = new TextView { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 4, Height = 4, ReadOnly = true }; + appWindow.Add (label, tvTerminator); + + var btnResponse = new Button { X = Pos.Center (), Y = Pos.Bottom (tvResponse) + 2, Text = "Send Request" }; + btnResponse.Accept += (s, e) => + { + var ansiEscapeSequenceRequest = new AnsiEscapeSequenceRequest + { + Request = tfRequest.Text, + Terminator = tfTerminator.Text, + Value = string.IsNullOrEmpty (tfValue.Text) ? null : tfValue.Text + }; + + var ansiEscapeSequenceResponse = AnsiEscapeSequenceRequest.ExecuteAnsiRequest ( + ansiEscapeSequenceRequest + ); + + tvResponse.Text =ansiEscapeSequenceResponse.Response; + tvError.Text = ansiEscapeSequenceResponse.Error; + tvValue.Text = ansiEscapeSequenceResponse.Value ?? ""; + tvTerminator.Text = ansiEscapeSequenceResponse.Terminator; + }; + appWindow.Add (btnResponse); + + appWindow.Add (new Label { Y = Pos.Bottom (btnResponse) + 2, Text = "You can send other requests by editing the TextFields." }); + + // Run - Start the application. + Application.Run (appWindow); + appWindow.Dispose (); + + // Shutdown - Calling Application.Shutdown is required. + Application.Shutdown (); + } +} From dd3179697debed40257ee4ac39dc7a4f88ae61e2 Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 1 Oct 2024 22:13:32 +0100 Subject: [PATCH 06/89] Improving scenario layout. --- .../Scenarios/AnsiEscapeSequenceRequest.cs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs index 7882c44490..e8b5a13e5a 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs @@ -30,16 +30,16 @@ public override void Main () var cbRequests = new ComboBox () { Width = 40, Height = 5, ReadOnly = true, Source = new ListWrapper (new (scrRequests)) }; appWindow.Add (cbRequests); - var label = new Label { Y = Pos.Bottom (cbRequests) + 1, Text = "Request:"}; - var tfRequest = new TextField { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 20 }; + var label = new Label { Y = Pos.Bottom (cbRequests) + 1, Text = "Request:" }; + var tfRequest = new TextField { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 20 }; appWindow.Add (label, tfRequest); - label = new Label { X = Pos.Right (tfRequest) + 1, Y = Pos.Top (tfRequest), Text = "Value:" }; - var tfValue = new TextField { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 6 }; + label = new Label { X = Pos.Right (tfRequest) + 1, Y = Pos.Top (tfRequest) - 1, Text = "Value:" }; + var tfValue = new TextField { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 6 }; appWindow.Add (label, tfValue); - label = new Label { X = Pos.Right (tfValue) + 1, Y = Pos.Top (tfValue), Text = "Terminator:" }; - var tfTerminator = new TextField { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 4 }; + label = new Label { X = Pos.Right (tfValue) + 1, Y = Pos.Top (tfValue) - 1, Text = "Terminator:" }; + var tfTerminator = new TextField { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 4 }; appWindow.Add (label, tfTerminator); cbRequests.SelectedItemChanged += (s, e) => @@ -70,19 +70,19 @@ public override void Main () cbRequests.SelectedItem = 0; label = new Label { Y = Pos.Bottom (tfRequest) + 2, Text = "Response:" }; - var tvResponse = new TextView { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 30, Height = 4, ReadOnly = true }; + var tvResponse = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 40, Height = 4, ReadOnly = true }; appWindow.Add (label, tvResponse); - label = new Label { X = Pos.Right (tvResponse) + 1, Y = Pos.Top (tvResponse), Text = "Error:" }; - var tvError = new TextView { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 20, Height = 4, ReadOnly = true }; + label = new Label { X = Pos.Right (tvResponse) + 1, Y = Pos.Top (tvResponse) - 1, Text = "Error:" }; + var tvError = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 40, Height = 4, ReadOnly = true }; appWindow.Add (label, tvError); - label = new Label { X = Pos.Right (tvError) + 1, Y = Pos.Top (tvError), Text = "Value:" }; - var tvValue = new TextView { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 6, Height = 4, ReadOnly = true }; + label = new Label { X = Pos.Right (tvError) + 1, Y = Pos.Top (tvError) - 1, Text = "Value:" }; + var tvValue = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 6, Height = 4, ReadOnly = true }; appWindow.Add (label, tvValue); - label = new Label { X = Pos.Right (tvValue) + 1, Y = Pos.Top (tvValue), Text = "Terminator:" }; - var tvTerminator = new TextView { X = Pos.Right (label) + 1, Y = Pos.Top (label), Width = 4, Height = 4, ReadOnly = true }; + label = new Label { X = Pos.Right (tvValue) + 1, Y = Pos.Top (tvValue) - 1, Text = "Terminator:" }; + var tvTerminator = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 4, Height = 4, ReadOnly = true }; appWindow.Add (label, tvTerminator); var btnResponse = new Button { X = Pos.Center (), Y = Pos.Bottom (tvResponse) + 2, Text = "Send Request" }; @@ -99,7 +99,7 @@ public override void Main () ansiEscapeSequenceRequest ); - tvResponse.Text =ansiEscapeSequenceResponse.Response; + tvResponse.Text = ansiEscapeSequenceResponse.Response; tvError.Text = ansiEscapeSequenceResponse.Error; tvValue.Text = ansiEscapeSequenceResponse.Value ?? ""; tvTerminator.Text = ansiEscapeSequenceResponse.Terminator; From 8d52fe731fc33fb3c102055518454e6fb7f91f6e Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 2 Oct 2024 01:21:36 +0100 Subject: [PATCH 07/89] Fix NetDriver read key issue. --- .../AnsiEscapeSequenceRequest.cs | 38 ++++++++++++++----- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 13 ++++--- 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index ca11e8a912..d6a5d3470b 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -18,19 +18,31 @@ public static AnsiEscapeSequenceResponse ExecuteAnsiRequest (AnsiEscapeSequenceR var response = new StringBuilder (); var error = new StringBuilder (); var savedIsReportingMouseMoves = false; + NetDriver? netDriver = null; try { switch (Application.Driver) { - case NetDriver netDriver: - savedIsReportingMouseMoves = netDriver.IsReportingMouseMoves; + case NetDriver: + netDriver = Application.Driver as NetDriver; + savedIsReportingMouseMoves = netDriver!.IsReportingMouseMoves; if (savedIsReportingMouseMoves) { netDriver.StopReportingMouseMoves (); } + while (Console.KeyAvailable) + { + netDriver._mainLoopDriver._netEvents._waitForStart.Set (); + netDriver._mainLoopDriver._netEvents._waitForStart.Reset (); + + netDriver._mainLoopDriver._netEvents._forceRead = true; + } + + netDriver._mainLoopDriver._netEvents._forceRead = false; + break; case CursesDriver cursesDriver: savedIsReportingMouseMoves = cursesDriver.IsReportingMouseMoves; @@ -43,12 +55,19 @@ public static AnsiEscapeSequenceResponse ExecuteAnsiRequest (AnsiEscapeSequenceR break; } - Thread.Sleep (100); // Allow time for mouse stopping and to flush the input buffer - - // Flush the input buffer to avoid reading stale input - while (Console.KeyAvailable) + if (netDriver is { }) + { + NetEvents._suspendRead = true; + } + else { - Console.ReadKey (true); + Thread.Sleep (100); // Allow time for mouse stopping and to flush the input buffer + + // Flush the input buffer to avoid reading stale input + while (Console.KeyAvailable) + { + Console.ReadKey (true); + } } // Send the ANSI escape sequence @@ -89,8 +108,9 @@ public static AnsiEscapeSequenceResponse ExecuteAnsiRequest (AnsiEscapeSequenceR { switch (Application.Driver) { - case NetDriver netDriver: - netDriver.StartReportingMouseMoves (); + case NetDriver: + NetEvents._suspendRead = false; + netDriver!.StartReportingMouseMoves (); break; case CursesDriver cursesDriver: diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 79ddbcde2d..6f5204faed 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -136,7 +136,7 @@ internal class NetEvents : IDisposable { private readonly ManualResetEventSlim _inputReady = new (false); private CancellationTokenSource _inputReadyCancellationTokenSource; - private readonly ManualResetEventSlim _waitForStart = new (false); + internal readonly ManualResetEventSlim _waitForStart = new (false); //CancellationTokenSource _waitForStartCancellationTokenSource; private readonly ManualResetEventSlim _winChange = new (false); @@ -202,7 +202,7 @@ private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellation { // if there is a key available, return it without waiting // (or dispatching work to the thread queue) - if (Console.KeyAvailable) + if (Console.KeyAvailable && !_suspendRead) { return Console.ReadKey (intercept); } @@ -211,7 +211,7 @@ private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellation { Task.Delay (100, cancellationToken).Wait (cancellationToken); - if (Console.KeyAvailable) + if (Console.KeyAvailable && !_suspendRead) { return Console.ReadKey (intercept); } @@ -222,6 +222,9 @@ private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellation return default (ConsoleKeyInfo); } + internal bool _forceRead; + internal static bool _suspendRead; + private void ProcessInputQueue () { while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false }) @@ -237,7 +240,7 @@ private void ProcessInputQueue () _waitForStart.Reset (); - if (_inputQueue.Count == 0) + if (_inputQueue.Count == 0 || _forceRead) { ConsoleKey key = 0; ConsoleModifiers mod = 0; @@ -812,7 +815,7 @@ internal class NetDriver : ConsoleDriver private const int COLOR_RED = 31; private const int COLOR_WHITE = 37; private const int COLOR_YELLOW = 33; - private NetMainLoop _mainLoopDriver; + internal NetMainLoop _mainLoopDriver; public bool IsWinPlatform { get; private set; } public NetWinVTConsole NetWinConsole { get; private set; } From 1d20bcec7227bf1928e083d59818d223a8622eb0 Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 2 Oct 2024 12:36:06 +0100 Subject: [PATCH 08/89] Change file name. --- ...siEscapeSequenceRequest.cs => AnsiEscapeSequenceRequests.cs} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename UICatalog/Scenarios/{AnsiEscapeSequenceRequest.cs => AnsiEscapeSequenceRequests.cs} (99%) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs similarity index 99% rename from UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs rename to UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index e8b5a13e5a..10f152c17c 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequest.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -4,7 +4,7 @@ namespace UICatalog.Scenarios; [ScenarioMetadata ("AnsiEscapeSequenceRequest", "Ansi Escape Sequence Request")] -[ScenarioCategory ("Controls")] +[ScenarioCategory ("Ansi Escape Sequence")] public sealed class AnsiEscapeSequenceRequests : Scenario { public override void Main () From c320fc229de25531d5e9aeca85b5014ebada286f Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 2 Oct 2024 17:15:45 +0100 Subject: [PATCH 09/89] Improves null dequeues handling. --- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 6f5204faed..7d9043a32e 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1754,7 +1754,13 @@ void IMainLoopDriver.Iteration () { while (_resultQueue.Count > 0) { - ProcessInput?.Invoke (_resultQueue.Dequeue ().Value); + // Always dequeue even if it's null and invoke if isn't null + InputResult? dequeueResult = _resultQueue.Dequeue (); + + if (dequeueResult is { }) + { + ProcessInput?.Invoke (dequeueResult.Value); + } } } @@ -1810,10 +1816,16 @@ private void NetInputHandler () _resultQueue.Enqueue (_netEvents.DequeueInput ()); } - while (_resultQueue.Count > 0 && _resultQueue.Peek () is null) + try { - _resultQueue.Dequeue (); + while (_resultQueue.Count > 0 && _resultQueue.Peek () is null) + { + // Dequeue null values + _resultQueue.Dequeue (); + } } + catch (InvalidOperationException) // Peek can raise an exception + { } if (_resultQueue.Count > 0) { From 8050202db89a81792e479b778650ab2be583ed15 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 5 Oct 2024 21:31:02 +0100 Subject: [PATCH 10/89] Replace ExecuteAnsiRequest with TryParse. --- .../AnsiEscapeSequenceRequest.cs | 7 ++++-- .../Scenarios/AnsiEscapeSequenceRequests.cs | 22 ++++++++++++++++--- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index d6a5d3470b..10ffd09536 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -12,8 +12,9 @@ public class AnsiEscapeSequenceRequest /// Execute an ANSI escape sequence escape which may return a response or error. /// /// The ANSI escape sequence to request. + /// When this method returns , an object containing the response with an empty error. /// A with the response, error, terminator and value. - public static AnsiEscapeSequenceResponse ExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) + public static bool TryParse (AnsiEscapeSequenceRequest ansiRequest, out AnsiEscapeSequenceResponse result) { var response = new StringBuilder (); var error = new StringBuilder (); @@ -137,7 +138,9 @@ public static AnsiEscapeSequenceResponse ExecuteAnsiRequest (AnsiEscapeSequenceR // Invoke the event if it's subscribed ansiRequest.ResponseReceived?.Invoke (ansiRequest, ansiResponse); - return ansiResponse; + result = ansiResponse; + + return string.IsNullOrWhiteSpace (result.Error) && !string.IsNullOrWhiteSpace (result.Response); } /// diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index 10f152c17c..4f0ffdf48e 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -86,6 +86,10 @@ public override void Main () appWindow.Add (label, tvTerminator); var btnResponse = new Button { X = Pos.Center (), Y = Pos.Bottom (tvResponse) + 2, Text = "Send Request" }; + + var lblSuccess = new Label { X = Pos.Center (), Y = Pos.Bottom (btnResponse) + 1 }; + appWindow.Add (lblSuccess); + btnResponse.Accept += (s, e) => { var ansiEscapeSequenceRequest = new AnsiEscapeSequenceRequest @@ -95,18 +99,30 @@ public override void Main () Value = string.IsNullOrEmpty (tfValue.Text) ? null : tfValue.Text }; - var ansiEscapeSequenceResponse = AnsiEscapeSequenceRequest.ExecuteAnsiRequest ( - ansiEscapeSequenceRequest + var success = AnsiEscapeSequenceRequest.TryParse ( + ansiEscapeSequenceRequest, + out AnsiEscapeSequenceResponse ansiEscapeSequenceResponse ); tvResponse.Text = ansiEscapeSequenceResponse.Response; tvError.Text = ansiEscapeSequenceResponse.Error; tvValue.Text = ansiEscapeSequenceResponse.Value ?? ""; tvTerminator.Text = ansiEscapeSequenceResponse.Terminator; + + if (success) + { + lblSuccess.ColorScheme = Colors.ColorSchemes ["Base"]; + lblSuccess.Text = "Successful"; + } + else + { + lblSuccess.ColorScheme = Colors.ColorSchemes ["Error"]; + lblSuccess.Text = "Error"; + } }; appWindow.Add (btnResponse); - appWindow.Add (new Label { Y = Pos.Bottom (btnResponse) + 2, Text = "You can send other requests by editing the TextFields." }); + appWindow.Add (new Label { Y = Pos.Bottom (lblSuccess) + 2, Text = "You can send other requests by editing the TextFields." }); // Run - Start the application. Application.Run (appWindow); From bdc6fe6873062eaa95a40f987eb95e4138b69684 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 5 Oct 2024 21:51:20 +0100 Subject: [PATCH 11/89] Code cleanup. --- .../AnsiEscapeSequenceRequest.cs | 73 ++++++++++--------- 1 file changed, 38 insertions(+), 35 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 10ffd09536..0db1af58c2 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -8,11 +8,48 @@ namespace Terminal.Gui; /// public class AnsiEscapeSequenceRequest { + /// + /// Request to send e.g. see + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Request + /// + /// + public required string Request { get; init; } + + /// + /// Invoked when the console responds with an ANSI response code that matches the + /// + /// + public event EventHandler? ResponseReceived; + + /// + /// + /// The terminator that uniquely identifies the type of response as responded + /// by the console. e.g. for + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Request + /// + /// the terminator is + /// + /// EscSeqUtils.CSI_SendDeviceAttributes.Terminator + /// + /// . + /// + /// + /// After sending a request, the first response with matching terminator will be matched + /// to the oldest outstanding request. + /// + /// + public required string Terminator { get; init; } + /// /// Execute an ANSI escape sequence escape which may return a response or error. /// /// The ANSI escape sequence to request. - /// When this method returns , an object containing the response with an empty error. + /// + /// When this method returns , an object containing the response with an empty + /// error. + /// /// A with the response, error, terminator and value. public static bool TryParse (AnsiEscapeSequenceRequest ansiRequest, out AnsiEscapeSequenceResponse result) { @@ -143,40 +180,6 @@ public static bool TryParse (AnsiEscapeSequenceRequest ansiRequest, out AnsiEsca return string.IsNullOrWhiteSpace (result.Error) && !string.IsNullOrWhiteSpace (result.Response); } - /// - /// Request to send e.g. see - /// - /// EscSeqUtils.CSI_SendDeviceAttributes.Request - /// - /// - public required string Request { get; init; } - - /// - /// Invoked when the console responds with an ANSI response code that matches the - /// - /// - public event EventHandler? ResponseReceived; - - /// - /// - /// The terminator that uniquely identifies the type of response as responded - /// by the console. e.g. for - /// - /// EscSeqUtils.CSI_SendDeviceAttributes.Request - /// - /// the terminator is - /// - /// EscSeqUtils.CSI_SendDeviceAttributes.Terminator - /// - /// . - /// - /// - /// After sending a request, the first response with matching terminator will be matched - /// to the oldest outstanding request. - /// - /// - public required string Terminator { get; init; } - /// /// The value expected in the response e.g. /// From 922f586904d1388cae6ed164e9d29a490bd9fb45 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 5 Oct 2024 22:31:38 +0100 Subject: [PATCH 12/89] Replace from TryParse to TryExecuteAnsiRequest. --- .../AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs | 2 +- UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 0db1af58c2..383eea28b0 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -51,7 +51,7 @@ public class AnsiEscapeSequenceRequest /// error. /// /// A with the response, error, terminator and value. - public static bool TryParse (AnsiEscapeSequenceRequest ansiRequest, out AnsiEscapeSequenceResponse result) + public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEscapeSequenceResponse result) { var response = new StringBuilder (); var error = new StringBuilder (); diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index 4f0ffdf48e..88bdada347 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -99,7 +99,7 @@ public override void Main () Value = string.IsNullOrEmpty (tfValue.Text) ? null : tfValue.Text }; - var success = AnsiEscapeSequenceRequest.TryParse ( + var success = AnsiEscapeSequenceRequest.TryExecuteAnsiRequest ( ansiEscapeSequenceRequest, out AnsiEscapeSequenceResponse ansiEscapeSequenceResponse ); From 2c76ed20ac947ed2c6cd39783c6b7491bcc6da8e Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 7 Oct 2024 12:52:29 +0100 Subject: [PATCH 13/89] Fix exception throwing if no terminator is specified. --- .../AnsiEscapeSequenceRequest.cs | 23 +++++++++++-------- .../Scenarios/AnsiEscapeSequenceRequests.cs | 2 +- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 383eea28b0..d8dc22ad30 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -57,6 +57,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, var error = new StringBuilder (); var savedIsReportingMouseMoves = false; NetDriver? netDriver = null; + var values = new string? [] { null }; try { @@ -124,14 +125,20 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, // Append the current key to the response response.Append (keyInfo.KeyChar); - if (keyInfo.KeyChar == ansiRequest.Terminator [^1]) // Check if the key is terminator (ANSI escape sequence ends) + // Read until no key is available if no terminator was specified or + // check if the key is terminator (ANSI escape sequence ends) + if (!string.IsNullOrEmpty (ansiRequest.Terminator) && keyInfo.KeyChar == ansiRequest.Terminator [^1]) { // Break out of the loop when terminator is found break; } } - if (!response.ToString ().EndsWith (ansiRequest.Terminator [^1])) + if (string.IsNullOrEmpty (ansiRequest.Terminator)) + { + error.AppendLine ("Terminator request is empty."); + } + else if (!response.ToString ().EndsWith (ansiRequest.Terminator [^1])) { throw new InvalidOperationException ($"Terminator doesn't ends with: '{ansiRequest.Terminator [^1]}'"); } @@ -142,6 +149,11 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, } finally { + if (string.IsNullOrEmpty (error.ToString ())) + { + (string? c1Control, string? code, values, string? terminator) = EscSeqUtils.GetEscapeResult (response.ToString ().ToCharArray ()); + } + if (savedIsReportingMouseMoves) { switch (Application.Driver) @@ -159,13 +171,6 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, } } - var values = new string? [] { null }; - - if (string.IsNullOrEmpty (error.ToString ())) - { - (string? c1Control, string? code, values, string? terminator) = EscSeqUtils.GetEscapeResult (response.ToString ().ToCharArray ()); - } - AnsiEscapeSequenceResponse ansiResponse = new () { Response = response.ToString (), Error = error.ToString (), diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index 88bdada347..eae5085bb3 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -85,7 +85,7 @@ public override void Main () var tvTerminator = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 4, Height = 4, ReadOnly = true }; appWindow.Add (label, tvTerminator); - var btnResponse = new Button { X = Pos.Center (), Y = Pos.Bottom (tvResponse) + 2, Text = "Send Request" }; + var btnResponse = new Button { X = Pos.Center (), Y = Pos.Bottom (tvResponse) + 2, Text = "Send Request", IsDefault = true }; var lblSuccess = new Label { X = Pos.Center (), Y = Pos.Bottom (btnResponse) + 1 }; appWindow.Add (lblSuccess); From 331a49e72b1212611629ba611b0d7fb9fc9fd5f1 Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 9 Oct 2024 12:54:57 +0100 Subject: [PATCH 14/89] Fix merge errors. --- UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index eae5085bb3..8ae89e3467 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -90,7 +90,7 @@ public override void Main () var lblSuccess = new Label { X = Pos.Center (), Y = Pos.Bottom (btnResponse) + 1 }; appWindow.Add (lblSuccess); - btnResponse.Accept += (s, e) => + btnResponse.Accepting += (s, e) => { var ansiEscapeSequenceRequest = new AnsiEscapeSequenceRequest { From e5c30eb442b549dacaba640661f3fd86db213e96 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sun, 13 Oct 2024 13:00:59 +0100 Subject: [PATCH 15/89] Make AnsiEscapeSequenceRequest agnostic of each driver. --- .../AnsiEscapeSequenceRequest.cs | 63 +++---------------- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 20 ++++++ .../CursesDriver/CursesDriver.cs | 14 ++++- .../ConsoleDrivers/FakeDriver/FakeDriver.cs | 22 +++++++ Terminal.Gui/ConsoleDrivers/NetDriver.cs | 27 +++++++- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 21 +++++++ 6 files changed, 106 insertions(+), 61 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index d8dc22ad30..1a3a40fd28 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -56,58 +56,21 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, var response = new StringBuilder (); var error = new StringBuilder (); var savedIsReportingMouseMoves = false; - NetDriver? netDriver = null; + ConsoleDriver? driver = null; var values = new string? [] { null }; try { - switch (Application.Driver) - { - case NetDriver: - netDriver = Application.Driver as NetDriver; - savedIsReportingMouseMoves = netDriver!.IsReportingMouseMoves; - - if (savedIsReportingMouseMoves) - { - netDriver.StopReportingMouseMoves (); - } - - while (Console.KeyAvailable) - { - netDriver._mainLoopDriver._netEvents._waitForStart.Set (); - netDriver._mainLoopDriver._netEvents._waitForStart.Reset (); - - netDriver._mainLoopDriver._netEvents._forceRead = true; - } - - netDriver._mainLoopDriver._netEvents._forceRead = false; + driver = Application.Driver; - break; - case CursesDriver cursesDriver: - savedIsReportingMouseMoves = cursesDriver.IsReportingMouseMoves; - - if (savedIsReportingMouseMoves) - { - cursesDriver.StopReportingMouseMoves (); - } - - break; - } + savedIsReportingMouseMoves = driver!.IsReportingMouseMoves; - if (netDriver is { }) + if (savedIsReportingMouseMoves) { - NetEvents._suspendRead = true; + driver.StopReportingMouseMoves (); } - else - { - Thread.Sleep (100); // Allow time for mouse stopping and to flush the input buffer - // Flush the input buffer to avoid reading stale input - while (Console.KeyAvailable) - { - Console.ReadKey (true); - } - } + driver!.IsSuspendRead = true; // Send the ANSI escape sequence Console.Write (ansiRequest.Request); @@ -156,18 +119,8 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, if (savedIsReportingMouseMoves) { - switch (Application.Driver) - { - case NetDriver: - NetEvents._suspendRead = false; - netDriver!.StartReportingMouseMoves (); - - break; - case CursesDriver cursesDriver: - cursesDriver.StartReportingMouseMoves (); - - break; - } + driver!.IsSuspendRead = false; + driver.StartReportingMouseMoves (); } } diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index 7d6de3834f..e0b8465605 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -562,6 +562,16 @@ public virtual Attribute MakeColor (in Color foreground, in Color background) #region Mouse and Keyboard + /// + /// Gets whether the mouse is reporting move events. + /// + public abstract bool IsReportingMouseMoves { get; internal set; } + + /// + /// Gets whether the terminal is reading input. + /// + public abstract bool IsSuspendRead { get; internal set; } + /// Event fired when a key is pressed down. This is a precursor to . public event EventHandler? KeyDown; @@ -608,6 +618,16 @@ public void OnMouseEvent (MouseEventArgs a) /// If simulates the Ctrl key being pressed. public abstract void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool ctrl); + /// + /// Provide handling for the terminal start reporting mouse events. + /// + public abstract void StartReportingMouseMoves (); + + /// + /// Provide handling for the terminal stop reporting mouse events. + /// + public abstract void StopReportingMouseMoves (); + #endregion } diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index ff4f95bdb6..41e1b08623 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -18,6 +18,7 @@ internal class CursesDriver : ConsoleDriver private MouseFlags _lastMouseFlags; private UnixMainLoop _mainLoopDriver; private object _processInputToken; + private bool _isSuspendRead; public override int Cols { @@ -177,9 +178,16 @@ public override bool SetCursorVisibility (CursorVisibility visibility) return true; } - public bool IsReportingMouseMoves { get; private set; } + public override bool IsReportingMouseMoves { get; internal set; } - public void StartReportingMouseMoves () + /// + public override bool IsSuspendRead + { + get => _isSuspendRead; + internal set => _isSuspendRead = value; + } + + public override void StartReportingMouseMoves () { if (!RunningUnitTests) { @@ -189,7 +197,7 @@ public void StartReportingMouseMoves () } } - public void StopReportingMouseMoves () + public override void StopReportingMouseMoves () { if (!RunningUnitTests) { diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index 73c12959f4..342fe48567 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -40,6 +40,20 @@ public Behaviors ( public static Behaviors FakeBehaviors = new (); public override bool SupportsTrueColor => false; + /// + public override bool IsReportingMouseMoves + { + get => _isReportingMouseMoves; + internal set => _isReportingMouseMoves = value; + } + + /// + public override bool IsSuspendRead + { + get => _isSuspendRead; + internal set => _isSuspendRead = value; + } + public FakeDriver () { Cols = FakeConsole.WindowWidth = FakeConsole.BufferWidth = FakeConsole.WIDTH; @@ -337,6 +351,8 @@ private KeyCode MapKey (ConsoleKeyInfo keyInfo) } private CursorVisibility _savedCursorVisibility; + private bool _isReportingMouseMoves; + private bool _isSuspendRead; private void MockKeyPressedHandler (ConsoleKeyInfo consoleKeyInfo) { @@ -392,6 +408,12 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al MockKeyPressedHandler (new ConsoleKeyInfo (keyChar, key, shift, alt, control)); } + /// + public override void StartReportingMouseMoves () { throw new NotImplementedException (); } + + /// + public override void StopReportingMouseMoves () { throw new NotImplementedException (); } + public void SetBufferSize (int width, int height) { FakeConsole.SetBufferSize (width, height); diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 7d9043a32e..ef82ecf8ec 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1328,6 +1328,7 @@ private bool SetCursorPosition (int col, int row) } private CursorVisibility? _cachedCursorVisibility; + private bool _isSuspendRead; public override void UpdateCursor () { @@ -1376,9 +1377,16 @@ public override bool EnsureCursorVisibility () #region Mouse Handling - public bool IsReportingMouseMoves { get; private set; } + public override bool IsReportingMouseMoves { get; internal set; } - public void StartReportingMouseMoves () + /// + public override bool IsSuspendRead + { + get => _isSuspendRead; + internal set => _isSuspendRead = _suspendRead = value; + } + + public override void StartReportingMouseMoves () { if (!RunningUnitTests) { @@ -1388,7 +1396,7 @@ public void StartReportingMouseMoves () } } - public void StopReportingMouseMoves () + public override void StopReportingMouseMoves () { if (!RunningUnitTests) { @@ -1396,6 +1404,19 @@ public void StopReportingMouseMoves () IsReportingMouseMoves = false; } + + while (_mainLoopDriver is { _netEvents: { }} && Console.KeyAvailable) + { + _mainLoopDriver._netEvents._waitForStart.Set (); + _mainLoopDriver._netEvents._waitForStart.Reset (); + + _mainLoopDriver._netEvents._forceRead = true; + } + + if (_mainLoopDriver is { _netEvents: { } }) + { + _mainLoopDriver._netEvents._forceRead = false; + } } private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index fd5c6901c1..26c01295da 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1035,6 +1035,20 @@ public WindowsDriver () public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal); + /// + public override bool IsReportingMouseMoves + { + get => _isReportingMouseMoves; + internal set => _isReportingMouseMoves = value; + } + + /// + public override bool IsSuspendRead + { + get => _isSuspendRead; + internal set => _isSuspendRead = value; + } + public WindowsConsole WinConsole { get; private set; } public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent) @@ -1162,6 +1176,11 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al } } + /// + public override void StartReportingMouseMoves () { throw new NotImplementedException (); } + + /// + public override void StopReportingMouseMoves () { throw new NotImplementedException (); } #region Not Implemented @@ -1188,6 +1207,8 @@ public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEve #region Cursor Handling private CursorVisibility? _cachedCursorVisibility; + private bool _isReportingMouseMoves; + private bool _isSuspendRead; public override void UpdateCursor () { From 7249de02efc4175d2ed2dd59616fc1eb76093199 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sun, 13 Oct 2024 13:40:56 +0100 Subject: [PATCH 16/89] Cannot run with unit tests. --- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index ef82ecf8ec..d20647ceb5 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1405,7 +1405,7 @@ public override void StopReportingMouseMoves () IsReportingMouseMoves = false; } - while (_mainLoopDriver is { _netEvents: { }} && Console.KeyAvailable) + while (_mainLoopDriver is { _netEvents: { } } && Console.KeyAvailable) { _mainLoopDriver._netEvents._waitForStart.Set (); _mainLoopDriver._netEvents._waitForStart.Reset (); From f850e736a2139e936c1e954d574e83acb3927701 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sun, 13 Oct 2024 14:00:31 +0100 Subject: [PATCH 17/89] Fix unit test. --- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index d20647ceb5..68c8141510 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1403,19 +1403,19 @@ public override void StopReportingMouseMoves () Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); IsReportingMouseMoves = false; - } - while (_mainLoopDriver is { _netEvents: { } } && Console.KeyAvailable) - { - _mainLoopDriver._netEvents._waitForStart.Set (); - _mainLoopDriver._netEvents._waitForStart.Reset (); + while (_mainLoopDriver is { _netEvents: { } } && Console.KeyAvailable) + { + _mainLoopDriver._netEvents._waitForStart.Set (); + _mainLoopDriver._netEvents._waitForStart.Reset (); - _mainLoopDriver._netEvents._forceRead = true; - } + _mainLoopDriver._netEvents._forceRead = true; + } - if (_mainLoopDriver is { _netEvents: { } }) - { - _mainLoopDriver._netEvents._forceRead = false; + if (_mainLoopDriver is { _netEvents: { } }) + { + _mainLoopDriver._netEvents._forceRead = false; + } } } From 67d497ce4edcd25f3dabf8a4d83d1d81d7b96ab2 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 14 Oct 2024 00:21:57 +0100 Subject: [PATCH 18/89] Fixes CursesDriver stale buffer. --- Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 41e1b08623..ce3c6686fa 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -204,6 +204,14 @@ public override void StopReportingMouseMoves () Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); IsReportingMouseMoves = false; + + Thread.Sleep (100); // Allow time for mouse stopping and to flush the input buffer + + // Flush the input buffer to avoid reading stale input + while (Console.KeyAvailable) + { + Console.ReadKey (true); + } } } From b35b9f537a5185c1d4fe9ebf7f7d11188bc102c5 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 14 Oct 2024 16:09:28 +0100 Subject: [PATCH 19/89] Add abstract WriteAnsi into the ConsoleDriver for each driver handling ansi escape sequence. --- .../AnsiEscapeSequenceRequest.cs | 2 +- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 7 +++++++ .../CursesDriver/CursesDriver.cs | 15 ++++++++++++++ .../ConsoleDrivers/FakeDriver/FakeDriver.cs | 15 ++++++++++++++ Terminal.Gui/ConsoleDrivers/NetDriver.cs | 17 +++++++++++++++- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 20 ++++++++++++------- 6 files changed, 67 insertions(+), 9 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 1a3a40fd28..20616d65f0 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -73,7 +73,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, driver!.IsSuspendRead = true; // Send the ANSI escape sequence - Console.Write (ansiRequest.Request); + driver.WriteAnsi (ansiRequest.Request); Console.Out.Flush (); // Ensure the request is sent // Read the response from stdin (response should come back as input) diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index e0b8465605..e3dd8d5e66 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -628,6 +628,13 @@ public void OnMouseEvent (MouseEventArgs a) /// public abstract void StopReportingMouseMoves (); + /// + /// Provide handling for the terminal write ANSI escape sequence. + /// + /// The ANSI escape sequence. + /// + public abstract bool WriteAnsi (string ansi); + #endregion } diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index ce3c6686fa..bbd172b0f8 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -215,6 +215,21 @@ public override void StopReportingMouseMoves () } } + /// + public override bool WriteAnsi (string ansi) + { + try + { + Console.Out.Write (ansi); + } + catch (Exception) + { + return false; + } + + return true; + } + public override void Suspend () { StopReportingMouseMoves (); diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index 342fe48567..568288c84a 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -414,6 +414,21 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al /// public override void StopReportingMouseMoves () { throw new NotImplementedException (); } + /// + public override bool WriteAnsi (string ansi) + { + try + { + Console.Out.Write (ansi); + } + catch (Exception) + { + return false; + } + + return true; + } + public void SetBufferSize (int width, int height) { FakeConsole.SetBufferSize (width, height); diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 68c8141510..b5e1073fd2 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1419,7 +1419,22 @@ public override void StopReportingMouseMoves () } } - private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me) + /// + public override bool WriteAnsi (string ansi) + { + try + { + Console.Out.Write (ansi); + } + catch (Exception) + { + return false; + } + + return true; + } + + private MouseEvent ToDriverMouse (NetEvents.MouseEvent me) { //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}"); diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 26c01295da..6670a4862c 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -134,7 +134,7 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord return result; } - public bool WriteANSI (string ansi) + internal bool WriteANSI (string ansi) { return WriteConsole (_screenBuffer, ansi, (uint)ansi.Length, out uint _, nint.Zero); } @@ -1177,13 +1177,17 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al } /// + public override bool WriteAnsi (string ansi) + { + return WinConsole?.WriteANSI (ansi) ?? false; + } + + #region Not Implemented + public override void StartReportingMouseMoves () { throw new NotImplementedException (); } - /// public override void StopReportingMouseMoves () { throw new NotImplementedException (); } - #region Not Implemented - public override void Suspend () { throw new NotImplementedException (); } #endregion @@ -1235,7 +1239,7 @@ public override void UpdateCursor () { var sb = new StringBuilder (); sb.Append (EscSeqUtils.CSI_SetCursorPosition (position.Y + 1, position.X + 1)); - WinConsole?.WriteANSI (sb.ToString ()); + WriteAnsi (sb.ToString ()); } if (_cachedCursorVisibility is { }) @@ -1271,7 +1275,8 @@ public override bool SetCursorVisibility (CursorVisibility visibility) { var sb = new StringBuilder (); sb.Append (visibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor); - return WinConsole?.WriteANSI (sb.ToString ()) ?? false; + + return WriteAnsi (sb.ToString ()); } } @@ -1286,7 +1291,8 @@ public override bool EnsureCursorVisibility () { var sb = new StringBuilder (); sb.Append (_cachedCursorVisibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor); - return WinConsole?.WriteANSI (sb.ToString ()) ?? false; + + return WriteAnsi (sb.ToString ()); } //if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) From a2e4d82fd72434d55ec7edfa0fb2a9cb187de549 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 14 Oct 2024 16:27:44 +0100 Subject: [PATCH 20/89] Add WriteAnsiDefault method to common code. --- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 14 ++++++++++++++ .../ConsoleDrivers/CursesDriver/CursesDriver.cs | 11 +---------- .../ConsoleDrivers/FakeDriver/FakeDriver.cs | 11 +---------- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 11 +---------- 4 files changed, 17 insertions(+), 30 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index e3dd8d5e66..a2ec4e27a1 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -635,6 +635,20 @@ public void OnMouseEvent (MouseEventArgs a) /// public abstract bool WriteAnsi (string ansi); + internal bool WriteAnsiDefault (string ansi) + { + try + { + Console.Out.Write (ansi); + } + catch (Exception) + { + return false; + } + + return true; + } + #endregion } diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index bbd172b0f8..c0ad1974e7 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -218,16 +218,7 @@ public override void StopReportingMouseMoves () /// public override bool WriteAnsi (string ansi) { - try - { - Console.Out.Write (ansi); - } - catch (Exception) - { - return false; - } - - return true; + return WriteAnsiDefault (ansi); } public override void Suspend () diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index 568288c84a..dc46b055b6 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -417,16 +417,7 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al /// public override bool WriteAnsi (string ansi) { - try - { - Console.Out.Write (ansi); - } - catch (Exception) - { - return false; - } - - return true; + return WriteAnsiDefault (ansi); } public void SetBufferSize (int width, int height) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index b5e1073fd2..d5d3611224 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1422,16 +1422,7 @@ public override void StopReportingMouseMoves () /// public override bool WriteAnsi (string ansi) { - try - { - Console.Out.Write (ansi); - } - catch (Exception) - { - return false; - } - - return true; + return WriteAnsiDefault (ansi); } private MouseEvent ToDriverMouse (NetEvents.MouseEvent me) From cc1d6685c836ea961136359a26d79536bf8fa6af Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 14 Oct 2024 17:00:50 +0100 Subject: [PATCH 21/89] Fix Window Terminal Preview using WindowsDriver. --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 6670a4862c..188d0c6539 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -30,7 +30,7 @@ internal class WindowsConsole public const int STD_INPUT_HANDLE = -10; private readonly nint _inputHandle; - private readonly nint _outputHandle; + private nint _outputHandle; private nint _screenBuffer; private readonly uint _originalConsoleMode; private CursorVisibility? _initialCursorVisibility; @@ -286,6 +286,14 @@ public void Cleanup () ConsoleMode = _originalConsoleMode; + _outputHandle = CreateConsoleScreenBuffer ( + DesiredAccess.GenericRead | DesiredAccess.GenericWrite, + ShareMode.FileShareRead | ShareMode.FileShareWrite, + nint.Zero, + 1, + nint.Zero + ); + if (!SetConsoleActiveScreenBuffer (_outputHandle)) { int err = Marshal.GetLastWin32Error (); From 5ce39961ad571a8da328855d1221a85dbcb09da7 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 14 Oct 2024 17:36:20 +0100 Subject: [PATCH 22/89] Prevents throwing if selected item is equal to minus 1. --- UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index 8ae89e3467..4d3f4dd0b8 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -44,6 +44,11 @@ public override void Main () cbRequests.SelectedItemChanged += (s, e) => { + if (cbRequests.SelectedItem == -1) + { + return; + } + var selAnsiEscapeSequenceRequestName = scrRequests [cbRequests.SelectedItem]; AnsiEscapeSequenceRequest selAnsiEscapeSequenceRequest = null; switch (selAnsiEscapeSequenceRequestName) From d96394152247510304b0e9daee349f2d380b06bc Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 15 Oct 2024 17:27:23 +0100 Subject: [PATCH 23/89] Preparing NetDriver to handle ansi response on demand. --- .../ConsoleDrivers/EscSeqUtils/EscSeqReq.cs | 71 +++++----- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 12 +- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 12 +- UnitTests/Input/EscSeqReqTests.cs | 54 +++++--- UnitTests/Input/EscSeqUtilsTests.cs | 131 +++++++++--------- 5 files changed, 141 insertions(+), 139 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs index 29ef5afa79..bd2c1372e6 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs @@ -1,4 +1,6 @@ -namespace Terminal.Gui; +#nullable enable + +namespace Terminal.Gui; /// /// Represents the status of an ANSI escape sequence request made to the terminal using @@ -8,22 +10,21 @@ public class EscSeqReqStatus { /// Creates a new state of escape sequence request. - /// The terminator. - /// The number of requests. - public EscSeqReqStatus (string terminator, int numReq) + /// The object. + public EscSeqReqStatus (AnsiEscapeSequenceRequest ansiRequest) { - Terminator = terminator; - NumRequests = NumOutstanding = numReq; + AnsiRequest = ansiRequest; + NumRequests = NumOutstanding = 1; } /// Gets the number of unfinished requests. public int NumOutstanding { get; set; } /// Gets the number of requests. - public int NumRequests { get; } + public int NumRequests { get; set; } /// Gets the Escape Sequence Terminator (e.g. ESC[8t ... t is the terminator). - public string Terminator { get; } + public AnsiEscapeSequenceRequest AnsiRequest { get; } } // TODO: This class is a singleton. It should use the singleton pattern. @@ -37,24 +38,28 @@ public class EscSeqRequests public List Statuses { get; } = new (); /// - /// Adds a new request for the ANSI Escape Sequence defined by . Adds a + /// Adds a new request for the ANSI Escape Sequence defined by . Adds a /// instance to list. /// - /// The terminator. - /// The number of requests. - public void Add (string terminator, int numReq = 1) + /// The object. + public void Add (AnsiEscapeSequenceRequest ansiRequest) { lock (Statuses) { - EscSeqReqStatus found = Statuses.Find (x => x.Terminator == terminator); + EscSeqReqStatus? found = Statuses.Find (x => x.AnsiRequest.Terminator == ansiRequest.Terminator); if (found is null) { - Statuses.Add (new EscSeqReqStatus (terminator, numReq)); + Statuses.Add (new (ansiRequest)); + } + else if (found.NumOutstanding < found.NumRequests) + { + found.NumOutstanding = Math.Min (found.NumOutstanding + 1, found.NumRequests); } - else if (found is { } && found.NumOutstanding < found.NumRequests) + else { - found.NumOutstanding = Math.Min (found.NumOutstanding + numReq, found.NumRequests); + found.NumRequests++; + found.NumOutstanding++; } } } @@ -64,54 +69,42 @@ public void Add (string terminator, int numReq = 1) /// list. /// /// + /// /// if exist, otherwise. - public bool HasResponse (string terminator) + public bool HasResponse (string terminator, out EscSeqReqStatus? seqReqStatus) { lock (Statuses) { - EscSeqReqStatus found = Statuses.Find (x => x.Terminator == terminator); - - if (found is null) - { - return false; - } - - if (found is { NumOutstanding: > 0 }) - { - return true; - } - - // BUGBUG: Why does an API that returns a bool remove the entry from the list? - // NetDriver and Unit tests never exercise this line of code. Maybe Curses does? - Statuses.Remove (found); + EscSeqReqStatus? found = Statuses.Find (x => x.AnsiRequest.Terminator == terminator); + seqReqStatus = found; - return false; + return found is { NumOutstanding: > 0 }; } } /// - /// Removes a request defined by . If a matching is + /// Removes a request defined by . If a matching is /// found and the number of outstanding requests is greater than 0, the number of outstanding requests is decremented. /// If the number of outstanding requests is 0, the is removed from /// . /// - /// The terminating string. - public void Remove (string terminator) + /// The object. + public void Remove (EscSeqReqStatus? seqReqStatus) { lock (Statuses) { - EscSeqReqStatus found = Statuses.Find (x => x.Terminator == terminator); + EscSeqReqStatus? found = Statuses.Find (x => x == seqReqStatus); if (found is null) { return; } - if (found is { } && found.NumOutstanding == 0) + if (found is { NumOutstanding: 0 }) { Statuses.Remove (found); } - else if (found is { } && found.NumOutstanding > 0) + else if (found is { NumOutstanding: > 0 }) { found.NumOutstanding--; diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index d32a8e01fe..698965d327 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -1,3 +1,4 @@ +#nullable enable namespace Terminal.Gui; /// @@ -170,7 +171,7 @@ public enum ClearScreenOptions /// Indicates if the escape sequence is a mouse event. /// The button state. /// The position. - /// Indicates if the escape sequence is a response to a request. + /// The object. /// The handler that will process the event. public static void DecodeEscSeq ( EscSeqRequests escSeqRequests, @@ -185,7 +186,7 @@ public static void DecodeEscSeq ( out bool isMouse, out List buttonState, out Point pos, - out bool isResponse, + out EscSeqReqStatus? seqReqStatus, Action continuousButtonPressedHandler ) { @@ -194,7 +195,7 @@ Action continuousButtonPressedHandler isMouse = false; buttonState = new List { 0 }; pos = default (Point); - isResponse = false; + seqReqStatus = null; char keyChar = '\0'; switch (c1Control) @@ -262,10 +263,9 @@ Action continuousButtonPressedHandler return; } - if (escSeqRequests is { } && escSeqRequests.HasResponse (terminator)) + if (escSeqRequests is { } && escSeqRequests.HasResponse (terminator, out seqReqStatus)) { - isResponse = true; - escSeqRequests.Remove (terminator); + escSeqRequests.Remove (seqReqStatus); return; } diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index d5d3611224..adad24b6e7 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -2,7 +2,6 @@ // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient. // -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping; @@ -202,7 +201,7 @@ private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellation { // if there is a key available, return it without waiting // (or dispatching work to the thread queue) - if (Console.KeyAvailable && !_suspendRead) + if (Console.KeyAvailable) { return Console.ReadKey (intercept); } @@ -211,7 +210,7 @@ private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellation { Task.Delay (100, cancellationToken).Wait (cancellationToken); - if (Console.KeyAvailable && !_suspendRead) + if (Console.KeyAvailable) { return Console.ReadKey (intercept); } @@ -223,7 +222,6 @@ private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellation } internal bool _forceRead; - internal static bool _suspendRead; private void ProcessInputQueue () { @@ -432,7 +430,7 @@ ref ConsoleModifiers mod out bool isMouse, out List mouseFlags, out Point pos, - out bool isReq, + out EscSeqReqStatus seqReqStatus, (f, p) => HandleMouseEvent (MapMouseFlags (f), p) ); @@ -446,7 +444,7 @@ ref ConsoleModifiers mod return; } - if (isReq) + if (seqReqStatus is { }) { HandleRequestResponseEvent (c1Control, code, values, terminating); @@ -1383,7 +1381,7 @@ public override bool EnsureCursorVisibility () public override bool IsSuspendRead { get => _isSuspendRead; - internal set => _isSuspendRead = _suspendRead = value; + internal set => _isSuspendRead = value; } public override void StartReportingMouseMoves () diff --git a/UnitTests/Input/EscSeqReqTests.cs b/UnitTests/Input/EscSeqReqTests.cs index 6b73b2af0f..d1499eabdd 100644 --- a/UnitTests/Input/EscSeqReqTests.cs +++ b/UnitTests/Input/EscSeqReqTests.cs @@ -6,30 +6,31 @@ public class EscSeqReqTests public void Add_Tests () { var escSeqReq = new EscSeqRequests (); - escSeqReq.Add ("t"); + escSeqReq.Add (new () { Request = "", Terminator = "t" }); Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].Terminator); + Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); Assert.Equal (1, escSeqReq.Statuses [^1].NumRequests); Assert.Equal (1, escSeqReq.Statuses [^1].NumOutstanding); - escSeqReq.Add ("t", 2); + escSeqReq.Add (new () { Request = "", Terminator = "t" }); Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].Terminator); - Assert.Equal (1, escSeqReq.Statuses [^1].NumRequests); - Assert.Equal (1, escSeqReq.Statuses [^1].NumOutstanding); - - escSeqReq = new EscSeqRequests (); - escSeqReq.Add ("t", 2); - Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].Terminator); + Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); Assert.Equal (2, escSeqReq.Statuses [^1].NumRequests); Assert.Equal (2, escSeqReq.Statuses [^1].NumOutstanding); - escSeqReq.Add ("t", 3); + escSeqReq = new (); + escSeqReq.Add (new () { Request = "", Terminator = "t" }); + escSeqReq.Add (new () { Request = "", Terminator = "t" }); Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].Terminator); + Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); Assert.Equal (2, escSeqReq.Statuses [^1].NumRequests); Assert.Equal (2, escSeqReq.Statuses [^1].NumOutstanding); + + escSeqReq.Add (new () { Request = "", Terminator = "t" }); + Assert.Single (escSeqReq.Statuses); + Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); + Assert.Equal (3, escSeqReq.Statuses [^1].NumRequests); + Assert.Equal (3, escSeqReq.Statuses [^1].NumOutstanding); } [Fact] @@ -44,18 +45,22 @@ public void Constructor_Defaults () public void Remove_Tests () { var escSeqReq = new EscSeqRequests (); - escSeqReq.Add ("t"); - escSeqReq.Remove ("t"); + escSeqReq.Add (new () { Request = "", Terminator = "t" }); + escSeqReq.HasResponse ("t", out EscSeqReqStatus seqReqStatus); + escSeqReq.Remove (seqReqStatus); Assert.Empty (escSeqReq.Statuses); - escSeqReq.Add ("t", 2); - escSeqReq.Remove ("t"); + escSeqReq.Add (new () { Request = "", Terminator = "t" }); + escSeqReq.Add (new () { Request = "", Terminator = "t" }); + escSeqReq.HasResponse ("t", out seqReqStatus); + escSeqReq.Remove (seqReqStatus); Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].Terminator); + Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); Assert.Equal (2, escSeqReq.Statuses [^1].NumRequests); Assert.Equal (1, escSeqReq.Statuses [^1].NumOutstanding); - escSeqReq.Remove ("t"); + escSeqReq.HasResponse ("t", out seqReqStatus); + escSeqReq.Remove (seqReqStatus); Assert.Empty (escSeqReq.Statuses); } @@ -63,10 +68,13 @@ public void Remove_Tests () public void Requested_Tests () { var escSeqReq = new EscSeqRequests (); - Assert.False (escSeqReq.HasResponse ("t")); + Assert.False (escSeqReq.HasResponse ("t", out EscSeqReqStatus seqReqStatus)); + Assert.Null (seqReqStatus); - escSeqReq.Add ("t"); - Assert.False (escSeqReq.HasResponse ("r")); - Assert.True (escSeqReq.HasResponse ("t")); + escSeqReq.Add (new () { Request = "", Terminator = "t" }); + Assert.False (escSeqReq.HasResponse ("r", out seqReqStatus)); + Assert.Null (seqReqStatus); + Assert.True (escSeqReq.HasResponse ("t", out seqReqStatus)); + Assert.NotNull (seqReqStatus); } } diff --git a/UnitTests/Input/EscSeqUtilsTests.cs b/UnitTests/Input/EscSeqUtilsTests.cs index 9b811f0026..7b6e6538e4 100644 --- a/UnitTests/Input/EscSeqUtilsTests.cs +++ b/UnitTests/Input/EscSeqUtilsTests.cs @@ -1,4 +1,6 @@ -namespace Terminal.Gui.InputTests; +using JetBrains.Annotations; + +namespace Terminal.Gui.InputTests; public class EscSeqUtilsTests { @@ -9,7 +11,8 @@ public class EscSeqUtilsTests private ConsoleKeyInfo [] _cki; private EscSeqRequests _escSeqReqProc; private bool _isKeyMouse; - private bool _isReq; + [CanBeNull] + private EscSeqReqStatus _seqReqStatus; private ConsoleKey _key; private ConsoleModifiers _mod; private List _mouseFlags; @@ -38,7 +41,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -50,9 +53,9 @@ public void DecodeEscSeq_Tests () Assert.Null (_values); Assert.Null (_terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -73,7 +76,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -85,9 +88,9 @@ public void DecodeEscSeq_Tests () Assert.Null (_values); Assert.Equal ("\u0012", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -108,7 +111,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -120,9 +123,9 @@ public void DecodeEscSeq_Tests () Assert.Null (_values); Assert.Equal ("r", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -148,7 +151,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -161,9 +164,9 @@ public void DecodeEscSeq_Tests () Assert.Null (_values [0]); Assert.Equal ("R", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -194,7 +197,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -208,9 +211,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("2", _values [^1]); Assert.Equal ("R", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -240,7 +243,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -254,9 +257,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("3", _values [^1]); Assert.Equal ("R", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -286,7 +289,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -300,9 +303,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("4", _values [^1]); Assert.Equal ("R", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -332,7 +335,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -346,9 +349,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("5", _values [^1]); Assert.Equal ("R", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -378,7 +381,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -392,9 +395,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("6", _values [^1]); Assert.Equal ("R", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -424,7 +427,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -438,9 +441,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("7", _values [^1]); Assert.Equal ("R", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -470,7 +473,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -484,9 +487,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("8", _values [^1]); Assert.Equal ("R", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -519,7 +522,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -534,9 +537,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("3", _values [^1]); Assert.Equal ("M", _terminating); Assert.True (_isKeyMouse); - Assert.Equal (new() { MouseFlags.Button1Pressed }, _mouseFlags); + Assert.Equal (new () { MouseFlags.Button1Pressed }, _mouseFlags); Assert.Equal (new (1, 2), _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -569,7 +572,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -587,11 +590,11 @@ public void DecodeEscSeq_Tests () Assert.Equal (2, _mouseFlags.Count); Assert.Equal ( - new() { MouseFlags.Button1Released, MouseFlags.Button1Clicked }, + new () { MouseFlags.Button1Released, MouseFlags.Button1Clicked }, _mouseFlags ); Assert.Equal (new (1, 2), _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -624,7 +627,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -639,9 +642,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("3", _values [^1]); Assert.Equal ("M", _terminating); Assert.True (_isKeyMouse); - Assert.Equal (new() { MouseFlags.Button1DoubleClicked }, _mouseFlags); + Assert.Equal (new () { MouseFlags.Button1DoubleClicked }, _mouseFlags); Assert.Equal (new (1, 2), _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); ClearAll (); @@ -672,7 +675,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -687,9 +690,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("3", _values [^1]); Assert.Equal ("M", _terminating); Assert.True (_isKeyMouse); - Assert.Equal (new() { MouseFlags.Button1TripleClicked }, _mouseFlags); + Assert.Equal (new () { MouseFlags.Button1TripleClicked }, _mouseFlags); Assert.Equal (new (1, 2), _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); var view = new View { Width = Dim.Fill (), Height = Dim.Fill (), WantContinuousButtonPressed = true }; var top = new Toplevel (); @@ -727,7 +730,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -742,9 +745,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("3", _values [^1]); Assert.Equal ("M", _terminating); Assert.True (_isKeyMouse); - Assert.Equal (new() { MouseFlags.Button1Pressed }, _mouseFlags); + Assert.Equal (new () { MouseFlags.Button1Pressed }, _mouseFlags); Assert.Equal (new (1, 2), _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Application.Iteration += (s, a) => { @@ -796,7 +799,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Null (_escSeqReqProc); @@ -811,9 +814,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("3", _values [^1]); Assert.Equal ("m", _terminating); Assert.True (_isKeyMouse); - Assert.Equal (new() { MouseFlags.Button1Released }, _mouseFlags); + Assert.Equal (new () { MouseFlags.Button1Released }, _mouseFlags); Assert.Equal (new (1, 2), _pos); - Assert.False (_isReq); + Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); @@ -821,7 +824,7 @@ public void DecodeEscSeq_Tests () Assert.Null (_escSeqReqProc); _escSeqReqProc = new (); - _escSeqReqProc.Add ("t"); + _escSeqReqProc.Add (new () { Request = "", Terminator = "t" }); _cki = new ConsoleKeyInfo [] { @@ -838,7 +841,7 @@ public void DecodeEscSeq_Tests () }; expectedCki = default (ConsoleKeyInfo); Assert.Single (_escSeqReqProc.Statuses); - Assert.Equal ("t", _escSeqReqProc.Statuses [^1].Terminator); + Assert.Equal ("t", _escSeqReqProc.Statuses [^1].AnsiRequest.Terminator); EscSeqUtils.DecodeEscSeq ( _escSeqReqProc, @@ -853,7 +856,7 @@ public void DecodeEscSeq_Tests () out _isKeyMouse, out _mouseFlags, out _pos, - out _isReq, + out _seqReqStatus, ProcessContinuousButtonPressed ); Assert.Empty (_escSeqReqProc.Statuses); @@ -868,9 +871,9 @@ public void DecodeEscSeq_Tests () Assert.Equal ("20", _values [^1]); Assert.Equal ("t", _terminating); Assert.False (_isKeyMouse); - Assert.Equal (new() { 0 }, _mouseFlags); + Assert.Equal (new () { 0 }, _mouseFlags); Assert.Equal (Point.Empty, _pos); - Assert.True (_isReq); + Assert.NotNull (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); } @@ -1073,7 +1076,7 @@ public void GetMouse_Tests () new ('M', 0, false, false, false) }; EscSeqUtils.GetMouse (cki, out List mouseFlags, out Point pos, ProcessContinuousButtonPressed); - Assert.Equal (new() { MouseFlags.Button1Pressed }, mouseFlags); + Assert.Equal (new () { MouseFlags.Button1Pressed }, mouseFlags); Assert.Equal (new (1, 2), pos); cki = new ConsoleKeyInfo [] @@ -1092,7 +1095,7 @@ public void GetMouse_Tests () Assert.Equal (2, mouseFlags.Count); Assert.Equal ( - new() { MouseFlags.Button1Released, MouseFlags.Button1Clicked }, + new () { MouseFlags.Button1Released, MouseFlags.Button1Clicked }, mouseFlags ); Assert.Equal (new (1, 2), pos); @@ -1110,7 +1113,7 @@ public void GetMouse_Tests () new ('M', 0, false, false, false) }; EscSeqUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); - Assert.Equal (new() { MouseFlags.Button1DoubleClicked }, mouseFlags); + Assert.Equal (new () { MouseFlags.Button1DoubleClicked }, mouseFlags); Assert.Equal (new (1, 2), pos); cki = new ConsoleKeyInfo [] @@ -1126,7 +1129,7 @@ public void GetMouse_Tests () new ('M', 0, false, false, false) }; EscSeqUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); - Assert.Equal (new() { MouseFlags.Button1TripleClicked }, mouseFlags); + Assert.Equal (new () { MouseFlags.Button1TripleClicked }, mouseFlags); Assert.Equal (new (1, 2), pos); cki = new ConsoleKeyInfo [] @@ -1142,7 +1145,7 @@ public void GetMouse_Tests () new ('m', 0, false, false, false) }; EscSeqUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); - Assert.Equal (new() { MouseFlags.Button1Released }, mouseFlags); + Assert.Equal (new () { MouseFlags.Button1Released }, mouseFlags); Assert.Equal (new (1, 2), pos); } @@ -1168,7 +1171,7 @@ private void ClearAll () _terminating = default (string); _values = default (string []); _isKeyMouse = default (bool); - _isReq = default (bool); + _seqReqStatus = null; _mouseFlags = default (List); _pos = default (Point); _arg1 = default (MouseFlags); From 0de826294868822a5a2a9eaddad878800765eb82 Mon Sep 17 00:00:00 2001 From: Tig Date: Mon, 14 Oct 2024 18:30:21 -0600 Subject: [PATCH 24/89] View.Mouse cleanup - WIP --- Terminal.Gui/View/View.Mouse.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Terminal.Gui/View/View.Mouse.cs b/Terminal.Gui/View/View.Mouse.cs index a76de77b34..eb6f4d6d39 100644 --- a/Terminal.Gui/View/View.Mouse.cs +++ b/Terminal.Gui/View/View.Mouse.cs @@ -318,6 +318,14 @@ protected virtual bool OnMouseEvent (MouseEventArgs mouseEvent) /// public event EventHandler? MouseEvent; + /// Raised when a mouse event occurs. + /// + /// + /// The coordinates are relative to . + /// + /// + public event EventHandler? MouseEvent; + #endregion Low Level Mouse Events #region Mouse Click Events From c3187482fc0345c65336fe8c67562111ef2ba20a Mon Sep 17 00:00:00 2001 From: Tig Date: Tue, 15 Oct 2024 06:52:05 -0600 Subject: [PATCH 25/89] View.Mouse cleanup - WIP3 --- Terminal.Gui/Views/ComboBox.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/Views/ComboBox.cs b/Terminal.Gui/Views/ComboBox.cs index 996056068c..72056992d3 100644 --- a/Terminal.Gui/Views/ComboBox.cs +++ b/Terminal.Gui/Views/ComboBox.cs @@ -880,7 +880,7 @@ protected override bool OnMouseEvent (MouseEventArgs me) return true; } - return res; + return false; } public override void OnDrawContent (Rectangle viewport) From 2ad9887ecba938197422fb43bc4bb0dfa45524a0 Mon Sep 17 00:00:00 2001 From: Tig Date: Tue, 15 Oct 2024 06:56:53 -0600 Subject: [PATCH 26/89] View.Mouse cleanup - Fixed combobox --- Terminal.Gui/Views/ComboBox.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/Views/ComboBox.cs b/Terminal.Gui/Views/ComboBox.cs index 72056992d3..996056068c 100644 --- a/Terminal.Gui/Views/ComboBox.cs +++ b/Terminal.Gui/Views/ComboBox.cs @@ -880,7 +880,7 @@ protected override bool OnMouseEvent (MouseEventArgs me) return true; } - return false; + return res; } public override void OnDrawContent (Rectangle viewport) From ec14b62adedca7708f445aea6b8535a77e9d3d8d Mon Sep 17 00:00:00 2001 From: Tig Date: Tue, 15 Oct 2024 07:40:42 -0600 Subject: [PATCH 27/89] Merged MouseEvent and MouseEventEventArgs into MouseEventArgs --- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index adad24b6e7..1c780e2910 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1423,7 +1423,7 @@ public override bool WriteAnsi (string ansi) return WriteAnsiDefault (ansi); } - private MouseEvent ToDriverMouse (NetEvents.MouseEvent me) + private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me) { //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}"); From 9dcfe02087d157ca9ee65d577c5b96a71fa188c4 Mon Sep 17 00:00:00 2001 From: Tig Date: Tue, 15 Oct 2024 10:48:00 -0600 Subject: [PATCH 28/89] Fixed Time/DateField crash --- Terminal.Gui/Views/DateField.cs | 2 +- Terminal.Gui/Views/TimeField.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Terminal.Gui/Views/DateField.cs b/Terminal.Gui/Views/DateField.cs index 9490a7b28c..641b5d3144 100644 --- a/Terminal.Gui/Views/DateField.cs +++ b/Terminal.Gui/Views/DateField.cs @@ -167,7 +167,7 @@ private void AdjCursorPosition (int point, bool increment = true) newPoint = 1; } - if (newPoint != point) + //if (newPoint != point) { CursorPosition = newPoint; } diff --git a/Terminal.Gui/Views/TimeField.cs b/Terminal.Gui/Views/TimeField.cs index ecc94a7be4..abd4048b23 100644 --- a/Terminal.Gui/Views/TimeField.cs +++ b/Terminal.Gui/Views/TimeField.cs @@ -225,7 +225,7 @@ private void AdjCursorPosition (int point, bool increment = true) newPoint = 1; } - if (newPoint != point) + //if (newPoint != point) { CursorPosition = newPoint; } From 59396aeb75f86adf7348bcbe8f7b3656e497756f Mon Sep 17 00:00:00 2001 From: Tig Date: Tue, 15 Oct 2024 10:55:23 -0600 Subject: [PATCH 29/89] Fixed Time/DateField crash 2 --- Terminal.Gui/Views/DateField.cs | 2 +- Terminal.Gui/Views/TimeField.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Terminal.Gui/Views/DateField.cs b/Terminal.Gui/Views/DateField.cs index 641b5d3144..9490a7b28c 100644 --- a/Terminal.Gui/Views/DateField.cs +++ b/Terminal.Gui/Views/DateField.cs @@ -167,7 +167,7 @@ private void AdjCursorPosition (int point, bool increment = true) newPoint = 1; } - //if (newPoint != point) + if (newPoint != point) { CursorPosition = newPoint; } diff --git a/Terminal.Gui/Views/TimeField.cs b/Terminal.Gui/Views/TimeField.cs index abd4048b23..ecc94a7be4 100644 --- a/Terminal.Gui/Views/TimeField.cs +++ b/Terminal.Gui/Views/TimeField.cs @@ -225,7 +225,7 @@ private void AdjCursorPosition (int point, bool increment = true) newPoint = 1; } - //if (newPoint != point) + if (newPoint != point) { CursorPosition = newPoint; } From 49096fa389536636393fb858443fd787ab6d70b9 Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 15 Oct 2024 19:32:13 +0100 Subject: [PATCH 30/89] Fix merge errors. --- Terminal.Gui/View/View.Mouse.cs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Terminal.Gui/View/View.Mouse.cs b/Terminal.Gui/View/View.Mouse.cs index eb6f4d6d39..a76de77b34 100644 --- a/Terminal.Gui/View/View.Mouse.cs +++ b/Terminal.Gui/View/View.Mouse.cs @@ -318,14 +318,6 @@ protected virtual bool OnMouseEvent (MouseEventArgs mouseEvent) /// public event EventHandler? MouseEvent; - /// Raised when a mouse event occurs. - /// - /// - /// The coordinates are relative to . - /// - /// - public event EventHandler? MouseEvent; - #endregion Low Level Mouse Events #region Mouse Click Events From 884011e99cdb76fe330af2d80bf3ca1343350dee Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 16 Oct 2024 01:30:02 +0100 Subject: [PATCH 31/89] Improving WriteAnsi method to return the response. --- .../AnsiEscapeSequenceRequest.cs | 38 ++--- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 35 +++- .../CursesDriver/CursesDriver.cs | 9 +- .../ConsoleDrivers/EscSeqUtils/EscSeqReq.cs | 72 +++----- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 4 +- .../ConsoleDrivers/FakeDriver/FakeDriver.cs | 9 +- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 160 +++++++++++------- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 17 +- UnitTests/Input/EscSeqReqTests.cs | 26 +-- UnitTests/Input/EscSeqUtilsTests.cs | 2 +- 10 files changed, 198 insertions(+), 174 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 20616d65f0..942a5f828b 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -16,6 +16,11 @@ public class AnsiEscapeSequenceRequest /// public required string Request { get; init; } + /// + /// Response received from the request. + /// + public string Response { get; internal set; } = string.Empty; + /// /// Invoked when the console responds with an ANSI response code that matches the /// @@ -53,7 +58,6 @@ public class AnsiEscapeSequenceRequest /// A with the response, error, terminator and value. public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEscapeSequenceResponse result) { - var response = new StringBuilder (); var error = new StringBuilder (); var savedIsReportingMouseMoves = false; ConsoleDriver? driver = null; @@ -73,35 +77,13 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, driver!.IsSuspendRead = true; // Send the ANSI escape sequence - driver.WriteAnsi (ansiRequest.Request); - Console.Out.Flush (); // Ensure the request is sent - - // Read the response from stdin (response should come back as input) - Thread.Sleep (100); // Allow time for the terminal to respond - - // Read input until no more characters are available or the terminator is encountered - while (Console.KeyAvailable) - { - // Peek the next key - ConsoleKeyInfo keyInfo = Console.ReadKey (true); // true to not display on the console - - // Append the current key to the response - response.Append (keyInfo.KeyChar); - - // Read until no key is available if no terminator was specified or - // check if the key is terminator (ANSI escape sequence ends) - if (!string.IsNullOrEmpty (ansiRequest.Terminator) && keyInfo.KeyChar == ansiRequest.Terminator [^1]) - { - // Break out of the loop when terminator is found - break; - } - } + ansiRequest.Response = driver.WriteAnsi (ansiRequest); if (string.IsNullOrEmpty (ansiRequest.Terminator)) { error.AppendLine ("Terminator request is empty."); } - else if (!response.ToString ().EndsWith (ansiRequest.Terminator [^1])) + else if (!ansiRequest.Response.EndsWith (ansiRequest.Terminator [^1])) { throw new InvalidOperationException ($"Terminator doesn't ends with: '{ansiRequest.Terminator [^1]}'"); } @@ -114,7 +96,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, { if (string.IsNullOrEmpty (error.ToString ())) { - (string? c1Control, string? code, values, string? terminator) = EscSeqUtils.GetEscapeResult (response.ToString ().ToCharArray ()); + (string? c1Control, string? code, values, string? terminator) = EscSeqUtils.GetEscapeResult (ansiRequest.Response.ToCharArray ()); } if (savedIsReportingMouseMoves) @@ -126,8 +108,8 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, AnsiEscapeSequenceResponse ansiResponse = new () { - Response = response.ToString (), Error = error.ToString (), - Terminator = string.IsNullOrEmpty (response.ToString ()) ? "" : response.ToString () [^1].ToString (), Value = values [0] + Response = ansiRequest.Response, Error = error.ToString (), + Terminator = string.IsNullOrEmpty (ansiRequest.Response) ? "" : ansiRequest.Response [^1].ToString (), Value = values [0] }; // Invoke the event if it's subscribed diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index a2ec4e27a1..8252ea5e56 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -629,17 +629,22 @@ public void OnMouseEvent (MouseEventArgs a) public abstract void StopReportingMouseMoves (); /// - /// Provide handling for the terminal write ANSI escape sequence. + /// Provide handling for the terminal write ANSI escape sequence request. /// - /// The ANSI escape sequence. + /// The object. /// - public abstract bool WriteAnsi (string ansi); + public abstract string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest); internal bool WriteAnsiDefault (string ansi) { try { Console.Out.Write (ansi); + Console.Out.Flush (); // Ensure the request is sent + + // Read the response from stdin (response should come back as input) + Thread.Sleep (100); // Allow time for the terminal to respond + } catch (Exception) { @@ -649,6 +654,30 @@ internal bool WriteAnsiDefault (string ansi) return true; } + internal string ReadAnsiDefault (AnsiEscapeSequenceRequest ansiRequest) + { + var response = new StringBuilder (); + + while (Console.KeyAvailable) + { + // Peek the next key + ConsoleKeyInfo keyInfo = Console.ReadKey (true); // true to not display on the console + + // Append the current key to the response + response.Append (keyInfo.KeyChar); + + // Read until no key is available if no terminator was specified or + // check if the key is terminator (ANSI escape sequence ends) + if (!string.IsNullOrEmpty (ansiRequest.Terminator) && keyInfo.KeyChar == ansiRequest.Terminator [^1]) + { + // Break out of the loop when terminator is found + break; + } + } + + return response.ToString (); + } + #endregion } diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index c0ad1974e7..6d1e3cbc39 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -216,9 +216,14 @@ public override void StopReportingMouseMoves () } /// - public override bool WriteAnsi (string ansi) + public override string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest) { - return WriteAnsiDefault (ansi); + if (WriteAnsiDefault (ansiRequest.Request)) + { + return ReadAnsiDefault (ansiRequest); + } + + return string.Empty; } public override void Suspend () diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs index bd2c1372e6..178f8f7a95 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs @@ -11,17 +11,7 @@ public class EscSeqReqStatus { /// Creates a new state of escape sequence request. /// The object. - public EscSeqReqStatus (AnsiEscapeSequenceRequest ansiRequest) - { - AnsiRequest = ansiRequest; - NumRequests = NumOutstanding = 1; - } - - /// Gets the number of unfinished requests. - public int NumOutstanding { get; set; } - - /// Gets the number of requests. - public int NumRequests { get; set; } + public EscSeqReqStatus (AnsiEscapeSequenceRequest ansiRequest) { AnsiRequest = ansiRequest; } /// Gets the Escape Sequence Terminator (e.g. ESC[8t ... t is the terminator). public AnsiEscapeSequenceRequest AnsiRequest { get; } @@ -34,9 +24,6 @@ public EscSeqReqStatus (AnsiEscapeSequenceRequest ansiRequest) /// public class EscSeqRequests { - /// Gets the list. - public List Statuses { get; } = new (); - /// /// Adds a new request for the ANSI Escape Sequence defined by . Adds a /// instance to list. @@ -46,21 +33,10 @@ public void Add (AnsiEscapeSequenceRequest ansiRequest) { lock (Statuses) { - EscSeqReqStatus? found = Statuses.Find (x => x.AnsiRequest.Terminator == ansiRequest.Terminator); - - if (found is null) - { - Statuses.Add (new (ansiRequest)); - } - else if (found.NumOutstanding < found.NumRequests) - { - found.NumOutstanding = Math.Min (found.NumOutstanding + 1, found.NumRequests); - } - else - { - found.NumRequests++; - found.NumOutstanding++; - } + Statuses.Enqueue (new (ansiRequest)); + Console.Out.Write (ansiRequest.Request); + Console.Out.Flush (); + Thread.Sleep (100); // Allow time for the terminal to respond } } @@ -75,10 +51,18 @@ public bool HasResponse (string terminator, out EscSeqReqStatus? seqReqStatus) { lock (Statuses) { - EscSeqReqStatus? found = Statuses.Find (x => x.AnsiRequest.Terminator == terminator); - seqReqStatus = found; + Statuses.TryPeek (out seqReqStatus); + + var result = seqReqStatus?.AnsiRequest.Terminator == terminator; - return found is { NumOutstanding: > 0 }; + if (result) + { + return true; + } + + seqReqStatus = null; + + return false; } } @@ -93,26 +77,10 @@ public void Remove (EscSeqReqStatus? seqReqStatus) { lock (Statuses) { - EscSeqReqStatus? found = Statuses.Find (x => x == seqReqStatus); - - if (found is null) - { - return; - } - - if (found is { NumOutstanding: 0 }) - { - Statuses.Remove (found); - } - else if (found is { NumOutstanding: > 0 }) - { - found.NumOutstanding--; - - if (found.NumOutstanding == 0) - { - Statuses.Remove (found); - } - } + Statuses.Dequeue (); } } + + /// Gets the list. + public Queue Statuses { get; } = new (); } diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 698965d327..a8c830f7e3 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -174,7 +174,7 @@ public enum ClearScreenOptions /// The object. /// The handler that will process the event. public static void DecodeEscSeq ( - EscSeqRequests escSeqRequests, + EscSeqRequests? escSeqRequests, ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ConsoleKeyInfo [] cki, @@ -497,7 +497,7 @@ public static (string c1Control, string code, string [] values, string terminati // PERF: This is expensive public static char [] GetKeyCharArray (ConsoleKeyInfo [] cki) { - char [] kChar = { }; + char [] kChar = []; var length = 0; foreach (ConsoleKeyInfo kc in cki) diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index dc46b055b6..10a53234d8 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -415,9 +415,14 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al public override void StopReportingMouseMoves () { throw new NotImplementedException (); } /// - public override bool WriteAnsi (string ansi) + public override string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest) { - return WriteAnsiDefault (ansi); + if (WriteAnsiDefault (ansiRequest.Request)) + { + return ReadAnsiDefault (ansiRequest); + } + + return string.Empty; } public void SetBufferSize (int width, int height) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 1c780e2910..2f9f2a0318 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -446,7 +446,17 @@ ref ConsoleModifiers mod if (seqReqStatus is { }) { - HandleRequestResponseEvent (c1Control, code, values, terminating); + //HandleRequestResponseEvent (c1Control, code, values, terminating); + StringBuilder sb = new (); + + foreach (ConsoleKeyInfo keyChar in cki) + { + sb.Append (keyChar.KeyChar); + } + + seqReqStatus.AnsiRequest.Response = sb.ToString (); + + ((NetDriver)_consoleDriver)._waitAnsiResponse.Set (); return; } @@ -590,64 +600,64 @@ private MouseButtonState MapMouseFlags (MouseFlags mouseFlags) private Point _lastCursorPosition; - private void HandleRequestResponseEvent (string c1Control, string code, string [] values, string terminating) - { - if (terminating == - - // BUGBUG: I can't find where we send a request for cursor position (ESC[?6n), so I'm not sure if this is needed. - // The observation is correct because the response isn't immediate and this is useless - EscSeqUtils.CSI_RequestCursorPositionReport.Terminator) - { - var point = new Point { X = int.Parse (values [1]) - 1, Y = int.Parse (values [0]) - 1 }; - - if (_lastCursorPosition.Y != point.Y) - { - _lastCursorPosition = point; - var eventType = EventType.WindowPosition; - var winPositionEv = new WindowPositionEvent { CursorPosition = point }; - - _inputQueue.Enqueue ( - new InputResult { EventType = eventType, WindowPositionEvent = winPositionEv } - ); - } - else - { - return; - } - } - else if (terminating == EscSeqUtils.CSI_ReportTerminalSizeInChars.Terminator) - { - if (values [0] == EscSeqUtils.CSI_ReportTerminalSizeInChars.Value) - { - EnqueueWindowSizeEvent ( - Math.Max (int.Parse (values [1]), 0), - Math.Max (int.Parse (values [2]), 0), - Math.Max (int.Parse (values [1]), 0), - Math.Max (int.Parse (values [2]), 0) - ); - } - else - { - EnqueueRequestResponseEvent (c1Control, code, values, terminating); - } - } - else - { - EnqueueRequestResponseEvent (c1Control, code, values, terminating); - } - - _inputReady.Set (); - } + //private void HandleRequestResponseEvent (string c1Control, string code, string [] values, string terminating) + //{ + // if (terminating == + + // // BUGBUG: I can't find where we send a request for cursor position (ESC[?6n), so I'm not sure if this is needed. + // // The observation is correct because the response isn't immediate and this is useless + // EscSeqUtils.CSI_RequestCursorPositionReport.Terminator) + // { + // var point = new Point { X = int.Parse (values [1]) - 1, Y = int.Parse (values [0]) - 1 }; + + // if (_lastCursorPosition.Y != point.Y) + // { + // _lastCursorPosition = point; + // var eventType = EventType.WindowPosition; + // var winPositionEv = new WindowPositionEvent { CursorPosition = point }; + + // _inputQueue.Enqueue ( + // new InputResult { EventType = eventType, WindowPositionEvent = winPositionEv } + // ); + // } + // else + // { + // return; + // } + // } + // else if (terminating == EscSeqUtils.CSI_ReportTerminalSizeInChars.Terminator) + // { + // if (values [0] == EscSeqUtils.CSI_ReportTerminalSizeInChars.Value) + // { + // EnqueueWindowSizeEvent ( + // Math.Max (int.Parse (values [1]), 0), + // Math.Max (int.Parse (values [2]), 0), + // Math.Max (int.Parse (values [1]), 0), + // Math.Max (int.Parse (values [2]), 0) + // ); + // } + // else + // { + // EnqueueRequestResponseEvent (c1Control, code, values, terminating); + // } + // } + // else + // { + // EnqueueRequestResponseEvent (c1Control, code, values, terminating); + // } + + // _inputReady.Set (); + //} - private void EnqueueRequestResponseEvent (string c1Control, string code, string [] values, string terminating) - { - var eventType = EventType.RequestResponse; - var requestRespEv = new RequestResponseEvent { ResultTuple = (c1Control, code, values, terminating) }; + //private void EnqueueRequestResponseEvent (string c1Control, string code, string [] values, string terminating) + //{ + // var eventType = EventType.RequestResponse; + // var requestRespEv = new RequestResponseEvent { ResultTuple = (c1Control, code, values, terminating) }; - _inputQueue.Enqueue ( - new InputResult { EventType = eventType, RequestResponseEvent = requestRespEv } - ); - } + // _inputQueue.Enqueue ( + // new InputResult { EventType = eventType, RequestResponseEvent = requestRespEv } + // ); + //} private void HandleMouseEvent (MouseButtonState buttonState, Point pos) { @@ -1042,6 +1052,11 @@ internal override void End () StopReportingMouseMoves (); + _ansiResponseTokenSource?.Cancel (); + _ansiResponseTokenSource?.Dispose (); + + _waitAnsiResponse?.Dispose (); + if (!RunningUnitTests) { Console.ResetColor (); @@ -1417,10 +1432,37 @@ public override void StopReportingMouseMoves () } } + internal ManualResetEventSlim _waitAnsiResponse = new (false); + private readonly CancellationTokenSource _ansiResponseTokenSource = new (); + /// - public override bool WriteAnsi (string ansi) + public override string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest) { - return WriteAnsiDefault (ansi); + _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest); + + try + { + if (!_ansiResponseTokenSource.IsCancellationRequested && Console.KeyAvailable) + { + _mainLoopDriver._netEvents._forceRead = true; + + _mainLoopDriver._netEvents._waitForStart.Set (); + + _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); + } + } + catch (OperationCanceledException) + { + return string.Empty; + } + finally + { + _waitAnsiResponse.Reset (); + } + + _mainLoopDriver._netEvents._forceRead = false; + + return ansiRequest.Response; } private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 188d0c6539..50ac3c9563 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1185,9 +1185,14 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al } /// - public override bool WriteAnsi (string ansi) + public override string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest) { - return WinConsole?.WriteANSI (ansi) ?? false; + if (WinConsole?.WriteANSI (ansiRequest.Request) == true) + { + return ReadAnsiDefault (ansiRequest); + } + + return string.Empty; } #region Not Implemented @@ -1247,7 +1252,7 @@ public override void UpdateCursor () { var sb = new StringBuilder (); sb.Append (EscSeqUtils.CSI_SetCursorPosition (position.Y + 1, position.X + 1)); - WriteAnsi (sb.ToString ()); + WinConsole?.WriteANSI (sb.ToString ()); } if (_cachedCursorVisibility is { }) @@ -1283,8 +1288,7 @@ public override bool SetCursorVisibility (CursorVisibility visibility) { var sb = new StringBuilder (); sb.Append (visibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor); - - return WriteAnsi (sb.ToString ()); + return WinConsole?.WriteANSI (sb.ToString ()) ?? false; } } @@ -1299,8 +1303,7 @@ public override bool EnsureCursorVisibility () { var sb = new StringBuilder (); sb.Append (_cachedCursorVisibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor); - - return WriteAnsi (sb.ToString ()); + return WinConsole?.WriteANSI (sb.ToString ()) ?? false; } //if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) diff --git a/UnitTests/Input/EscSeqReqTests.cs b/UnitTests/Input/EscSeqReqTests.cs index d1499eabdd..9f6921796f 100644 --- a/UnitTests/Input/EscSeqReqTests.cs +++ b/UnitTests/Input/EscSeqReqTests.cs @@ -8,29 +8,21 @@ public void Add_Tests () var escSeqReq = new EscSeqRequests (); escSeqReq.Add (new () { Request = "", Terminator = "t" }); Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); - Assert.Equal (1, escSeqReq.Statuses [^1].NumRequests); - Assert.Equal (1, escSeqReq.Statuses [^1].NumOutstanding); + Assert.Equal ("t", escSeqReq.Statuses.ToArray () [^1].AnsiRequest.Terminator); escSeqReq.Add (new () { Request = "", Terminator = "t" }); - Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); - Assert.Equal (2, escSeqReq.Statuses [^1].NumRequests); - Assert.Equal (2, escSeqReq.Statuses [^1].NumOutstanding); + Assert.Equal (2, escSeqReq.Statuses.Count); + Assert.Equal ("t", escSeqReq.Statuses.ToArray () [^1].AnsiRequest.Terminator); escSeqReq = new (); escSeqReq.Add (new () { Request = "", Terminator = "t" }); escSeqReq.Add (new () { Request = "", Terminator = "t" }); - Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); - Assert.Equal (2, escSeqReq.Statuses [^1].NumRequests); - Assert.Equal (2, escSeqReq.Statuses [^1].NumOutstanding); + Assert.Equal (2, escSeqReq.Statuses.Count); + Assert.Equal ("t", escSeqReq.Statuses.ToArray () [^1].AnsiRequest.Terminator); escSeqReq.Add (new () { Request = "", Terminator = "t" }); - Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); - Assert.Equal (3, escSeqReq.Statuses [^1].NumRequests); - Assert.Equal (3, escSeqReq.Statuses [^1].NumOutstanding); + Assert.Equal (3, escSeqReq.Statuses.Count); + Assert.Equal ("t", escSeqReq.Statuses.ToArray () [^1].AnsiRequest.Terminator); } [Fact] @@ -55,9 +47,7 @@ public void Remove_Tests () escSeqReq.HasResponse ("t", out seqReqStatus); escSeqReq.Remove (seqReqStatus); Assert.Single (escSeqReq.Statuses); - Assert.Equal ("t", escSeqReq.Statuses [^1].AnsiRequest.Terminator); - Assert.Equal (2, escSeqReq.Statuses [^1].NumRequests); - Assert.Equal (1, escSeqReq.Statuses [^1].NumOutstanding); + Assert.Equal ("t", escSeqReq.Statuses.ToArray () [^1].AnsiRequest.Terminator); escSeqReq.HasResponse ("t", out seqReqStatus); escSeqReq.Remove (seqReqStatus); diff --git a/UnitTests/Input/EscSeqUtilsTests.cs b/UnitTests/Input/EscSeqUtilsTests.cs index 7b6e6538e4..ccf8a218c4 100644 --- a/UnitTests/Input/EscSeqUtilsTests.cs +++ b/UnitTests/Input/EscSeqUtilsTests.cs @@ -841,7 +841,7 @@ public void DecodeEscSeq_Tests () }; expectedCki = default (ConsoleKeyInfo); Assert.Single (_escSeqReqProc.Statuses); - Assert.Equal ("t", _escSeqReqProc.Statuses [^1].AnsiRequest.Terminator); + Assert.Equal ("t", _escSeqReqProc.Statuses.ToArray () [^1].AnsiRequest.Terminator); EscSeqUtils.DecodeEscSeq ( _escSeqReqProc, From 93483288c65f261f1bf1e5cd2494d934dfbec49e Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 16 Oct 2024 10:41:02 +0100 Subject: [PATCH 32/89] Rename to WriteAnsiRequest. --- .../AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs | 2 +- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 8 ++++---- Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs | 6 +++--- Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs | 6 +++--- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 2 +- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 4 ++-- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 942a5f828b..4f7b272fbf 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -77,7 +77,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, driver!.IsSuspendRead = true; // Send the ANSI escape sequence - ansiRequest.Response = driver.WriteAnsi (ansiRequest); + ansiRequest.Response = driver.WriteAnsiRequest (ansiRequest); if (string.IsNullOrEmpty (ansiRequest.Terminator)) { diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index 8252ea5e56..fd1e6b9652 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -632,10 +632,10 @@ public void OnMouseEvent (MouseEventArgs a) /// Provide handling for the terminal write ANSI escape sequence request. /// /// The object. - /// - public abstract string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest); + /// The request response. + public abstract string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest); - internal bool WriteAnsiDefault (string ansi) + internal bool WriteAnsiRequestDefault (string ansi) { try { @@ -654,7 +654,7 @@ internal bool WriteAnsiDefault (string ansi) return true; } - internal string ReadAnsiDefault (AnsiEscapeSequenceRequest ansiRequest) + internal string ReadAnsiResponseDefault (AnsiEscapeSequenceRequest ansiRequest) { var response = new StringBuilder (); diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 6d1e3cbc39..75d7ec5d8f 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -216,11 +216,11 @@ public override void StopReportingMouseMoves () } /// - public override string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest) + public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { - if (WriteAnsiDefault (ansiRequest.Request)) + if (WriteAnsiRequestDefault (ansiRequest.Request)) { - return ReadAnsiDefault (ansiRequest); + return ReadAnsiResponseDefault (ansiRequest); } return string.Empty; diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index 10a53234d8..c5ff53a3b0 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -415,11 +415,11 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al public override void StopReportingMouseMoves () { throw new NotImplementedException (); } /// - public override string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest) + public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { - if (WriteAnsiDefault (ansiRequest.Request)) + if (WriteAnsiRequestDefault (ansiRequest.Request)) { - return ReadAnsiDefault (ansiRequest); + return ReadAnsiResponseDefault (ansiRequest); } return string.Empty; diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 2f9f2a0318..e29b7a5665 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1436,7 +1436,7 @@ public override void StopReportingMouseMoves () private readonly CancellationTokenSource _ansiResponseTokenSource = new (); /// - public override string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest) + public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest); diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 50ac3c9563..fb21ad0820 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1185,11 +1185,11 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al } /// - public override string WriteAnsi (AnsiEscapeSequenceRequest ansiRequest) + public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { if (WinConsole?.WriteANSI (ansiRequest.Request) == true) { - return ReadAnsiDefault (ansiRequest); + return ReadAnsiResponseDefault (ansiRequest); } return string.Empty; From 1645d1f95652d07237e7c4eb129885629b08c62e Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 16 Oct 2024 18:50:45 +0100 Subject: [PATCH 33/89] Ensure dequeue on bad requests or without response in NetDriver. --- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index e29b7a5665..7f56a14684 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1435,7 +1435,7 @@ public override void StopReportingMouseMoves () internal ManualResetEventSlim _waitAnsiResponse = new (false); private readonly CancellationTokenSource _ansiResponseTokenSource = new (); - /// + /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest); @@ -1457,11 +1457,21 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) } finally { + if (_mainLoopDriver is { }) + { + _mainLoopDriver._netEvents._forceRead = false; + } + + if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0 + && string.IsNullOrEmpty (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Peek ().AnsiRequest.Response)) + { + // Bad request or no response at all + _mainLoopDriver._netEvents.EscSeqRequests.Statuses.Dequeue (); + } + _waitAnsiResponse.Reset (); } - _mainLoopDriver._netEvents._forceRead = false; - return ansiRequest.Response; } From 34fb5b56ab5be3525a5afb7f7249bc93f39dcad9 Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 16 Oct 2024 19:01:15 +0100 Subject: [PATCH 34/89] Non-blocking ReadConsoleInput in WindowsDriver. --- .../AnsiEscapeSequenceRequest.cs | 10 ++- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 79 ++++++++++++++++--- 2 files changed, 77 insertions(+), 12 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 4f7b272fbf..b37e086f2b 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -79,11 +79,17 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, // Send the ANSI escape sequence ansiRequest.Response = driver.WriteAnsiRequest (ansiRequest); + if (!string.IsNullOrEmpty (ansiRequest.Response) && !ansiRequest.Response.StartsWith (EscSeqUtils.KeyEsc)) + { + throw new InvalidOperationException ("Invalid escape character!"); + } + if (string.IsNullOrEmpty (ansiRequest.Terminator)) { - error.AppendLine ("Terminator request is empty."); + throw new InvalidOperationException ("Terminator request is empty."); } - else if (!ansiRequest.Response.EndsWith (ansiRequest.Terminator [^1])) + + if (!ansiRequest.Response.EndsWith (ansiRequest.Terminator [^1])) { throw new InvalidOperationException ($"Terminator doesn't ends with: '{ansiRequest.Terminator [^1]}'"); } diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index fb21ad0820..a900e1d887 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -781,6 +781,9 @@ public readonly string ToString (ConsoleKeyInfoEx ex) [DllImport ("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle (nint handle); + [DllImport ("kernel32.dll", SetLastError = true)] + public static extern bool PeekConsoleInput (nint hConsoleInput, out InputRecord lpBuffer, uint nLength, out uint lpNumberOfEventsRead); + [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)] public static extern bool ReadConsoleInput ( nint hConsoleInput, @@ -888,14 +891,19 @@ public InputRecord [] ReadConsoleInput () { const int bufferSize = 1; nint pRecord = Marshal.AllocHGlobal (Marshal.SizeOf () * bufferSize); + uint numberEventsRead = 0; try { - ReadConsoleInput ( - _inputHandle, - pRecord, - bufferSize, - out uint numberEventsRead); + + if (PeekConsoleInput (_inputHandle, out InputRecord inputRecord, 1, out uint eventsRead) && eventsRead > 0) + { + ReadConsoleInput ( + _inputHandle, + pRecord, + bufferSize, + out numberEventsRead); + } return numberEventsRead == 0 ? null @@ -1187,9 +1195,38 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { - if (WinConsole?.WriteANSI (ansiRequest.Request) == true) + while (_mainLoopDriver is { } && Console.KeyAvailable) + { + _mainLoopDriver._waitForProbe.Set (); + _mainLoopDriver._waitForProbe.Reset (); + + _mainLoopDriver._forceRead = true; + } + + if (_mainLoopDriver is { }) + { + _mainLoopDriver._forceRead = false; + } + + _mainLoopDriver._suspendRead = true; + + try + { + if (WinConsole?.WriteANSI (ansiRequest.Request) == true) + { + Thread.Sleep (100); // Allow time for the terminal to respond + + return ReadAnsiResponseDefault (ansiRequest); + } + } + catch (Exception e) { - return ReadAnsiResponseDefault (ansiRequest); + return string.Empty; + } + finally + { + _mainLoopDriver._suspendRead = false; + } return string.Empty; @@ -2192,7 +2229,7 @@ internal class WindowsMainLoop : IMainLoopDriver // The records that we keep fetching private readonly Queue _resultQueue = new (); - private readonly ManualResetEventSlim _waitForProbe = new (false); + internal readonly ManualResetEventSlim _waitForProbe = new (false); private readonly WindowsConsole _winConsole; private CancellationTokenSource _eventReadyTokenSource = new (); private readonly CancellationTokenSource _inputHandlerTokenSource = new (); @@ -2310,6 +2347,9 @@ void IMainLoopDriver.TearDown () _mainLoop = null; } + internal bool _forceRead; + internal bool _suspendRead; + private void WindowsInputHandler () { while (_mainLoop is { }) @@ -2325,6 +2365,7 @@ private void WindowsInputHandler () { // Wakes the _waitForProbe if it's waiting _waitForProbe.Set (); + return; } finally @@ -2337,9 +2378,27 @@ private void WindowsInputHandler () } } - if (_resultQueue?.Count == 0) + if (_resultQueue?.Count == 0 || _forceRead) { - _resultQueue.Enqueue (_winConsole.ReadConsoleInput ()); + while (!_inputHandlerTokenSource.IsCancellationRequested) + { + if (!_suspendRead) + { + WindowsConsole.InputRecord[] inpRec = _winConsole.ReadConsoleInput (); + + if (inpRec is { }) + { + _resultQueue!.Enqueue (inpRec); + + break; + } + } + + if (!_forceRead) + { + Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + } + } } _eventReady.Set (); From 7fa098f0abfe7405b8dce3a3f49fed4a42dcf893 Mon Sep 17 00:00:00 2001 From: BDisp Date: Fri, 18 Oct 2024 13:42:00 +0100 Subject: [PATCH 35/89] Remove unnecessary IsSuspendRead property. --- .../AnsiEscapeSequenceRequest.cs | 3 --- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 11 +++-------- .../ConsoleDrivers/CursesDriver/CursesDriver.cs | 7 ------- .../ConsoleDrivers/FakeDriver/FakeDriver.cs | 14 +------------- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 7 ------- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 14 +------------- 6 files changed, 5 insertions(+), 51 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index b37e086f2b..38d0450d00 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -74,8 +74,6 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, driver.StopReportingMouseMoves (); } - driver!.IsSuspendRead = true; - // Send the ANSI escape sequence ansiRequest.Response = driver.WriteAnsiRequest (ansiRequest); @@ -107,7 +105,6 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, if (savedIsReportingMouseMoves) { - driver!.IsSuspendRead = false; driver.StartReportingMouseMoves (); } } diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index fd1e6b9652..f3225eceb0 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -567,11 +567,6 @@ public virtual Attribute MakeColor (in Color foreground, in Color background) /// public abstract bool IsReportingMouseMoves { get; internal set; } - /// - /// Gets whether the terminal is reading input. - /// - public abstract bool IsSuspendRead { get; internal set; } - /// Event fired when a key is pressed down. This is a precursor to . public event EventHandler? KeyDown; @@ -619,17 +614,17 @@ public void OnMouseEvent (MouseEventArgs a) public abstract void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool ctrl); /// - /// Provide handling for the terminal start reporting mouse events. + /// Provide handling for the terminal start reporting mouse events. /// public abstract void StartReportingMouseMoves (); /// - /// Provide handling for the terminal stop reporting mouse events. + /// Provide handling for the terminal stop reporting mouse events. /// public abstract void StopReportingMouseMoves (); /// - /// Provide handling for the terminal write ANSI escape sequence request. + /// Provide handling for the terminal write ANSI escape sequence request. /// /// The object. /// The request response. diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 75d7ec5d8f..ff949f1fcf 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -180,13 +180,6 @@ public override bool SetCursorVisibility (CursorVisibility visibility) public override bool IsReportingMouseMoves { get; internal set; } - /// - public override bool IsSuspendRead - { - get => _isSuspendRead; - internal set => _isSuspendRead = value; - } - public override void StartReportingMouseMoves () { if (!RunningUnitTests) diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index c5ff53a3b0..2335e98349 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -41,18 +41,7 @@ public Behaviors ( public override bool SupportsTrueColor => false; /// - public override bool IsReportingMouseMoves - { - get => _isReportingMouseMoves; - internal set => _isReportingMouseMoves = value; - } - - /// - public override bool IsSuspendRead - { - get => _isSuspendRead; - internal set => _isSuspendRead = value; - } + public override bool IsReportingMouseMoves { get; internal set; } public FakeDriver () { @@ -351,7 +340,6 @@ private KeyCode MapKey (ConsoleKeyInfo keyInfo) } private CursorVisibility _savedCursorVisibility; - private bool _isReportingMouseMoves; private bool _isSuspendRead; private void MockKeyPressedHandler (ConsoleKeyInfo consoleKeyInfo) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 7f56a14684..2b35cff1bd 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1392,13 +1392,6 @@ public override bool EnsureCursorVisibility () public override bool IsReportingMouseMoves { get; internal set; } - /// - public override bool IsSuspendRead - { - get => _isSuspendRead; - internal set => _isSuspendRead = value; - } - public override void StartReportingMouseMoves () { if (!RunningUnitTests) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index a900e1d887..7da7b27297 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1052,18 +1052,7 @@ public WindowsDriver () public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal); /// - public override bool IsReportingMouseMoves - { - get => _isReportingMouseMoves; - internal set => _isReportingMouseMoves = value; - } - - /// - public override bool IsSuspendRead - { - get => _isSuspendRead; - internal set => _isSuspendRead = value; - } + public override bool IsReportingMouseMoves { get; internal set; } public WindowsConsole WinConsole { get; private set; } @@ -1261,7 +1250,6 @@ public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEve #region Cursor Handling private CursorVisibility? _cachedCursorVisibility; - private bool _isReportingMouseMoves; private bool _isSuspendRead; public override void UpdateCursor () From 9759b97ef3be1450d8b4ef84a2507245e8752059 Mon Sep 17 00:00:00 2001 From: BDisp Date: Fri, 18 Oct 2024 20:09:43 +0100 Subject: [PATCH 36/89] Remove unused variable. --- Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs | 1 - Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs | 1 - Terminal.Gui/ConsoleDrivers/NetDriver.cs | 1 - Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 1 - 4 files changed, 4 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index ff949f1fcf..206b2ba8e9 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -18,7 +18,6 @@ internal class CursesDriver : ConsoleDriver private MouseFlags _lastMouseFlags; private UnixMainLoop _mainLoopDriver; private object _processInputToken; - private bool _isSuspendRead; public override int Cols { diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index 2335e98349..527de31d24 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -340,7 +340,6 @@ private KeyCode MapKey (ConsoleKeyInfo keyInfo) } private CursorVisibility _savedCursorVisibility; - private bool _isSuspendRead; private void MockKeyPressedHandler (ConsoleKeyInfo consoleKeyInfo) { diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 2b35cff1bd..fe49423cbc 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1341,7 +1341,6 @@ private bool SetCursorPosition (int col, int row) } private CursorVisibility? _cachedCursorVisibility; - private bool _isSuspendRead; public override void UpdateCursor () { diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 7da7b27297..3359e87bcc 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1250,7 +1250,6 @@ public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEve #region Cursor Handling private CursorVisibility? _cachedCursorVisibility; - private bool _isSuspendRead; public override void UpdateCursor () { From 1ecff5e5da8d942b1730b7c7587dab5235357a40 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 19 Oct 2024 00:39:57 +0100 Subject: [PATCH 37/89] Fix ansi multi-thread requests handling in the NetDriver. --- .../AnsiEscapeSequenceRequest.cs | 14 +++- .../ConsoleDrivers/EscSeqUtils/EscSeqReq.cs | 7 +- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 75 ++++++++++++++----- 3 files changed, 73 insertions(+), 23 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 38d0450d00..b78e773d0f 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -8,6 +8,8 @@ namespace Terminal.Gui; /// public class AnsiEscapeSequenceRequest { + internal readonly object _responseLock = new (); // Per-instance lock + /// /// Request to send e.g. see /// @@ -89,12 +91,14 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, if (!ansiRequest.Response.EndsWith (ansiRequest.Terminator [^1])) { - throw new InvalidOperationException ($"Terminator doesn't ends with: '{ansiRequest.Terminator [^1]}'"); + char resp = string.IsNullOrEmpty (ansiRequest.Response) ? ' ' : ansiRequest.Response.Last (); + + throw new InvalidOperationException ($"Terminator ends with '{resp}'\nand doesn't end with: '{ansiRequest.Terminator [^1]}'"); } } catch (Exception ex) { - error.AppendLine ($"Error executing ANSI request: {ex.Message}"); + error.AppendLine ($"Error executing ANSI request:\n{ansiRequest.Response}\n{ex.Message}"); } finally { @@ -105,7 +109,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, if (savedIsReportingMouseMoves) { - driver.StartReportingMouseMoves (); + driver?.StartReportingMouseMoves (); } } @@ -132,4 +136,8 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, /// different value. /// public string? Value { get; init; } + + internal void RaiseResponseFromInput (AnsiEscapeSequenceRequest ansiRequest, string response) { ResponseFromInput?.Invoke (ansiRequest, response); } + + internal event EventHandler? ResponseFromInput; } diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs index 178f8f7a95..8f7a56a19d 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs @@ -77,7 +77,12 @@ public void Remove (EscSeqReqStatus? seqReqStatus) { lock (Statuses) { - Statuses.Dequeue (); + Statuses.TryDequeue (out var request); + + if (request != seqReqStatus) + { + throw new InvalidOperationException ("Both EscSeqReqStatus objects aren't equals."); + } } } diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index fe49423cbc..ebf88efb01 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -2,6 +2,7 @@ // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient. // +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping; @@ -275,17 +276,29 @@ private void ProcessInputQueue () } _isEscSeq = true; - newConsoleKeyInfo = consoleKeyInfo; - _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki); - if (Console.KeyAvailable) + if (consoleKeyInfo.KeyChar != Key.Esc && consoleKeyInfo.KeyChar <= Key.Space) { - continue; + ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); + _cki = null; + _isEscSeq = false; + + ProcessMapConsoleKeyInfo (consoleKeyInfo); } + else + { + newConsoleKeyInfo = consoleKeyInfo; + _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki); - ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); - _cki = null; - _isEscSeq = false; + if (Console.KeyAvailable) + { + continue; + } + + ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); + _cki = null; + _isEscSeq = false; + } break; } @@ -454,9 +467,11 @@ ref ConsoleModifiers mod sb.Append (keyChar.KeyChar); } - seqReqStatus.AnsiRequest.Response = sb.ToString (); - - ((NetDriver)_consoleDriver)._waitAnsiResponse.Set (); + lock (seqReqStatus.AnsiRequest._responseLock) + { + seqReqStatus.AnsiRequest.Response = sb.ToString (); + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, sb.ToString ()); + } return; } @@ -1424,22 +1439,41 @@ public override void StopReportingMouseMoves () } } - internal ManualResetEventSlim _waitAnsiResponse = new (false); + private readonly ManualResetEventSlim _waitAnsiResponse = new (false); private readonly CancellationTokenSource _ansiResponseTokenSource = new (); /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { - _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest); + var response = string.Empty; try { + lock (ansiRequest._responseLock) + { + ansiRequest.ResponseFromInput += (s, e) => + { + Debug.Assert (s == ansiRequest); + + ansiRequest.Response = response = e; + + _waitAnsiResponse.Set (); + }; + + _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest); + } + if (!_ansiResponseTokenSource.IsCancellationRequested && Console.KeyAvailable) { _mainLoopDriver._netEvents._forceRead = true; _mainLoopDriver._netEvents._waitForStart.Set (); + if (!_mainLoopDriver._waitForProbe.IsSet) + { + _mainLoopDriver._waitForProbe.Set (); + } + _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); } } @@ -1454,17 +1488,20 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) _mainLoopDriver._netEvents._forceRead = false; } - if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0 - && string.IsNullOrEmpty (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Peek ().AnsiRequest.Response)) + if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) { - // Bad request or no response at all - _mainLoopDriver._netEvents.EscSeqRequests.Statuses.Dequeue (); + if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0 + && string.IsNullOrEmpty (request.AnsiRequest.Response)) + { + // Bad request or no response at all + _mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryDequeue (out _); + } } _waitAnsiResponse.Reset (); } - return ansiRequest.Response; + return response; } private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me) @@ -1756,7 +1793,7 @@ internal class NetMainLoop : IMainLoopDriver private readonly ManualResetEventSlim _eventReady = new (false); private readonly CancellationTokenSource _inputHandlerTokenSource = new (); private readonly Queue _resultQueue = new (); - private readonly ManualResetEventSlim _waitForProbe = new (false); + internal readonly ManualResetEventSlim _waitForProbe = new (false); private readonly CancellationTokenSource _eventReadyTokenSource = new (); private MainLoop _mainLoop; @@ -1856,7 +1893,7 @@ private void NetInputHandler () { try { - if (!_inputHandlerTokenSource.IsCancellationRequested) + if (!_netEvents._forceRead && !_inputHandlerTokenSource.IsCancellationRequested) { _waitForProbe.Wait (_inputHandlerTokenSource.Token); } From 9a840dd29b8210998fdf01b1a22dbf9eb44dcbd7 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 19 Oct 2024 13:55:51 +0100 Subject: [PATCH 38/89] Remove unnecessary WriteAnsiRequestDefault method. --- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 19 ------------------- .../ConsoleDrivers/FakeDriver/FakeDriver.cs | 10 +--------- 2 files changed, 1 insertion(+), 28 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index f3225eceb0..35c90d9850 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -630,25 +630,6 @@ public void OnMouseEvent (MouseEventArgs a) /// The request response. public abstract string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest); - internal bool WriteAnsiRequestDefault (string ansi) - { - try - { - Console.Out.Write (ansi); - Console.Out.Flush (); // Ensure the request is sent - - // Read the response from stdin (response should come back as input) - Thread.Sleep (100); // Allow time for the terminal to respond - - } - catch (Exception) - { - return false; - } - - return true; - } - internal string ReadAnsiResponseDefault (AnsiEscapeSequenceRequest ansiRequest) { var response = new StringBuilder (); diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index 527de31d24..66fcb32d16 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -402,15 +402,7 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al public override void StopReportingMouseMoves () { throw new NotImplementedException (); } /// - public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) - { - if (WriteAnsiRequestDefault (ansiRequest.Request)) - { - return ReadAnsiResponseDefault (ansiRequest); - } - - return string.Empty; - } + public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { throw new NotImplementedException (); } public void SetBufferSize (int width, int height) { From cc4f7e9a9fdb7038d0ee4eec1c1cd3915ce1c725 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 19 Oct 2024 19:03:31 +0100 Subject: [PATCH 39/89] Simplifying code. --- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 10 ++++++---- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 16 ++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index ebf88efb01..be1173b131 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1445,6 +1445,11 @@ public override void StopReportingMouseMoves () /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { + if (_mainLoopDriver is null) + { + return string.Empty; + } + var response = string.Empty; try @@ -1483,10 +1488,7 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) } finally { - if (_mainLoopDriver is { }) - { - _mainLoopDriver._netEvents._forceRead = false; - } + _mainLoopDriver._netEvents._forceRead = false; if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) { diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 3359e87bcc..79fcd7d627 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1184,7 +1184,12 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { - while (_mainLoopDriver is { } && Console.KeyAvailable) + if (_mainLoopDriver is null) + { + return string.Empty; + } + + while (Console.KeyAvailable) { _mainLoopDriver._waitForProbe.Set (); _mainLoopDriver._waitForProbe.Reset (); @@ -1192,11 +1197,7 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) _mainLoopDriver._forceRead = true; } - if (_mainLoopDriver is { }) - { - _mainLoopDriver._forceRead = false; - } - + _mainLoopDriver._forceRead = false; _mainLoopDriver._suspendRead = true; try @@ -1208,14 +1209,13 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) return ReadAnsiResponseDefault (ansiRequest); } } - catch (Exception e) + catch (Exception) { return string.Empty; } finally { _mainLoopDriver._suspendRead = false; - } return string.Empty; From 542d82dd552a74db023c199f6e9b41dd704c2b96 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sun, 20 Oct 2024 00:33:36 +0100 Subject: [PATCH 40/89] Remove response from error. --- .../AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index b78e773d0f..d7d1e24afa 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -98,7 +98,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, } catch (Exception ex) { - error.AppendLine ($"Error executing ANSI request:\n{ansiRequest.Response}\n{ex.Message}"); + error.AppendLine ($"Error executing ANSI request:\n{ex.Message}"); } finally { From 974914261039a8483ee1beee7f2ad8d80e9d219c Mon Sep 17 00:00:00 2001 From: BDisp Date: Sun, 20 Oct 2024 01:02:43 +0100 Subject: [PATCH 41/89] Set _forceRead as true before set _waitForProbe. --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 79fcd7d627..a25408ac28 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1191,10 +1191,10 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) while (Console.KeyAvailable) { + _mainLoopDriver._forceRead = true; + _mainLoopDriver._waitForProbe.Set (); _mainLoopDriver._waitForProbe.Reset (); - - _mainLoopDriver._forceRead = true; } _mainLoopDriver._forceRead = false; From 9eb70236d67ead0feeafe4380ac24e288b590696 Mon Sep 17 00:00:00 2001 From: BDisp Date: Sun, 20 Oct 2024 01:05:53 +0100 Subject: [PATCH 42/89] Improves CursesDriver to allow non-blocking input polling. --- .../CursesDriver/CursesDriver.cs | 32 +++++- .../CursesDriver/UnixMainLoop.cs | 104 +++++++++++++++++- 2 files changed, 127 insertions(+), 9 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 206b2ba8e9..4b90d3596d 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -210,12 +210,38 @@ public override void StopReportingMouseMoves () /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { - if (WriteAnsiRequestDefault (ansiRequest.Request)) + if (_mainLoopDriver is null) { - return ReadAnsiResponseDefault (ansiRequest); + return string.Empty; + } + + while (Console.KeyAvailable) + { + _mainLoopDriver._forceRead = true; + + _mainLoopDriver._waitForInput.Set (); + _mainLoopDriver._waitForInput.Reset (); } - return string.Empty; + _mainLoopDriver._forceRead = false; + _mainLoopDriver._suspendRead = true; + + try + { + Console.Out.Write (ansiRequest.Request); + Console.Out.Flush (); // Ensure the request is sent + Task.Delay (100).Wait (); // Allow time for the terminal to respond + + return ReadAnsiResponseDefault (ansiRequest); + } + catch (Exception) + { + return string.Empty; + } + finally + { + _mainLoopDriver._suspendRead = false; + } } public override void Suspend () diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs index 34139815c5..c7a9a26125 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs @@ -46,6 +46,10 @@ public enum Condition : short private bool _pollDirty = true; private Pollfd [] _pollMap; private bool _winChanged; + private readonly ManualResetEventSlim _eventReady = new (false); + internal readonly ManualResetEventSlim _waitForInput = new (false); + private readonly CancellationTokenSource _eventReadyTokenSource = new (); + private readonly CancellationTokenSource _inputHandlerTokenSource = new (); public UnixMainLoop (ConsoleDriver consoleDriver = null) { @@ -89,22 +93,99 @@ void IMainLoopDriver.Setup (MainLoop mainLoop) { throw new NotSupportedException ("libc not found", e); } + + Task.Run (CursesInputHandler, _inputHandlerTokenSource.Token); + } + + internal bool _forceRead; + internal bool _suspendRead; + private int n; + + private void CursesInputHandler () + { + while (_mainLoop is { }) + { + try + { + UpdatePollMap (); + + if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead) + { + _waitForInput.Wait (_inputHandlerTokenSource.Token); + } + } + catch (OperationCanceledException) + { + return; + } + finally + { + if (!_inputHandlerTokenSource.IsCancellationRequested) + { + _waitForInput.Reset (); + } + } + + while (!_inputHandlerTokenSource.IsCancellationRequested) + { + if (!_suspendRead) + { + n = poll (_pollMap, (uint)_pollMap.Length, 0); + + if (n == KEY_RESIZE) + { + _winChanged = true; + + break; + } + + if (n > 0) + { + break; + } + } + + if (!_forceRead) + { + Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + } + } + + _eventReady.Set (); + } } bool IMainLoopDriver.EventsPending () { - UpdatePollMap (); + _waitForInput.Set (); - bool checkTimersResult = _mainLoop.CheckTimersAndIdleHandlers (out int pollTimeout); + if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) + { + return true; + } - int n = poll (_pollMap, (uint)_pollMap.Length, pollTimeout); + try + { + if (!_eventReadyTokenSource.IsCancellationRequested) + { + _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token); + } + } + catch (OperationCanceledException) + { + return true; + } + finally + { + _eventReady.Reset (); + } - if (n == KEY_RESIZE) + if (!_eventReadyTokenSource.IsCancellationRequested) { - _winChanged = true; + return n > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged; } - return checkTimersResult || n >= KEY_RESIZE; + return true; } void IMainLoopDriver.Iteration () @@ -118,6 +199,8 @@ void IMainLoopDriver.Iteration () _cursesDriver.ProcessWinChange (); } + n = 0; + if (_pollMap is null) { return; @@ -148,6 +231,15 @@ void IMainLoopDriver.TearDown () { _descriptorWatchers?.Clear (); + _inputHandlerTokenSource?.Cancel (); + _inputHandlerTokenSource?.Dispose (); + + _waitForInput?.Dispose (); + + _eventReadyTokenSource?.Cancel (); + _eventReadyTokenSource?.Dispose (); + _eventReady?.Dispose (); + _mainLoop = null; } From 4090ea4070a306c4fc9a70de58feae6f6ab4bbff Mon Sep 17 00:00:00 2001 From: BDisp Date: Sun, 20 Oct 2024 01:07:23 +0100 Subject: [PATCH 43/89] Avoids response starting without Esc char on stressing tests. --- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index 35c90d9850..59dd20e3ee 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -633,14 +633,18 @@ public void OnMouseEvent (MouseEventArgs a) internal string ReadAnsiResponseDefault (AnsiEscapeSequenceRequest ansiRequest) { var response = new StringBuilder (); + int index = 0; while (Console.KeyAvailable) { // Peek the next key ConsoleKeyInfo keyInfo = Console.ReadKey (true); // true to not display on the console - // Append the current key to the response - response.Append (keyInfo.KeyChar); + if ((index == 0 && keyInfo.KeyChar == EscSeqUtils.KeyEsc) || (index > 0 && keyInfo.KeyChar != EscSeqUtils.KeyEsc)) + { + // Append the current key to the response + response.Append (keyInfo.KeyChar); + } // Read until no key is available if no terminator was specified or // check if the key is terminator (ANSI escape sequence ends) @@ -649,6 +653,8 @@ internal string ReadAnsiResponseDefault (AnsiEscapeSequenceRequest ansiRequest) // Break out of the loop when terminator is found break; } + + index++; } return response.ToString (); From 5ef34b8e54b875dc93f42f91db94340b171b7951 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 21 Oct 2024 12:25:38 +0100 Subject: [PATCH 44/89] Refactoring code. --- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 74 +++++++++---------- UnitTests/Input/EscSeqUtilsTests.cs | 1 + 2 files changed, 38 insertions(+), 37 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index a8c830f7e3..e08fcffff0 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -123,19 +123,19 @@ public enum ClearScreenOptions public static readonly string CSI_SaveCursorAndActivateAltBufferNoBackscroll = CSI + "?1049h"; //private static bool isButtonReleased; - private static bool isButtonClicked; + private static bool _isButtonClicked; - private static bool isButtonDoubleClicked; + private static bool _isButtonDoubleClicked; //private static MouseFlags? lastMouseButtonReleased; // QUESTION: What's the difference between isButtonClicked and isButtonPressed? // Some clarity or comments would be handy, here. // It also seems like some enforcement of valid states might be a good idea. - private static bool isButtonPressed; - private static bool isButtonTripleClicked; + private static bool _isButtonPressed; + private static bool _isButtonTripleClicked; - private static MouseFlags? lastMouseButtonPressed; - private static Point? point; + private static MouseFlags? _lastMouseButtonPressed; + private static Point? _point; /// /// Control sequence for disabling mouse events. @@ -774,32 +774,32 @@ Action continuousButtonPressedHandler mouseFlags = [MouseFlags.AllEvents]; - if (lastMouseButtonPressed != null - && !isButtonPressed + if (_lastMouseButtonPressed != null + && !_isButtonPressed && !buttonState.HasFlag (MouseFlags.ReportMousePosition) && !buttonState.HasFlag (MouseFlags.Button1Released) && !buttonState.HasFlag (MouseFlags.Button2Released) && !buttonState.HasFlag (MouseFlags.Button3Released) && !buttonState.HasFlag (MouseFlags.Button4Released)) { - lastMouseButtonPressed = null; - isButtonPressed = false; + _lastMouseButtonPressed = null; + _isButtonPressed = false; } - if ((!isButtonClicked - && !isButtonDoubleClicked + if ((!_isButtonClicked + && !_isButtonDoubleClicked && (buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed || buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed) - && lastMouseButtonPressed is null) - || (isButtonPressed && lastMouseButtonPressed is { } && buttonState.HasFlag (MouseFlags.ReportMousePosition))) + && _lastMouseButtonPressed is null) + || (_isButtonPressed && _lastMouseButtonPressed is { } && buttonState.HasFlag (MouseFlags.ReportMousePosition))) { mouseFlags [0] = buttonState; - lastMouseButtonPressed = buttonState; - isButtonPressed = true; + _lastMouseButtonPressed = buttonState; + _isButtonPressed = true; - point = pos; + _point = pos; if ((mouseFlags [0] & MouseFlags.ReportMousePosition) == 0) { @@ -818,7 +818,7 @@ Action continuousButtonPressedHandler } else if (mouseFlags [0].HasFlag (MouseFlags.ReportMousePosition)) { - point = pos; + _point = pos; // The isButtonPressed must always be true, otherwise we can lose the feature // If mouse flags has ReportMousePosition this feature won't run @@ -826,25 +826,25 @@ Action continuousButtonPressedHandler //isButtonPressed = false; } } - else if (isButtonDoubleClicked + else if (_isButtonDoubleClicked && (buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed || buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed)) { mouseFlags [0] = GetButtonTripleClicked (buttonState); - isButtonDoubleClicked = false; - isButtonTripleClicked = true; + _isButtonDoubleClicked = false; + _isButtonTripleClicked = true; } - else if (isButtonClicked + else if (_isButtonClicked && (buttonState == MouseFlags.Button1Pressed || buttonState == MouseFlags.Button2Pressed || buttonState == MouseFlags.Button3Pressed || buttonState == MouseFlags.Button4Pressed)) { mouseFlags [0] = GetButtonDoubleClicked (buttonState); - isButtonClicked = false; - isButtonDoubleClicked = true; + _isButtonClicked = false; + _isButtonDoubleClicked = true; Application.MainLoop.AddIdle ( () => @@ -866,24 +866,24 @@ Action continuousButtonPressedHandler // }); //} - else if (!isButtonClicked - && !isButtonDoubleClicked + else if (!_isButtonClicked + && !_isButtonDoubleClicked && (buttonState == MouseFlags.Button1Released || buttonState == MouseFlags.Button2Released || buttonState == MouseFlags.Button3Released || buttonState == MouseFlags.Button4Released)) { mouseFlags [0] = buttonState; - isButtonPressed = false; + _isButtonPressed = false; - if (isButtonTripleClicked) + if (_isButtonTripleClicked) { - isButtonTripleClicked = false; + _isButtonTripleClicked = false; } - else if (pos.X == point?.X && pos.Y == point?.Y) + else if (pos.X == _point?.X && pos.Y == _point?.Y) { mouseFlags.Add (GetButtonClicked (buttonState)); - isButtonClicked = true; + _isButtonClicked = true; Application.MainLoop.AddIdle ( () => @@ -894,7 +894,7 @@ Action continuousButtonPressedHandler }); } - point = pos; + _point = pos; //if ((lastMouseButtonPressed & MouseFlags.ReportMousePosition) == 0) { // lastMouseButtonReleased = buttonState; @@ -1104,13 +1104,13 @@ private static MouseFlags GetButtonTripleClicked (MouseFlags mouseFlag) private static async Task ProcessButtonClickedAsync () { await Task.Delay (300); - isButtonClicked = false; + _isButtonClicked = false; } private static async Task ProcessButtonDoubleClickedAsync () { await Task.Delay (300); - isButtonDoubleClicked = false; + _isButtonDoubleClicked = false; } private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag, Action continuousButtonPressedHandler) @@ -1118,7 +1118,7 @@ private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseF // PERF: Pause and poll in a hot loop. // This should be replaced with event dispatch and a synchronization primitive such as AutoResetEvent. // Will make a massive difference in responsiveness. - while (isButtonPressed) + while (_isButtonPressed) { await Task.Delay (100); @@ -1129,9 +1129,9 @@ private static async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseF break; } - if (isButtonPressed && lastMouseButtonPressed is { } && (mouseFlag & MouseFlags.ReportMousePosition) == 0) + if (_isButtonPressed && _lastMouseButtonPressed is { } && (mouseFlag & MouseFlags.ReportMousePosition) == 0) { - Application.Invoke (() => continuousButtonPressedHandler (mouseFlag, point ?? Point.Empty)); + Application.Invoke (() => continuousButtonPressedHandler (mouseFlag, _point ?? Point.Empty)); } } } diff --git a/UnitTests/Input/EscSeqUtilsTests.cs b/UnitTests/Input/EscSeqUtilsTests.cs index ccf8a218c4..7edb30d5e6 100644 --- a/UnitTests/Input/EscSeqUtilsTests.cs +++ b/UnitTests/Input/EscSeqUtilsTests.cs @@ -1,4 +1,5 @@ using JetBrains.Annotations; +// ReSharper disable HeuristicUnreachableCode namespace Terminal.Gui.InputTests; From c1063a00fec6612bf400ff2cadfe7484b98ba42e Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 31 Oct 2024 19:10:46 +0000 Subject: [PATCH 45/89] Remove unneeded abstract ConsoleDriver objects. --- .../AnsiEscapeSequenceRequest.cs | 20 ++--------- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 36 ++++++++----------- .../CursesDriver/CursesDriver.cs | 18 ++-------- .../ConsoleDrivers/FakeDriver/FakeDriver.cs | 10 ++---- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 23 ++---------- 5 files changed, 23 insertions(+), 84 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index d7d1e24afa..76bd24101d 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -61,23 +61,14 @@ public class AnsiEscapeSequenceRequest public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEscapeSequenceResponse result) { var error = new StringBuilder (); - var savedIsReportingMouseMoves = false; - ConsoleDriver? driver = null; var values = new string? [] { null }; try { - driver = Application.Driver; - - savedIsReportingMouseMoves = driver!.IsReportingMouseMoves; - - if (savedIsReportingMouseMoves) - { - driver.StopReportingMouseMoves (); - } + ConsoleDriver? driver = Application.Driver; // Send the ANSI escape sequence - ansiRequest.Response = driver.WriteAnsiRequest (ansiRequest); + ansiRequest.Response = driver?.WriteAnsiRequest (ansiRequest)!; if (!string.IsNullOrEmpty (ansiRequest.Response) && !ansiRequest.Response.StartsWith (EscSeqUtils.KeyEsc)) { @@ -104,12 +95,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, { if (string.IsNullOrEmpty (error.ToString ())) { - (string? c1Control, string? code, values, string? terminator) = EscSeqUtils.GetEscapeResult (ansiRequest.Response.ToCharArray ()); - } - - if (savedIsReportingMouseMoves) - { - driver?.StartReportingMouseMoves (); + (string? _, string? _, values, string? _) = EscSeqUtils.GetEscapeResult (ansiRequest.Response.ToCharArray ()); } } diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index 59dd20e3ee..2adb68e983 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -144,7 +144,7 @@ public void AddRune (Rune rune) // 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 + // 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) @@ -167,7 +167,7 @@ public void AddRune (Rune rune) if (normalized.Length == 1) { // It normalized! We can just set the Cell to the left with the - // normalized codepoint + // normalized codepoint Contents [Row, Col - 1].Rune = (Rune)normalized [0]; // Ignore. Don't move to next column because we're already there @@ -377,7 +377,7 @@ public void FillRect (Rectangle rect, Rune rune = default) { Contents [r, c] = new Cell { - Rune = (rune != default ? rune : (Rune)' '), + Rune = rune != default ? rune : (Rune)' ', Attribute = CurrentAttribute, IsDirty = true }; _dirtyLines! [r] = true; @@ -562,11 +562,6 @@ public virtual Attribute MakeColor (in Color foreground, in Color background) #region Mouse and Keyboard - /// - /// Gets whether the mouse is reporting move events. - /// - public abstract bool IsReportingMouseMoves { get; internal set; } - /// Event fired when a key is pressed down. This is a precursor to . public event EventHandler? KeyDown; @@ -613,16 +608,6 @@ public void OnMouseEvent (MouseEventArgs a) /// If simulates the Ctrl key being pressed. public abstract void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool ctrl); - /// - /// Provide handling for the terminal start reporting mouse events. - /// - public abstract void StartReportingMouseMoves (); - - /// - /// Provide handling for the terminal stop reporting mouse events. - /// - public abstract void StopReportingMouseMoves (); - /// /// Provide handling for the terminal write ANSI escape sequence request. /// @@ -630,22 +615,29 @@ public void OnMouseEvent (MouseEventArgs a) /// The request response. public abstract string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest); + /// + /// Provide proper writing to send escape sequence recognized by the . + /// + /// + public abstract void WriteRaw (string ansi); + internal string ReadAnsiResponseDefault (AnsiEscapeSequenceRequest ansiRequest) { var response = new StringBuilder (); - int index = 0; + var index = 0; while (Console.KeyAvailable) { // Peek the next key ConsoleKeyInfo keyInfo = Console.ReadKey (true); // true to not display on the console - if ((index == 0 && keyInfo.KeyChar == EscSeqUtils.KeyEsc) || (index > 0 && keyInfo.KeyChar != EscSeqUtils.KeyEsc)) + if (index == 0 && keyInfo.KeyChar != EscSeqUtils.KeyEsc) { - // Append the current key to the response - response.Append (keyInfo.KeyChar); + break; } + response.Append (keyInfo.KeyChar); + // Read until no key is available if no terminator was specified or // check if the key is terminator (ANSI escape sequence ends) if (!string.IsNullOrEmpty (ansiRequest.Terminator) && keyInfo.KeyChar == ansiRequest.Terminator [^1]) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 940facee8e..5092d266ca 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -177,33 +177,19 @@ public override bool SetCursorVisibility (CursorVisibility visibility) return true; } - public override bool IsReportingMouseMoves { get; internal set; } - - public override void StartReportingMouseMoves () + public void StartReportingMouseMoves () { if (!RunningUnitTests) { Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); - - IsReportingMouseMoves = true; } } - public override void StopReportingMouseMoves () + public void StopReportingMouseMoves () { if (!RunningUnitTests) { Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); - - IsReportingMouseMoves = false; - - Thread.Sleep (100); // Allow time for mouse stopping and to flush the input buffer - - // Flush the input buffer to avoid reading stale input - while (Console.KeyAvailable) - { - Console.ReadKey (true); - } } } diff --git a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs index 66fcb32d16..24d39f4c1c 100644 --- a/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs @@ -40,9 +40,6 @@ public Behaviors ( public static Behaviors FakeBehaviors = new (); public override bool SupportsTrueColor => false; - /// - public override bool IsReportingMouseMoves { get; internal set; } - public FakeDriver () { Cols = FakeConsole.WindowWidth = FakeConsole.BufferWidth = FakeConsole.WIDTH; @@ -396,13 +393,10 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al } /// - public override void StartReportingMouseMoves () { throw new NotImplementedException (); } - - /// - public override void StopReportingMouseMoves () { throw new NotImplementedException (); } + public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { throw new NotImplementedException (); } /// - public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { throw new NotImplementedException (); } + public override void WriteRaw (string ansi) { throw new NotImplementedException (); } public void SetBufferSize (int width, int height) { diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 18a2bd3b47..b74a39ae43 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1414,38 +1414,19 @@ public override bool EnsureCursorVisibility () #region Mouse Handling - public override bool IsReportingMouseMoves { get; internal set; } - - public override void StartReportingMouseMoves () + public void StartReportingMouseMoves () { if (!RunningUnitTests) { Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); - - IsReportingMouseMoves = true; } } - public override void StopReportingMouseMoves () + public void StopReportingMouseMoves () { if (!RunningUnitTests) { Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); - - IsReportingMouseMoves = false; - - while (_mainLoopDriver is { _netEvents: { } } && Console.KeyAvailable) - { - _mainLoopDriver._netEvents._waitForStart.Set (); - _mainLoopDriver._netEvents._waitForStart.Reset (); - - _mainLoopDriver._netEvents._forceRead = true; - } - - if (_mainLoopDriver is { _netEvents: { } }) - { - _mainLoopDriver._netEvents._forceRead = false; - } } } From 1b6963f8db20b55c0519217d31bd5de35941f2d9 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 31 Oct 2024 20:12:05 +0000 Subject: [PATCH 46/89] Improves a lot of console key mappings. --- .../ConsoleDrivers/ConsoleKeyMapping.cs | 34 ++ .../ConsoleDrivers/EscSeqUtils/EscSeqReq.cs | 16 +- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 512 +++++++++++++++--- UnitTests/Input/EscSeqUtilsTests.cs | 403 +++++++++++++- 4 files changed, 844 insertions(+), 121 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs b/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs index c3497f3acd..25f87bc568 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs @@ -704,6 +704,32 @@ internal static uint MapKeyCodeToConsoleKey (KeyCode keyValue, out bool isConsol return (uint)ConsoleKey.F24; case KeyCode.Tab | KeyCode.ShiftMask: return (uint)ConsoleKey.Tab; + case KeyCode.Space: + return (uint)ConsoleKey.Spacebar; + default: + uint c = (char)keyValue; + + if (c is >= (char)ConsoleKey.A and <= (char)ConsoleKey.Z) + { + return c; + } + + if ((c - 32) is >= (char)ConsoleKey.A and <= (char)ConsoleKey.Z) + { + return (c - 32); + } + + if (Enum.IsDefined (typeof (ConsoleKey), keyValue.ToString ())) + { + return (uint)keyValue; + } + + // DEL + if ((uint)keyValue == 127) + { + return (uint)ConsoleKey.Backspace; + } + break; } isConsoleKey = false; @@ -867,6 +893,14 @@ public static KeyCode MapConsoleKeyInfoToKeyCode (ConsoleKeyInfo consoleKeyInfo) case ConsoleKey.Tab: keyCode = KeyCode.Tab; + break; + case ConsoleKey.Spacebar: + keyCode = KeyCode.Space; + + break; + case ConsoleKey.Backspace: + keyCode = KeyCode.Backspace; + break; default: if ((int)consoleKeyInfo.KeyChar is >= 1 and <= 26) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs index 8f7a56a19d..4dc98937bc 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs @@ -29,14 +29,22 @@ public class EscSeqRequests /// instance to list. /// /// The object. - public void Add (AnsiEscapeSequenceRequest ansiRequest) + /// The driver in use. + public void Add (AnsiEscapeSequenceRequest ansiRequest, ConsoleDriver? driver = null) { lock (Statuses) { Statuses.Enqueue (new (ansiRequest)); - Console.Out.Write (ansiRequest.Request); - Console.Out.Flush (); - Thread.Sleep (100); // Allow time for the terminal to respond + + if (driver is null) + { + Console.Out.Write (ansiRequest.Request); + Console.Out.Flush (); + } + else + { + driver.WriteRaw (ansiRequest.Request); + } } } diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 8a62c076e6..cd7a991399 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -1,4 +1,6 @@ #nullable enable +using Terminal.Gui.ConsoleDrivers; + namespace Terminal.Gui; /// @@ -156,6 +158,11 @@ public enum ClearScreenOptions /// public static string CSI_ClearScreen (ClearScreenOptions option) { return $"{CSI}{(int)option}J"; } + /// + /// Specify the incomplete array not yet recognized as valid ANSI escape sequence. + /// + public static ConsoleKeyInfo []? IncompleteCkInfos { get; set; } + /// /// Decodes an ANSI escape sequence. /// @@ -193,10 +200,10 @@ Action continuousButtonPressedHandler char [] kChars = GetKeyCharArray (cki); (c1Control, code, values, terminator) = GetEscapeResult (kChars); isMouse = false; - buttonState = new List { 0 }; + buttonState = [0]; pos = default (Point); seqReqStatus = null; - char keyChar = '\0'; + var keyChar = '\0'; switch (c1Control) { @@ -205,53 +212,112 @@ Action continuousButtonPressedHandler { key = ConsoleKey.Escape; - newConsoleKeyInfo = new ConsoleKeyInfo ( - cki [0].KeyChar, - key, - (mod & ConsoleModifiers.Shift) != 0, - (mod & ConsoleModifiers.Alt) != 0, - (mod & ConsoleModifiers.Control) != 0); + newConsoleKeyInfo = new ( + cki [0].KeyChar, + key, + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); } - else if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26) + else if ((uint)cki [1].KeyChar >= 1 && (uint)cki [1].KeyChar <= 26 && (uint)cki [1].KeyChar != '\n' && (uint)cki [1].KeyChar != '\r') { key = (ConsoleKey)(char)(cki [1].KeyChar + (uint)ConsoleKey.A - 1); + mod = ConsoleModifiers.Alt | ConsoleModifiers.Control; + + newConsoleKeyInfo = new ( + cki [1].KeyChar, + key, + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); + } + else if (cki [1].KeyChar >= 65 && cki [1].KeyChar <= 90) + { + key = (ConsoleKey)cki [1].KeyChar; + mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt; + + newConsoleKeyInfo = new ( + cki [1].KeyChar, + (ConsoleKey)Math.Min ((uint)key, 255), + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); + } + else if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122) + { + key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0]; + mod = ConsoleModifiers.Alt; + + newConsoleKeyInfo = new ( + cki [1].KeyChar, + (ConsoleKey)Math.Min ((uint)key, 255), + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); + } + else if (cki [1].KeyChar is '\0' or ' ') + { + key = ConsoleKey.Spacebar; - newConsoleKeyInfo = new ConsoleKeyInfo ( - cki [1].KeyChar, - key, - false, - true, - true); + if (kChars.Length > 1 && kChars [1] == '\0') + { + mod = ConsoleModifiers.Alt | ConsoleModifiers.Control; + } + else + { + mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt; + } + + newConsoleKeyInfo = new ( + cki [1].KeyChar, + (ConsoleKey)Math.Min ((uint)key, 255), + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); } - else + else if (cki [1].KeyChar is '\n' or '\r') { - if (cki [1].KeyChar >= 97 && cki [1].KeyChar <= 122) + key = ConsoleKey.Enter; + + if (kChars.Length > 1 && kChars [1] == '\n') { - key = (ConsoleKey)cki [1].KeyChar.ToString ().ToUpper () [0]; + mod = ConsoleModifiers.Alt | ConsoleModifiers.Control; } else { - key = (ConsoleKey)cki [1].KeyChar; + mod = ConsoleModifiers.Shift | ConsoleModifiers.Alt; } - newConsoleKeyInfo = new ConsoleKeyInfo ( - (char)key, - (ConsoleKey)Math.Min ((uint)key, 255), - false, - true, - false); + newConsoleKeyInfo = new ( + cki [1].KeyChar, + (ConsoleKey)Math.Min ((uint)key, 255), + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); + } + else + { + key = (ConsoleKey)cki [1].KeyChar; + mod = ConsoleModifiers.Alt; + + newConsoleKeyInfo = new ( + cki [1].KeyChar, + (ConsoleKey)Math.Min ((uint)key, 255), + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); } break; case "SS3": key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar); - newConsoleKeyInfo = new ConsoleKeyInfo ( - keyChar, - key, - (mod & ConsoleModifiers.Shift) != 0, - (mod & ConsoleModifiers.Alt) != 0, - (mod & ConsoleModifiers.Control) != 0); + newConsoleKeyInfo = new ( + keyChar, + key, + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); break; case "CSI": @@ -279,31 +345,32 @@ Action continuousButtonPressedHandler mod |= GetConsoleModifiers (values [1]); } - newConsoleKeyInfo = new ConsoleKeyInfo ( - keyChar, - key, - (mod & ConsoleModifiers.Shift) != 0, - (mod & ConsoleModifiers.Alt) != 0, - (mod & ConsoleModifiers.Control) != 0); + newConsoleKeyInfo = new ( + keyChar, + key, + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); } else { // BUGBUG: See https://github.com/gui-cs/Terminal.Gui/issues/2803 // This is caused by NetDriver depending on Console.KeyAvailable? - throw new InvalidOperationException ("CSI response, but there's no terminator"); + //throw new InvalidOperationException ("CSI response, but there's no terminator"); - //newConsoleKeyInfo = new ConsoleKeyInfo ('\0', - // key, - // (mod & ConsoleModifiers.Shift) != 0, - // (mod & ConsoleModifiers.Alt) != 0, - // (mod & ConsoleModifiers.Control) != 0); + IncompleteCkInfos = cki; } + break; + default: + newConsoleKeyInfo = MapConsoleKeyInfo (cki [0]); + key = newConsoleKeyInfo.Key; + mod = newConsoleKeyInfo.Modifiers; + break; } } - #nullable enable /// /// Gets the c1Control used in the called escape sequence. /// @@ -369,6 +436,7 @@ public static ConsoleKey GetConsoleKey (char terminator, string? value, ref Cons ('B', _) => ConsoleKey.DownArrow, ('C', _) => ConsoleKey.RightArrow, ('D', _) => ConsoleKey.LeftArrow, + ('E', _) => ConsoleKey.Clear, ('F', _) => ConsoleKey.End, ('H', _) => ConsoleKey.Home, ('P', _) => ConsoleKey.F1, @@ -388,18 +456,19 @@ public static ConsoleKey GetConsoleKey (char terminator, string? value, ref Cons ('~', "21") => ConsoleKey.F10, ('~', "23") => ConsoleKey.F11, ('~', "24") => ConsoleKey.F12, - ('l', _) => ConsoleKey.Add, - ('m', _) => ConsoleKey.Subtract, - ('p', _) => ConsoleKey.Insert, - ('q', _) => ConsoleKey.End, - ('r', _) => ConsoleKey.DownArrow, - ('s', _) => ConsoleKey.PageDown, - ('t', _) => ConsoleKey.LeftArrow, - ('u', _) => ConsoleKey.Clear, - ('v', _) => ConsoleKey.RightArrow, - ('w', _) => ConsoleKey.Home, - ('x', _) => ConsoleKey.UpArrow, - ('y', _) => ConsoleKey.PageUp, + // These terminators are used by macOS on a numeric keypad without keys modifiers + ('l', null) => ConsoleKey.Add, + ('m', null) => ConsoleKey.Subtract, + ('p', null) => ConsoleKey.Insert, + ('q', null) => ConsoleKey.End, + ('r', null) => ConsoleKey.DownArrow, + ('s', null) => ConsoleKey.PageDown, + ('t', null) => ConsoleKey.LeftArrow, + ('u', null) => ConsoleKey.Clear, + ('v', null) => ConsoleKey.RightArrow, + ('w', null) => ConsoleKey.Home, + ('x', null) => ConsoleKey.UpArrow, + ('y', null) => ConsoleKey.PageUp, (_, _) => 0 }; } @@ -434,7 +503,7 @@ public static ConsoleModifiers GetConsoleModifiers (string? value) /// public static (string c1Control, string code, string [] values, string terminating) GetEscapeResult (char [] kChar) { - if (kChar is null || kChar.Length == 0) + if (kChar is null || kChar.Length == 0 || (kChar.Length == 1 && kChar [0] != KeyEsc)) { return (null, null, null, null); } @@ -803,7 +872,7 @@ Action continuousButtonPressedHandler if ((mouseFlags [0] & MouseFlags.ReportMousePosition) == 0) { - Application.MainLoop.AddIdle ( + Application.MainLoop?.AddIdle ( () => { // INTENT: What's this trying to do? @@ -846,7 +915,7 @@ Action continuousButtonPressedHandler _isButtonClicked = false; _isButtonDoubleClicked = true; - Application.MainLoop.AddIdle ( + Application.MainLoop?.AddIdle ( () => { Task.Run (async () => await ProcessButtonDoubleClickedAsync ()); @@ -885,7 +954,7 @@ Action continuousButtonPressedHandler mouseFlags.Add (GetButtonClicked (buttonState)); _isButtonClicked = true; - Application.MainLoop.AddIdle ( + Application.MainLoop?.AddIdle ( () => { Task.Run (async () => await ProcessButtonClickedAsync ()); @@ -952,7 +1021,7 @@ Action continuousButtonPressedHandler public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) { ConsoleKeyInfo newConsoleKeyInfo = consoleKeyInfo; - ConsoleKey key; + ConsoleKey key = ConsoleKey.None; char keyChar = consoleKeyInfo.KeyChar; switch ((uint)keyChar) @@ -960,56 +1029,165 @@ public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) case 0: if (consoleKeyInfo.Key == (ConsoleKey)64) { // Ctrl+Space in Windows. - newConsoleKeyInfo = new ConsoleKeyInfo ( - ' ', - ConsoleKey.Spacebar, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0); + newConsoleKeyInfo = new ( + consoleKeyInfo.KeyChar, + ConsoleKey.Spacebar, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0); + } + else if (consoleKeyInfo.Key == ConsoleKey.None) + { + newConsoleKeyInfo = new ( + consoleKeyInfo.KeyChar, + ConsoleKey.Spacebar, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, + true); } break; - case uint n when n > 0 && n <= KeyEsc: - if (consoleKeyInfo.Key == 0 && consoleKeyInfo.KeyChar == '\r') + case uint n when n is > 0 and <= KeyEsc: + if (consoleKeyInfo is { Key: 0, KeyChar: '\t' }) + { + key = ConsoleKey.Tab; + + newConsoleKeyInfo = new ( + consoleKeyInfo.KeyChar, + key, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0); + } + else if (consoleKeyInfo is { Key: 0, KeyChar: '\r' }) { key = ConsoleKey.Enter; - newConsoleKeyInfo = new ConsoleKeyInfo ( - consoleKeyInfo.KeyChar, - key, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0); + newConsoleKeyInfo = new ( + consoleKeyInfo.KeyChar, + key, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0); + } + else if (consoleKeyInfo is { Key: 0, KeyChar: '\n' }) + { + key = ConsoleKey.Enter; + + newConsoleKeyInfo = new ( + consoleKeyInfo.KeyChar, + key, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, + true); } else if (consoleKeyInfo.Key == 0) { key = (ConsoleKey)(char)(consoleKeyInfo.KeyChar + (uint)ConsoleKey.A - 1); - newConsoleKeyInfo = new ConsoleKeyInfo ( - (char)key, - key, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, - true); + newConsoleKeyInfo = new ( + consoleKeyInfo.KeyChar, + key, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, + true); } break; case 127: // DEL - newConsoleKeyInfo = new ConsoleKeyInfo ( - consoleKeyInfo.KeyChar, - ConsoleKey.Backspace, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, - (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0); + key = ConsoleKey.Backspace; + + newConsoleKeyInfo = new ( + consoleKeyInfo.KeyChar, + key, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0); break; default: - newConsoleKeyInfo = consoleKeyInfo; + uint ck = ConsoleKeyMapping.MapKeyCodeToConsoleKey ((KeyCode)consoleKeyInfo.KeyChar, out bool isConsoleKey); + + if (isConsoleKey) + { + key = (ConsoleKey)ck; + } + + newConsoleKeyInfo = new ( + consoleKeyInfo.KeyChar, + key, + GetShiftMod (consoleKeyInfo.Modifiers), + (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0); break; } return newConsoleKeyInfo; + + bool GetShiftMod (ConsoleModifiers modifiers) + { + if (consoleKeyInfo.KeyChar is >= (char)ConsoleKey.A and <= (char)ConsoleKey.Z && modifiers == ConsoleModifiers.None) + { + return true; + } + + return (modifiers & ConsoleModifiers.Shift) != 0; + } + } + + private static MouseFlags _lastMouseFlags; + + /// + /// Provides a handler to be invoked when mouse continuous button pressed is processed. + /// + public static event EventHandler ContinuousButtonPressed; + + /// + /// Provides a default mouse event handler that can be used by any driver. + /// + /// The mouse flags event. + /// The mouse position. + public static void ProcessMouseEvent (MouseFlags mouseFlag, Point pos) + { + bool WasButtonReleased (MouseFlags flag) + { + return flag.HasFlag (MouseFlags.Button1Released) + || flag.HasFlag (MouseFlags.Button2Released) + || flag.HasFlag (MouseFlags.Button3Released) + || flag.HasFlag (MouseFlags.Button4Released); + } + + bool IsButtonNotPressed (MouseFlags flag) + { + return !flag.HasFlag (MouseFlags.Button1Pressed) + && !flag.HasFlag (MouseFlags.Button2Pressed) + && !flag.HasFlag (MouseFlags.Button3Pressed) + && !flag.HasFlag (MouseFlags.Button4Pressed); + } + + bool IsButtonClickedOrDoubleClicked (MouseFlags flag) + { + return flag.HasFlag (MouseFlags.Button1Clicked) + || flag.HasFlag (MouseFlags.Button2Clicked) + || flag.HasFlag (MouseFlags.Button3Clicked) + || flag.HasFlag (MouseFlags.Button4Clicked) + || flag.HasFlag (MouseFlags.Button1DoubleClicked) + || flag.HasFlag (MouseFlags.Button2DoubleClicked) + || flag.HasFlag (MouseFlags.Button3DoubleClicked) + || flag.HasFlag (MouseFlags.Button4DoubleClicked); + } + + if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) || (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0)) + { + return; + } + + _lastMouseFlags = mouseFlag; + + var me = new MouseEventArgs { Flags = mouseFlag, Position = pos }; + + ContinuousButtonPressed?.Invoke ((mouseFlag, pos), me); } /// @@ -1021,7 +1199,61 @@ public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) public static ConsoleKeyInfo [] ResizeArray (ConsoleKeyInfo consoleKeyInfo, ConsoleKeyInfo [] cki) { Array.Resize (ref cki, cki is null ? 1 : cki.Length + 1); - cki [cki.Length - 1] = consoleKeyInfo; + cki [^1] = consoleKeyInfo; + + return cki; + } + + /// + /// Insert a array into the another array at the specified + /// index. + /// + /// The array to insert. + /// The array where will be added the array. + /// The start index to insert the array, default is 0. + /// The array with another array inserted. + public static ConsoleKeyInfo [] InsertArray ([CanBeNull] ConsoleKeyInfo [] toInsert, ConsoleKeyInfo [] cki, int index = 0) + { + if (toInsert is null) + { + return cki; + } + + if (cki is null) + { + return toInsert; + } + + if (index < 0) + { + index = 0; + } + + ConsoleKeyInfo [] backupCki = cki.Clone () as ConsoleKeyInfo []; + + Array.Resize (ref cki, cki.Length + toInsert.Length); + + for (var i = 0; i < cki.Length; i++) + { + if (i == index) + { + for (var j = 0; j < toInsert.Length; j++) + { + cki [i] = toInsert [j]; + i++; + } + + for (int k = index; k < backupCki!.Length; k++) + { + cki [i] = backupCki [k]; + i++; + } + } + else + { + cki [i] = backupCki! [i]; + } + } return cki; } @@ -1156,6 +1388,108 @@ private static MouseFlags SetControlKeyStates (MouseFlags buttonState, MouseFlag return mouseFlag; } + /// + /// Split a raw string into a list of string with the correct ansi escape sequence. + /// + /// The raw string containing one or many ansi escape sequence. + /// A list with a valid ansi escape sequence. + public static List SplitEscapeRawString (string rawData) + { + List splitList = []; + var isEscSeq = false; + var split = string.Empty; + char previousChar = '\0'; + + for (var i = 0; i < rawData.Length; i++) + { + char c = rawData [i]; + + if (c == '\u001B') + { + isEscSeq = true; + + split = AddAndClearSplit (); + + split += c.ToString (); + } + else if (!isEscSeq && c >= Key.Space) + { + split = AddAndClearSplit (); + splitList.Add (c.ToString ()); + } + else if (previousChar != '\u001B' && c < Key.Space)// uint n when n is > 0 and <= KeyEsc + { + isEscSeq = false; + split = AddAndClearSplit (); + splitList.Add (c.ToString ()); + } + else + { + split += c.ToString (); + } + + if (!string.IsNullOrEmpty (split) && i == rawData.Length - 1) + { + splitList.Add (split); + } + + previousChar = c; + } + + return splitList; + + string AddAndClearSplit () + { + if (!string.IsNullOrEmpty (split)) + { + splitList.Add (split); + split = string.Empty; + } + + return split; + } + } + + /// + /// Convert a array to string. + /// + /// + /// The string representing the array. + public static string ToString (ConsoleKeyInfo [] consoleKeyInfos) + { + StringBuilder sb = new (); + + foreach (ConsoleKeyInfo keyChar in consoleKeyInfos) + { + sb.Append (keyChar.KeyChar); + } + + return sb.ToString (); + } + + /// + /// Convert a string to array. + /// + /// + /// The representing the string. + public static ConsoleKeyInfo [] ToConsoleKeyInfoArray (string ansi) + { + if (ansi is null) + { + return null; + } + + ConsoleKeyInfo [] cki = new ConsoleKeyInfo [ansi.Length]; + + for (var i = 0; i < ansi.Length; i++) + { + char c = ansi [i]; + cki [i] = new (c, 0, false, false, false); + } + + return cki; + } + #region Cursor //ESC [ M - RI Reverse Index – Performs the reverse operation of \n, moves cursor up one line, maintains horizontal position, scrolls buffer if necessary* diff --git a/UnitTests/Input/EscSeqUtilsTests.cs b/UnitTests/Input/EscSeqUtilsTests.cs index 7edb30d5e6..5991cd26cc 100644 --- a/UnitTests/Input/EscSeqUtilsTests.cs +++ b/UnitTests/Input/EscSeqUtilsTests.cs @@ -23,7 +23,7 @@ public class EscSeqUtilsTests [Fact] [AutoInitShutdown] - public void DecodeEscSeq_Tests () + public void DecodeEscSeq_Multiple_Tests () { // ESC _cki = new ConsoleKeyInfo [] { new ('\u001b', 0, false, false, false) }; @@ -83,7 +83,7 @@ public void DecodeEscSeq_Tests () Assert.Null (_escSeqReqProc); Assert.Equal (expectedCki, _newConsoleKeyInfo); Assert.Equal (ConsoleKey.R, _key); - Assert.Equal (0, (int)_mod); + Assert.Equal (ConsoleModifiers.Alt | ConsoleModifiers.Control, _mod); Assert.Equal ("ESC", _c1Control); Assert.Null (_code); Assert.Null (_values); @@ -97,7 +97,7 @@ public void DecodeEscSeq_Tests () ClearAll (); _cki = new ConsoleKeyInfo [] { new ('\u001b', 0, false, false, false), new ('r', 0, false, false, false) }; - expectedCki = new ('R', ConsoleKey.R, false, true, false); + expectedCki = new ('r', ConsoleKey.R, false, true, false); EscSeqUtils.DecodeEscSeq ( _escSeqReqProc, @@ -118,7 +118,7 @@ public void DecodeEscSeq_Tests () Assert.Null (_escSeqReqProc); Assert.Equal (expectedCki, _newConsoleKeyInfo); Assert.Equal (ConsoleKey.R, _key); - Assert.Equal (0, (int)_mod); + Assert.Equal (ConsoleModifiers.Alt, _mod); Assert.Equal ("ESC", _c1Control); Assert.Null (_code); Assert.Null (_values); @@ -877,6 +877,260 @@ public void DecodeEscSeq_Tests () Assert.NotNull (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); + + ClearAll (); + } + + [Theory] + [InlineData ('A', ConsoleKey.A, true, true, false, "ESC", '\u001b', 'A')] + [InlineData ('a', ConsoleKey.A, false, true, false, "ESC", '\u001b', 'a')] + [InlineData ('\0', ConsoleKey.Spacebar, false, true, true, "ESC", '\u001b', '\0')] + [InlineData (' ', ConsoleKey.Spacebar, true, true, false, "ESC", '\u001b', ' ')] + [InlineData ('\n', ConsoleKey.Enter, false, true, true, "ESC", '\u001b', '\n')] + [InlineData ('\r', ConsoleKey.Enter, true, true, false, "ESC", '\u001b', '\r')] + public void DecodeEscSeq_More_Multiple_Tests ( + char keyChar, + ConsoleKey consoleKey, + bool shift, + bool alt, + bool control, + string c1Control, + params char [] kChars + ) + { + _cki = new ConsoleKeyInfo [kChars.Length]; + + for (var i = 0; i < kChars.Length; i++) + { + char kChar = kChars [i]; + _cki [i] = new (kChar, 0, false, false, false); + } + + var expectedCki = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control); + + EscSeqUtils.DecodeEscSeq ( + _escSeqReqProc, + ref _newConsoleKeyInfo, + ref _key, + _cki, + ref _mod, + out _c1Control, + out _code, + out _values, + out _terminating, + out _isKeyMouse, + out _mouseFlags, + out _pos, + out _seqReqStatus, + ProcessContinuousButtonPressed + ); + Assert.Null (_escSeqReqProc); + Assert.Equal (expectedCki, _newConsoleKeyInfo); + Assert.Equal (consoleKey, _key); + + ConsoleModifiers mods = new (); + + if (shift) + { + mods = ConsoleModifiers.Shift; + } + + if (alt) + { + mods |= ConsoleModifiers.Alt; + } + + if (control) + { + mods |= ConsoleModifiers.Control; + } + + Assert.Equal (mods, _mod); + Assert.Equal (c1Control, _c1Control); + Assert.Null (_code); + Assert.Null (_values); + Assert.Equal (keyChar.ToString (), _terminating); + Assert.False (_isKeyMouse); + Assert.Equal (new () { 0 }, _mouseFlags); + Assert.Equal (Point.Empty, _pos); + Assert.Null (_seqReqStatus); + Assert.Equal (0, (int)_arg1); + Assert.Equal (Point.Empty, _arg2); + + ClearAll (); + } + + [Fact] + public void DecodeEscSeq_IncompleteCKInfos () + { + // This is simulated response from a CSI_ReportTerminalSizeInChars + _cki = + [ + new ('\u001b', 0, false, false, false), + new ('[', 0, false, false, false), + new ('8', 0, false, false, false), + new (';', 0, false, false, false), + new ('1', 0, false, false, false), + ]; + + ConsoleKeyInfo expectedCki = default; + + EscSeqUtils.DecodeEscSeq ( + _escSeqReqProc, + ref _newConsoleKeyInfo, + ref _key, + _cki, + ref _mod, + out _c1Control, + out _code, + out _values, + out _terminating, + out _isKeyMouse, + out _mouseFlags, + out _pos, + out _seqReqStatus, + ProcessContinuousButtonPressed + ); + Assert.Null (_escSeqReqProc); + Assert.Equal (expectedCki, _newConsoleKeyInfo); + Assert.Equal (ConsoleKey.None, _key); + Assert.Equal (ConsoleModifiers.None, _mod); + Assert.Equal ("CSI", _c1Control); + Assert.Null (_code); + Assert.Equal (2, _values.Length); + Assert.Equal ("", _terminating); + Assert.False (_isKeyMouse); + Assert.Equal ([0], _mouseFlags); + Assert.Equal (Point.Empty, _pos); + Assert.Null (_seqReqStatus); + Assert.Equal (0, (int)_arg1); + Assert.Equal (Point.Empty, _arg2); + Assert.Equal (_cki, EscSeqUtils.IncompleteCkInfos); + + _cki = EscSeqUtils.InsertArray ( + EscSeqUtils.IncompleteCkInfos, + [ + new ('0', 0, false, false, false), + new (';', 0, false, false, false), + new ('2', 0, false, false, false), + new ('0', 0, false, false, false), + new ('t', 0, false, false, false) + ]); + + expectedCki = default; + + EscSeqUtils.DecodeEscSeq ( + _escSeqReqProc, + ref _newConsoleKeyInfo, + ref _key, + _cki, + ref _mod, + out _c1Control, + out _code, + out _values, + out _terminating, + out _isKeyMouse, + out _mouseFlags, + out _pos, + out _seqReqStatus, + ProcessContinuousButtonPressed + ); + Assert.Null (_escSeqReqProc); + Assert.Equal (expectedCki, _newConsoleKeyInfo); + Assert.Equal (ConsoleKey.None, _key); + + Assert.Equal (ConsoleModifiers.None, _mod); + Assert.Equal ("CSI", _c1Control); + Assert.Null (_code); + Assert.Equal (3, _values.Length); + Assert.Equal ("t", _terminating); + Assert.False (_isKeyMouse); + Assert.Equal ([0], _mouseFlags); + Assert.Equal (Point.Empty, _pos); + Assert.Null (_seqReqStatus); + Assert.Equal (0, (int)_arg1); + Assert.Equal (Point.Empty, _arg2); + Assert.NotEqual (_cki, EscSeqUtils.IncompleteCkInfos); + Assert.Contains (EscSeqUtils.ToString (EscSeqUtils.IncompleteCkInfos), EscSeqUtils.ToString (_cki)); + + ClearAll (); + } + + [Theory] + [InlineData ('\u001B', ConsoleKey.Escape, false, false, false)] + [InlineData ('\r', ConsoleKey.Enter, false, false, false)] + [InlineData ('1', ConsoleKey.D1, false, false, false)] + [InlineData ('!', ConsoleKey.None, false, false, false)] + [InlineData ('a', ConsoleKey.A, false, false, false)] + [InlineData ('A', ConsoleKey.A, true, false, false)] + [InlineData ('\u0001', ConsoleKey.A, false, false, true)] + [InlineData ('\0', ConsoleKey.Spacebar, false, false, true)] + [InlineData ('\n', ConsoleKey.Enter, false, false, true)] + [InlineData ('\t', ConsoleKey.Tab, false, false, false)] + public void DecodeEscSeq_Single_Tests (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control) + { + _cki = [new (keyChar, 0, false, false, false)]; + var expectedCki = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control); + + EscSeqUtils.DecodeEscSeq ( + _escSeqReqProc, + ref _newConsoleKeyInfo, + ref _key, + _cki, + ref _mod, + out _c1Control, + out _code, + out _values, + out _terminating, + out _isKeyMouse, + out _mouseFlags, + out _pos, + out _seqReqStatus, + ProcessContinuousButtonPressed + ); + Assert.Null (_escSeqReqProc); + Assert.Equal (expectedCki, _newConsoleKeyInfo); + Assert.Equal (consoleKey, _key); + + ConsoleModifiers mods = new (); + + if (shift) + { + mods = ConsoleModifiers.Shift; + } + + if (alt) + { + mods |= ConsoleModifiers.Alt; + } + + if (control) + { + mods |= ConsoleModifiers.Control; + } + + Assert.Equal (mods, _mod); + + if (keyChar == '\u001B') + { + Assert.Equal ("ESC", _c1Control); + } + else + { + Assert.Null (_c1Control); + } + + Assert.Null (_code); + Assert.Null (_values); + Assert.Null (_terminating); + Assert.False (_isKeyMouse); + Assert.Equal (new () { 0 }, _mouseFlags); + Assert.Equal (Point.Empty, _pos); + Assert.Null (_seqReqStatus); + Assert.Equal (0, (int)_arg1); + Assert.Equal (Point.Empty, _arg2); + + ClearAll (); } [Fact] @@ -920,39 +1174,39 @@ public void GetC1ControlChar_Tests () public void GetConsoleInputKey_ConsoleKeyInfo () { var cki = new ConsoleKeyInfo ('r', 0, false, false, false); - var expectedCki = new ConsoleKeyInfo ('r', 0, false, false, false); + var expectedCki = new ConsoleKeyInfo ('r', ConsoleKey.R, false, false, false); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, true, false, false); - expectedCki = new ('r', 0, true, false, false); + expectedCki = new ('r', ConsoleKey.R, true, false, false); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, false, true, false); - expectedCki = new ('r', 0, false, true, false); + expectedCki = new ('r', ConsoleKey.R, false, true, false); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, false, false, true); - expectedCki = new ('r', 0, false, false, true); + expectedCki = new ('r', ConsoleKey.R, false, false, true); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, true, true, false); - expectedCki = new ('r', 0, true, true, false); + expectedCki = new ('r', ConsoleKey.R, true, true, false); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, false, true, true); - expectedCki = new ('r', 0, false, true, true); + expectedCki = new ('r', ConsoleKey.R, false, true, true); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, true, true, true); - expectedCki = new ('r', 0, true, true, true); + expectedCki = new ('r', ConsoleKey.R, true, true, true); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('\u0012', 0, false, false, false); - expectedCki = new ('R', ConsoleKey.R, false, false, true); + expectedCki = new ('\u0012', ConsoleKey.R, false, false, true); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('\0', (ConsoleKey)64, false, false, true); - expectedCki = new (' ', ConsoleKey.Spacebar, false, false, true); + expectedCki = new ('\0', ConsoleKey.Spacebar, false, false, true); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('\r', 0, false, false, false); @@ -964,7 +1218,7 @@ public void GetConsoleInputKey_ConsoleKeyInfo () Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); cki = new ('R', 0, false, false, false); - expectedCki = new ('R', 0, false, false, false); + expectedCki = new ('R', ConsoleKey.R, true, false, false); Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); } @@ -999,18 +1253,19 @@ public void GetConsoleKey_Tests () Assert.Equal (ConsoleKey.F11, EscSeqUtils.GetConsoleKey ('~', "23", ref mod, ref keyChar)); Assert.Equal (ConsoleKey.F12, EscSeqUtils.GetConsoleKey ('~', "24", ref mod, ref keyChar)); Assert.Equal (0, (int)EscSeqUtils.GetConsoleKey ('~', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Add, EscSeqUtils.GetConsoleKey ('l', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Subtract, EscSeqUtils.GetConsoleKey ('m', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Insert, EscSeqUtils.GetConsoleKey ('p', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.End, EscSeqUtils.GetConsoleKey ('q', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.DownArrow, EscSeqUtils.GetConsoleKey ('r', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.PageDown, EscSeqUtils.GetConsoleKey ('s', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.LeftArrow, EscSeqUtils.GetConsoleKey ('t', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Clear, EscSeqUtils.GetConsoleKey ('u', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.RightArrow, EscSeqUtils.GetConsoleKey ('v', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Home, EscSeqUtils.GetConsoleKey ('w', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.UpArrow, EscSeqUtils.GetConsoleKey ('x', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.PageUp, EscSeqUtils.GetConsoleKey ('y', "", ref mod, ref keyChar)); + // These terminators are used by macOS on a numeric keypad without keys modifiers + Assert.Equal (ConsoleKey.Add, EscSeqUtils.GetConsoleKey ('l', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Subtract, EscSeqUtils.GetConsoleKey ('m', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Insert, EscSeqUtils.GetConsoleKey ('p', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.End, EscSeqUtils.GetConsoleKey ('q', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.DownArrow, EscSeqUtils.GetConsoleKey ('r', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.PageDown, EscSeqUtils.GetConsoleKey ('s', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.LeftArrow, EscSeqUtils.GetConsoleKey ('t', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Clear, EscSeqUtils.GetConsoleKey ('u', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.RightArrow, EscSeqUtils.GetConsoleKey ('v', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Home, EscSeqUtils.GetConsoleKey ('w', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.UpArrow, EscSeqUtils.GetConsoleKey ('x', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.PageUp, EscSeqUtils.GetConsoleKey ('y', null, ref mod, ref keyChar)); } [Fact] @@ -1031,9 +1286,9 @@ public void GetConsoleModifiers_Tests () } [Fact] - public void GetEscapeResult_Tests () + public void GetEscapeResult_Multiple_Tests () { - char [] kChars = { '\u001b', '[', '5', ';', '1', '0', 'r' }; + char [] kChars = ['\u001b', '[', '5', ';', '1', '0', 'r']; (_c1Control, _code, _values, _terminating) = EscSeqUtils.GetEscapeResult (kChars); Assert.Equal ("CSI", _c1Control); Assert.Null (_code); @@ -1043,6 +1298,31 @@ public void GetEscapeResult_Tests () Assert.Equal ("r", _terminating); } + [Theory] + [InlineData ('\u001B')] + [InlineData (['\r'])] + [InlineData (['1'])] + [InlineData (['!'])] + [InlineData (['a'])] + [InlineData (['A'])] + public void GetEscapeResult_Single_Tests (params char [] kChars) + { + (_c1Control, _code, _values, _terminating) = EscSeqUtils.GetEscapeResult (kChars); + + if (kChars [0] == '\u001B') + { + Assert.Equal ("ESC", _c1Control); + } + else + { + Assert.Null (_c1Control); + } + + Assert.Null (_code); + Assert.Null (_values); + Assert.Null (_terminating); + } + [Fact] public void GetKeyCharArray_Tests () { @@ -1160,6 +1440,73 @@ public void ResizeArray_ConsoleKeyInfo () Assert.Equal (cki, expectedCkInfos [0]); } + [Fact] + public void SplitEscapeRawString_Multiple_Tests () + { + string rawData = + "\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\r"; + + List splitList = EscSeqUtils.SplitEscapeRawString (rawData); + Assert.Equal (18, splitList.Count); + Assert.Equal ("\r", splitList [0]); + Assert.Equal ("\u001b[<35;50;1m", splitList [1]); + Assert.Equal ("\u001b[<35;49;1m", splitList [2]); + Assert.Equal ("\u001b[<35;47;1m", splitList [3]); + Assert.Equal ("\u001b[<35;46;1m", splitList [4]); + Assert.Equal ("\u001b[<35;45;2m", splitList [5]); + Assert.Equal ("\u001b[<35;44;2m", splitList [6]); + Assert.Equal ("\u001b[<35;43;3m", splitList [7]); + Assert.Equal ("\u001b[<35;42;3m", splitList [8]); + Assert.Equal ("\u001b[<35;41;4m", splitList [9]); + Assert.Equal ("\u001b[<35;40;5m", splitList [10]); + Assert.Equal ("\u001b[<35;39;6m", splitList [11]); + Assert.Equal ("\u001b[<35;49;1m", splitList [12]); + Assert.Equal ("\u001b[<35;48;2m", splitList [13]); + Assert.Equal ("\u001b[<0;33;6M", splitList [14]); + Assert.Equal ("\u001b[<0;33;6m", splitList [15]); + Assert.Equal ("\u001bOC", splitList [16]); + Assert.Equal ("\r", splitList [^1]); + } + + [Theory] + [InlineData ("[<35;50;1m")] + [InlineData ("\r")] + [InlineData ("1")] + [InlineData ("!")] + [InlineData ("a")] + [InlineData ("A")] + public void SplitEscapeRawString_Single_Tests (string rawData) + { + List splitList = EscSeqUtils.SplitEscapeRawString (rawData); + Assert.Single (splitList); + Assert.Equal (rawData, splitList [0]); + } + + [Theory] + [InlineData (null, null, null, null)] + [InlineData ("\u001b[8;1", null, null, "\u001b[8;1")] + [InlineData (null, "\u001b[8;1", 5, "\u001b[8;1")] + [InlineData ("\u001b[8;1", null, 5, "\u001b[8;1")] + [InlineData ("\u001b[8;1", "0;20t", -1, "\u001b[8;10;20t")] + [InlineData ("\u001b[8;1", "0;20t", 0, "\u001b[8;10;20t")] + [InlineData ("0;20t", "\u001b[8;1", 5, "\u001b[8;10;20t")] + [InlineData ("0;20t", "\u001b[8;1", 3, "\u001b[80;20t;1")] + public void InsertArray_Tests (string toInsert, string current, int? index, string expected) + { + ConsoleKeyInfo [] toIns = EscSeqUtils.ToConsoleKeyInfoArray (toInsert); + ConsoleKeyInfo [] cki = EscSeqUtils.ToConsoleKeyInfoArray (current); + ConsoleKeyInfo [] result = EscSeqUtils.ToConsoleKeyInfoArray (expected); + + if (index is null) + { + Assert.Equal (result, EscSeqUtils.InsertArray (toIns, cki)); + } + else + { + Assert.Equal (result, EscSeqUtils.InsertArray (toIns, cki, (int)index)); + } + } + private void ClearAll () { _escSeqReqProc = default (EscSeqRequests); From ba607f13804e1512a8e05289abae1322af5f06e0 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 31 Oct 2024 20:14:22 +0000 Subject: [PATCH 47/89] Commenting GetIsKeyCodeAtoZ contradiction debug check. --- Terminal.Gui/Input/Key.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Terminal.Gui/Input/Key.cs b/Terminal.Gui/Input/Key.cs index 11f8d938e2..d69552aa61 100644 --- a/Terminal.Gui/Input/Key.cs +++ b/Terminal.Gui/Input/Key.cs @@ -208,13 +208,13 @@ public KeyCode KeyCode get => _keyCode; init { -#if DEBUG - if (GetIsKeyCodeAtoZ (value) && (value & KeyCode.Space) != 0) - { - throw new ArgumentException ($"Invalid KeyCode: {value} is invalid.", nameof (value)); - } +//#if DEBUG +// if (GetIsKeyCodeAtoZ (value) && (value & KeyCode.Space) != 0) +// { +// throw new ArgumentException ($"Invalid KeyCode: {value} is invalid.", nameof (value)); +// } -#endif +//#endif _keyCode = value; } } From ee8d0404075aec3529e9c90bc27effc240aefa84 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 31 Oct 2024 20:30:22 +0000 Subject: [PATCH 48/89] Fix NetDriver and WindowsDriver. --- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 65 +++++++++++++++----- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 27 +++----- 2 files changed, 61 insertions(+), 31 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index b74a39ae43..df57c6b2f0 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -198,7 +198,7 @@ public NetEvents (ConsoleDriver consoleDriver) return null; } - private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, bool intercept = true) + private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, bool intercept = true) { // if there is a key available, return it without waiting // (or dispatching work to the thread queue) @@ -215,6 +215,30 @@ private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellation { return Console.ReadKey (intercept); } + + if (EscSeqUtils.IncompleteCkInfos is null && EscSeqRequests is { Statuses.Count: > 0 }) + { + if (_retries > 1) + { + EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); + + lock (seqReqStatus.AnsiRequest._responseLock) + { + seqReqStatus.AnsiRequest.Response = string.Empty; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + } + + _retries = 0; + } + else + { + _retries++; + } + } + else + { + _retries = 0; + } } cancellationToken.ThrowIfCancellationRequested (); @@ -223,6 +247,7 @@ private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellation } internal bool _forceRead; + private int _retries; private void ProcessInputQueue () { @@ -230,7 +255,10 @@ private void ProcessInputQueue () { try { - _waitForStart.Wait (_inputReadyCancellationTokenSource.Token); + if (!_forceRead) + { + _waitForStart.Wait (_inputReadyCancellationTokenSource.Token); + } } catch (OperationCanceledException) { @@ -258,6 +286,11 @@ private void ProcessInputQueue () return; } + if (EscSeqUtils.IncompleteCkInfos is { }) + { + EscSeqUtils.InsertArray (EscSeqUtils.IncompleteCkInfos, _cki); + } + if ((consoleKeyInfo.KeyChar == (char)KeyCode.Esc && !_isEscSeq) || (consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq)) { @@ -277,7 +310,7 @@ private void ProcessInputQueue () _isEscSeq = true; - if (consoleKeyInfo.KeyChar != Key.Esc && consoleKeyInfo.KeyChar <= Key.Space) + if (_cki is { } && _cki [^1].KeyChar != Key.Esc && consoleKeyInfo.KeyChar != Key.Esc && consoleKeyInfo.KeyChar <= Key.Space) { ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); _cki = null; @@ -322,6 +355,11 @@ private void ProcessInputQueue () ProcessMapConsoleKeyInfo (consoleKeyInfo); + if (_retries > 0) + { + _retries = 0; + } + break; } } @@ -460,17 +498,13 @@ ref ConsoleModifiers mod if (seqReqStatus is { }) { //HandleRequestResponseEvent (c1Control, code, values, terminating); - StringBuilder sb = new (); - foreach (ConsoleKeyInfo keyChar in cki) - { - sb.Append (keyChar.KeyChar); - } + var ckiString = EscSeqUtils.ToString (cki); lock (seqReqStatus.AnsiRequest._responseLock) { - seqReqStatus.AnsiRequest.Response = sb.ToString (); - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, sb.ToString ()); + seqReqStatus.AnsiRequest.Response = ckiString; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, ckiString); } return; @@ -1165,7 +1199,7 @@ internal override MainLoop Init () return new MainLoop (_mainLoopDriver); } - + private void ProcessInput (InputResult inputEvent) { switch (inputEvent.EventType) @@ -1457,12 +1491,12 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) }; _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest); - } - if (!_ansiResponseTokenSource.IsCancellationRequested && Console.KeyAvailable) - { _mainLoopDriver._netEvents._forceRead = true; + } + if (!_ansiResponseTokenSource.IsCancellationRequested) + { _mainLoopDriver._netEvents._waitForStart.Set (); if (!_mainLoopDriver._waitForProbe.IsSet) @@ -1497,6 +1531,9 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) return response; } + /// + public override void WriteRaw (string ansi) { throw new NotImplementedException (); } + private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me) { //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}"); diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 71bdb2c478..57848301a0 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -18,9 +18,7 @@ using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; -using System.Text; using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping; -using static Terminal.Gui.SpinnerStyle; namespace Terminal.Gui; @@ -1066,9 +1064,6 @@ public WindowsDriver () public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal); - /// - public override bool IsReportingMouseMoves { get; internal set; } - public WindowsConsole WinConsole { get; private set; } public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent) @@ -1196,7 +1191,7 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al } } - /// + /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { if (_mainLoopDriver is null) @@ -1217,12 +1212,11 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) try { - if (WinConsole?.WriteANSI (ansiRequest.Request) == true) - { - Thread.Sleep (100); // Allow time for the terminal to respond + WriteRaw (ansiRequest.Request); - return ReadAnsiResponseDefault (ansiRequest); - } + Thread.Sleep (100); // Allow time for the terminal to respond + + return ReadAnsiResponseDefault (ansiRequest); } catch (Exception) { @@ -1232,18 +1226,17 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { _mainLoopDriver._suspendRead = false; } - - return string.Empty; } #region Not Implemented - public override void StartReportingMouseMoves () { throw new NotImplementedException (); } - - public override void StopReportingMouseMoves () { throw new NotImplementedException (); } - public override void Suspend () { throw new NotImplementedException (); } + public override void WriteRaw (string ansi) + { + WinConsole?.WriteANSI (ansi); + } + #endregion public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent) From 8ab7ec5096313d78eaaa71133e8b56fb16d2c755 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 31 Oct 2024 21:03:37 +0000 Subject: [PATCH 49/89] Fix for WindowsDriver. --- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index 2adb68e983..e3cdb72521 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -633,7 +633,7 @@ internal string ReadAnsiResponseDefault (AnsiEscapeSequenceRequest ansiRequest) if (index == 0 && keyInfo.KeyChar != EscSeqUtils.KeyEsc) { - break; + continue; } response.Append (keyInfo.KeyChar); From de45b4bf397574e8f6f71efa673b9d78a6ff566d Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 31 Oct 2024 21:31:05 +0000 Subject: [PATCH 50/89] Refactoring a lot CursesDriver. --- .../CursesDriver/CursesDriver.cs | 465 ++++------------- .../CursesDriver/GetTIOCGWINSZ.c | 11 + .../CursesDriver/GetTIOCGWINSZ.sh | 17 + .../CursesDriver/UnixMainLoop.cs | 470 +++++++++++++----- .../ConsoleDrivers/CursesDriver/binding.cs | 13 + .../ConsoleDrivers/CursesDriver/constants.cs | 2 - Terminal.Gui/Terminal.Gui.csproj | 71 +-- .../compiled-binaries/libGetTIOCGWINSZ.dylib | Bin 0 -> 16512 bytes .../compiled-binaries/libGetTIOCGWINSZ.so | Bin 0 -> 15160 bytes 9 files changed, 519 insertions(+), 530 deletions(-) create mode 100644 Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.c create mode 100644 Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.sh create mode 100644 Terminal.Gui/compiled-binaries/libGetTIOCGWINSZ.dylib create mode 100644 Terminal.Gui/compiled-binaries/libGetTIOCGWINSZ.so diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 5092d266ca..1f4f2bc3ff 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -17,7 +17,6 @@ internal class CursesDriver : ConsoleDriver private CursorVisibility? _initialCursorVisibility; private MouseFlags _lastMouseFlags; private UnixMainLoop _mainLoopDriver; - private object _processInputToken; public override int Cols { @@ -42,7 +41,21 @@ internal set public override bool SupportsTrueColor => true; /// - public override bool EnsureCursorVisibility () { return false; } + public override bool EnsureCursorVisibility () + { + if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) + { + GetCursorVisibility (out CursorVisibility cursorVisibility); + _currentCursorVisibility = cursorVisibility; + SetCursorVisibility (CursorVisibility.Invisible); + + return false; + } + + SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default); + + return _currentCursorVisibility == CursorVisibility.Default; + } /// public override bool GetCursorVisibility (out CursorVisibility visibility) @@ -193,6 +206,9 @@ public void StopReportingMouseMoves () } } + private readonly ManualResetEventSlim _waitAnsiResponse = new (false); + private readonly CancellationTokenSource _ansiResponseTokenSource = new (); + /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { @@ -201,33 +217,61 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) return string.Empty; } - while (Console.KeyAvailable) + var response = string.Empty; + + try { - _mainLoopDriver._forceRead = true; + lock (ansiRequest._responseLock) + { + ansiRequest.ResponseFromInput += (s, e) => + { + Debug.Assert (s == ansiRequest); - _mainLoopDriver._waitForInput.Set (); - _mainLoopDriver._waitForInput.Reset (); - } + ansiRequest.Response = response = e; - _mainLoopDriver._forceRead = false; - _mainLoopDriver._suspendRead = true; + _waitAnsiResponse.Set (); + }; - try - { - Console.Out.Write (ansiRequest.Request); - Console.Out.Flush (); // Ensure the request is sent - Task.Delay (100).Wait (); // Allow time for the terminal to respond + _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this); - return ReadAnsiResponseDefault (ansiRequest); + _mainLoopDriver._forceRead = true; + } + + if (!_ansiResponseTokenSource.IsCancellationRequested) + { + _mainLoopDriver._waitForInput.Set (); + + _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); + } } - catch (Exception) + catch (OperationCanceledException) { return string.Empty; } finally { - _mainLoopDriver._suspendRead = false; + _mainLoopDriver._forceRead = false; + + if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) + { + if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0 + && string.IsNullOrEmpty (request.AnsiRequest.Response)) + { + // Bad request or no response at all + _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _); + } + } + + _waitAnsiResponse.Reset (); } + + return response; + } + + /// + public override void WriteRaw (string ansi) + { + _mainLoopDriver.WriteRaw (ansi); } public override void Suspend () @@ -254,14 +298,18 @@ public override void UpdateCursor () if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows) { - Curses.move (Row, Col); - if (Force16Colors) { + Curses.move (Row, Col); + Curses.raw (); Curses.noecho (); Curses.refresh (); } + else + { + _mainLoopDriver.WriteRaw (EscSeqUtils.CSI_SetCursorPosition (Row + 1, Col + 1)); + } } } @@ -490,14 +538,13 @@ private bool SetCursorPosition (int col, int row) internal override void End () { + _ansiResponseTokenSource?.Cancel (); + _ansiResponseTokenSource?.Dispose (); + _waitAnsiResponse?.Dispose (); + StopReportingMouseMoves (); SetCursorVisibility (CursorVisibility.Default); - if (_mainLoopDriver is { }) - { - _mainLoopDriver.RemoveWatch (_processInputToken); - } - if (RunningUnitTests) { return; @@ -567,17 +614,6 @@ internal override MainLoop Init () { Curses.timeout (0); } - - _processInputToken = _mainLoopDriver?.AddWatch ( - 0, - UnixMainLoop.Condition.PollIn, - x => - { - ProcessInput (); - - return true; - } - ); } CurrentAttribute = new Attribute (ColorName16.White, ColorName16.Black); @@ -611,6 +647,7 @@ internal override MainLoop Init () if (!RunningUnitTests) { Curses.CheckWinChange (); + ClearContents (); if (Force16Colors) { @@ -621,316 +658,48 @@ internal override MainLoop Init () return new MainLoop (_mainLoopDriver); } - internal void ProcessInput () + internal void ProcessInput (UnixMainLoop.PollData inputEvent) { - int wch; - int code = Curses.get_wch (out wch); - - //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}"); - if (code == Curses.ERR) + switch (inputEvent.EventType) { - return; - } + case UnixMainLoop.EventType.Key: + ConsoleKeyInfo consoleKeyInfo = inputEvent.KeyEvent; - var k = KeyCode.Null; + KeyCode map = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo); - if (code == Curses.KEY_CODE_YES) - { - while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize) - { - ProcessWinChange (); - code = Curses.get_wch (out wch); - } - - if (wch == 0) - { - return; - } - - if (wch == Curses.KeyMouse) - { - int wch2 = wch; - - while (wch2 == Curses.KeyMouse) + if (map == KeyCode.Null) { - Key kea = null; - - ConsoleKeyInfo [] cki = - { - new ((char)KeyCode.Esc, 0, false, false, false), - new ('[', 0, false, false, false), - new ('<', 0, false, false, false) - }; - code = 0; - HandleEscSeqResponse (ref code, ref k, ref wch2, ref kea, ref cki); - } - - return; - } - - k = MapCursesKey (wch); - - if (wch >= 277 && wch <= 288) - { - // Shift+(F1 - F12) - wch -= 12; - k = KeyCode.ShiftMask | MapCursesKey (wch); - } - else if (wch >= 289 && wch <= 300) - { - // Ctrl+(F1 - F12) - wch -= 24; - k = KeyCode.CtrlMask | MapCursesKey (wch); - } - else if (wch >= 301 && wch <= 312) - { - // Ctrl+Shift+(F1 - F12) - wch -= 36; - k = KeyCode.CtrlMask | KeyCode.ShiftMask | MapCursesKey (wch); - } - else if (wch >= 313 && wch <= 324) - { - // Alt+(F1 - F12) - wch -= 48; - k = KeyCode.AltMask | MapCursesKey (wch); - } - else if (wch >= 325 && wch <= 327) - { - // Shift+Alt+(F1 - F3) - wch -= 60; - k = KeyCode.ShiftMask | KeyCode.AltMask | MapCursesKey (wch); - } - - OnKeyDown (new Key (k)); - OnKeyUp (new Key (k)); - - return; - } - - // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey - if (wch == 27) - { - Curses.timeout (10); - - code = Curses.get_wch (out int wch2); - - if (code == Curses.KEY_CODE_YES) - { - k = KeyCode.AltMask | MapCursesKey (wch); - } - - Key key = null; - - if (code == 0) - { - // The ESC-number handling, debatable. - // Simulates the AltMask itself by pressing Alt + Space. - // Needed for macOS - if (wch2 == (int)KeyCode.Space) - { - k = KeyCode.AltMask | KeyCode.Space; - } - else if (wch2 - (int)KeyCode.Space >= (uint)KeyCode.A - && wch2 - (int)KeyCode.Space <= (uint)KeyCode.Z) - { - k = (KeyCode)((uint)KeyCode.AltMask + (wch2 - (int)KeyCode.Space)); - } - else if (wch2 >= (uint)KeyCode.A - 64 && wch2 <= (uint)KeyCode.Z - 64) - { - k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + (wch2 + 64)); - } - else if (wch2 >= (uint)KeyCode.D0 && wch2 <= (uint)KeyCode.D9) - { - k = (KeyCode)((uint)KeyCode.AltMask + (uint)KeyCode.D0 + (wch2 - (uint)KeyCode.D0)); - } - else - { - ConsoleKeyInfo [] cki = - [ - new ((char)KeyCode.Esc, 0, false, false, false), new ((char)wch2, 0, false, false, false) - ]; - HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki); - - return; + break; } - //else if (wch2 == Curses.KeyCSI) - //{ - // ConsoleKeyInfo [] cki = - // { - // new ((char)KeyCode.Esc, 0, false, false, false), new ('[', 0, false, false, false) - // }; - // HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki); - - // return; - //} - //else - //{ - // // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa. - // if (((KeyCode)wch2 & KeyCode.CtrlMask) != 0) - // { - // k = (KeyCode)((uint)KeyCode.CtrlMask + (wch2 & ~(int)KeyCode.CtrlMask)); - // } - - // if (wch2 == 0) - // { - // k = KeyCode.CtrlMask | KeyCode.AltMask | KeyCode.Space; - // } - // //else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z) - // //{ - // // k = KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.Space; - // //} - // else if (wch2 < 256) - // { - // k = (KeyCode)wch2; // | KeyCode.AltMask; - // } - // else - // { - // k = (KeyCode)((uint)(KeyCode.AltMask | KeyCode.CtrlMask) + wch2); - // } - //} - - key = new Key (k); - } - else - { - key = Key.Esc; - } - OnKeyDown (key); - OnKeyUp (key); - } - else if (wch == Curses.KeyTab) - { - k = MapCursesKey (wch); - OnKeyDown (new Key (k)); - OnKeyUp (new Key (k)); - } - else if (wch == 127) - { - // Backspace needed for macOS - k = KeyCode.Backspace; - OnKeyDown (new Key (k)); - OnKeyUp (new Key (k)); - } - else - { - // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa. - k = (KeyCode)wch; + OnKeyDown (new Key (map)); + OnKeyUp (new Key (map)); - if (wch == 0) - { - k = KeyCode.CtrlMask | KeyCode.Space; - } - else if (wch >= (uint)KeyCode.A - 64 && wch <= (uint)KeyCode.Z - 64) - { - if ((KeyCode)(wch + 64) != KeyCode.J) - { - k = KeyCode.CtrlMask | (KeyCode)(wch + 64); - } - } - else if (wch >= (uint)KeyCode.A && wch <= (uint)KeyCode.Z) - { - k = (KeyCode)wch | KeyCode.ShiftMask; - } - - if (wch == '\n' || wch == '\r') - { - k = KeyCode.Enter; - } + break; + case UnixMainLoop.EventType.Mouse: + MouseEventArgs me = new MouseEventArgs { Position = inputEvent.MouseEvent.Position, Flags = inputEvent.MouseEvent.MouseFlags }; + OnMouseEvent (me); - // Strip the KeyCode.Space flag off if it's set - //if (k != KeyCode.Space && k.HasFlag (KeyCode.Space)) - if (Key.GetIsKeyCodeAtoZ (k) && (k & KeyCode.Space) != 0) - { - k &= ~KeyCode.Space; - } + break; + case UnixMainLoop.EventType.WindowSize: + Size size = new (inputEvent.WindowSizeEvent.Size.Width, inputEvent.WindowSizeEvent.Size.Height); + ProcessWinChange (inputEvent.WindowSizeEvent.Size); - OnKeyDown (new Key (k)); - OnKeyUp (new Key (k)); + break; + default: + throw new ArgumentOutOfRangeException (); } } - internal void ProcessWinChange () + private void ProcessWinChange (Size size) { - if (!RunningUnitTests && Curses.CheckWinChange ()) + if (!RunningUnitTests && Curses.ChangeWindowSize (size.Height, size.Width)) { ClearContents (); OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows))); } } - private void HandleEscSeqResponse ( - ref int code, - ref KeyCode k, - ref int wch2, - ref Key keyEventArgs, - ref ConsoleKeyInfo [] cki - ) - { - ConsoleKey ck = 0; - ConsoleModifiers mod = 0; - - while (code == 0) - { - code = Curses.get_wch (out wch2); - var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false); - - if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse) - { - EscSeqUtils.DecodeEscSeq ( - null, - ref consoleKeyInfo, - ref ck, - cki, - ref mod, - out _, - out _, - out _, - out _, - out bool isKeyMouse, - out List mouseFlags, - out Point pos, - out _, - ProcessMouseEvent - ); - - if (isKeyMouse) - { - foreach (MouseFlags mf in mouseFlags) - { - ProcessMouseEvent (mf, pos); - } - - cki = null; - - if (wch2 == 27) - { - cki = EscSeqUtils.ResizeArray ( - new ConsoleKeyInfo ( - (char)KeyCode.Esc, - 0, - false, - false, - false - ), - cki - ); - } - } - else - { - k = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo); - keyEventArgs = new Key (k); - OnKeyDown (keyEventArgs); - } - } - else - { - cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki); - } - } - } - private static KeyCode MapCursesKey (int cursesKey) { switch (cursesKey) @@ -1008,52 +777,6 @@ private static KeyCode MapCursesKey (int cursesKey) } } - private void ProcessMouseEvent (MouseFlags mouseFlag, Point pos) - { - bool WasButtonReleased (MouseFlags flag) - { - return flag.HasFlag (MouseFlags.Button1Released) - || flag.HasFlag (MouseFlags.Button2Released) - || flag.HasFlag (MouseFlags.Button3Released) - || flag.HasFlag (MouseFlags.Button4Released); - } - - bool IsButtonNotPressed (MouseFlags flag) - { - return !flag.HasFlag (MouseFlags.Button1Pressed) - && !flag.HasFlag (MouseFlags.Button2Pressed) - && !flag.HasFlag (MouseFlags.Button3Pressed) - && !flag.HasFlag (MouseFlags.Button4Pressed); - } - - bool IsButtonClickedOrDoubleClicked (MouseFlags flag) - { - return flag.HasFlag (MouseFlags.Button1Clicked) - || flag.HasFlag (MouseFlags.Button2Clicked) - || flag.HasFlag (MouseFlags.Button3Clicked) - || flag.HasFlag (MouseFlags.Button4Clicked) - || flag.HasFlag (MouseFlags.Button1DoubleClicked) - || flag.HasFlag (MouseFlags.Button2DoubleClicked) - || flag.HasFlag (MouseFlags.Button3DoubleClicked) - || flag.HasFlag (MouseFlags.Button4DoubleClicked); - } - - Debug.WriteLine ($"CursesDriver: ({pos.X},{pos.Y}) - {mouseFlag}"); - - - if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) || (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0)) - { - return; - } - - _lastMouseFlags = mouseFlag; - - var me = new MouseEventArgs { Flags = mouseFlag, Position = pos }; - //Debug.WriteLine ($"CursesDriver: ({me.Position}) - {me.Flags}"); - - OnMouseEvent (me); - } - #region Color Handling /// Creates an Attribute from the provided curses-based foreground and background color numbers diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.c b/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.c new file mode 100644 index 0000000000..d289b7ef30 --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.c @@ -0,0 +1,11 @@ +#include +#include + +// This function is used to get the value of the TIOCGWINSZ variable, +// which may have different values ​​on different Unix operating systems. +// In Linux=0x005413, in Darwin and OpenBSD=0x40087468, +// In Solaris=0x005468 +// The best solution is having a function that get the real value of the current OS +int get_tiocgwinsz_value() { + return TIOCGWINSZ; +} \ No newline at end of file diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.sh b/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.sh new file mode 100644 index 0000000000..e94706eb18 --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +# Create output directory if it doesn't exist +mkdir -p ../../compiled-binaries + +# Determine the output file extension based on the OS +if [[ "$OSTYPE" == "linux-gnu"* ]]; then + OUTPUT_FILE="../../compiled-binaries/libGetTIOCGWINSZ.so" +elif [[ "$OSTYPE" == "darwin"* ]]; then + OUTPUT_FILE="../../compiled-binaries/libGetTIOCGWINSZ.dylib" +else + echo "Unsupported OS: $OSTYPE" + exit 1 +fi + +# Compile the C file +gcc -shared -fPIC -o "$OUTPUT_FILE" GetTIOCGWINSZ.c diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs index c7a9a26125..081284358e 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs @@ -2,6 +2,7 @@ // mainloop.cs: Linux/Curses MainLoop implementation. // +using System.Collections.Concurrent; using System.Runtime.InteropServices; namespace Terminal.Gui; @@ -36,18 +37,13 @@ public enum Condition : short PollNval = 32 } - public const int KEY_RESIZE = unchecked ((int)0xffffffffffffffff); - private static readonly nint _ignore = Marshal.AllocHGlobal (1); - private readonly CursesDriver _cursesDriver; - private readonly Dictionary _descriptorWatchers = new (); - private readonly int [] _wakeUpPipes = new int [2]; private MainLoop _mainLoop; - private bool _pollDirty = true; private Pollfd [] _pollMap; - private bool _winChanged; + private readonly ConcurrentQueue _pollDataQueue = new (); private readonly ManualResetEventSlim _eventReady = new (false); internal readonly ManualResetEventSlim _waitForInput = new (false); + private readonly ManualResetEventSlim _windowSizeChange = new (false); private readonly CancellationTokenSource _eventReadyTokenSource = new (); private readonly CancellationTokenSource _inputHandlerTokenSource = new (); @@ -57,11 +53,13 @@ public UnixMainLoop (ConsoleDriver consoleDriver = null) _cursesDriver = (CursesDriver)Application.Driver; } + public EscSeqRequests EscSeqRequests { get; } = new (); + void IMainLoopDriver.Wakeup () { if (!ConsoleDriver.RunningUnitTests) { - write (_wakeUpPipes [1], _ignore, 1); + _eventReady.Set (); } } @@ -76,88 +74,293 @@ void IMainLoopDriver.Setup (MainLoop mainLoop) try { - pipe (_wakeUpPipes); - - AddWatch ( - _wakeUpPipes [0], - Condition.PollIn, - ml => - { - read (_wakeUpPipes [0], _ignore, 1); - - return true; - } - ); + // Setup poll for stdin (fd 0) and pipe (fd 1) + _pollMap = new Pollfd [1]; + _pollMap [0].fd = 0; // stdin (file descriptor 0) + _pollMap [0].events = (short)Condition.PollIn; // Monitor input for reading } catch (DllNotFoundException e) { throw new NotSupportedException ("libc not found", e); } + EscSeqUtils.ContinuousButtonPressed += EscSeqUtils_ContinuousButtonPressed; + Task.Run (CursesInputHandler, _inputHandlerTokenSource.Token); + Task.Run (WindowSizeHandler, _inputHandlerTokenSource.Token); } - internal bool _forceRead; - internal bool _suspendRead; - private int n; + private static readonly int TIOCGWINSZ = GetTIOCGWINSZValue (); - private void CursesInputHandler () + private const string PlaceholderLibrary = "compiled-binaries/libGetTIOCGWINSZ"; // Placeholder, won't directly load + + [DllImport (PlaceholderLibrary, EntryPoint = "get_tiocgwinsz_value")] + private static extern int GetTIOCGWINSZValueInternal (); + + public static int GetTIOCGWINSZValue () { - while (_mainLoop is { }) + // Determine the correct library path based on the OS + string libraryPath = Path.Combine ( + AppContext.BaseDirectory, + "compiled-binaries", + RuntimeInformation.IsOSPlatform (OSPlatform.OSX) ? "libGetTIOCGWINSZ.dylib" : "libGetTIOCGWINSZ.so"); + + // Load the native library manually + nint handle = NativeLibrary.Load (libraryPath); + + // Ensure the handle is valid + if (handle == nint.Zero) + { + throw new DllNotFoundException ($"Unable to load library: {libraryPath}"); + } + + return GetTIOCGWINSZValueInternal (); + } + + private void EscSeqUtils_ContinuousButtonPressed (object sender, MouseEventArgs e) + { + _pollDataQueue!.Enqueue (EnqueueMouseEvent (e.Flags, e.Position)); + } + + private void WindowSizeHandler () + { + var ws = new Winsize (); + ioctl (0, TIOCGWINSZ, ref ws); + + // Store initial window size + int rows = ws.ws_row; + int cols = ws.ws_col; + + while (_inputHandlerTokenSource is { IsCancellationRequested: false }) { try { - UpdatePollMap (); + _windowSizeChange.Wait (_inputHandlerTokenSource.Token); + _windowSizeChange.Reset (); - if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead) + while (!_inputHandlerTokenSource.IsCancellationRequested) { - _waitForInput.Wait (_inputHandlerTokenSource.Token); + // Wait for a while then check if screen has changed sizes + Task.Delay (500, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + + ioctl (0, TIOCGWINSZ, ref ws); + + if (rows != ws.ws_row || cols != ws.ws_col) + { + rows = ws.ws_row; + cols = ws.ws_col; + + _pollDataQueue!.Enqueue (EnqueueWindowSizeEvent (rows, cols)); + + break; + } } } catch (OperationCanceledException) { return; } - finally + + _eventReady.Set (); + } + } + + internal bool _forceRead; + private int _retries; + + private void CursesInputHandler () + { + while (_mainLoop is { }) + { + try { - if (!_inputHandlerTokenSource.IsCancellationRequested) + if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead) { - _waitForInput.Reset (); + _waitForInput.Wait (_inputHandlerTokenSource.Token); } } + catch (OperationCanceledException) + { + return; + } - while (!_inputHandlerTokenSource.IsCancellationRequested) + if (_pollDataQueue?.Count == 0 || _forceRead) { - if (!_suspendRead) + while (!_inputHandlerTokenSource.IsCancellationRequested) { - n = poll (_pollMap, (uint)_pollMap.Length, 0); + int n = poll (_pollMap, (uint)_pollMap.Length, 0); - if (n == KEY_RESIZE) + if (n > 0) { - _winChanged = true; + // Check if stdin has data + if ((_pollMap [0].revents & (int)Condition.PollIn) != 0) + { + // Allocate memory for the buffer + var buf = new byte [2048]; + nint bufPtr = Marshal.AllocHGlobal (buf.Length); + + try + { + // Read from the stdin + int bytesRead = read (_pollMap [0].fd, bufPtr, buf.Length); + + if (bytesRead > 0) + { + // Copy the data from unmanaged memory to a byte array + var buffer = new byte [bytesRead]; + Marshal.Copy (bufPtr, buffer, 0, bytesRead); + + // Convert the byte array to a string (assuming UTF-8 encoding) + string data = Encoding.UTF8.GetString (buffer); + + if (EscSeqUtils.IncompleteCkInfos is { }) + { + data = data.Insert (0, EscSeqUtils.ToString (EscSeqUtils.IncompleteCkInfos)); + EscSeqUtils.IncompleteCkInfos = null; + } + + // Enqueue the data + ProcessEnqueuePollData (data); + } + } + finally + { + // Free the allocated memory + Marshal.FreeHGlobal (bufPtr); + } + } + + if (_retries > 0) + { + _retries = 0; + } break; } - if (n > 0) + if (EscSeqUtils.IncompleteCkInfos is null && EscSeqRequests is { Statuses.Count: > 0 }) { - break; + if (_retries > 1) + { + EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); + + lock (seqReqStatus.AnsiRequest._responseLock) + { + seqReqStatus.AnsiRequest.Response = string.Empty; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + } + + _retries = 0; + } + else + { + _retries++; + } + } + else + { + _retries = 0; } - } - if (!_forceRead) - { - Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + try + { + Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + } + catch (OperationCanceledException) + { + return; + } } } + _waitForInput.Reset (); _eventReady.Set (); } } + private void ProcessEnqueuePollData (string pollData) + { + foreach (string split in EscSeqUtils.SplitEscapeRawString (pollData)) + { + EnqueuePollData (split); + } + } + + private void EnqueuePollData (string pollDataPart) + { + ConsoleKeyInfo [] cki = EscSeqUtils.ToConsoleKeyInfoArray (pollDataPart); + + ConsoleKey key = 0; + ConsoleModifiers mod = 0; + ConsoleKeyInfo newConsoleKeyInfo = default; + + EscSeqUtils.DecodeEscSeq ( + EscSeqRequests, + ref newConsoleKeyInfo, + ref key, + cki, + ref mod, + out string c1Control, + out string code, + out string [] values, + out string terminating, + out bool isMouse, + out List mouseFlags, + out Point pos, + out EscSeqReqStatus seqReqStatus, + EscSeqUtils.ProcessMouseEvent + ); + + if (isMouse) + { + foreach (MouseFlags mf in mouseFlags) + { + _pollDataQueue!.Enqueue (EnqueueMouseEvent (mf, pos)); + } + + return; + } + + if (seqReqStatus is { }) + { + var ckiString = EscSeqUtils.ToString (cki); + + lock (seqReqStatus.AnsiRequest._responseLock) + { + seqReqStatus.AnsiRequest.Response = ckiString; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, ckiString); + } + + return; + } + + if (newConsoleKeyInfo != default) + { + _pollDataQueue!.Enqueue (EnqueueKeyboardEvent (newConsoleKeyInfo)); + } + } + + private PollData EnqueueMouseEvent (MouseFlags mouseFlags, Point pos) + { + var mouseEvent = new MouseEvent { Position = pos, MouseFlags = mouseFlags }; + + return new () { EventType = EventType.Mouse, MouseEvent = mouseEvent }; + } + + private PollData EnqueueKeyboardEvent (ConsoleKeyInfo keyInfo) + { + return new () { EventType = EventType.Key, KeyEvent = keyInfo }; + } + + private PollData EnqueueWindowSizeEvent (int rows, int cols) + { + return new () { EventType = EventType.WindowSize, WindowSizeEvent = new () { Size = new (cols, rows) } }; + } + bool IMainLoopDriver.EventsPending () { _waitForInput.Set (); + _windowSizeChange.Set (); if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) { @@ -182,7 +385,7 @@ bool IMainLoopDriver.EventsPending () if (!_eventReadyTokenSource.IsCancellationRequested) { - return n > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged; + return _pollDataQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _); } return true; @@ -190,52 +393,28 @@ bool IMainLoopDriver.EventsPending () void IMainLoopDriver.Iteration () { - if (_winChanged) - { - _winChanged = false; - _cursesDriver.ProcessInput (); - - // This is needed on the mac. See https://github.com/gui-cs/Terminal.Gui/pull/2922#discussion_r1365992426 - _cursesDriver.ProcessWinChange (); - } - - n = 0; - - if (_pollMap is null) + // Dequeue and process the data + while (_pollDataQueue.TryDequeue (out PollData inputRecords)) { - return; - } - - foreach (Pollfd p in _pollMap) - { - Watch watch; - - if (p.revents == 0) - { - continue; - } - - if (!_descriptorWatchers.TryGetValue (p.fd, out watch)) + if (inputRecords is { }) { - continue; - } - - if (!watch.Callback (_mainLoop)) - { - _descriptorWatchers.Remove (p.fd); + _cursesDriver.ProcessInput (inputRecords); } } } void IMainLoopDriver.TearDown () { - _descriptorWatchers?.Clear (); + EscSeqUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed; _inputHandlerTokenSource?.Cancel (); _inputHandlerTokenSource?.Dispose (); - _waitForInput?.Dispose (); + _windowSizeChange.Dispose(); + + _pollDataQueue?.Clear (); + _eventReadyTokenSource?.Cancel (); _eventReadyTokenSource?.Dispose (); _eventReady?.Dispose (); @@ -243,72 +422,36 @@ void IMainLoopDriver.TearDown () _mainLoop = null; } - /// Watches a file descriptor for activity. - /// - /// When the condition is met, the provided callback is invoked. If the callback returns false, the watch is - /// automatically removed. The return value is a token that represents this watch, you can use this token to remove the - /// watch by calling RemoveWatch. - /// - internal object AddWatch (int fileDescriptor, Condition condition, Func callback) + internal void WriteRaw (string ansiRequest) { - if (callback is null) - { - throw new ArgumentNullException (nameof (callback)); - } - - var watch = new Watch { Condition = condition, Callback = callback, File = fileDescriptor }; - _descriptorWatchers [fileDescriptor] = watch; - _pollDirty = true; + // Write to stdout (fd 1) + write (STDOUT_FILENO, ansiRequest, ansiRequest.Length); - return watch; - } - - /// Removes an active watch from the mainloop. - /// The token parameter is the value returned from AddWatch - internal void RemoveWatch (object token) - { - if (!ConsoleDriver.RunningUnitTests) - { - if (token is not Watch watch) - { - return; - } - - _descriptorWatchers.Remove (watch.File); - } + // Flush the stdout buffer immediately using fsync + fsync (STDOUT_FILENO); } - [DllImport ("libc")] - private static extern int pipe ([In] [Out] int [] pipes); - [DllImport ("libc")] private static extern int poll ([In] [Out] Pollfd [] ufds, uint nfds, int timeout); [DllImport ("libc")] private static extern int read (int fd, nint buf, nint n); - private void UpdatePollMap () - { - if (!_pollDirty) - { - return; - } + // File descriptor for stdout + private const int STDOUT_FILENO = 1; - _pollDirty = false; + [DllImport ("libc")] + private static extern int write (int fd, string buf, int n); - _pollMap = new Pollfd [_descriptorWatchers.Count]; - var i = 0; + [DllImport ("libc", SetLastError = true)] + private static extern int fsync (int fd); - foreach (int fd in _descriptorWatchers.Keys) - { - _pollMap [i].fd = fd; - _pollMap [i].events = (short)_descriptorWatchers [fd].Condition; - i++; - } - } + // Get the stdout pointer for flushing + [DllImport ("libc", SetLastError = true)] + private static extern nint stdout (); - [DllImport ("libc")] - private static extern int write (int fd, nint buf, nint n); + [DllImport ("libc", SetLastError = true)] + private static extern int ioctl (int fd, int request, ref Winsize ws); [StructLayout (LayoutKind.Sequential)] private struct Pollfd @@ -324,4 +467,75 @@ private class Watch public Condition Condition; public int File; } + + /// + /// Window or terminal size structure. This information is stored by the kernel in order to provide a consistent + /// interface, but is not used by the kernel. + /// + [StructLayout (LayoutKind.Sequential)] + public struct Winsize + { + public ushort ws_row; // Number of rows + public ushort ws_col; // Number of columns + public ushort ws_xpixel; // Width in pixels (unused) + public ushort ws_ypixel; // Height in pixels (unused) + } + + #region Events + + public enum EventType + { + Key = 1, + Mouse = 2, + WindowSize = 3 + } + + public struct MouseEvent + { + public Point Position; + public MouseFlags MouseFlags; + } + + public struct WindowSizeEvent + { + public Size Size; + } + + public struct PollData + { + public EventType EventType; + public ConsoleKeyInfo KeyEvent; + public MouseEvent MouseEvent; + public WindowSizeEvent WindowSizeEvent; + + public readonly override string ToString () + { + return EventType switch + { + EventType.Key => ToString (KeyEvent), + EventType.Mouse => MouseEvent.ToString (), + EventType.WindowSize => WindowSizeEvent.ToString (), + _ => "Unknown event type: " + EventType + }; + } + + /// Prints a ConsoleKeyInfoEx structure + /// + /// + public readonly string ToString (ConsoleKeyInfo cki) + { + var ke = new Key ((KeyCode)cki.KeyChar); + var sb = new StringBuilder (); + sb.Append ($"Key: {(KeyCode)cki.Key} ({cki.Key})"); + sb.Append ((cki.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty); + sb.Append ((cki.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty); + sb.Append ((cki.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty); + sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)cki.KeyChar}) "); + string s = sb.ToString ().TrimEnd (',').TrimEnd (' '); + + return $"[ConsoleKeyInfo({s})]"; + } + } + + #endregion } diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/binding.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/binding.cs index 16caaa05ca..d791194019 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/binding.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/binding.cs @@ -143,6 +143,19 @@ public static bool CheckWinChange () return false; } + public static bool ChangeWindowSize (int l, int c) + { + if (l != lines || c != cols) + { + lines = l; + cols = c; + + return true; + } + + return false; + } + public static int clearok (nint win, bool bf) { return methods.clearok (win, bf); } public static int COLOR_PAIRS () { return methods.COLOR_PAIRS (); } public static int curs_set (int visibility) { return methods.curs_set (visibility); } diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/constants.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/constants.cs index 5700b779f8..2984147a21 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/constants.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/constants.cs @@ -55,8 +55,6 @@ public partial class Curses public const int COLOR_GRAY = 0x8; public const int KEY_CODE_YES = 0x100; public const int ERR = unchecked ((int)0xffffffff); - public const int TIOCGWINSZ = 0x5413; - public const int TIOCGWINSZ_MAC = 0x40087468; [Flags] public enum Event : long { diff --git a/Terminal.Gui/Terminal.Gui.csproj b/Terminal.Gui/Terminal.Gui.csproj index 08813a50f8..88d57c26be 100644 --- a/Terminal.Gui/Terminal.Gui.csproj +++ b/Terminal.Gui/Terminal.Gui.csproj @@ -11,9 +11,9 @@ - - Terminal.Gui - + + Terminal.Gui + @@ -143,35 +143,48 @@ - - - - $(MSBuildThisFileDirectory)..\local_packages\ - - $(MSBuildThisFileDirectory)bin\$(Configuration)\ - + + + + $(MSBuildThisFileDirectory)..\local_packages\ + + $(MSBuildThisFileDirectory)bin\$(Configuration)\ + - - - + + + - - - - + + + + - - + + - - + + - - + + - + + + + + + true + compiled-binaries/ + PreserveNewest + + + + + true + compiled-binaries/ + PreserveNewest + + + \ No newline at end of file diff --git a/Terminal.Gui/compiled-binaries/libGetTIOCGWINSZ.dylib b/Terminal.Gui/compiled-binaries/libGetTIOCGWINSZ.dylib new file mode 100644 index 0000000000000000000000000000000000000000..06c30292e9f9ec317f59a3dcddc432cba30f553b GIT binary patch literal 16512 zcmeI3ziJdw6voeFH3^ttuu4#5Dn&87i%DS>2Q?&%5(B$p5ag0%C&|EON3yeO(qtP8 z8!PR%*9Wlo0W4Fc6l{C}g~jjOxfh2aV3+E<>^JAnoO@>PZ>BxpfBzayhy)c88Hc8! z;h4xfnSm!V2mOSMX)SNGG*ep9+3`iBRcK|GF`D(R>-*&qHD(S@S`K_e8d62}tS|{0BiL+MY>BE)hjkV^BYWol=kwuY#eFKq5 z9laJ@Tt^%t*0bm{HlqAFd$1ZSzjdg%%Kx!=?|=SP6lmWo>7VPL>PsI!e;m!9oQCOL z+5$U!D8h$O#TIFLPRU>LE0;S4>$371XAnw4iti_dDzS1{pthH0HtyR z(mv~v$RzA77wfsXNPq-LfCNZ@1W14cNPq-LfCNZ@1W14cNPq-LfCNZ@1W14cNPq-L zfCNZ@1W14cNPq-LfCNZ@1W14cNPq-LfCNZ@1W14cNPq-LfCNZ@1W14cNPq-L;5-RD zTYdlI>s~e)z5Hh9tFO6-7p=}y>%2T>#;yG9yT&??J%yb!b~ge)vTfb`62jbZ(o81|* z8ieo|3%DzKSgw#sK*G;vKc&TBYL@?6kw-*@tj1kIz9~Bhn7X%C9+vT@MFQ7EVT?N@ zxI==2+$r&p(IBlqN1o?2C#WMW-&&cr3gc!37nW-T2gze_+x3H&`Y+?{6kM1`=okkQ z<2^_?=H*fwZu5YQ*XTY>37?Rn`h0Q@UNe2$hZNCsoaZu6CcypWqOvOCNDMlDVbtB&*L26movy?7qKo_&by zSE#iM=fr0AYuIdP`tu zuKAkL&Q#fDsr#Gn(ir%)<+?u; z2Y-wvURZGUR;3cp9QT^apCt}{6g}Z5DBu1anSUwY_&tf1cE$0e9rd*y0=(Gy4dY&1 z@CA#z&wDE<)oa|RREx@|TiT~M(Fu_h|E3>*`x`87x|n!=Hu1r^Er}1#&r3v3CO*ID zEvE$ik|0_>J<`%n;{ea&Pj$NFR;BeriG!W1xSM$X2XATOh0ZuBXLgs%GHFkl!k3>XFs z1D6K_k=66=Swok?zqMJj<#LQ<2gxy#7f4Q#PnZ19=$T? ztP~yfsjJ}^xk@DJRQdZQH++};{bD)K`m7Y4`ZegJPfM{WYJ%HDU(CVO_5_0J-hyppwHgT2Y_ zxMf4hS2sMhaiiU_=_WCUGt}x_`#WF#T&}e$#rM03>YZb9zu|8d`*_HHz1Xo{5Pv6i zBJ^JdD;8K#YuxSITNKtq;0^94kBjvO`#wLuSz&#_{wj6q&A-ug9rg1pQ->{Nn3MJL zyyeHYs_^}I&$nM)xh`ax5j*Y^>|ar*Nzp0{@%F7BKx|ux4CFZyO|+`<{(|>6>O`m# zUBzGtu4Q9GpxmCR?yGp^^R?2h^oTnwMqPNCpTYB%QCmFL5#Q^mXvnvUA=>Pu{D3j1IHv5> zWR8*r(km#t;AR{)D%+>P9?y98Xx>w{=T6Wo-xOuLV?zH}iXhMeNN^v5Nc1V6lT9aS z+`PvbX*kDols#N5Dw|e9mTqvJCHkLCyzlU5y=)_YJLhACvSJ^AnU51y;~SmxLA-1y zP*oT8{-C`B<6}RA!N1LWhq40!B!kcSvd4QFM5$G*3Ve7t7?kNp!8`z7b# zMsMqy_9$sQH{jc3qL9-P9iBhN=W{BY6Z>`L^G-hZ@LV8iDm*}cKZLgg2O0YK45wF5 zgzy~#fc!T+FU0Ek#{>X5gNcd^=Q|L>PkXYwpty~ZA zACjXQkLQ3k!6Pn=hdx6cj=}t`Sm3c5;CZa-_9-cBlkkcQ`1KV_&;h<$V(nCi?v#WN ti}M Date: Fri, 1 Nov 2024 14:20:09 +0000 Subject: [PATCH 51/89] Cleanup unused code and comments. --- .../CursesDriver/UnixMainLoop.cs | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs index 081284358e..6bf9f6d8f8 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs @@ -49,8 +49,7 @@ public enum Condition : short public UnixMainLoop (ConsoleDriver consoleDriver = null) { - // UnixDriver doesn't use the consoleDriver parameter, but the WindowsDriver does. - _cursesDriver = (CursesDriver)Application.Driver; + _cursesDriver = (CursesDriver)consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver)); } public EscSeqRequests EscSeqRequests { get; } = new (); @@ -74,7 +73,7 @@ void IMainLoopDriver.Setup (MainLoop mainLoop) try { - // Setup poll for stdin (fd 0) and pipe (fd 1) + // Setup poll for stdin (fd 0) _pollMap = new Pollfd [1]; _pollMap [0].fd = 0; // stdin (file descriptor 0) _pollMap [0].events = (short)Condition.PollIn; // Monitor input for reading @@ -244,7 +243,7 @@ private void CursesInputHandler () { EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); - lock (seqReqStatus.AnsiRequest._responseLock) + lock (seqReqStatus!.AnsiRequest._responseLock) { seqReqStatus.AnsiRequest.Response = string.Empty; seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); @@ -446,10 +445,6 @@ internal void WriteRaw (string ansiRequest) [DllImport ("libc", SetLastError = true)] private static extern int fsync (int fd); - // Get the stdout pointer for flushing - [DllImport ("libc", SetLastError = true)] - private static extern nint stdout (); - [DllImport ("libc", SetLastError = true)] private static extern int ioctl (int fd, int request, ref Winsize ws); @@ -461,13 +456,6 @@ private struct Pollfd public readonly short revents; } - private class Watch - { - public Func Callback; - public Condition Condition; - public int File; - } - /// /// Window or terminal size structure. This information is stored by the kernel in order to provide a consistent /// interface, but is not used by the kernel. From 126bcef1119e950f1cf96f3e60db1e53d63b0620 Mon Sep 17 00:00:00 2001 From: BDisp Date: Fri, 1 Nov 2024 20:08:49 +0000 Subject: [PATCH 52/89] Add EscSeqRequests support to WindowsDriver. --- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 31 --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 217 ++++++++++++++----- 2 files changed, 166 insertions(+), 82 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index e3cdb72521..b37c50c53e 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -621,37 +621,6 @@ public void OnMouseEvent (MouseEventArgs a) /// public abstract void WriteRaw (string ansi); - internal string ReadAnsiResponseDefault (AnsiEscapeSequenceRequest ansiRequest) - { - var response = new StringBuilder (); - var index = 0; - - while (Console.KeyAvailable) - { - // Peek the next key - ConsoleKeyInfo keyInfo = Console.ReadKey (true); // true to not display on the console - - if (index == 0 && keyInfo.KeyChar != EscSeqUtils.KeyEsc) - { - continue; - } - - response.Append (keyInfo.KeyChar); - - // Read until no key is available if no terminator was specified or - // check if the key is terminator (ANSI escape sequence ends) - if (!string.IsNullOrEmpty (ansiRequest.Terminator) && keyInfo.KeyChar == ansiRequest.Terminator [^1]) - { - // Break out of the loop when terminator is found - break; - } - - index++; - } - - return response.ToString (); - } - #endregion } diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 57848301a0..c19d6376de 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -24,6 +24,8 @@ namespace Terminal.Gui; internal class WindowsConsole { + internal WindowsMainLoop _mainLoop; + public const int STD_OUTPUT_HANDLE = -11; public const int STD_INPUT_HANDLE = -10; @@ -149,7 +151,13 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord internal bool WriteANSI (string ansi) { - return WriteConsole (_screenBuffer, ansi, (uint)ansi.Length, out uint _, nint.Zero); + if (WriteConsole (_screenBuffer, ansi, (uint)ansi.Length, out uint _, nint.Zero)) + { + // Flush the output to make sure it's sent immediately + return FlushFileBuffers (_screenBuffer); + } + + return false; } public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window) @@ -800,7 +808,7 @@ public readonly string ToString (ConsoleKeyInfoEx ex) [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)] public static extern bool ReadConsoleInput ( nint hConsoleInput, - nint lpBuffer, + out InputRecord lpBuffer, uint nLength, out uint lpNumberOfEventsRead ); @@ -833,6 +841,9 @@ private static extern bool WriteConsole ( nint lpReserved ); + [DllImport ("kernel32.dll", SetLastError = true)] + static extern bool FlushFileBuffers (nint hFile); + [DllImport ("kernel32.dll")] private static extern bool SetConsoleCursorPosition (nint hConsoleOutput, Coord dwCursorPosition); @@ -900,35 +911,110 @@ internal void FlushConsoleInputBuffer () } } + private int _retries; + public InputRecord [] ReadConsoleInput () { const int bufferSize = 1; - nint pRecord = Marshal.AllocHGlobal (Marshal.SizeOf () * bufferSize); + InputRecord inputRecord = default; uint numberEventsRead = 0; + StringBuilder ansiSequence = new StringBuilder (); + bool readingSequence = false; - try + while (true) { + try + { + // Peek to check if there is any input available + if (PeekConsoleInput (_inputHandle, out _, bufferSize, out uint eventsRead) && eventsRead > 0) + { + // Read the input since it is available + ReadConsoleInput ( + _inputHandle, + out inputRecord, + bufferSize, + out numberEventsRead); + + if (inputRecord.EventType == EventType.Key) + { + KeyEventRecord keyEvent = inputRecord.KeyEvent; + + if (keyEvent.bKeyDown) + { + char inputChar = keyEvent.UnicodeChar; + + // Check if input is part of an ANSI escape sequence + if (inputChar == '\u001B') // Escape character + { + // Peek to check if there is any input available with key event and bKeyDown + if (PeekConsoleInput (_inputHandle, out InputRecord peekRecord, bufferSize, out eventsRead) && eventsRead > 0) + { + if (peekRecord is { EventType: EventType.Key, KeyEvent.bKeyDown: true }) + { + // It's really an ANSI request response + readingSequence = true; + ansiSequence.Clear (); // Start a new sequence + ansiSequence.Append (inputChar); + + continue; + } + } + } + else if (readingSequence) + { + ansiSequence.Append (inputChar); + + // Check if the sequence has ended with an expected command terminator + if (_mainLoop.EscSeqRequests is { } && _mainLoop.EscSeqRequests.HasResponse (inputChar.ToString (), out EscSeqReqStatus seqReqStatus)) + { + // Finished reading the sequence and remove the enqueued request + _mainLoop.EscSeqRequests.Remove (seqReqStatus); + + lock (seqReqStatus!.AnsiRequest._responseLock) + { + seqReqStatus.AnsiRequest.Response = ansiSequence.ToString (); + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response); + } + } + + continue; + } + } + } + } - if (PeekConsoleInput (_inputHandle, out InputRecord inputRecord, 1, out uint eventsRead) && eventsRead > 0) + if (EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) + { + if (_retries > 1) + { + _mainLoop.EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); + + lock (seqReqStatus!.AnsiRequest._responseLock) + { + seqReqStatus.AnsiRequest.Response = string.Empty; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + } + + _retries = 0; + } + else + { + _retries++; + } + } + else + { + _retries = 0; + } + + return numberEventsRead == 0 + ? null + : [inputRecord]; + } + catch (Exception) { - ReadConsoleInput ( - _inputHandle, - pRecord, - bufferSize, - out numberEventsRead); + return null; } - - return numberEventsRead == 0 - ? null - : new [] { Marshal.PtrToStructure (pRecord) }; - } - catch (Exception) - { - return null; - } - finally - { - Marshal.FreeHGlobal (pRecord); } } @@ -1191,6 +1277,9 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al } } + private readonly ManualResetEventSlim _waitAnsiResponse = new (false); + private readonly CancellationTokenSource _ansiResponseTokenSource = new (); + /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { @@ -1199,44 +1288,66 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) return string.Empty; } - while (Console.KeyAvailable) + var response = string.Empty; + + try { - _mainLoopDriver._forceRead = true; + lock (ansiRequest._responseLock) + { + ansiRequest.ResponseFromInput += (s, e) => + { + Debug.Assert (s == ansiRequest); - _mainLoopDriver._waitForProbe.Set (); - _mainLoopDriver._waitForProbe.Reset (); - } + ansiRequest.Response = response = e; - _mainLoopDriver._forceRead = false; - _mainLoopDriver._suspendRead = true; + _waitAnsiResponse.Set (); + }; - try - { - WriteRaw (ansiRequest.Request); + _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this); - Thread.Sleep (100); // Allow time for the terminal to respond + _mainLoopDriver._forceRead = true; + } - return ReadAnsiResponseDefault (ansiRequest); + if (!_ansiResponseTokenSource.IsCancellationRequested) + { + _mainLoopDriver._waitForProbe.Set (); + + _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); + } } - catch (Exception) + catch (OperationCanceledException) { return string.Empty; } finally { - _mainLoopDriver._suspendRead = false; - } - } + _mainLoopDriver._forceRead = false; - #region Not Implemented + if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) + { + if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0 + && string.IsNullOrEmpty (request.AnsiRequest.Response)) + { + // Bad request or no response at all + _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _); + } + } - public override void Suspend () { throw new NotImplementedException (); } + _waitAnsiResponse.Reset (); + } + + return response; + } public override void WriteRaw (string ansi) { WinConsole?.WriteANSI (ansi); } + #region Not Implemented + + public override void Suspend () { throw new NotImplementedException (); } + #endregion public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent) @@ -2234,8 +2345,11 @@ public WindowsMainLoop (ConsoleDriver consoleDriver = null) { _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver)); _winConsole = ((WindowsDriver)consoleDriver).WinConsole; + _winConsole._mainLoop = this; } + public EscSeqRequests EscSeqRequests { get; } = new (); + void IMainLoopDriver.Setup (MainLoop mainLoop) { _mainLoop = mainLoop; @@ -2343,7 +2457,6 @@ void IMainLoopDriver.TearDown () } internal bool _forceRead; - internal bool _suspendRead; private void WindowsInputHandler () { @@ -2351,7 +2464,7 @@ private void WindowsInputHandler () { try { - if (!_inputHandlerTokenSource.IsCancellationRequested) + if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead) { _waitForProbe.Wait (_inputHandlerTokenSource.Token); } @@ -2377,21 +2490,23 @@ private void WindowsInputHandler () { while (!_inputHandlerTokenSource.IsCancellationRequested) { - if (!_suspendRead) - { - WindowsConsole.InputRecord[] inpRec = _winConsole.ReadConsoleInput (); + WindowsConsole.InputRecord [] inpRec = _winConsole.ReadConsoleInput (); - if (inpRec is { }) - { - _resultQueue!.Enqueue (inpRec); + if (inpRec is { }) + { + _resultQueue!.Enqueue (inpRec); - break; - } + break; } if (!_forceRead) { - Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + try + { + Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + } + catch (OperationCanceledException) + { } } } } From 5b39c3d5a6e7db76fafd07add5f6ca35625948de Mon Sep 17 00:00:00 2001 From: BDisp Date: Fri, 1 Nov 2024 20:38:22 +0000 Subject: [PATCH 53/89] Fix unit test. --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index c19d6376de..6e9c7e0964 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -2345,7 +2345,11 @@ public WindowsMainLoop (ConsoleDriver consoleDriver = null) { _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver)); _winConsole = ((WindowsDriver)consoleDriver).WinConsole; - _winConsole._mainLoop = this; + + if (!ConsoleDriver.RunningUnitTests) + { + _winConsole._mainLoop = this; + } } public EscSeqRequests EscSeqRequests { get; } = new (); From c89efe554358d4b2cf2e0582d5bfe6845bb3f20b Mon Sep 17 00:00:00 2001 From: tznind Date: Sat, 2 Nov 2024 07:51:25 +0000 Subject: [PATCH 54/89] Add tab view for single/multi request sends --- .../Scenarios/AnsiEscapeSequenceRequests.cs | 77 +++++++++++++++---- 1 file changed, 60 insertions(+), 17 deletions(-) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index 4d3f4dd0b8..a56cd0c27f 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -12,12 +12,49 @@ public override void Main () // Init Application.Init (); + TabView tv = new TabView + { + Width = Dim.Fill (), + Height = Dim.Fill () + }; + + Tab single = new Tab (); + single.DisplayText = "Single"; + single.View = BuildSingleTab (); + + Tab bulk = new (); + bulk.DisplayText = "Multi"; + bulk.View = BuildBulkTab (); + + tv.AddTab (single, true); + tv.AddTab (bulk, false); + // Setup - Create a top-level application window and configure it. Window appWindow = new () { Title = GetQuitKeyAndName (), }; - appWindow.Padding.Thickness = new (1); + + appWindow.Add (tv); + + // Run - Start the application. + Application.Run (appWindow); + bulk.View.Dispose (); + single.View.Dispose (); + appWindow.Dispose (); + + // Shutdown - Calling Application.Shutdown is required. + Application.Shutdown (); + } + private View BuildSingleTab () + { + View w = new View () + { + Width = Dim.Fill(), + Height = Dim.Fill () + }; + + w.Padding.Thickness = new (1); var scrRequests = new List { @@ -28,19 +65,19 @@ public override void Main () }; var cbRequests = new ComboBox () { Width = 40, Height = 5, ReadOnly = true, Source = new ListWrapper (new (scrRequests)) }; - appWindow.Add (cbRequests); + w.Add (cbRequests); var label = new Label { Y = Pos.Bottom (cbRequests) + 1, Text = "Request:" }; var tfRequest = new TextField { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 20 }; - appWindow.Add (label, tfRequest); + w.Add (label, tfRequest); label = new Label { X = Pos.Right (tfRequest) + 1, Y = Pos.Top (tfRequest) - 1, Text = "Value:" }; var tfValue = new TextField { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 6 }; - appWindow.Add (label, tfValue); + w.Add (label, tfValue); label = new Label { X = Pos.Right (tfValue) + 1, Y = Pos.Top (tfValue) - 1, Text = "Terminator:" }; var tfTerminator = new TextField { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 4 }; - appWindow.Add (label, tfTerminator); + w.Add (label, tfTerminator); cbRequests.SelectedItemChanged += (s, e) => { @@ -76,24 +113,24 @@ public override void Main () label = new Label { Y = Pos.Bottom (tfRequest) + 2, Text = "Response:" }; var tvResponse = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 40, Height = 4, ReadOnly = true }; - appWindow.Add (label, tvResponse); + w.Add (label, tvResponse); label = new Label { X = Pos.Right (tvResponse) + 1, Y = Pos.Top (tvResponse) - 1, Text = "Error:" }; var tvError = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 40, Height = 4, ReadOnly = true }; - appWindow.Add (label, tvError); + w.Add (label, tvError); label = new Label { X = Pos.Right (tvError) + 1, Y = Pos.Top (tvError) - 1, Text = "Value:" }; var tvValue = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 6, Height = 4, ReadOnly = true }; - appWindow.Add (label, tvValue); + w.Add (label, tvValue); label = new Label { X = Pos.Right (tvValue) + 1, Y = Pos.Top (tvValue) - 1, Text = "Terminator:" }; var tvTerminator = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 4, Height = 4, ReadOnly = true }; - appWindow.Add (label, tvTerminator); + w.Add (label, tvTerminator); var btnResponse = new Button { X = Pos.Center (), Y = Pos.Bottom (tvResponse) + 2, Text = "Send Request", IsDefault = true }; var lblSuccess = new Label { X = Pos.Center (), Y = Pos.Bottom (btnResponse) + 1 }; - appWindow.Add (lblSuccess); + w.Add (lblSuccess); btnResponse.Accepting += (s, e) => { @@ -125,15 +162,21 @@ out AnsiEscapeSequenceResponse ansiEscapeSequenceResponse lblSuccess.Text = "Error"; } }; - appWindow.Add (btnResponse); + w.Add (btnResponse); - appWindow.Add (new Label { Y = Pos.Bottom (lblSuccess) + 2, Text = "You can send other requests by editing the TextFields." }); + w.Add (new Label { Y = Pos.Bottom (lblSuccess) + 2, Text = "You can send other requests by editing the TextFields." }); - // Run - Start the application. - Application.Run (appWindow); - appWindow.Dispose (); + return w; + } - // Shutdown - Calling Application.Shutdown is required. - Application.Shutdown (); + private View BuildBulkTab () + { + View w = new View () + { + Width = Dim.Fill (), + Height = Dim.Fill () + }; + + return w; } } From 0ddc11c41b19dd2207b9d973b266f744412a03ab Mon Sep 17 00:00:00 2001 From: tznind Date: Sat, 2 Nov 2024 07:55:22 +0000 Subject: [PATCH 55/89] Add bulk send to scenario --- .../Scenarios/AnsiEscapeSequenceRequests.cs | 193 ++++++++++++++++++ 1 file changed, 193 insertions(+) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index a56cd0c27f..c1f6f8930b 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -1,4 +1,7 @@ +using System; using System.Collections.Generic; +using System.Linq; +using System.Text; using Terminal.Gui; namespace UICatalog.Scenarios; @@ -7,6 +10,18 @@ namespace UICatalog.Scenarios; [ScenarioCategory ("Ansi Escape Sequence")] public sealed class AnsiEscapeSequenceRequests : Scenario { + private GraphView _graphView; + + private DateTime start = DateTime.Now; + private ScatterSeries _sentSeries; + private ScatterSeries _answeredSeries; + + private List sends = new (); + + private object lockAnswers = new object (); + private Dictionary answers = new (); + private Label _lblSummary; + public override void Main () { // Init @@ -177,6 +192,184 @@ private View BuildBulkTab () Height = Dim.Fill () }; + var lbl = new Label () + { + Text = "This scenario tests Ansi request/response processing. Use the TextView to ensure regular user interaction continues as normal during sends", + Height = 2, + Width = Dim.Fill () + }; + + Application.AddTimeout ( + TimeSpan.FromMilliseconds (1000), + () => + { + lock (lockAnswers) + { + UpdateGraph (); + + UpdateResponses (); + } + + + + return true; + }); + + var tv = new TextView () + { + Y = Pos.Bottom (lbl), + Width = Dim.Percent (50), + Height = Dim.Fill () + }; + + + var lblDar = new Label () + { + Y = Pos.Bottom (lbl), + X = Pos.Right (tv) + 1, + Text = "DAR per second", + }; + var cbDar = new NumericUpDown () + { + X = Pos.Right (lblDar), + Y = Pos.Bottom (lbl), + Value = 0, + }; + + cbDar.ValueChanging += (s, e) => + { + if (e.NewValue < 0 || e.NewValue > 20) + { + e.Cancel = true; + } + }; + w.Add (cbDar); + + int lastSendTime = Environment.TickCount; + object lockObj = new object (); + Application.AddTimeout ( + TimeSpan.FromMilliseconds (50), + () => + { + lock (lockObj) + { + if (cbDar.Value > 0) + { + int interval = 1000 / cbDar.Value; // Calculate the desired interval in milliseconds + int currentTime = Environment.TickCount; // Current system time in milliseconds + + // Check if the time elapsed since the last send is greater than the interval + if (currentTime - lastSendTime >= interval) + { + SendDar (); // Send the request + lastSendTime = currentTime; // Update the last send time + } + } + } + + return true; + }); + + + _graphView = new GraphView () + { + Y = Pos.Bottom (cbDar), + X = Pos.Right (tv), + Width = Dim.Fill (), + Height = Dim.Fill (1) + }; + + _lblSummary = new Label () + { + Y = Pos.Bottom (_graphView), + X = Pos.Right (tv), + Width = Dim.Fill () + }; + + SetupGraph (); + + w.Add (lbl); + w.Add (lblDar); + w.Add (cbDar); + w.Add (tv); + w.Add (_graphView); + w.Add (_lblSummary); + return w; } + private void UpdateResponses () + { + _lblSummary.Text = GetSummary (); + _lblSummary.SetNeedsDisplay (); + } + + private string GetSummary () + { + if (answers.Count == 0) + { + return "No requests sent yet"; + } + + var last = answers.Last ().Value; + + var unique = answers.Values.Distinct ().Count (); + var total = answers.Count; + + return $"Last:{last} U:{unique} T:{total}"; + } + + private void SetupGraph () + { + + _graphView.Series.Add (_sentSeries = new ScatterSeries ()); + _graphView.Series.Add (_answeredSeries = new ScatterSeries ()); + + _sentSeries.Fill = new GraphCellToRender (new Rune ('.'), new Attribute (ColorName16.BrightGreen, ColorName16.Black)); + _answeredSeries.Fill = new GraphCellToRender (new Rune ('.'), new Attribute (ColorName16.BrightRed, ColorName16.Black)); + + // Todo: + // _graphView.Annotations.Add (_sentSeries new PathAnnotation {}); + + _graphView.CellSize = new PointF (1, 1); + _graphView.MarginBottom = 2; + _graphView.AxisX.Increment = 1; + _graphView.AxisX.Text = "Seconds"; + _graphView.GraphColor = new Attribute (Color.Green, Color.Black); + } + + private void UpdateGraph () + { + _sentSeries.Points = sends + .GroupBy (ToSeconds) + .Select (g => new PointF (g.Key, g.Count ())) + .ToList (); + + _answeredSeries.Points = answers.Keys + .GroupBy (ToSeconds) + .Select (g => new PointF (g.Key, g.Count ())) + .ToList (); + // _graphView.ScrollOffset = new PointF(,0); + _graphView.SetNeedsDisplay (); + + } + + private int ToSeconds (DateTime t) + { + return (int)(DateTime.Now - t).TotalSeconds; + } + + private void SendDar () + { + sends.Add (DateTime.Now); + var result = Application.Driver.WriteAnsiRequest (EscSeqUtils.CSI_SendDeviceAttributes); + HandleResponse (result); + } + + private void HandleResponse (string response) + { + lock (lockAnswers) + { + answers.Add (DateTime.Now, response); + } + } } From 64ad1a9901e2dc58041a8e96a114500dc53191ef Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 2 Nov 2024 17:16:07 +0000 Subject: [PATCH 56/89] Fix a bug which was sending the terminator to the mainloop. --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 6e9c7e0964..f6c0c53ed6 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -974,6 +974,8 @@ public InputRecord [] ReadConsoleInput () { seqReqStatus.AnsiRequest.Response = ansiSequence.ToString (); seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response); + // Clear the terminator for not be enqueued + inputRecord = default (InputRecord); } } From a2872cdb9adda020111bb06327aad4d8b724c8ae Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 2 Nov 2024 17:17:36 +0000 Subject: [PATCH 57/89] Ensures a new iteration when _eventReady is already set. --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index f6c0c53ed6..d3bad7059d 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -2517,7 +2517,15 @@ private void WindowsInputHandler () } } - _eventReady.Set (); + if (_eventReady.IsSet) + { + // it's already in an iteration and ensures set to iterate again + Application.Invoke (() => _eventReady.Set ()); + } + else + { + _eventReady.Set (); + } } } From 68b41a3962d87221a81176bf0288f5fb2a8db0fa Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 2 Nov 2024 18:52:23 +0000 Subject: [PATCH 58/89] Set CanFocus true and only SetNeedsDisplay if were sent or answered. --- UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index c1f6f8930b..e23203a74f 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -66,7 +66,8 @@ private View BuildSingleTab () View w = new View () { Width = Dim.Fill(), - Height = Dim.Fill () + Height = Dim.Fill (), + CanFocus = true }; w.Padding.Thickness = new (1); @@ -189,7 +190,8 @@ private View BuildBulkTab () View w = new View () { Width = Dim.Fill (), - Height = Dim.Fill () + Height = Dim.Fill (), + CanFocus = true }; var lbl = new Label () @@ -349,7 +351,10 @@ private void UpdateGraph () .Select (g => new PointF (g.Key, g.Count ())) .ToList (); // _graphView.ScrollOffset = new PointF(,0); - _graphView.SetNeedsDisplay (); + if (_sentSeries.Points.Count > 0 || _answeredSeries.Points.Count > 0) + { + _graphView.SetNeedsDisplay (); + } } From c999fc0028a4f642d45ba748525c22627ba640ee Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 2 Nov 2024 21:06:43 +0000 Subject: [PATCH 59/89] Trying fix unit tests. --- Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs | 8 +------- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 6 ++++++ Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 8 +++++++- UnitTests/Application/SynchronizatonContextTests.cs | 7 ++++--- 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs index 6bf9f6d8f8..52364f5dbf 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs @@ -54,13 +54,7 @@ public UnixMainLoop (ConsoleDriver consoleDriver = null) public EscSeqRequests EscSeqRequests { get; } = new (); - void IMainLoopDriver.Wakeup () - { - if (!ConsoleDriver.RunningUnitTests) - { - _eventReady.Set (); - } - } + void IMainLoopDriver.Wakeup () { _eventReady.Set (); } void IMainLoopDriver.Setup (MainLoop mainLoop) { diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index df57c6b2f0..10c41d1277 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1844,6 +1844,12 @@ public NetMainLoop (ConsoleDriver consoleDriver = null) void IMainLoopDriver.Setup (MainLoop mainLoop) { _mainLoop = mainLoop; + + if (ConsoleDriver.RunningUnitTests) + { + return; + } + Task.Run (NetInputHandler, _inputHandlerTokenSource.Token); } diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index d3bad7059d..2715099600 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -2346,10 +2346,10 @@ internal class WindowsMainLoop : IMainLoopDriver public WindowsMainLoop (ConsoleDriver consoleDriver = null) { _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver)); - _winConsole = ((WindowsDriver)consoleDriver).WinConsole; if (!ConsoleDriver.RunningUnitTests) { + _winConsole = ((WindowsDriver)consoleDriver).WinConsole; _winConsole._mainLoop = this; } } @@ -2359,6 +2359,12 @@ public WindowsMainLoop (ConsoleDriver consoleDriver = null) void IMainLoopDriver.Setup (MainLoop mainLoop) { _mainLoop = mainLoop; + + if (ConsoleDriver.RunningUnitTests) + { + return; + } + Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token); #if HACK_CHECK_WINCHANGED Task.Run (CheckWinChange); diff --git a/UnitTests/Application/SynchronizatonContextTests.cs b/UnitTests/Application/SynchronizatonContextTests.cs index fce4a3250d..9f98046499 100644 --- a/UnitTests/Application/SynchronizatonContextTests.cs +++ b/UnitTests/Application/SynchronizatonContextTests.cs @@ -4,7 +4,7 @@ namespace Terminal.Gui.ApplicationTests; public class SyncrhonizationContextTests { - [Fact(Skip = "Causes ubuntu to crash in github action.")] + [Fact] public void SynchronizationContext_CreateCopy () { Application.Init (); @@ -20,11 +20,12 @@ public void SynchronizationContext_CreateCopy () [Theory] [InlineData (typeof (FakeDriver))] - //[InlineData (typeof (NetDriver))] + [InlineData (typeof (NetDriver))] [InlineData (typeof (WindowsDriver))] - //[InlineData (typeof (CursesDriver))] + [InlineData (typeof (CursesDriver))] public void SynchronizationContext_Post (Type driverType) { + ConsoleDriver.RunningUnitTests = true; Application.Init (driverName: driverType.Name); SynchronizationContext context = SynchronizationContext.Current; From 3c4564c9079b31139a77f08359310aa980836f7c Mon Sep 17 00:00:00 2001 From: BDisp Date: Sat, 2 Nov 2024 21:12:08 +0000 Subject: [PATCH 60/89] Explain what the colors represent. --- UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index e23203a74f..321af7c2ed 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -196,7 +196,7 @@ private View BuildBulkTab () var lbl = new Label () { - Text = "This scenario tests Ansi request/response processing. Use the TextView to ensure regular user interaction continues as normal during sends", + Text = "This scenario tests Ansi request/response processing. Use the TextView to ensure regular user interaction continues as normal during sends. Responses are in red, queued messages are in green.", Height = 2, Width = Dim.Fill () }; From 2e0bc0162d12172b7a0af65bc0fd77bb5a98811b Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 4 Nov 2024 00:29:34 +0000 Subject: [PATCH 61/89] Fixes #3807. WindowsDriver doesn't process characters with accents. --- Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs | 5 +++-- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 7 ++++--- Terminal.Gui/Input/Key.cs | 15 +++++++++++---- UnitTests/Input/KeyTests.cs | 12 +++++------- 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs b/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs index 25f87bc568..503e7cd572 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs @@ -249,7 +249,7 @@ public static ConsoleModifiers MapToConsoleModifiers (KeyCode key) { var modifiers = new ConsoleModifiers (); - if (key.HasFlag (KeyCode.ShiftMask)) + if (key.HasFlag (KeyCode.ShiftMask) || char.IsUpper ((char)key)) { modifiers |= ConsoleModifiers.Shift; } @@ -590,7 +590,8 @@ internal static uint GetKeyCharFromUnicodeChar ( if (uc != UnicodeCategory.NonSpacingMark && uc != UnicodeCategory.OtherLetter) { - consoleKey = char.ToUpper (stFormD [i]); + char ck = char.ToUpper (stFormD [i]); + consoleKey = (uint)(ck > 0 && ck <= 255 ? char.ToUpper (stFormD [i]) : 0); scode = GetScanCode ("VirtualKey", char.ToUpper (stFormD [i]), 0); if (scode is { }) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 2715099600..1b9085e235 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1891,12 +1891,13 @@ private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx) // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask if (char.IsUpper (keyInfo.KeyChar)) { - return (KeyCode)(uint)keyInfo.Key | KeyCode.ShiftMask; + // Always return the KeyChar because it may be an À, À with Oem1, etc + return (KeyCode)keyInfo.KeyChar | KeyCode.ShiftMask; } } - // Return the Key (not KeyChar!) - return (KeyCode)keyInfo.Key; + // Always return the KeyChar because it may be an á, à with Oem1, etc + return (KeyCode)keyInfo.KeyChar; } // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC diff --git a/Terminal.Gui/Input/Key.cs b/Terminal.Gui/Input/Key.cs index d69552aa61..3c8b75d94d 100644 --- a/Terminal.Gui/Input/Key.cs +++ b/Terminal.Gui/Input/Key.cs @@ -1,5 +1,6 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; +using Terminal.Gui.ConsoleDrivers; namespace Terminal.Gui; @@ -288,7 +289,10 @@ public static bool GetIsKeyCodeAtoZ (KeyCode keyCode) return false; } - if ((keyCode & ~KeyCode.Space & ~KeyCode.ShiftMask) is >= KeyCode.A and <= KeyCode.Z) + // A to Z may have , , , , with Oem1, etc + ConsoleKeyInfo cki = ConsoleKeyMapping.GetConsoleKeyInfoFromKeyCode (keyCode); + + if (cki.Key is >= ConsoleKey.A and <= ConsoleKey.Z) { return true; } @@ -521,9 +525,12 @@ public static string ToString (KeyCode key, Rune separator) // Handle special cases and modifiers on their own if (key != KeyCode.SpecialMask && (baseKey != KeyCode.Null || hasModifiers)) { - if ((key & KeyCode.SpecialMask) != 0 && (baseKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z) + // A to Z may have , , , , with Oem1, etc + ConsoleKeyInfo cki = ConsoleKeyMapping.GetConsoleKeyInfoFromKeyCode (baseKey); + + if ((key & KeyCode.SpecialMask) != 0 && cki.Key is >= ConsoleKey.A and <= ConsoleKey.Z) { - sb.Append (baseKey & ~KeyCode.Space); + sb.Append (((char)(baseKey & ~KeyCode.Space)).ToString ()); } else { @@ -706,7 +713,7 @@ out parsedInt if (GetIsKeyCodeAtoZ (keyCode) && (keyCode & KeyCode.Space) != 0) { - keyCode = keyCode & ~KeyCode.Space; + keyCode &= ~KeyCode.Space; } key = new (keyCode | modifiers); diff --git a/UnitTests/Input/KeyTests.cs b/UnitTests/Input/KeyTests.cs index fa2695e5f9..1916c1d9bf 100644 --- a/UnitTests/Input/KeyTests.cs +++ b/UnitTests/Input/KeyTests.cs @@ -17,7 +17,7 @@ public class KeyTests { "Alt+A", Key.A.WithAlt }, { "Shift+A", Key.A.WithShift }, { "A", Key.A.WithShift }, - { "â", new ((KeyCode)'â') }, + { "â", new ((KeyCode)'Â') }, { "Shift+â", new ((KeyCode)'â' | KeyCode.ShiftMask) }, { "Shift+Â", new ((KeyCode)'Â' | KeyCode.ShiftMask) }, { "Ctrl+Shift+CursorUp", Key.CursorUp.WithShift.WithCtrl }, @@ -342,12 +342,10 @@ public void Standard_Keys_Should_Equal_KeyCode () [InlineData ((KeyCode)'{', "{")] [InlineData ((KeyCode)'\'', "\'")] [InlineData ((KeyCode)'ó', "ó")] - [InlineData ( - (KeyCode)'Ó' | KeyCode.ShiftMask, - "Shift+Ó" - )] // TODO: This is not correct, it should be Shift+ó or just Ó + [InlineData ((KeyCode)'Ó' | KeyCode.ShiftMask, "Ó")] + [InlineData ((KeyCode)'ó' | KeyCode.ShiftMask, "Ó")] [InlineData ((KeyCode)'Ó', "Ó")] - [InlineData ((KeyCode)'ç' | KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.CtrlMask, "Ctrl+Alt+Shift+ç")] + [InlineData ((KeyCode)'ç' | KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.CtrlMask, "Ctrl+Alt+Shift+Ç")] [InlineData ((KeyCode)'a', "a")] // 97 or Key.Space | Key.A [InlineData ((KeyCode)'A', "a")] // 65 or equivalent to Key.A, but A-Z are mapped to lower case by drivers [InlineData (KeyCode.ShiftMask | KeyCode.A, "A")] @@ -470,7 +468,7 @@ public void ToStringWithSeparator_ShouldReturnFormattedString (KeyCode key, char [InlineData ("Alt+A", KeyCode.A | KeyCode.AltMask)] [InlineData ("Shift+A", KeyCode.A | KeyCode.ShiftMask)] [InlineData ("A", KeyCode.A | KeyCode.ShiftMask)] - [InlineData ("â", (KeyCode)'â')] + [InlineData ("â", (KeyCode)'Â')] [InlineData ("Shift+â", (KeyCode)'â' | KeyCode.ShiftMask)] [InlineData ("Shift+Â", (KeyCode)'Â' | KeyCode.ShiftMask)] [InlineData ("Ctrl+Shift+CursorUp", KeyCode.ShiftMask | KeyCode.CtrlMask | KeyCode.CursorUp)] From 2d8bfd51a17bb1d4c62a6a85468d833d27033d12 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 4 Nov 2024 00:34:51 +0000 Subject: [PATCH 62/89] Fix comment. --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 1b9085e235..2c62de4662 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1891,7 +1891,7 @@ private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx) // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask if (char.IsUpper (keyInfo.KeyChar)) { - // Always return the KeyChar because it may be an À, À with Oem1, etc + // Always return the KeyChar because it may be an Á, À with Oem1, etc return (KeyCode)keyInfo.KeyChar | KeyCode.ShiftMask; } } From 808896d8002f44ded06982af5e73c7ed6a4f7031 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 4 Nov 2024 18:34:38 +0000 Subject: [PATCH 63/89] Fix bug where some key were not been split. --- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 6 +++++- UnitTests/Input/EscSeqUtilsTests.cs | 14 ++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index cd7a991399..ab7f4bb046 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -338,6 +338,8 @@ Action continuousButtonPressedHandler if (!string.IsNullOrEmpty (terminator)) { + System.Diagnostics.Debug.Assert (terminator.Length == 1); + key = GetConsoleKey (terminator [0], values [0], ref mod, ref keyChar); if (key != 0 && values.Length > 1) @@ -1417,7 +1419,9 @@ public static List SplitEscapeRawString (string rawData) split = AddAndClearSplit (); splitList.Add (c.ToString ()); } - else if (previousChar != '\u001B' && c < Key.Space)// uint n when n is > 0 and <= KeyEsc + else if ((previousChar != '\u001B' && c <= Key.Space) || (previousChar != '\u001B' && c == 127) + || (char.IsLetter (previousChar) && char.IsLower (c) && char.IsLetter (c)) + || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsLetter (c))) { isEscSeq = false; split = AddAndClearSplit (); diff --git a/UnitTests/Input/EscSeqUtilsTests.cs b/UnitTests/Input/EscSeqUtilsTests.cs index 5991cd26cc..3b028b60e4 100644 --- a/UnitTests/Input/EscSeqUtilsTests.cs +++ b/UnitTests/Input/EscSeqUtilsTests.cs @@ -1440,12 +1440,14 @@ public void ResizeArray_ConsoleKeyInfo () Assert.Equal (cki, expectedCkInfos [0]); } - [Fact] - public void SplitEscapeRawString_Multiple_Tests () + [Theory] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\r", "\r")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOCe", "e")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOCV", "V")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\u007f", "\u007f")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC ", " ")] + public void SplitEscapeRawString_Multiple_Tests (string rawData, string expectedLast) { - string rawData = - "\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\r"; - List splitList = EscSeqUtils.SplitEscapeRawString (rawData); Assert.Equal (18, splitList.Count); Assert.Equal ("\r", splitList [0]); @@ -1465,7 +1467,7 @@ public void SplitEscapeRawString_Multiple_Tests () Assert.Equal ("\u001b[<0;33;6M", splitList [14]); Assert.Equal ("\u001b[<0;33;6m", splitList [15]); Assert.Equal ("\u001bOC", splitList [16]); - Assert.Equal ("\r", splitList [^1]); + Assert.Equal (expectedLast, splitList [^1]); } [Theory] From 782325f6b73d519400bc9f2ac8fe6facef80941f Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 4 Nov 2024 18:36:16 +0000 Subject: [PATCH 64/89] Change to ConcurrentQueue. --- Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs index 4dc98937bc..c96c8f08bb 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs @@ -1,5 +1,7 @@ #nullable enable +using System.Collections.Concurrent; + namespace Terminal.Gui; /// @@ -95,5 +97,5 @@ public void Remove (EscSeqReqStatus? seqReqStatus) } /// Gets the list. - public Queue Statuses { get; } = new (); + public ConcurrentQueue Statuses { get; } = new (); } From e2f3b7b5e13a1186d566930cc4eae74a1c98f23e Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 4 Nov 2024 18:37:27 +0000 Subject: [PATCH 65/89] Using empty string instead of space. --- .../AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 76bd24101d..662736e931 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -82,7 +82,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, if (!ansiRequest.Response.EndsWith (ansiRequest.Terminator [^1])) { - char resp = string.IsNullOrEmpty (ansiRequest.Response) ? ' ' : ansiRequest.Response.Last (); + string resp = string.IsNullOrEmpty (ansiRequest.Response) ? "" : ansiRequest.Response.Last ().ToString (); throw new InvalidOperationException ($"Terminator ends with '{resp}'\nand doesn't end with: '{ansiRequest.Terminator [^1]}'"); } From e35b37fb4d65187044ce032125772b5742ff0297 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 4 Nov 2024 20:01:49 +0000 Subject: [PATCH 66/89] Add InvalidRequestTerminator property. --- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index ab7f4bb046..59c10b548e 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -163,6 +163,11 @@ public enum ClearScreenOptions /// public static ConsoleKeyInfo []? IncompleteCkInfos { get; set; } + /// + /// Represent a response that was requested by an invalid terminator. + /// + public static string? InvalidRequestTerminator { get; set; } + /// /// Decodes an ANSI escape sequence. /// @@ -347,12 +352,22 @@ Action continuousButtonPressedHandler mod |= GetConsoleModifiers (values [1]); } - newConsoleKeyInfo = new ( - keyChar, - key, - (mod & ConsoleModifiers.Shift) != 0, - (mod & ConsoleModifiers.Alt) != 0, - (mod & ConsoleModifiers.Control) != 0); + if (keyChar != 0 || key != 0 || mod != 0) + { + newConsoleKeyInfo = new ( + keyChar, + key, + (mod & ConsoleModifiers.Shift) != 0, + (mod & ConsoleModifiers.Alt) != 0, + (mod & ConsoleModifiers.Control) != 0); + } + else + { + // It's request response that wasn't handled by a valid request terminator + System.Diagnostics.Debug.Assert (escSeqRequests is { Statuses.Count: > 0 }); + + InvalidRequestTerminator = ToString (cki); + } } else { From da21ef1320848fe2ab34afe3e9596f32b87b6b7a Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 4 Nov 2024 20:04:50 +0000 Subject: [PATCH 67/89] Improves drivers responses to being more reliable. --- .../CursesDriver/UnixMainLoop.cs | 48 +++++++++--- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 78 +++++++++++++------ Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 53 ++++++++----- 3 files changed, 121 insertions(+), 58 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs index 52364f5dbf..52014cb55a 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs @@ -176,6 +176,13 @@ private void CursesInputHandler () { return; } + finally + { + if (!_inputHandlerTokenSource.IsCancellationRequested) + { + _waitForInput.Reset (); + } + } if (_pollDataQueue?.Count == 0 || _forceRead) { @@ -235,12 +242,15 @@ private void CursesInputHandler () { if (_retries > 1) { - EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); - - lock (seqReqStatus!.AnsiRequest._responseLock) + if (EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) { - seqReqStatus.AnsiRequest.Response = string.Empty; - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + lock (seqReqStatus!.AnsiRequest._responseLock) + { + EscSeqRequests.Statuses.TryDequeue (out _); + + seqReqStatus.AnsiRequest.Response = string.Empty; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + } } _retries = 0; @@ -257,7 +267,10 @@ private void CursesInputHandler () try { - Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + if (!_forceRead) + { + Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + } } catch (OperationCanceledException) { @@ -266,7 +279,6 @@ private void CursesInputHandler () } } - _waitForInput.Reset (); _eventReady.Set (); } } @@ -327,6 +339,22 @@ private void EnqueuePollData (string pollDataPart) return; } + if (!string.IsNullOrEmpty (EscSeqUtils.InvalidRequestTerminator)) + { + if (EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus result)) + { + lock (result.AnsiRequest._responseLock) + { + result.AnsiRequest.Response = EscSeqUtils.InvalidRequestTerminator; + result.AnsiRequest.RaiseResponseFromInput (result.AnsiRequest, EscSeqUtils.InvalidRequestTerminator); + + EscSeqUtils.InvalidRequestTerminator = null; + } + } + + return; + } + if (newConsoleKeyInfo != default) { _pollDataQueue!.Enqueue (EnqueueKeyboardEvent (newConsoleKeyInfo)); @@ -420,8 +448,7 @@ internal void WriteRaw (string ansiRequest) // Write to stdout (fd 1) write (STDOUT_FILENO, ansiRequest, ansiRequest.Length); - // Flush the stdout buffer immediately using fsync - fsync (STDOUT_FILENO); + Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); } [DllImport ("libc")] @@ -436,9 +463,6 @@ internal void WriteRaw (string ansiRequest) [DllImport ("libc")] private static extern int write (int fd, string buf, int n); - [DllImport ("libc", SetLastError = true)] - private static extern int fsync (int fd); - [DllImport ("libc", SetLastError = true)] private static extern int ioctl (int fd, int request, ref Winsize ws); diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 10c41d1277..3afaafd042 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -2,6 +2,7 @@ // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient. // +using System.Collections.Concurrent; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; @@ -140,7 +141,7 @@ internal class NetEvents : IDisposable //CancellationTokenSource _waitForStartCancellationTokenSource; private readonly ManualResetEventSlim _winChange = new (false); - private readonly Queue _inputQueue = new (); + private readonly ConcurrentQueue _inputQueue = new (); private readonly ConsoleDriver _consoleDriver; private ConsoleKeyInfo [] _cki; private bool _isEscSeq; @@ -191,7 +192,10 @@ public NetEvents (ConsoleDriver consoleDriver) #endif if (_inputQueue.Count > 0) { - return _inputQueue.Dequeue (); + if (_inputQueue.TryDequeue (out InputResult? result)) + { + return result; + } } } @@ -200,17 +204,10 @@ public NetEvents (ConsoleDriver consoleDriver) private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, bool intercept = true) { - // if there is a key available, return it without waiting - // (or dispatching work to the thread queue) - if (Console.KeyAvailable) - { - return Console.ReadKey (intercept); - } - while (!cancellationToken.IsCancellationRequested) { - Task.Delay (100, cancellationToken).Wait (cancellationToken); - + // if there is a key available, return it without waiting + // (or dispatching work to the thread queue) if (Console.KeyAvailable) { return Console.ReadKey (intercept); @@ -220,12 +217,15 @@ private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, { if (_retries > 1) { - EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); - - lock (seqReqStatus.AnsiRequest._responseLock) + if (EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) { - seqReqStatus.AnsiRequest.Response = string.Empty; - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + lock (seqReqStatus!.AnsiRequest._responseLock) + { + EscSeqRequests.Statuses.TryDequeue (out _); + + seqReqStatus.AnsiRequest.Response = string.Empty; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + } } _retries = 0; @@ -239,6 +239,11 @@ private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, { _retries = 0; } + + if (!_forceRead) + { + Task.Delay (100, cancellationToken).Wait (cancellationToken); + } } cancellationToken.ThrowIfCancellationRequested (); @@ -310,7 +315,10 @@ private void ProcessInputQueue () _isEscSeq = true; - if (_cki is { } && _cki [^1].KeyChar != Key.Esc && consoleKeyInfo.KeyChar != Key.Esc && consoleKeyInfo.KeyChar <= Key.Space) + if ((_cki is { } && _cki [^1].KeyChar != Key.Esc && consoleKeyInfo.KeyChar != Key.Esc && consoleKeyInfo.KeyChar <= Key.Space) + || (_cki is { } && _cki [^1].KeyChar != '\u001B' && consoleKeyInfo.KeyChar == 127) + || (_cki is { } && char.IsLetter (_cki [^1].KeyChar) && char.IsLower (consoleKeyInfo.KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar)) + || (_cki is { Length: > 2 } && char.IsLetter (_cki [^1].KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar))) { ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); _cki = null; @@ -510,7 +518,26 @@ ref ConsoleModifiers mod return; } - HandleKeyboardEvent (newConsoleKeyInfo); + if (!string.IsNullOrEmpty (EscSeqUtils.InvalidRequestTerminator)) + { + if (EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus result)) + { + lock (result.AnsiRequest._responseLock) + { + result.AnsiRequest.Response = EscSeqUtils.InvalidRequestTerminator; + result.AnsiRequest.RaiseResponseFromInput (result.AnsiRequest, EscSeqUtils.InvalidRequestTerminator); + + EscSeqUtils.InvalidRequestTerminator = null; + } + } + + return; + } + + if (newConsoleKeyInfo != default) + { + HandleKeyboardEvent (newConsoleKeyInfo); + } } [UnconditionalSuppressMessage ("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "")] @@ -1822,7 +1849,7 @@ internal class NetMainLoop : IMainLoopDriver private readonly ManualResetEventSlim _eventReady = new (false); private readonly CancellationTokenSource _inputHandlerTokenSource = new (); - private readonly Queue _resultQueue = new (); + private readonly ConcurrentQueue _resultQueue = new (); internal readonly ManualResetEventSlim _waitForProbe = new (false); private readonly CancellationTokenSource _eventReadyTokenSource = new (); private MainLoop _mainLoop; @@ -1897,11 +1924,12 @@ void IMainLoopDriver.Iteration () while (_resultQueue.Count > 0) { // Always dequeue even if it's null and invoke if isn't null - InputResult? dequeueResult = _resultQueue.Dequeue (); - - if (dequeueResult is { }) + if (_resultQueue.TryDequeue (out InputResult? dequeueResult)) { - ProcessInput?.Invoke (dequeueResult.Value); + if (dequeueResult is { }) + { + ProcessInput?.Invoke (dequeueResult.Value); + } } } } @@ -1960,10 +1988,10 @@ private void NetInputHandler () try { - while (_resultQueue.Count > 0 && _resultQueue.Peek () is null) + while (_resultQueue.Count > 0 && _resultQueue.TryPeek (out InputResult? result) && result is null) { // Dequeue null values - _resultQueue.Dequeue (); + _resultQueue.TryDequeue (out _); } } catch (InvalidOperationException) // Peek can raise an exception diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 2c62de4662..d6223dd966 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -8,13 +8,14 @@ // 2) The values provided during Init (and the first WindowsConsole.EventType.WindowBufferSize) are not correct. // // If HACK_CHECK_WINCHANGED is defined then we ignore WindowsConsole.EventType.WindowBufferSize events -// and instead check the console size every every 500ms in a thread in WidowsMainLoop. +// and instead check the console size every 500ms in a thread in WidowsMainLoop. // As of Windows 11 23H2 25947.1000 and/or WT 1.19.2682 tearing no longer occurs when using // the WindowsConsole.EventType.WindowBufferSize event. However, on Init the window size is // still incorrect so we still need this hack. #define HACK_CHECK_WINCHANGED +using System.Collections.Concurrent; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; @@ -920,6 +921,7 @@ public InputRecord [] ReadConsoleInput () uint numberEventsRead = 0; StringBuilder ansiSequence = new StringBuilder (); bool readingSequence = false; + bool raisedResponse = false; while (true) { @@ -972,6 +974,7 @@ public InputRecord [] ReadConsoleInput () lock (seqReqStatus!.AnsiRequest._responseLock) { + raisedResponse = true; seqReqStatus.AnsiRequest.Response = ansiSequence.ToString (); seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response); // Clear the terminator for not be enqueued @@ -985,16 +988,31 @@ public InputRecord [] ReadConsoleInput () } } - if (EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) + if (readingSequence && !raisedResponse && EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) { - if (_retries > 1) + _mainLoop.EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); + + lock (seqReqStatus!.AnsiRequest._responseLock) { - _mainLoop.EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); + seqReqStatus.AnsiRequest.Response = ansiSequence.ToString (); + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response); + } - lock (seqReqStatus!.AnsiRequest._responseLock) + _retries = 0; + } + else if (EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) + { + if (_retries > 1) + { + if (_mainLoop.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) { - seqReqStatus.AnsiRequest.Response = string.Empty; - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + lock (seqReqStatus!.AnsiRequest._responseLock) + { + _mainLoop.EscSeqRequests.Statuses.TryDequeue (out _); + + seqReqStatus.AnsiRequest.Response = string.Empty; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + } } _retries = 0; @@ -2337,7 +2355,7 @@ internal class WindowsMainLoop : IMainLoopDriver private readonly ManualResetEventSlim _eventReady = new (false); // The records that we keep fetching - private readonly Queue _resultQueue = new (); + private readonly ConcurrentQueue _resultQueue = new (); internal readonly ManualResetEventSlim _waitForProbe = new (false); private readonly WindowsConsole _winConsole; private CancellationTokenSource _eventReadyTokenSource = new (); @@ -2422,11 +2440,12 @@ void IMainLoopDriver.Iteration () { while (_resultQueue.Count > 0) { - WindowsConsole.InputRecord [] inputRecords = _resultQueue.Dequeue (); - - if (inputRecords is { Length: > 0 }) + if (_resultQueue.TryDequeue (out WindowsConsole.InputRecord [] inputRecords)) { - ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]); + if (inputRecords is { Length: > 0 }) + { + ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]); + } } } #if HACK_CHECK_WINCHANGED @@ -2524,15 +2543,7 @@ private void WindowsInputHandler () } } - if (_eventReady.IsSet) - { - // it's already in an iteration and ensures set to iterate again - Application.Invoke (() => _eventReady.Set ()); - } - else - { - _eventReady.Set (); - } + _eventReady.Set (); } } From 81eb301b56e8bd57c24d46a8875378083fda94ca Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 4 Nov 2024 20:25:04 +0000 Subject: [PATCH 68/89] Fix escSeqRequests that may be null running unit tests. --- Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 59c10b548e..4b283afb10 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -364,7 +364,7 @@ Action continuousButtonPressedHandler else { // It's request response that wasn't handled by a valid request terminator - System.Diagnostics.Debug.Assert (escSeqRequests is { Statuses.Count: > 0 }); + System.Diagnostics.Debug.Assert (escSeqRequests is null or { Statuses.Count: > 0 }); InvalidRequestTerminator = ToString (cki); } From 173f8205bef51366b4b338ea55c6cc4f1e6a14b6 Mon Sep 17 00:00:00 2001 From: BDisp Date: Mon, 4 Nov 2024 23:04:11 +0000 Subject: [PATCH 69/89] Disable HACK_CHECK_WINCHANGED. --- Terminal.Gui/Application/Application.Run.cs | 1 + Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 22 +++++++++++--------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/Terminal.Gui/Application/Application.Run.cs b/Terminal.Gui/Application/Application.Run.cs index 966fb04c68..e782934e06 100644 --- a/Terminal.Gui/Application/Application.Run.cs +++ b/Terminal.Gui/Application/Application.Run.cs @@ -493,6 +493,7 @@ public static void Refresh () { if (tl.LayoutNeeded) { + tl.SetRelativeLayout (new (Driver!.Cols, Driver.Rows)); tl.LayoutSubviews (); } diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index d6223dd966..515ca001e3 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -13,7 +13,7 @@ // the WindowsConsole.EventType.WindowBufferSize event. However, on Init the window size is // still incorrect so we still need this hack. -#define HACK_CHECK_WINCHANGED +//#define HACK_CHECK_WINCHANGED using System.Collections.Concurrent; using System.ComponentModel; @@ -1708,15 +1708,17 @@ internal void ProcessInput (WindowsConsole.InputRecord inputEvent) break; #if !HACK_CHECK_WINCHANGED - case WindowsConsole.EventType.WindowBufferSize: - - Cols = inputEvent.WindowBufferSizeEvent._size.X; - Rows = inputEvent.WindowBufferSizeEvent._size.Y; - - ResizeScreen (); - ClearContents (); - TerminalResized.Invoke (); - break; + case WindowsConsole.EventType.WindowBufferSize: + + Cols = inputEvent.WindowBufferSizeEvent._size.X; + Rows = inputEvent.WindowBufferSizeEvent._size.Y; + + ResizeScreen (); + ClearContents (); + Application.Top?.SetNeedsLayout (); + Application.Refresh (); + + break; #endif } } From 472ec453f598b7030a4a39e1303be0960251adaf Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 5 Nov 2024 00:37:57 +0000 Subject: [PATCH 70/89] Remove _screenBuffer and only using the alternate buffer. --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 365 ++++++++++--------- 1 file changed, 185 insertions(+), 180 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 515ca001e3..d4c7bfc3a7 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -32,7 +32,7 @@ internal class WindowsConsole private readonly nint _inputHandle; private nint _outputHandle; - private nint _screenBuffer; + //private nint _screenBuffer; private readonly uint _originalConsoleMode; private CursorVisibility? _initialCursorVisibility; private CursorVisibility? _currentCursorVisibility; @@ -58,10 +58,10 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord { //Debug.WriteLine ("WriteToConsole"); - if (_screenBuffer == nint.Zero) - { - ReadFromConsoleOutput (size, bufferSize, ref window); - } + //if (_screenBuffer == nint.Zero) + //{ + // ReadFromConsoleOutput (size, bufferSize, ref window); + //} var result = false; @@ -80,7 +80,7 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord }; } - result = WriteConsoleOutput (_screenBuffer, ci, bufferSize, new Coord { X = window.Left, Y = window.Top }, ref window); + result = WriteConsoleOutput (_outputHandle, ci, bufferSize, new Coord { X = window.Left, Y = window.Top }, ref window); } else { @@ -125,7 +125,7 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord if (s != _lastWrite) { // supply console with the new content - result = WriteConsole (_screenBuffer, s, (uint)s.Length, out uint _, nint.Zero); + result = WriteConsole (_outputHandle, s, (uint)s.Length, out uint _, nint.Zero); } _lastWrite = s; @@ -133,7 +133,7 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord foreach (var sixel in Application.Sixel) { SetCursorPosition (new Coord ((short)sixel.ScreenPosition.X, (short)sixel.ScreenPosition.Y)); - WriteConsole (_screenBuffer, sixel.SixelData, (uint)sixel.SixelData.Length, out uint _, nint.Zero); + WriteConsole (_outputHandle, sixel.SixelData, (uint)sixel.SixelData.Length, out uint _, nint.Zero); } } @@ -143,7 +143,8 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord if (err != 0) { - throw new Win32Exception (err); + //throw new Win32Exception (err); + // It's resizing } } @@ -152,10 +153,10 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord internal bool WriteANSI (string ansi) { - if (WriteConsole (_screenBuffer, ansi, (uint)ansi.Length, out uint _, nint.Zero)) + if (WriteConsole (_outputHandle, ansi, (uint)ansi.Length, out uint _, nint.Zero)) { // Flush the output to make sure it's sent immediately - return FlushFileBuffers (_screenBuffer); + return FlushFileBuffers (_outputHandle); } return false; @@ -163,34 +164,34 @@ internal bool WriteANSI (string ansi) public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window) { - _screenBuffer = CreateConsoleScreenBuffer ( - DesiredAccess.GenericRead | DesiredAccess.GenericWrite, - ShareMode.FileShareRead | ShareMode.FileShareWrite, - nint.Zero, - 1, - nint.Zero - ); + //_screenBuffer = CreateConsoleScreenBuffer ( + // DesiredAccess.GenericRead | DesiredAccess.GenericWrite, + // ShareMode.FileShareRead | ShareMode.FileShareWrite, + // nint.Zero, + // 1, + // nint.Zero + // ); - if (_screenBuffer == INVALID_HANDLE_VALUE) - { - int err = Marshal.GetLastWin32Error (); + //if (_screenBuffer == INVALID_HANDLE_VALUE) + //{ + // int err = Marshal.GetLastWin32Error (); - if (err != 0) - { - throw new Win32Exception (err); - } - } + // if (err != 0) + // { + // throw new Win32Exception (err); + // } + //} SetInitialCursorVisibility (); - if (!SetConsoleActiveScreenBuffer (_screenBuffer)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } + //if (!SetConsoleActiveScreenBuffer (_screenBuffer)) + //{ + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + //} _originalStdOutChars = new CharInfo [size.Height * size.Width]; - if (!ReadConsoleOutput (_screenBuffer, _originalStdOutChars, coords, new Coord { X = 0, Y = 0 }, ref window)) + if (!ReadConsoleOutput (_outputHandle, _originalStdOutChars, coords, new Coord { X = 0, Y = 0 }, ref window)) { throw new Win32Exception (Marshal.GetLastWin32Error ()); } @@ -198,7 +199,7 @@ public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window public bool SetCursorPosition (Coord position) { - return SetConsoleCursorPosition (_screenBuffer, position); + return SetConsoleCursorPosition (_outputHandle, position); } public void SetInitialCursorVisibility () @@ -211,14 +212,14 @@ public void SetInitialCursorVisibility () public bool GetCursorVisibility (out CursorVisibility visibility) { - if (_screenBuffer == nint.Zero) + if (_outputHandle == nint.Zero) { visibility = CursorVisibility.Invisible; return false; } - if (!GetConsoleCursorInfo (_screenBuffer, out ConsoleCursorInfo info)) + if (!GetConsoleCursorInfo (_outputHandle, out ConsoleCursorInfo info)) { int err = Marshal.GetLastWin32Error (); @@ -286,7 +287,7 @@ public bool SetCursorVisibility (CursorVisibility visibility) bVisible = ((uint)visibility & 0xFF00) != 0 }; - if (!SetConsoleCursorInfo (_screenBuffer, ref info)) + if (!SetConsoleCursorInfo (_outputHandle, ref info)) { return false; } @@ -304,7 +305,7 @@ public void Cleanup () SetCursorVisibility (_initialCursorVisibility.Value); } - SetConsoleOutputWindow (out _); + //SetConsoleOutputWindow (out _); ConsoleMode = _originalConsoleMode; @@ -322,139 +323,139 @@ public void Cleanup () Console.WriteLine ("Error: {0}", err); } - if (_screenBuffer != nint.Zero) - { - CloseHandle (_screenBuffer); - } - - _screenBuffer = nint.Zero; - } - - internal Size GetConsoleBufferWindow (out Point position) - { - if (_screenBuffer == nint.Zero) - { - position = Point.Empty; - - return Size.Empty; - } - - var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); - csbi.cbSize = (uint)Marshal.SizeOf (csbi); - - if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - { - //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ()); - position = Point.Empty; - - return Size.Empty; - } - - Size sz = new ( - csbi.srWindow.Right - csbi.srWindow.Left + 1, - csbi.srWindow.Bottom - csbi.srWindow.Top + 1); - position = new (csbi.srWindow.Left, csbi.srWindow.Top); - - return sz; - } - - internal Size GetConsoleOutputWindow (out Point position) - { - var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); - csbi.cbSize = (uint)Marshal.SizeOf (csbi); - - if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } - - Size sz = new ( - csbi.srWindow.Right - csbi.srWindow.Left + 1, - csbi.srWindow.Bottom - csbi.srWindow.Top + 1); - position = new (csbi.srWindow.Left, csbi.srWindow.Top); - - return sz; - } - - internal Size SetConsoleWindow (short cols, short rows) - { - var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); - csbi.cbSize = (uint)Marshal.SizeOf (csbi); - - if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } - - Coord maxWinSize = GetLargestConsoleWindowSize (_screenBuffer); - short newCols = Math.Min (cols, maxWinSize.X); - short newRows = Math.Min (rows, maxWinSize.Y); - csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1)); - csbi.srWindow = new SmallRect (0, 0, newCols, newRows); - csbi.dwMaximumWindowSize = new Coord (newCols, newRows); - - if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } - - var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0)); - - if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) - { - //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ()); - return new (cols, rows); - } - - SetConsoleOutputWindow (csbi); + //if (_screenBuffer != nint.Zero) + //{ + // CloseHandle (_screenBuffer); + //} - return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1); + //_screenBuffer = nint.Zero; } - private void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi) - { - if (_screenBuffer != nint.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } - } - - internal Size SetConsoleOutputWindow (out Point position) - { - if (_screenBuffer == nint.Zero) - { - position = Point.Empty; - - return Size.Empty; - } - - var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); - csbi.cbSize = (uint)Marshal.SizeOf (csbi); - - if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } - - Size sz = new ( - csbi.srWindow.Right - csbi.srWindow.Left + 1, - Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0)); - position = new (csbi.srWindow.Left, csbi.srWindow.Top); - SetConsoleOutputWindow (csbi); - var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0)); - - if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } - - if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } - - return sz; - } + //internal Size GetConsoleBufferWindow (out Point position) + //{ + // if (_screenBuffer == nint.Zero) + // { + // position = Point.Empty; + + // return Size.Empty; + // } + + // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); + // csbi.cbSize = (uint)Marshal.SizeOf (csbi); + + // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ()); + // position = Point.Empty; + + // return Size.Empty; + // } + + // Size sz = new ( + // csbi.srWindow.Right - csbi.srWindow.Left + 1, + // csbi.srWindow.Bottom - csbi.srWindow.Top + 1); + // position = new (csbi.srWindow.Left, csbi.srWindow.Top); + + // return sz; + //} + + //internal Size GetConsoleOutputWindow (out Point position) + //{ + // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); + // csbi.cbSize = (uint)Marshal.SizeOf (csbi); + + // if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // Size sz = new ( + // csbi.srWindow.Right - csbi.srWindow.Left + 1, + // csbi.srWindow.Bottom - csbi.srWindow.Top + 1); + // position = new (csbi.srWindow.Left, csbi.srWindow.Top); + + // return sz; + //} + + //internal Size SetConsoleWindow (short cols, short rows) + //{ + // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); + // csbi.cbSize = (uint)Marshal.SizeOf (csbi); + + // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // Coord maxWinSize = GetLargestConsoleWindowSize (_screenBuffer); + // short newCols = Math.Min (cols, maxWinSize.X); + // short newRows = Math.Min (rows, maxWinSize.Y); + // csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1)); + // csbi.srWindow = new SmallRect (0, 0, newCols, newRows); + // csbi.dwMaximumWindowSize = new Coord (newCols, newRows); + + // if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0)); + + // if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) + // { + // //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ()); + // return new (cols, rows); + // } + + // SetConsoleOutputWindow (csbi); + + // return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1); + //} + + //private void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi) + //{ + // if (_screenBuffer != nint.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + //} + + //internal Size SetConsoleOutputWindow (out Point position) + //{ + // if (_screenBuffer == nint.Zero) + // { + // position = Point.Empty; + + // return Size.Empty; + // } + + // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); + // csbi.cbSize = (uint)Marshal.SizeOf (csbi); + + // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // Size sz = new ( + // csbi.srWindow.Right - csbi.srWindow.Left + 1, + // Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0)); + // position = new (csbi.srWindow.Left, csbi.srWindow.Top); + // SetConsoleOutputWindow (csbi); + // var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0)); + + // if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // return sz; + //} private uint ConsoleMode { @@ -1487,12 +1488,12 @@ public override bool EnsureCursorVisibility () public override void UpdateScreen () { - Size windowSize = WinConsole?.GetConsoleBufferWindow (out Point _) ?? new Size (Cols, Rows); + //Size windowSize = WinConsole?.GetConsoleBufferWindow (out Point _) ?? new Size (Cols, Rows); - if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) - { - return; - } + //if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) + //{ + // return; + //} var bufferCoords = new WindowsConsole.Coord { @@ -1561,7 +1562,8 @@ public override void UpdateScreen () if (err != 0) { - throw new Win32Exception (err); + //throw new Win32Exception (err); + // It's resizing } } @@ -1598,14 +1600,17 @@ internal override MainLoop Init () { try { - if (WinConsole is { }) - { - // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init. - // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED - Size winSize = WinConsole.GetConsoleOutputWindow (out Point pos); - Cols = winSize.Width; - Rows = winSize.Height; - } + //if (WinConsole is { }) + //{ + // // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init. + // // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED + // Size winSize = WinConsole.GetConsoleOutputWindow (out Point pos); + // Cols = winSize.Width; + // Rows = winSize.Height; + //} + + Cols = Console.WindowWidth; + Rows = Console.WindowHeight; WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion); From ad4f6c49e12b7971a5bb3a9b6ef61d87a1522165 Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 5 Nov 2024 00:49:33 +0000 Subject: [PATCH 71/89] Fix unit test. --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index d4c7bfc3a7..4bcad4b219 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1648,7 +1648,11 @@ internal override MainLoop Init () _mainLoopDriver.WinChanged = ChangeWin; #endif - WinConsole?.SetInitialCursorVisibility (); + if (!RunningUnitTests) + { + WinConsole?.SetInitialCursorVisibility (); + } + return new MainLoop (_mainLoopDriver); } From f73c8173ba8c7f944dfdad5ad053b087df0b87fc Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 5 Nov 2024 01:25:40 +0000 Subject: [PATCH 72/89] Fix unit tests. --- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 72 ++++++++++---------- 1 file changed, 35 insertions(+), 37 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 4bcad4b219..1ee0e8023b 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -143,8 +143,7 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord if (err != 0) { - //throw new Win32Exception (err); - // It's resizing + throw new Win32Exception (err); } } @@ -359,23 +358,23 @@ public void Cleanup () // return sz; //} - //internal Size GetConsoleOutputWindow (out Point position) - //{ - // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); - // csbi.cbSize = (uint)Marshal.SizeOf (csbi); + internal Size GetConsoleOutputWindow (out Point position) + { + var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); + csbi.cbSize = (uint)Marshal.SizeOf (csbi); - // if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) - // { - // throw new Win32Exception (Marshal.GetLastWin32Error ()); - // } + if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) + { + throw new Win32Exception (Marshal.GetLastWin32Error ()); + } - // Size sz = new ( - // csbi.srWindow.Right - csbi.srWindow.Left + 1, - // csbi.srWindow.Bottom - csbi.srWindow.Top + 1); - // position = new (csbi.srWindow.Left, csbi.srWindow.Top); + Size sz = new ( + csbi.srWindow.Right - csbi.srWindow.Left + 1, + csbi.srWindow.Bottom - csbi.srWindow.Top + 1); + position = new (csbi.srWindow.Left, csbi.srWindow.Top); - // return sz; - //} + return sz; + } //internal Size SetConsoleWindow (short cols, short rows) //{ @@ -1223,9 +1222,12 @@ public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsol public override void Refresh () { - UpdateScreen (); - //WinConsole?.SetInitialCursorVisibility (); - UpdateCursor (); + if (!RunningUnitTests) + { + UpdateScreen (); + //WinConsole?.SetInitialCursorVisibility (); + UpdateCursor (); + } } public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control) @@ -1488,12 +1490,12 @@ public override bool EnsureCursorVisibility () public override void UpdateScreen () { - //Size windowSize = WinConsole?.GetConsoleBufferWindow (out Point _) ?? new Size (Cols, Rows); + Size windowSize = WinConsole?.GetConsoleOutputWindow (out Point _) ?? new Size (Cols, Rows); - //if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) - //{ - // return; - //} + if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) + { + return; + } var bufferCoords = new WindowsConsole.Coord { @@ -1562,8 +1564,7 @@ public override void UpdateScreen () if (err != 0) { - //throw new Win32Exception (err); - // It's resizing + throw new Win32Exception (err); } } @@ -1600,17 +1601,14 @@ internal override MainLoop Init () { try { - //if (WinConsole is { }) - //{ - // // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init. - // // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED - // Size winSize = WinConsole.GetConsoleOutputWindow (out Point pos); - // Cols = winSize.Width; - // Rows = winSize.Height; - //} - - Cols = Console.WindowWidth; - Rows = Console.WindowHeight; + if (WinConsole is { }) + { + // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init. + // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED + Size winSize = WinConsole.GetConsoleOutputWindow (out Point pos); + Cols = winSize.Width; + Rows = winSize.Height; + } WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion); From 7921ae35f744af36065d057877e97d61e9924101 Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 5 Nov 2024 17:55:29 +0000 Subject: [PATCH 73/89] Returns ansiRequest.Response instead of a variable for more thread safe. --- .../CursesDriver/CursesDriver.cs | 19 ++++++++++--------- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 19 ++++++++++--------- Terminal.Gui/ConsoleDrivers/WindowsDriver.cs | 19 ++++++++++--------- 3 files changed, 30 insertions(+), 27 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 1f4f2bc3ff..1086bd6e38 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -217,8 +217,6 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) return string.Empty; } - var response = string.Empty; - try { lock (ansiRequest._responseLock) @@ -226,8 +224,7 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) ansiRequest.ResponseFromInput += (s, e) => { Debug.Assert (s == ansiRequest); - - ansiRequest.Response = response = e; + Debug.Assert (e == ansiRequest.Response); _waitAnsiResponse.Set (); }; @@ -248,7 +245,8 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { return string.Empty; } - finally + + lock (ansiRequest._responseLock) { _mainLoopDriver._forceRead = false; @@ -257,15 +255,18 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0 && string.IsNullOrEmpty (request.AnsiRequest.Response)) { - // Bad request or no response at all - _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _); + lock (request!.AnsiRequest._responseLock) + { + // Bad request or no response at all + _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _); + } } } _waitAnsiResponse.Reset (); - } - return response; + return ansiRequest.Response; + } } /// diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index 3afaafd042..afa78ff6a2 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -1502,8 +1502,6 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) return string.Empty; } - var response = string.Empty; - try { lock (ansiRequest._responseLock) @@ -1511,8 +1509,7 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) ansiRequest.ResponseFromInput += (s, e) => { Debug.Assert (s == ansiRequest); - - ansiRequest.Response = response = e; + Debug.Assert (e == ansiRequest.Response); _waitAnsiResponse.Set (); }; @@ -1538,7 +1535,8 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { return string.Empty; } - finally + + lock (ansiRequest._responseLock) { _mainLoopDriver._netEvents._forceRead = false; @@ -1547,15 +1545,18 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0 && string.IsNullOrEmpty (request.AnsiRequest.Response)) { - // Bad request or no response at all - _mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryDequeue (out _); + lock (request!.AnsiRequest._responseLock) + { + // Bad request or no response at all + _mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryDequeue (out _); + } } } _waitAnsiResponse.Reset (); - } - return response; + return ansiRequest.Response; + } } /// diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs index 1ee0e8023b..83763e0818 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs @@ -1311,8 +1311,6 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) return string.Empty; } - var response = string.Empty; - try { lock (ansiRequest._responseLock) @@ -1320,8 +1318,7 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) ansiRequest.ResponseFromInput += (s, e) => { Debug.Assert (s == ansiRequest); - - ansiRequest.Response = response = e; + Debug.Assert (e == ansiRequest.Response); _waitAnsiResponse.Set (); }; @@ -1342,7 +1339,8 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { return string.Empty; } - finally + + lock (ansiRequest._responseLock) { _mainLoopDriver._forceRead = false; @@ -1351,15 +1349,18 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0 && string.IsNullOrEmpty (request.AnsiRequest.Response)) { - // Bad request or no response at all - _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _); + lock (request!.AnsiRequest._responseLock) + { + // Bad request or no response at all + _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _); + } } } _waitAnsiResponse.Reset (); - } - return response; + return ansiRequest.Response; + } } public override void WriteRaw (string ansi) From ecbbed0f6dfeed36954fe8b7f67173f15c047518 Mon Sep 17 00:00:00 2001 From: BDisp Date: Tue, 5 Nov 2024 18:34:58 +0000 Subject: [PATCH 74/89] For re-run CI. --- Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 1086bd6e38..4568bcf461 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -209,7 +209,7 @@ public void StopReportingMouseMoves () private readonly ManualResetEventSlim _waitAnsiResponse = new (false); private readonly CancellationTokenSource _ansiResponseTokenSource = new (); - /// + /// public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { if (_mainLoopDriver is null) From 2919d55817972112f17118346252be7583b3963c Mon Sep 17 00:00:00 2001 From: Tig Date: Wed, 6 Nov 2024 11:33:02 -0700 Subject: [PATCH 75/89] Code Review --- .../AnsiEscapeSequenceRequest.cs | 38 +- .../AnsiEscapeSequenceResponse.cs | 27 +- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 665 ++---- .../ConsoleDrivers/ConsoleKeyMapping.cs | 1 + .../CursesDriver/CursesDriver.cs | 1167 +++++----- .../CursesDriver/GetTIOCGWINSZ.c | 9 +- .../ConsoleDrivers/EscSeqUtils/EscSeqReq.cs | 15 +- .../EscSeqUtils/EscSeqReqStatus.cs | 17 + .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 14 +- Terminal.Gui/ConsoleDrivers/KeyCode.cs | 321 +++ Terminal.Gui/ConsoleDrivers/NetDriver.cs | 2007 ----------------- .../ConsoleDrivers/NetDriver/NetDriver.cs | 965 ++++++++ .../ConsoleDrivers/NetDriver/NetEvents.cs | 753 +++++++ .../ConsoleDrivers/NetDriver/NetMainLoop.cs | 173 ++ .../NetDriver/NetWinVTConsole.cs | 125 + .../WindowsDriver/WindowsConsole.cs | 1109 +++++++++ .../{ => WindowsDriver}/WindowsDriver.cs | 1106 +-------- Terminal.Gui/Terminal.Gui.csproj | 3 +- .../Scenarios/AnsiEscapeSequenceRequests.cs | 200 +- 19 files changed, 4406 insertions(+), 4309 deletions(-) create mode 100644 Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReqStatus.cs create mode 100644 Terminal.Gui/ConsoleDrivers/KeyCode.cs delete mode 100644 Terminal.Gui/ConsoleDrivers/NetDriver.cs create mode 100644 Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs create mode 100644 Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs create mode 100644 Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs create mode 100644 Terminal.Gui/ConsoleDrivers/NetDriver/NetWinVTConsole.cs create mode 100644 Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs rename Terminal.Gui/ConsoleDrivers/{ => WindowsDriver}/WindowsDriver.cs (60%) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 662736e931..2e8da6bfed 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -4,35 +4,38 @@ namespace Terminal.Gui; /// /// Describes an ongoing ANSI request sent to the console. /// Use to handle the response -/// when console answers the request. +/// when the console answers the request. /// public class AnsiEscapeSequenceRequest { internal readonly object _responseLock = new (); // Per-instance lock /// - /// Request to send e.g. see + /// Gets the request string to send e.g. see /// /// EscSeqUtils.CSI_SendDeviceAttributes.Request /// /// public required string Request { get; init; } + // QUESTION: Could the type of this propperty be AnsiEscapeSequenceResponse? This would remove the + // QUESTION: removal of the redundant Rresponse, Terminator, and ExpectedRespnseValue properties from this class? + // QUESTION: Does string.Empty indicate no response recevied? If not, perhaps make this property nullable? /// - /// Response received from the request. + /// Gets the response received from the request. /// public string Response { get; internal set; } = string.Empty; /// - /// Invoked when the console responds with an ANSI response code that matches the + /// Raised when the console responds with an ANSI response code that matches the /// /// public event EventHandler? ResponseReceived; /// /// - /// The terminator that uniquely identifies the type of response as responded - /// by the console. e.g. for + /// Gets the terminator that uniquely identifies the response received from + /// the console. e.g. for /// /// EscSeqUtils.CSI_SendDeviceAttributes.Request /// @@ -50,15 +53,15 @@ public class AnsiEscapeSequenceRequest public required string Terminator { get; init; } /// - /// Execute an ANSI escape sequence escape which may return a response or error. + /// Attempt an ANSI escape sequence request which may return a response or error. /// /// The ANSI escape sequence to request. /// - /// When this method returns , an object containing the response with an empty - /// error. + /// When this method returns , the response. will + /// be . /// - /// A with the response, error, terminator and value. - public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEscapeSequenceResponse result) + /// A with the response, error, terminator, and value. + public static bool TryRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEscapeSequenceResponse result) { var error = new StringBuilder (); var values = new string? [] { null }; @@ -72,7 +75,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, if (!string.IsNullOrEmpty (ansiRequest.Response) && !ansiRequest.Response.StartsWith (EscSeqUtils.KeyEsc)) { - throw new InvalidOperationException ("Invalid escape character!"); + throw new InvalidOperationException ($"Invalid Response: {ansiRequest.Response}"); } if (string.IsNullOrEmpty (ansiRequest.Terminator)) @@ -102,7 +105,7 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, AnsiEscapeSequenceResponse ansiResponse = new () { Response = ansiRequest.Response, Error = error.ToString (), - Terminator = string.IsNullOrEmpty (ansiRequest.Response) ? "" : ansiRequest.Response [^1].ToString (), Value = values [0] + Terminator = string.IsNullOrEmpty (ansiRequest.Response) ? "" : ansiRequest.Response [^1].ToString (), ExpectedResponseValue = values [0] }; // Invoke the event if it's subscribed @@ -114,16 +117,17 @@ public static bool TryExecuteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest, } /// - /// The value expected in the response e.g. + /// The value expected in the response after the CSI e.g. /// /// EscSeqUtils.CSI_ReportTerminalSizeInChars.Value /// - /// which will have a 't' as terminator but also other different request may return the same terminator with a - /// different value. + /// should result in a response of the form ESC [ 8 ; height ; width t. In this case, + /// will be "8". /// - public string? Value { get; init; } + public string? ExpectedResponseValue { get; init; } internal void RaiseResponseFromInput (AnsiEscapeSequenceRequest ansiRequest, string response) { ResponseFromInput?.Invoke (ansiRequest, response); } + // QUESTION: What is this for? Please provide a descriptive comment. internal event EventHandler? ResponseFromInput; } diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs index df98511558..2cc8208015 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs @@ -2,20 +2,23 @@ namespace Terminal.Gui; /// -/// Describes a finished ANSI received from the console. +/// Describes a response received from the console as a result of a request being sent via . /// public class AnsiEscapeSequenceResponse { + // QUESTION: Should this be nullable to indicate there was no error, or is string.Empty sufficient? /// - /// Error received from e.g. see + /// Gets the error string received from e.g. see /// /// EscSeqUtils.CSI_SendDeviceAttributes.Request /// + /// . /// public required string Error { get; init; } + // QUESTION: Does string.Empty indicate no response recevied? If not, perhaps make this property nullable? /// - /// Response received from e.g. see + /// Gets the Response string received from e.g. see /// /// EscSeqUtils.CSI_SendDeviceAttributes.Request /// @@ -23,10 +26,11 @@ public class AnsiEscapeSequenceResponse /// public required string Response { get; init; } + // QUESTION: Does string.Empty indicate no terminator expected? If not, perhaps make this property nullable? /// /// - /// The terminator that uniquely identifies the type of response as responded - /// by the console. e.g. for + /// Gets the terminator that uniquely identifies the response received from + /// the console. e.g. for /// /// EscSeqUtils.CSI_SendDeviceAttributes.Request /// @@ -34,20 +38,23 @@ public class AnsiEscapeSequenceResponse /// /// EscSeqUtils.CSI_SendDeviceAttributes.Terminator /// + /// . /// /// - /// The received terminator must match to the terminator sent by the request. + /// After sending a request, the first response with matching terminator will be matched + /// to the oldest outstanding request. /// /// public required string Terminator { get; init; } /// - /// The value expected in the response e.g. + /// The value expected in the response after the CSI e.g. /// /// EscSeqUtils.CSI_ReportTerminalSizeInChars.Value /// - /// which will have a 't' as terminator but also other different request may return the same terminator with a - /// different value. + /// should result in a response of the form ESC [ 8 ; height ; width t. In this case, + /// will be "8". /// - public string? Value { get; init; } + + public string? ExpectedResponseValue { get; init; } } diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index b37c50c53e..d6ccf99914 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -1,7 +1,4 @@ #nullable enable -// -// ConsoleDriver.cs: Base class for Terminal.Gui ConsoleDriver implementations. -// using System.Diagnostics; @@ -15,6 +12,53 @@ namespace Terminal.Gui; /// 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 string WriteAnsiRequest (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 . + /// + /// + public 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; @@ -23,30 +67,18 @@ public abstract class ConsoleDriver /// Gets the location and size of the terminal screen. internal Rectangle Screen => new (0, 0, Cols, Rows); - private Rectangle _clip; + /// Redraws the physical screen with the contents that have been queued up via any of the printing commands. + public abstract void UpdateScreen (); - /// - /// 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; - } + /// Called when the terminal size changes. Fires the event. + /// + public void OnSizeChanged (SizeChangedEventArgs args) { SizeChanged?.Invoke (this, args); } - // Don't ever let Clip be bigger than Screen - _clip = Rectangle.Intersect (Screen, value); - } - } + /// The event fired when the terminal is resized. + public event EventHandler? SizeChanged; - /// Get the operating system clipboard. - public IClipboard? Clipboard { get; internal set; } + /// 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 @@ -75,6 +107,43 @@ 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. @@ -95,16 +164,27 @@ internal set /// The topmost row in the terminal. public virtual int Top { get; internal set; } = 0; + private Rectangle _clip; + /// - /// Set this to true in any unit tests that attempt to test drivers other than FakeDriver. - /// - /// public ColorTests () - /// { - /// ConsoleDriver.RunningUnitTests = true; - /// } - /// + /// Gets or sets the clip rectangle that and are subject + /// to. /// - internal static bool RunningUnitTests { get; set; } + /// 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. /// @@ -310,10 +390,38 @@ public void AddStr (string str) } } + /// 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; @@ -325,21 +433,22 @@ public void ClearContents () { for (var c = 0; c < Cols; c++) { - Contents [row, c] = new Cell + 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. + /// Sets as dirty for situations where views + /// don't need layout and redrawing, but just refresh the screen. /// public void SetContentsAsDirty () { @@ -351,37 +460,8 @@ public void SetContentsAsDirty () { Contents [row, c].IsDirty = true; } - _dirtyLines! [row] = true; - } - } - } - /// Determines if the terminal cursor should be visible or not and sets it accordingly. - /// upon success - public abstract bool EnsureCursorVisibility (); - - /// 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 Cell - { - Rune = rune != default ? rune : (Rune)' ', - Attribute = CurrentAttribute, IsDirty = true - }; - _dirtyLines! [r] = true; - } + _dirtyLines! [row] = true; } } } @@ -394,79 +474,28 @@ public void FillRect (Rectangle rect, Rune rune = default) /// 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); - /// Returns the name of the driver and relevant library version information. - /// - public virtual string GetVersionInfo () { return GetType ().Name; } - - /// 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; - } - - /// Called when the terminal size changes. Fires the event. - /// - public void OnSizeChanged (SizeChangedEventArgs args) { SizeChanged?.Invoke (this, args); } - - /// Updates the screen to reflect all the changes that have been done to the display buffer - public abstract void Refresh (); + /// 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); - /// The event fired when the terminal is resized. - public event EventHandler? SizeChanged; - - /// 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 (); - - /// Sets the position of the terminal cursor to and . - public abstract void UpdateCursor (); - - /// Redraws the physical screen with the contents that have been queued up via any of the printing commands. - public abstract void UpdateScreen (); + #endregion Cursor Handling #region Setup & Teardown @@ -518,7 +547,7 @@ public Attribute CurrentAttribute // 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 Attribute (value.Foreground, value.Background); + _currentAttribute = new (value.Foreground, value.Background); return; } @@ -551,16 +580,33 @@ public Attribute SetAttribute (Attribute c) public virtual Attribute MakeColor (in Color foreground, in Color background) { // Encode the colors into the int value. - return new Attribute ( - -1, // only used by cursesdriver! - foreground, - background - ); + return new ( + -1, // only used by cursesdriver! + foreground, + background + ); } - #endregion + #endregion Color Handling - #region Mouse and Keyboard + #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; @@ -587,19 +633,8 @@ public virtual Attribute MakeColor (in Color foreground, in Color background) /// public void OnKeyUp (Key a) { KeyUp?.Invoke (this, a); } - /// 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); - } - + // 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. @@ -608,337 +643,5 @@ public void OnMouseEvent (MouseEventArgs a) /// If simulates the Ctrl key being pressed. public abstract void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool ctrl); - /// - /// Provide handling for the terminal write ANSI escape sequence request. - /// - /// The object. - /// The request response. - public abstract string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest); - - /// - /// Provide proper writing to send escape sequence recognized by the . - /// - /// - public abstract void WriteRaw (string ansi); - - #endregion -} - -/// -/// The enumeration encodes key information from s and provides a -/// consistent way for application code to specify keys and receive key events. -/// -/// The class provides a higher-level abstraction, with helper methods and properties for -/// common operations. For example, and provide a convenient way -/// to check whether the Alt or Ctrl modifier keys were pressed when a key was pressed. -/// -/// -/// -/// -/// Lowercase alpha keys are encoded as values between 65 and 90 corresponding to the un-shifted A to Z keys on a -/// keyboard. Enum values are provided for these (e.g. , , etc.). -/// Even though the values are the same as the ASCII values for uppercase characters, these enum values represent -/// *lowercase*, un-shifted characters. -/// -/// -/// Numeric keys are the values between 48 and 57 corresponding to 0 to 9 (e.g. , -/// , etc.). -/// -/// -/// The shift modifiers (, , and -/// ) can be combined (with logical or) with the other key codes to represent shifted -/// keys. For example, the enum value represents the un-shifted 'a' key, while -/// | represents the 'A' key (shifted 'a' key). Likewise, -/// | represents the 'Alt+A' key combination. -/// -/// -/// All other keys that produce a printable character are encoded as the Unicode value of the character. For -/// example, the for the '!' character is 33, which is the Unicode value for '!'. Likewise, -/// `â` is 226, `Â` is 194, etc. -/// -/// -/// If the is set, then the value is that of the special mask, otherwise, the value is -/// the one of the lower bits (as extracted by ). -/// -/// -[Flags] -public enum KeyCode : uint -{ - /// - /// Mask that indicates that the key is a unicode codepoint. Values outside this range indicate the key has shift - /// modifiers or is a special key like function keys, arrows keys and so on. - /// - CharMask = 0x_f_ffff, - - /// - /// If the is set, then the value is that of the special mask, otherwise, the value is - /// in the lower bits (as extracted by ). - /// - SpecialMask = 0x_fff0_0000, - - /// - /// When this value is set, the Key encodes the sequence Shift-KeyValue. The actual value must be extracted by - /// removing the ShiftMask. - /// - ShiftMask = 0x_1000_0000, - - /// - /// When this value is set, the Key encodes the sequence Alt-KeyValue. The actual value must be extracted by - /// removing the AltMask. - /// - AltMask = 0x_8000_0000, - - /// - /// When this value is set, the Key encodes the sequence Ctrl-KeyValue. The actual value must be extracted by - /// removing the CtrlMask. - /// - CtrlMask = 0x_4000_0000, - - /// The key code representing an invalid or empty key. - Null = 0, - - /// Backspace key. - Backspace = 8, - - /// The key code for the tab key (forwards tab key). - Tab = 9, - - /// The key code for the return key. - Enter = ConsoleKey.Enter, - - /// The key code for the clear key. - Clear = 12, - - /// The key code for the escape key. - Esc = 27, - - /// The key code for the space bar key. - Space = 32, - - /// Digit 0. - D0 = 48, - - /// Digit 1. - D1, - - /// Digit 2. - D2, - - /// Digit 3. - D3, - - /// Digit 4. - D4, - - /// Digit 5. - D5, - - /// Digit 6. - D6, - - /// Digit 7. - D7, - - /// Digit 8. - D8, - - /// Digit 9. - D9, - - /// The key code for the A key - A = 65, - - /// The key code for the B key - B, - - /// The key code for the C key - C, - - /// The key code for the D key - D, - - /// The key code for the E key - E, - - /// The key code for the F key - F, - - /// The key code for the G key - G, - - /// The key code for the H key - H, - - /// The key code for the I key - I, - - /// The key code for the J key - J, - - /// The key code for the K key - K, - - /// The key code for the L key - L, - - /// The key code for the M key - M, - - /// The key code for the N key - N, - - /// The key code for the O key - O, - - /// The key code for the P key - P, - - /// The key code for the Q key - Q, - - /// The key code for the R key - R, - - /// The key code for the S key - S, - - /// The key code for the T key - T, - - /// The key code for the U key - U, - - /// The key code for the V key - V, - - /// The key code for the W key - W, - - /// The key code for the X key - X, - - /// The key code for the Y key - Y, - - /// The key code for the Z key - Z, - - ///// - ///// The key code for the Delete key. - ///// - //Delete = 127, - - // --- Special keys --- - // The values below are common non-alphanum keys. Their values are - // based on the .NET ConsoleKey values, which, in-turn are based on the - // VK_ values from the Windows API. - // We add MaxCodePoint to avoid conflicts with the Unicode values. - - /// The maximum Unicode codepoint value. Used to encode the non-alphanumeric control keys. - MaxCodePoint = 0x10FFFF, - - /// Cursor up key - CursorUp = MaxCodePoint + ConsoleKey.UpArrow, - - /// Cursor down key. - CursorDown = MaxCodePoint + ConsoleKey.DownArrow, - - /// Cursor left key. - CursorLeft = MaxCodePoint + ConsoleKey.LeftArrow, - - /// Cursor right key. - CursorRight = MaxCodePoint + ConsoleKey.RightArrow, - - /// Page Up key. - PageUp = MaxCodePoint + ConsoleKey.PageUp, - - /// Page Down key. - PageDown = MaxCodePoint + ConsoleKey.PageDown, - - /// Home key. - Home = MaxCodePoint + ConsoleKey.Home, - - /// End key. - End = MaxCodePoint + ConsoleKey.End, - - /// Insert (INS) key. - Insert = MaxCodePoint + ConsoleKey.Insert, - - /// Delete (DEL) key. - Delete = MaxCodePoint + ConsoleKey.Delete, - - /// Print screen character key. - PrintScreen = MaxCodePoint + ConsoleKey.PrintScreen, - - /// F1 key. - F1 = MaxCodePoint + ConsoleKey.F1, - - /// F2 key. - F2 = MaxCodePoint + ConsoleKey.F2, - - /// F3 key. - F3 = MaxCodePoint + ConsoleKey.F3, - - /// F4 key. - F4 = MaxCodePoint + ConsoleKey.F4, - - /// F5 key. - F5 = MaxCodePoint + ConsoleKey.F5, - - /// F6 key. - F6 = MaxCodePoint + ConsoleKey.F6, - - /// F7 key. - F7 = MaxCodePoint + ConsoleKey.F7, - - /// F8 key. - F8 = MaxCodePoint + ConsoleKey.F8, - - /// F9 key. - F9 = MaxCodePoint + ConsoleKey.F9, - - /// F10 key. - F10 = MaxCodePoint + ConsoleKey.F10, - - /// F11 key. - F11 = MaxCodePoint + ConsoleKey.F11, - - /// F12 key. - F12 = MaxCodePoint + ConsoleKey.F12, - - /// F13 key. - F13 = MaxCodePoint + ConsoleKey.F13, - - /// F14 key. - F14 = MaxCodePoint + ConsoleKey.F14, - - /// F15 key. - F15 = MaxCodePoint + ConsoleKey.F15, - - /// F16 key. - F16 = MaxCodePoint + ConsoleKey.F16, - - /// F17 key. - F17 = MaxCodePoint + ConsoleKey.F17, - - /// F18 key. - F18 = MaxCodePoint + ConsoleKey.F18, - - /// F19 key. - F19 = MaxCodePoint + ConsoleKey.F19, - - /// F20 key. - F20 = MaxCodePoint + ConsoleKey.F20, - - /// F21 key. - F21 = MaxCodePoint + ConsoleKey.F21, - - /// F22 key. - F22 = MaxCodePoint + ConsoleKey.F22, - - /// F23 key. - F23 = MaxCodePoint + ConsoleKey.F23, - - /// F24 key. - F24 = MaxCodePoint + ConsoleKey.F24 + #endregion Keyboard Handling } diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs b/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs index 503e7cd572..6fce2e040f 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleKeyMapping.cs @@ -3,6 +3,7 @@ namespace Terminal.Gui.ConsoleDrivers; +// QUESTION: This class combines Windows specific code with cross-platform code. Should this be split into two classes? /// Helper class to handle the scan code and virtual key from a . public static class ConsoleKeyMapping { diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 4568bcf461..e0225b3aae 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -1,4 +1,5 @@ -// +// TODO: #nullable enable +// // Driver.cs: Curses-based Driver // @@ -9,86 +10,55 @@ namespace Terminal.Gui; -/// This is the Curses driver for the gui.cs/Terminal framework. +/// A Linux/Mac driver based on the Curses libary. internal class CursesDriver : ConsoleDriver { - public Curses.Window _window; - private CursorVisibility? _currentCursorVisibility; - private CursorVisibility? _initialCursorVisibility; - private MouseFlags _lastMouseFlags; - private UnixMainLoop _mainLoopDriver; + public override string GetVersionInfo () { return $"{Curses.curses_version ()}"; } - public override int Cols + public override void Refresh () { - get => Curses.Cols; - internal set - { - Curses.Cols = value; - ClearContents (); - } + UpdateScreen (); + UpdateCursor (); } - public override int Rows + public override void Suspend () { - get => Curses.Lines; - internal set - { - Curses.Lines = value; - ClearContents (); - } - } - - public override bool SupportsTrueColor => true; + StopReportingMouseMoves (); - /// - public override bool EnsureCursorVisibility () - { - if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) + if (!RunningUnitTests) { - GetCursorVisibility (out CursorVisibility cursorVisibility); - _currentCursorVisibility = cursorVisibility; - SetCursorVisibility (CursorVisibility.Invisible); + Platform.Suspend (); - return false; + if (Force16Colors) + { + Curses.Window.Standard.redrawwin (); + Curses.refresh (); + } } - SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default); - - return _currentCursorVisibility == CursorVisibility.Default; + StartReportingMouseMoves (); } - /// - public override bool GetCursorVisibility (out CursorVisibility visibility) - { - visibility = CursorVisibility.Invisible; + #region Screen and Contents - if (!_currentCursorVisibility.HasValue) + public override int Cols + { + get => Curses.Cols; + internal set { - return false; + Curses.Cols = value; + ClearContents (); } - - visibility = _currentCursorVisibility.Value; - - return true; } - public override string GetVersionInfo () { return $"{Curses.curses_version ()}"; } - - public static bool Is_WSL_Platform () + public override int Rows { - // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell - //if (new CursesClipboard ().IsSupported) { - // // If xclip is installed on Linux under WSL, this will return true. - // return false; - //} - (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true); - - if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) + get => Curses.Lines; + internal set { - return true; + Curses.Lines = value; + ClearContents (); } - - return false; } public override bool IsRuneSupported (Rune rune) @@ -118,330 +88,134 @@ public override void Move (int col, int row) } } - public override void Refresh () + public override void UpdateScreen () { - UpdateScreen (); - UpdateCursor (); - } + if (Force16Colors) + { + for (var row = 0; row < Rows; row++) + { + if (!_dirtyLines [row]) + { + continue; + } - public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control) - { - KeyCode key; + _dirtyLines [row] = false; - if (consoleKey == ConsoleKey.Packet) - { - var mod = new ConsoleModifiers (); + for (var col = 0; col < Cols; col++) + { + if (Contents [row, col].IsDirty == false) + { + continue; + } - if (shift) - { - mod |= ConsoleModifiers.Shift; - } + if (RunningUnitTests) + { + // In unit tests, we don't want to actually write to the screen. + continue; + } - if (alt) - { - mod |= ConsoleModifiers.Alt; + Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().PlatformColor); + + Rune rune = Contents [row, col].Rune; + + if (rune.IsBmp) + { + // BUGBUG: CursesDriver doesn't render CharMap correctly for wide chars (and other Unicode) - Curses is doing something funky with glyphs that report GetColums() of 1 yet are rendered wide. E.g. 0x2064 (invisible times) is reported as 1 column but is rendered as 2. WindowsDriver & NetDriver correctly render this as 1 column, overlapping the next cell. + if (rune.GetColumns () < 2) + { + Curses.mvaddch (row, col, rune.Value); + } + else /*if (col + 1 < Cols)*/ + { + Curses.mvaddwstr (row, col, rune.ToString ()); + } + } + else + { + Curses.mvaddwstr (row, col, rune.ToString ()); + + if (rune.GetColumns () > 1 && col + 1 < Cols) + { + // TODO: This is a hack to deal with non-BMP and wide characters. + //col++; + Curses.mvaddch (row, ++col, '*'); + } + } + } } - if (control) + if (!RunningUnitTests) { - mod |= ConsoleModifiers.Control; + Curses.move (Row, Col); + _window.wrefresh (); } - - var cKeyInfo = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control); - cKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (cKeyInfo); - key = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (cKeyInfo); } else { - key = (KeyCode)keyChar; - } + if (RunningUnitTests + || Console.WindowHeight < 1 + || Contents.Length != Rows * Cols + || Rows != Console.WindowHeight) + { + return; + } - OnKeyDown (new Key (key)); - OnKeyUp (new Key (key)); + var top = 0; + var left = 0; + int rows = Rows; + int cols = Cols; + var output = new StringBuilder (); + Attribute? redrawAttr = null; + int lastCol = -1; - //OnKeyPressed (new KeyEventArgsEventArgs (key)); - } + CursorVisibility? savedVisibility = _currentCursorVisibility; + SetCursorVisibility (CursorVisibility.Invisible); - /// - public override bool SetCursorVisibility (CursorVisibility visibility) - { - if (_initialCursorVisibility.HasValue == false) - { - return false; - } + for (int row = top; row < rows; row++) + { + if (Console.WindowHeight < 1) + { + return; + } - if (!RunningUnitTests) - { - Curses.curs_set (((int)visibility >> 16) & 0x000000FF); - } + if (!_dirtyLines [row]) + { + continue; + } - if (visibility != CursorVisibility.Invisible) - { - Console.Out.Write ( - EscSeqUtils.CSI_SetCursorStyle ( - (EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) - & 0xFF) - ) - ); - } + if (!SetCursorPosition (0, row)) + { + return; + } - _currentCursorVisibility = visibility; + _dirtyLines [row] = false; + output.Clear (); - return true; - } + for (int col = left; col < cols; col++) + { + lastCol = -1; + var outputWidth = 0; - public void StartReportingMouseMoves () - { - if (!RunningUnitTests) - { - Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); - } - } + for (; col < cols; col++) + { + if (!Contents [row, col].IsDirty) + { + if (output.Length > 0) + { + WriteToConsole (output, ref lastCol, row, ref outputWidth); + } + else if (lastCol == -1) + { + lastCol = col; + } - public void StopReportingMouseMoves () - { - if (!RunningUnitTests) - { - Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); - } - } + if (lastCol + 1 < cols) + { + lastCol++; + } - private readonly ManualResetEventSlim _waitAnsiResponse = new (false); - private readonly CancellationTokenSource _ansiResponseTokenSource = new (); - - /// - public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) - { - if (_mainLoopDriver is null) - { - return string.Empty; - } - - try - { - lock (ansiRequest._responseLock) - { - ansiRequest.ResponseFromInput += (s, e) => - { - Debug.Assert (s == ansiRequest); - Debug.Assert (e == ansiRequest.Response); - - _waitAnsiResponse.Set (); - }; - - _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this); - - _mainLoopDriver._forceRead = true; - } - - if (!_ansiResponseTokenSource.IsCancellationRequested) - { - _mainLoopDriver._waitForInput.Set (); - - _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); - } - } - catch (OperationCanceledException) - { - return string.Empty; - } - - lock (ansiRequest._responseLock) - { - _mainLoopDriver._forceRead = false; - - if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) - { - if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0 - && string.IsNullOrEmpty (request.AnsiRequest.Response)) - { - lock (request!.AnsiRequest._responseLock) - { - // Bad request or no response at all - _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _); - } - } - } - - _waitAnsiResponse.Reset (); - - return ansiRequest.Response; - } - } - - /// - public override void WriteRaw (string ansi) - { - _mainLoopDriver.WriteRaw (ansi); - } - - public override void Suspend () - { - StopReportingMouseMoves (); - - if (!RunningUnitTests) - { - Platform.Suspend (); - - if (Force16Colors) - { - Curses.Window.Standard.redrawwin (); - Curses.refresh (); - } - } - - StartReportingMouseMoves (); - } - - public override void UpdateCursor () - { - EnsureCursorVisibility (); - - if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows) - { - if (Force16Colors) - { - Curses.move (Row, Col); - - Curses.raw (); - Curses.noecho (); - Curses.refresh (); - } - else - { - _mainLoopDriver.WriteRaw (EscSeqUtils.CSI_SetCursorPosition (Row + 1, Col + 1)); - } - } - } - - public override void UpdateScreen () - { - if (Force16Colors) - { - for (var row = 0; row < Rows; row++) - { - if (!_dirtyLines [row]) - { - continue; - } - - _dirtyLines [row] = false; - - for (var col = 0; col < Cols; col++) - { - if (Contents [row, col].IsDirty == false) - { - continue; - } - - if (RunningUnitTests) - { - // In unit tests, we don't want to actually write to the screen. - continue; - } - - Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().PlatformColor); - - Rune rune = Contents [row, col].Rune; - - if (rune.IsBmp) - { - // BUGBUG: CursesDriver doesn't render CharMap correctly for wide chars (and other Unicode) - Curses is doing something funky with glyphs that report GetColums() of 1 yet are rendered wide. E.g. 0x2064 (invisible times) is reported as 1 column but is rendered as 2. WindowsDriver & NetDriver correctly render this as 1 column, overlapping the next cell. - if (rune.GetColumns () < 2) - { - Curses.mvaddch (row, col, rune.Value); - } - else /*if (col + 1 < Cols)*/ - { - Curses.mvaddwstr (row, col, rune.ToString ()); - } - } - else - { - Curses.mvaddwstr (row, col, rune.ToString ()); - - if (rune.GetColumns () > 1 && col + 1 < Cols) - { - // TODO: This is a hack to deal with non-BMP and wide characters. - //col++; - Curses.mvaddch (row, ++col, '*'); - } - } - } - } - - if (!RunningUnitTests) - { - Curses.move (Row, Col); - _window.wrefresh (); - } - } - else - { - if (RunningUnitTests - || Console.WindowHeight < 1 - || Contents.Length != Rows * Cols - || Rows != Console.WindowHeight) - { - return; - } - - var top = 0; - var left = 0; - int rows = Rows; - int cols = Cols; - var output = new StringBuilder (); - Attribute? redrawAttr = null; - int lastCol = -1; - - CursorVisibility? savedVisibility = _currentCursorVisibility; - SetCursorVisibility (CursorVisibility.Invisible); - - for (int row = top; row < rows; row++) - { - if (Console.WindowHeight < 1) - { - return; - } - - if (!_dirtyLines [row]) - { - continue; - } - - if (!SetCursorPosition (0, row)) - { - return; - } - - _dirtyLines [row] = false; - output.Clear (); - - for (int col = left; col < cols; col++) - { - lastCol = -1; - var outputWidth = 0; - - for (; col < cols; col++) - { - if (!Contents [row, col].IsDirty) - { - if (output.Length > 0) - { - WriteToConsole (output, ref lastCol, row, ref outputWidth); - } - else if (lastCol == -1) - { - lastCol = col; - } - - if (lastCol + 1 < cols) - { - lastCol++; - } - - continue; - } + continue; + } if (lastCol == -1) { @@ -507,10 +281,10 @@ public override void UpdateScreen () } // SIXELS - foreach (var s in Application.Sixel) + foreach (SixelToRender s in Application.Sixel) { SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y); - Console.Write(s.SixelData); + Console.Write (s.SixelData); } SetCursorPosition (0, 0); @@ -528,39 +302,382 @@ void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int out } } - private bool SetCursorPosition (int col, int row) - { - // + 1 is needed because non-Windows is based on 1 instead of 0 and - // Console.CursorTop/CursorLeft isn't reliable. - Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1)); + #endregion Screen and Contents - return true; - } + #region Color Handling - internal override void End () + public override bool SupportsTrueColor => true; + + /// Creates an Attribute from the provided curses-based foreground and background color numbers + /// Contains the curses color number for the foreground (color, plus any attributes) + /// Contains the curses color number for the background (color, plus any attributes) + /// + private static Attribute MakeColor (short foreground, short background) { - _ansiResponseTokenSource?.Cancel (); - _ansiResponseTokenSource?.Dispose (); - _waitAnsiResponse?.Dispose (); + //var v = (short)((ushort)foreground | (background << 4)); + var v = (short)(((ushort)(foreground & 0xffff) << 16) | (background & 0xffff)); - StopReportingMouseMoves (); - SetCursorVisibility (CursorVisibility.Default); + // TODO: for TrueColor - Use InitExtendedPair + Curses.InitColorPair (v, foreground, background); - if (RunningUnitTests) - { - return; - } + return new ( + Curses.ColorPair (v), + CursesColorNumberToColorName16 (foreground), + CursesColorNumberToColorName16 (background) + ); + } - // throws away any typeahead that has been typed by - // the user and has not yet been read by the program. - Curses.flushinp (); + /// + /// + /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4 + /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are + /// converted to curses color encoding before being encoded. + /// + public override Attribute MakeColor (in Color foreground, in Color background) + { + if (!RunningUnitTests && Force16Colors) + { + return MakeColor ( + ColorNameToCursesColorNumber (foreground.GetClosestNamedColor16 ()), + ColorNameToCursesColorNumber (background.GetClosestNamedColor16 ()) + ); + } - Curses.endwin (); + return new ( + 0, + foreground, + background + ); + } + + private static short ColorNameToCursesColorNumber (ColorName16 color) + { + switch (color) + { + case ColorName16.Black: + return Curses.COLOR_BLACK; + case ColorName16.Blue: + return Curses.COLOR_BLUE; + case ColorName16.Green: + return Curses.COLOR_GREEN; + case ColorName16.Cyan: + return Curses.COLOR_CYAN; + case ColorName16.Red: + return Curses.COLOR_RED; + case ColorName16.Magenta: + return Curses.COLOR_MAGENTA; + case ColorName16.Yellow: + return Curses.COLOR_YELLOW; + case ColorName16.Gray: + return Curses.COLOR_WHITE; + case ColorName16.DarkGray: + return Curses.COLOR_GRAY; + case ColorName16.BrightBlue: + return Curses.COLOR_BLUE | Curses.COLOR_GRAY; + case ColorName16.BrightGreen: + return Curses.COLOR_GREEN | Curses.COLOR_GRAY; + case ColorName16.BrightCyan: + return Curses.COLOR_CYAN | Curses.COLOR_GRAY; + case ColorName16.BrightRed: + return Curses.COLOR_RED | Curses.COLOR_GRAY; + case ColorName16.BrightMagenta: + return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY; + case ColorName16.BrightYellow: + return Curses.COLOR_YELLOW | Curses.COLOR_GRAY; + case ColorName16.White: + return Curses.COLOR_WHITE | Curses.COLOR_GRAY; + } + + throw new ArgumentException ("Invalid color code"); + } + + private static ColorName16 CursesColorNumberToColorName16 (short color) + { + switch (color) + { + case Curses.COLOR_BLACK: + return ColorName16.Black; + case Curses.COLOR_BLUE: + return ColorName16.Blue; + case Curses.COLOR_GREEN: + return ColorName16.Green; + case Curses.COLOR_CYAN: + return ColorName16.Cyan; + case Curses.COLOR_RED: + return ColorName16.Red; + case Curses.COLOR_MAGENTA: + return ColorName16.Magenta; + case Curses.COLOR_YELLOW: + return ColorName16.Yellow; + case Curses.COLOR_WHITE: + return ColorName16.Gray; + case Curses.COLOR_GRAY: + return ColorName16.DarkGray; + case Curses.COLOR_BLUE | Curses.COLOR_GRAY: + return ColorName16.BrightBlue; + case Curses.COLOR_GREEN | Curses.COLOR_GRAY: + return ColorName16.BrightGreen; + case Curses.COLOR_CYAN | Curses.COLOR_GRAY: + return ColorName16.BrightCyan; + case Curses.COLOR_RED | Curses.COLOR_GRAY: + return ColorName16.BrightRed; + case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY: + return ColorName16.BrightMagenta; + case Curses.COLOR_YELLOW | Curses.COLOR_GRAY: + return ColorName16.BrightYellow; + case Curses.COLOR_WHITE | Curses.COLOR_GRAY: + return ColorName16.White; + } + + throw new ArgumentException ("Invalid curses color code"); + } + + #endregion + + #region Cursor Support + + private CursorVisibility? _currentCursorVisibility; + private CursorVisibility? _initialCursorVisibility; + + /// + public override bool EnsureCursorVisibility () + { + if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) + { + GetCursorVisibility (out CursorVisibility cursorVisibility); + _currentCursorVisibility = cursorVisibility; + SetCursorVisibility (CursorVisibility.Invisible); + + return false; + } + + SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default); + + return _currentCursorVisibility == CursorVisibility.Default; + } + + /// + public override bool GetCursorVisibility (out CursorVisibility visibility) + { + visibility = CursorVisibility.Invisible; + + if (!_currentCursorVisibility.HasValue) + { + return false; + } + + visibility = _currentCursorVisibility.Value; + + return true; + } + + /// + public override bool SetCursorVisibility (CursorVisibility visibility) + { + if (_initialCursorVisibility.HasValue == false) + { + return false; + } + + if (!RunningUnitTests) + { + Curses.curs_set (((int)visibility >> 16) & 0x000000FF); + } + + if (visibility != CursorVisibility.Invisible) + { + Console.Out.Write ( + EscSeqUtils.CSI_SetCursorStyle ( + (EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) + & 0xFF) + ) + ); + } + + _currentCursorVisibility = visibility; + + return true; + } + + public override void UpdateCursor () + { + EnsureCursorVisibility (); + + if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows) + { + if (Force16Colors) + { + Curses.move (Row, Col); + + Curses.raw (); + Curses.noecho (); + Curses.refresh (); + } + else + { + _mainLoopDriver.WriteRaw (EscSeqUtils.CSI_SetCursorPosition (Row + 1, Col + 1)); + } + } + } + + #endregion Cursor Support + + #region Keyboard Support + + public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control) + { + KeyCode key; + + if (consoleKey == ConsoleKey.Packet) + { + var mod = new ConsoleModifiers (); + + if (shift) + { + mod |= ConsoleModifiers.Shift; + } + + if (alt) + { + mod |= ConsoleModifiers.Alt; + } + + if (control) + { + mod |= ConsoleModifiers.Control; + } + + var cKeyInfo = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control); + cKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (cKeyInfo); + key = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (cKeyInfo); + } + else + { + key = (KeyCode)keyChar; + } + + OnKeyDown (new (key)); + OnKeyUp (new (key)); + + //OnKeyPressed (new KeyEventArgsEventArgs (key)); + } + + // TODO: Unused- Remove + private static KeyCode MapCursesKey (int cursesKey) + { + switch (cursesKey) + { + case Curses.KeyF1: return KeyCode.F1; + case Curses.KeyF2: return KeyCode.F2; + case Curses.KeyF3: return KeyCode.F3; + case Curses.KeyF4: return KeyCode.F4; + case Curses.KeyF5: return KeyCode.F5; + case Curses.KeyF6: return KeyCode.F6; + case Curses.KeyF7: return KeyCode.F7; + case Curses.KeyF8: return KeyCode.F8; + case Curses.KeyF9: return KeyCode.F9; + case Curses.KeyF10: return KeyCode.F10; + case Curses.KeyF11: return KeyCode.F11; + case Curses.KeyF12: return KeyCode.F12; + case Curses.KeyUp: return KeyCode.CursorUp; + case Curses.KeyDown: return KeyCode.CursorDown; + case Curses.KeyLeft: return KeyCode.CursorLeft; + case Curses.KeyRight: return KeyCode.CursorRight; + case Curses.KeyHome: return KeyCode.Home; + case Curses.KeyEnd: return KeyCode.End; + case Curses.KeyNPage: return KeyCode.PageDown; + case Curses.KeyPPage: return KeyCode.PageUp; + case Curses.KeyDeleteChar: return KeyCode.Delete; + case Curses.KeyInsertChar: return KeyCode.Insert; + case Curses.KeyTab: return KeyCode.Tab; + case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask; + case Curses.KeyBackspace: return KeyCode.Backspace; + case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask; + case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask; + case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask; + case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask; + case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask; + case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask; + case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask; + case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask; + case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask; + case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask; + case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask; + case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask; + case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask; + case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask; + case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask; + case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask; + case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask; + case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask; + case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask; + case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask; + case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask; + case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask; + case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask; + case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask; + case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask; + case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask; + case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask; + case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask; + case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask; + case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask; + case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask; + case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask; + case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask; + case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask; + case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask; + case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask; + case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask; + case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask; + case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask; + case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask; + case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask; + case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask; + case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask; + case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask; + default: return KeyCode.Null; + } + } + + #endregion Keyboard Support + + #region Mouse Support + public void StartReportingMouseMoves () + { + if (!RunningUnitTests) + { + Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); + } + } + + public void StopReportingMouseMoves () + { + if (!RunningUnitTests) + { + Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); + } + } + + #endregion Mouse Support + + private bool SetCursorPosition (int col, int row) + { + // + 1 is needed because non-Windows is based on 1 instead of 0 and + // Console.CursorTop/CursorLeft isn't reliable. + Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1)); + + return true; } + #region Init/End/MainLoop + + public Curses.Window _window; + private UnixMainLoop _mainLoopDriver; + internal override MainLoop Init () { - _mainLoopDriver = new UnixMainLoop (this); + _mainLoopDriver = new (this); if (!RunningUnitTests) { @@ -617,7 +734,7 @@ internal override MainLoop Init () } } - CurrentAttribute = new Attribute (ColorName16.White, ColorName16.Black); + CurrentAttribute = new (ColorName16.White, ColorName16.Black); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { @@ -656,7 +773,7 @@ internal override MainLoop Init () } } - return new MainLoop (_mainLoopDriver); + return new (_mainLoopDriver); } internal void ProcessInput (UnixMainLoop.PollData inputEvent) @@ -673,12 +790,12 @@ internal void ProcessInput (UnixMainLoop.PollData inputEvent) break; } - OnKeyDown (new Key (map)); - OnKeyUp (new Key (map)); + OnKeyDown (new (map)); + OnKeyUp (new (map)); break; case UnixMainLoop.EventType.Mouse: - MouseEventArgs me = new MouseEventArgs { Position = inputEvent.MouseEvent.Position, Flags = inputEvent.MouseEvent.MouseFlags }; + var me = new MouseEventArgs { Position = inputEvent.MouseEvent.Position, Flags = inputEvent.MouseEvent.MouseFlags }; OnMouseEvent (me); break; @@ -691,222 +808,126 @@ internal void ProcessInput (UnixMainLoop.PollData inputEvent) throw new ArgumentOutOfRangeException (); } } - private void ProcessWinChange (Size size) { if (!RunningUnitTests && Curses.ChangeWindowSize (size.Height, size.Width)) { ClearContents (); - OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows))); + OnSizeChanged (new (new (Cols, Rows))); } } - private static KeyCode MapCursesKey (int cursesKey) + internal override void End () { - switch (cursesKey) + _ansiResponseTokenSource?.Cancel (); + _ansiResponseTokenSource?.Dispose (); + _waitAnsiResponse?.Dispose (); + + StopReportingMouseMoves (); + SetCursorVisibility (CursorVisibility.Default); + + if (RunningUnitTests) { - case Curses.KeyF1: return KeyCode.F1; - case Curses.KeyF2: return KeyCode.F2; - case Curses.KeyF3: return KeyCode.F3; - case Curses.KeyF4: return KeyCode.F4; - case Curses.KeyF5: return KeyCode.F5; - case Curses.KeyF6: return KeyCode.F6; - case Curses.KeyF7: return KeyCode.F7; - case Curses.KeyF8: return KeyCode.F8; - case Curses.KeyF9: return KeyCode.F9; - case Curses.KeyF10: return KeyCode.F10; - case Curses.KeyF11: return KeyCode.F11; - case Curses.KeyF12: return KeyCode.F12; - case Curses.KeyUp: return KeyCode.CursorUp; - case Curses.KeyDown: return KeyCode.CursorDown; - case Curses.KeyLeft: return KeyCode.CursorLeft; - case Curses.KeyRight: return KeyCode.CursorRight; - case Curses.KeyHome: return KeyCode.Home; - case Curses.KeyEnd: return KeyCode.End; - case Curses.KeyNPage: return KeyCode.PageDown; - case Curses.KeyPPage: return KeyCode.PageUp; - case Curses.KeyDeleteChar: return KeyCode.Delete; - case Curses.KeyInsertChar: return KeyCode.Insert; - case Curses.KeyTab: return KeyCode.Tab; - case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask; - case Curses.KeyBackspace: return KeyCode.Backspace; - case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask; - case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask; - case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask; - case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask; - case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask; - case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask; - case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask; - case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask; - case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask; - case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask; - case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask; - case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask; - case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask; - case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask; - case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask; - case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask; - case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask; - case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask; - case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask; - case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask; - case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask; - case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask; - case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask; - case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask; - case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask; - case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask; - case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask; - case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask; - case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask; - case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask; - case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask; - case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask; - case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask; - case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask; - case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask; - case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask; - case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask; - case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask; - case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask; - case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask; - case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask; - case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask; - case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask; - case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask; - default: return KeyCode.Null; + return; } + + // throws away any typeahead that has been typed by + // the user and has not yet been read by the program. + Curses.flushinp (); + + Curses.endwin (); } - #region Color Handling + #endregion Init/End/MainLoop - /// Creates an Attribute from the provided curses-based foreground and background color numbers - /// Contains the curses color number for the foreground (color, plus any attributes) - /// Contains the curses color number for the background (color, plus any attributes) - /// - private static Attribute MakeColor (short foreground, short background) + public static bool Is_WSL_Platform () { - //var v = (short)((ushort)foreground | (background << 4)); - var v = (short)(((ushort)(foreground & 0xffff) << 16) | (background & 0xffff)); + // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell + //if (new CursesClipboard ().IsSupported) { + // // If xclip is installed on Linux under WSL, this will return true. + // return false; + //} + (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true); - // TODO: for TrueColor - Use InitExtendedPair - Curses.InitColorPair (v, foreground, background); + if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) + { + return true; + } - return new Attribute ( - Curses.ColorPair (v), - CursesColorNumberToColorName16 (foreground), - CursesColorNumberToColorName16 (background) - ); + return false; } + #region Low-Level Unix Stuff + + + private readonly ManualResetEventSlim _waitAnsiResponse = new (false); + private readonly CancellationTokenSource _ansiResponseTokenSource = new (); /// - /// - /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4 - /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are - /// converted to curses color encoding before being encoded. - /// - public override Attribute MakeColor (in Color foreground, in Color background) + public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { - if (!RunningUnitTests && Force16Colors) + if (_mainLoopDriver is null) { - return MakeColor ( - ColorNameToCursesColorNumber (foreground.GetClosestNamedColor16 ()), - ColorNameToCursesColorNumber (background.GetClosestNamedColor16 ()) - ); + return string.Empty; } - return new Attribute ( - 0, - foreground, - background - ); - } - - private static short ColorNameToCursesColorNumber (ColorName16 color) - { - switch (color) + try { - case ColorName16.Black: - return Curses.COLOR_BLACK; - case ColorName16.Blue: - return Curses.COLOR_BLUE; - case ColorName16.Green: - return Curses.COLOR_GREEN; - case ColorName16.Cyan: - return Curses.COLOR_CYAN; - case ColorName16.Red: - return Curses.COLOR_RED; - case ColorName16.Magenta: - return Curses.COLOR_MAGENTA; - case ColorName16.Yellow: - return Curses.COLOR_YELLOW; - case ColorName16.Gray: - return Curses.COLOR_WHITE; - case ColorName16.DarkGray: - return Curses.COLOR_GRAY; - case ColorName16.BrightBlue: - return Curses.COLOR_BLUE | Curses.COLOR_GRAY; - case ColorName16.BrightGreen: - return Curses.COLOR_GREEN | Curses.COLOR_GRAY; - case ColorName16.BrightCyan: - return Curses.COLOR_CYAN | Curses.COLOR_GRAY; - case ColorName16.BrightRed: - return Curses.COLOR_RED | Curses.COLOR_GRAY; - case ColorName16.BrightMagenta: - return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY; - case ColorName16.BrightYellow: - return Curses.COLOR_YELLOW | Curses.COLOR_GRAY; - case ColorName16.White: - return Curses.COLOR_WHITE | Curses.COLOR_GRAY; - } + lock (ansiRequest._responseLock) + { + ansiRequest.ResponseFromInput += (s, e) => + { + Debug.Assert (s == ansiRequest); + Debug.Assert (e == ansiRequest.Response); - throw new ArgumentException ("Invalid color code"); - } + _waitAnsiResponse.Set (); + }; - private static ColorName16 CursesColorNumberToColorName16 (short color) - { - switch (color) + _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this); + + _mainLoopDriver._forceRead = true; + } + + if (!_ansiResponseTokenSource.IsCancellationRequested) + { + _mainLoopDriver._waitForInput.Set (); + + _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); + } + } + catch (OperationCanceledException) { - case Curses.COLOR_BLACK: - return ColorName16.Black; - case Curses.COLOR_BLUE: - return ColorName16.Blue; - case Curses.COLOR_GREEN: - return ColorName16.Green; - case Curses.COLOR_CYAN: - return ColorName16.Cyan; - case Curses.COLOR_RED: - return ColorName16.Red; - case Curses.COLOR_MAGENTA: - return ColorName16.Magenta; - case Curses.COLOR_YELLOW: - return ColorName16.Yellow; - case Curses.COLOR_WHITE: - return ColorName16.Gray; - case Curses.COLOR_GRAY: - return ColorName16.DarkGray; - case Curses.COLOR_BLUE | Curses.COLOR_GRAY: - return ColorName16.BrightBlue; - case Curses.COLOR_GREEN | Curses.COLOR_GRAY: - return ColorName16.BrightGreen; - case Curses.COLOR_CYAN | Curses.COLOR_GRAY: - return ColorName16.BrightCyan; - case Curses.COLOR_RED | Curses.COLOR_GRAY: - return ColorName16.BrightRed; - case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY: - return ColorName16.BrightMagenta; - case Curses.COLOR_YELLOW | Curses.COLOR_GRAY: - return ColorName16.BrightYellow; - case Curses.COLOR_WHITE | Curses.COLOR_GRAY: - return ColorName16.White; + return string.Empty; } - throw new ArgumentException ("Invalid curses color code"); + lock (ansiRequest._responseLock) + { + _mainLoopDriver._forceRead = false; + + if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) + { + if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0 + && string.IsNullOrEmpty (request.AnsiRequest.Response)) + { + lock (request!.AnsiRequest._responseLock) + { + // Bad request or no response at all + _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _); + } + } + } + + _waitAnsiResponse.Reset (); + + return ansiRequest.Response; + } } - #endregion + /// + public override void WriteRaw (string ansi) { _mainLoopDriver.WriteRaw (ansi); } + } +// TODO: One type per file - move to another file internal static class Platform { private static int _suspendSignal; @@ -986,3 +1007,5 @@ private static int GetSuspendSignal () [DllImport ("libc")] private static extern int uname (nint buf); } + +#endregion Low-Level Unix Stuff diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.c b/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.c index d289b7ef30..6ca9471d2c 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.c +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/GetTIOCGWINSZ.c @@ -1,11 +1,12 @@ #include #include -// This function is used to get the value of the TIOCGWINSZ variable, +// Used to get the value of the TIOCGWINSZ variable, // which may have different values ​​on different Unix operating systems. -// In Linux=0x005413, in Darwin and OpenBSD=0x40087468, -// In Solaris=0x005468 -// The best solution is having a function that get the real value of the current OS +// Linux=0x005413 +// Darwin and OpenBSD=0x40087468, +// Solaris=0x005468 +// See https://stackoverflow.com/questions/16237137/what-is-termios-tiocgwinsz int get_tiocgwinsz_value() { return TIOCGWINSZ; } \ No newline at end of file diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs index c96c8f08bb..280f3f9e71 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs @@ -4,20 +4,7 @@ namespace Terminal.Gui; -/// -/// Represents the status of an ANSI escape sequence request made to the terminal using -/// . -/// -/// -public class EscSeqReqStatus -{ - /// Creates a new state of escape sequence request. - /// The object. - public EscSeqReqStatus (AnsiEscapeSequenceRequest ansiRequest) { AnsiRequest = ansiRequest; } - - /// Gets the Escape Sequence Terminator (e.g. ESC[8t ... t is the terminator). - public AnsiEscapeSequenceRequest AnsiRequest { get; } -} +// QUESTION: Can this class be moved/refactored/combined with the new AnsiEscapeSequenceRequest/Response class? // TODO: This class is a singleton. It should use the singleton pattern. /// diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReqStatus.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReqStatus.cs new file mode 100644 index 0000000000..c9561ec7bf --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReqStatus.cs @@ -0,0 +1,17 @@ +#nullable enable +namespace Terminal.Gui; + +/// +/// Represents the status of an ANSI escape sequence request made to the terminal using +/// . +/// +/// +public class EscSeqReqStatus +{ + /// Creates a new state of escape sequence request. + /// The object. + public EscSeqReqStatus (AnsiEscapeSequenceRequest ansiRequest) { AnsiRequest = ansiRequest; } + + /// Gets the Escape Sequence Terminator (e.g. ESC[8t ... t is the terminator). + public AnsiEscapeSequenceRequest AnsiRequest { get; } +} diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 4b283afb10..99e5bce8f9 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -3,6 +3,13 @@ namespace Terminal.Gui; +// QUESTION: Should this class be refactored into separate classes for: +// QUESTION: CSI definitions +// QUESTION: Primitives like DecodeEsqReq +// QUESTION: Screen/Color/Cursor handling +// QUESTION: Mouse handling +// QUESTION: Keyboard handling + /// /// Provides a platform-independent API for managing ANSI escape sequences. /// @@ -14,6 +21,7 @@ namespace Terminal.Gui; /// public static class EscSeqUtils { + // TODO: One type per file - Move this enum to a separate file. /// /// Options for ANSI ESC "[xJ" - Clears part of the screen. /// @@ -40,6 +48,9 @@ public enum ClearScreenOptions EntireScreenAndScrollbackBuffer = 3 } + // QUESTION: I wonder if EscSeqUtils.CSI_... should be more strongly typed such that this (and Terminator could be + // QUESTION: public required CSIRequests Request { get; init; } + // QUESTION: public required CSITerminators Terminator { get; init; } /// /// Escape key code (ASCII 27/0x1B). /// @@ -419,6 +430,7 @@ public static string GetC1ControlChar (in char c) }; } + /// /// Gets the depending on terminating and value. /// @@ -1721,7 +1733,7 @@ public enum DECSCUSR_Style /// https://terminalguide.namepad.de/seq/csi_st-18/ /// The terminator indicating a reply to : ESC [ 8 ; height ; width t /// - public static readonly AnsiEscapeSequenceRequest CSI_ReportTerminalSizeInChars = new () { Request = CSI + "18t", Terminator = "t", Value = "8" }; + public static readonly AnsiEscapeSequenceRequest CSI_ReportTerminalSizeInChars = new () { Request = CSI + "18t", Terminator = "t", ExpectedResponseValue = "8" }; #endregion } diff --git a/Terminal.Gui/ConsoleDrivers/KeyCode.cs b/Terminal.Gui/ConsoleDrivers/KeyCode.cs new file mode 100644 index 0000000000..183322ec80 --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/KeyCode.cs @@ -0,0 +1,321 @@ +#nullable enable +namespace Terminal.Gui; + +/// +/// The enumeration encodes key information from s and provides a +/// consistent way for application code to specify keys and receive key events. +/// +/// The class provides a higher-level abstraction, with helper methods and properties for +/// common operations. For example, and provide a convenient way +/// to check whether the Alt or Ctrl modifier keys were pressed when a key was pressed. +/// +/// +/// +/// +/// Lowercase alpha keys are encoded as values between 65 and 90 corresponding to the un-shifted A to Z keys on a +/// keyboard. Enum values are provided for these (e.g. , , etc.). +/// Even though the values are the same as the ASCII values for uppercase characters, these enum values represent +/// *lowercase*, un-shifted characters. +/// +/// +/// Numeric keys are the values between 48 and 57 corresponding to 0 to 9 (e.g. , +/// , etc.). +/// +/// +/// The shift modifiers (, , and +/// ) can be combined (with logical or) with the other key codes to represent shifted +/// keys. For example, the enum value represents the un-shifted 'a' key, while +/// | represents the 'A' key (shifted 'a' key). Likewise, +/// | represents the 'Alt+A' key combination. +/// +/// +/// All other keys that produce a printable character are encoded as the Unicode value of the character. For +/// example, the for the '!' character is 33, which is the Unicode value for '!'. Likewise, +/// `â` is 226, `Â` is 194, etc. +/// +/// +/// If the is set, then the value is that of the special mask, otherwise, the value is +/// the one of the lower bits (as extracted by ). +/// +/// +[Flags] +public enum KeyCode : uint +{ + /// + /// Mask that indicates that the key is a unicode codepoint. Values outside this range indicate the key has shift + /// modifiers or is a special key like function keys, arrows keys and so on. + /// + CharMask = 0x_f_ffff, + + /// + /// If the is set, then the value is that of the special mask, otherwise, the value is + /// in the lower bits (as extracted by ). + /// + SpecialMask = 0x_fff0_0000, + + /// + /// When this value is set, the Key encodes the sequence Shift-KeyValue. The actual value must be extracted by + /// removing the ShiftMask. + /// + ShiftMask = 0x_1000_0000, + + /// + /// When this value is set, the Key encodes the sequence Alt-KeyValue. The actual value must be extracted by + /// removing the AltMask. + /// + AltMask = 0x_8000_0000, + + /// + /// When this value is set, the Key encodes the sequence Ctrl-KeyValue. The actual value must be extracted by + /// removing the CtrlMask. + /// + CtrlMask = 0x_4000_0000, + + /// The key code representing an invalid or empty key. + Null = 0, + + /// Backspace key. + Backspace = 8, + + /// The key code for the tab key (forwards tab key). + Tab = 9, + + /// The key code for the return key. + Enter = ConsoleKey.Enter, + + /// The key code for the clear key. + Clear = 12, + + /// The key code for the escape key. + Esc = 27, + + /// The key code for the space bar key. + Space = 32, + + /// Digit 0. + D0 = 48, + + /// Digit 1. + D1, + + /// Digit 2. + D2, + + /// Digit 3. + D3, + + /// Digit 4. + D4, + + /// Digit 5. + D5, + + /// Digit 6. + D6, + + /// Digit 7. + D7, + + /// Digit 8. + D8, + + /// Digit 9. + D9, + + /// The key code for the A key + A = 65, + + /// The key code for the B key + B, + + /// The key code for the C key + C, + + /// The key code for the D key + D, + + /// The key code for the E key + E, + + /// The key code for the F key + F, + + /// The key code for the G key + G, + + /// The key code for the H key + H, + + /// The key code for the I key + I, + + /// The key code for the J key + J, + + /// The key code for the K key + K, + + /// The key code for the L key + L, + + /// The key code for the M key + M, + + /// The key code for the N key + N, + + /// The key code for the O key + O, + + /// The key code for the P key + P, + + /// The key code for the Q key + Q, + + /// The key code for the R key + R, + + /// The key code for the S key + S, + + /// The key code for the T key + T, + + /// The key code for the U key + U, + + /// The key code for the V key + V, + + /// The key code for the W key + W, + + /// The key code for the X key + X, + + /// The key code for the Y key + Y, + + /// The key code for the Z key + Z, + + ///// + ///// The key code for the Delete key. + ///// + //Delete = 127, + + // --- Special keys --- + // The values below are common non-alphanum keys. Their values are + // based on the .NET ConsoleKey values, which, in-turn are based on the + // VK_ values from the Windows API. + // We add MaxCodePoint to avoid conflicts with the Unicode values. + + /// The maximum Unicode codepoint value. Used to encode the non-alphanumeric control keys. + MaxCodePoint = 0x10FFFF, + + /// Cursor up key + CursorUp = MaxCodePoint + ConsoleKey.UpArrow, + + /// Cursor down key. + CursorDown = MaxCodePoint + ConsoleKey.DownArrow, + + /// Cursor left key. + CursorLeft = MaxCodePoint + ConsoleKey.LeftArrow, + + /// Cursor right key. + CursorRight = MaxCodePoint + ConsoleKey.RightArrow, + + /// Page Up key. + PageUp = MaxCodePoint + ConsoleKey.PageUp, + + /// Page Down key. + PageDown = MaxCodePoint + ConsoleKey.PageDown, + + /// Home key. + Home = MaxCodePoint + ConsoleKey.Home, + + /// End key. + End = MaxCodePoint + ConsoleKey.End, + + /// Insert (INS) key. + Insert = MaxCodePoint + ConsoleKey.Insert, + + /// Delete (DEL) key. + Delete = MaxCodePoint + ConsoleKey.Delete, + + /// Print screen character key. + PrintScreen = MaxCodePoint + ConsoleKey.PrintScreen, + + /// F1 key. + F1 = MaxCodePoint + ConsoleKey.F1, + + /// F2 key. + F2 = MaxCodePoint + ConsoleKey.F2, + + /// F3 key. + F3 = MaxCodePoint + ConsoleKey.F3, + + /// F4 key. + F4 = MaxCodePoint + ConsoleKey.F4, + + /// F5 key. + F5 = MaxCodePoint + ConsoleKey.F5, + + /// F6 key. + F6 = MaxCodePoint + ConsoleKey.F6, + + /// F7 key. + F7 = MaxCodePoint + ConsoleKey.F7, + + /// F8 key. + F8 = MaxCodePoint + ConsoleKey.F8, + + /// F9 key. + F9 = MaxCodePoint + ConsoleKey.F9, + + /// F10 key. + F10 = MaxCodePoint + ConsoleKey.F10, + + /// F11 key. + F11 = MaxCodePoint + ConsoleKey.F11, + + /// F12 key. + F12 = MaxCodePoint + ConsoleKey.F12, + + /// F13 key. + F13 = MaxCodePoint + ConsoleKey.F13, + + /// F14 key. + F14 = MaxCodePoint + ConsoleKey.F14, + + /// F15 key. + F15 = MaxCodePoint + ConsoleKey.F15, + + /// F16 key. + F16 = MaxCodePoint + ConsoleKey.F16, + + /// F17 key. + F17 = MaxCodePoint + ConsoleKey.F17, + + /// F18 key. + F18 = MaxCodePoint + ConsoleKey.F18, + + /// F19 key. + F19 = MaxCodePoint + ConsoleKey.F19, + + /// F20 key. + F20 = MaxCodePoint + ConsoleKey.F20, + + /// F21 key. + F21 = MaxCodePoint + ConsoleKey.F21, + + /// F22 key. + F22 = MaxCodePoint + ConsoleKey.F22, + + /// F23 key. + F23 = MaxCodePoint + ConsoleKey.F23, + + /// F24 key. + F24 = MaxCodePoint + ConsoleKey.F24 +} diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs deleted file mode 100644 index afa78ff6a2..0000000000 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ /dev/null @@ -1,2007 +0,0 @@ -// -// NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient. -// - -using System.Collections.Concurrent; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Runtime.InteropServices; -using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping; -using static Terminal.Gui.NetEvents; - -namespace Terminal.Gui; - -internal class NetWinVTConsole -{ - private const uint DISABLE_NEWLINE_AUTO_RETURN = 8; - private const uint ENABLE_ECHO_INPUT = 4; - private const uint ENABLE_EXTENDED_FLAGS = 128; - private const uint ENABLE_INSERT_MODE = 32; - private const uint ENABLE_LINE_INPUT = 2; - private const uint ENABLE_LVB_GRID_WORLDWIDE = 10; - private const uint ENABLE_MOUSE_INPUT = 16; - - // Input modes. - private const uint ENABLE_PROCESSED_INPUT = 1; - - // Output modes. - private const uint ENABLE_PROCESSED_OUTPUT = 1; - private const uint ENABLE_QUICK_EDIT_MODE = 64; - private const uint ENABLE_VIRTUAL_TERMINAL_INPUT = 512; - private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4; - private const uint ENABLE_WINDOW_INPUT = 8; - private const uint ENABLE_WRAP_AT_EOL_OUTPUT = 2; - private const int STD_ERROR_HANDLE = -12; - private const int STD_INPUT_HANDLE = -10; - private const int STD_OUTPUT_HANDLE = -11; - - private readonly nint _errorHandle; - private readonly nint _inputHandle; - private readonly uint _originalErrorConsoleMode; - private readonly uint _originalInputConsoleMode; - private readonly uint _originalOutputConsoleMode; - private readonly nint _outputHandle; - - public NetWinVTConsole () - { - _inputHandle = GetStdHandle (STD_INPUT_HANDLE); - - if (!GetConsoleMode (_inputHandle, out uint mode)) - { - throw new ApplicationException ($"Failed to get input console mode, error code: {GetLastError ()}."); - } - - _originalInputConsoleMode = mode; - - if ((mode & ENABLE_VIRTUAL_TERMINAL_INPUT) < ENABLE_VIRTUAL_TERMINAL_INPUT) - { - mode |= ENABLE_VIRTUAL_TERMINAL_INPUT; - - if (!SetConsoleMode (_inputHandle, mode)) - { - throw new ApplicationException ($"Failed to set input console mode, error code: {GetLastError ()}."); - } - } - - _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE); - - if (!GetConsoleMode (_outputHandle, out mode)) - { - throw new ApplicationException ($"Failed to get output console mode, error code: {GetLastError ()}."); - } - - _originalOutputConsoleMode = mode; - - if ((mode & (ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN) - { - mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN; - - if (!SetConsoleMode (_outputHandle, mode)) - { - throw new ApplicationException ($"Failed to set output console mode, error code: {GetLastError ()}."); - } - } - - _errorHandle = GetStdHandle (STD_ERROR_HANDLE); - - if (!GetConsoleMode (_errorHandle, out mode)) - { - throw new ApplicationException ($"Failed to get error console mode, error code: {GetLastError ()}."); - } - - _originalErrorConsoleMode = mode; - - if ((mode & DISABLE_NEWLINE_AUTO_RETURN) < DISABLE_NEWLINE_AUTO_RETURN) - { - mode |= DISABLE_NEWLINE_AUTO_RETURN; - - if (!SetConsoleMode (_errorHandle, mode)) - { - throw new ApplicationException ($"Failed to set error console mode, error code: {GetLastError ()}."); - } - } - } - - public void Cleanup () - { - if (!SetConsoleMode (_inputHandle, _originalInputConsoleMode)) - { - throw new ApplicationException ($"Failed to restore input console mode, error code: {GetLastError ()}."); - } - - if (!SetConsoleMode (_outputHandle, _originalOutputConsoleMode)) - { - throw new ApplicationException ($"Failed to restore output console mode, error code: {GetLastError ()}."); - } - - if (!SetConsoleMode (_errorHandle, _originalErrorConsoleMode)) - { - throw new ApplicationException ($"Failed to restore error console mode, error code: {GetLastError ()}."); - } - } - - [DllImport ("kernel32.dll")] - private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode); - - [DllImport ("kernel32.dll")] - private static extern uint GetLastError (); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern nint GetStdHandle (int nStdHandle); - - [DllImport ("kernel32.dll")] - private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode); -} - -internal class NetEvents : IDisposable -{ - private readonly ManualResetEventSlim _inputReady = new (false); - private CancellationTokenSource _inputReadyCancellationTokenSource; - internal readonly ManualResetEventSlim _waitForStart = new (false); - - //CancellationTokenSource _waitForStartCancellationTokenSource; - private readonly ManualResetEventSlim _winChange = new (false); - private readonly ConcurrentQueue _inputQueue = new (); - private readonly ConsoleDriver _consoleDriver; - private ConsoleKeyInfo [] _cki; - private bool _isEscSeq; -#if PROCESS_REQUEST - bool _neededProcessRequest; -#endif - public EscSeqRequests EscSeqRequests { get; } = new (); - - public NetEvents (ConsoleDriver consoleDriver) - { - _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver)); - _inputReadyCancellationTokenSource = new CancellationTokenSource (); - - Task.Run (ProcessInputQueue, _inputReadyCancellationTokenSource.Token); - - Task.Run (CheckWindowSizeChange, _inputReadyCancellationTokenSource.Token); - } - - public InputResult? DequeueInput () - { - while (_inputReadyCancellationTokenSource != null - && !_inputReadyCancellationTokenSource.Token.IsCancellationRequested) - { - _waitForStart.Set (); - _winChange.Set (); - - try - { - if (!_inputReadyCancellationTokenSource.Token.IsCancellationRequested) - { - if (_inputQueue.Count == 0) - { - _inputReady.Wait (_inputReadyCancellationTokenSource.Token); - } - } - } - catch (OperationCanceledException) - { - return null; - } - finally - { - _inputReady.Reset (); - } - -#if PROCESS_REQUEST - _neededProcessRequest = false; -#endif - if (_inputQueue.Count > 0) - { - if (_inputQueue.TryDequeue (out InputResult? result)) - { - return result; - } - } - } - - return null; - } - - private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, bool intercept = true) - { - while (!cancellationToken.IsCancellationRequested) - { - // if there is a key available, return it without waiting - // (or dispatching work to the thread queue) - if (Console.KeyAvailable) - { - return Console.ReadKey (intercept); - } - - if (EscSeqUtils.IncompleteCkInfos is null && EscSeqRequests is { Statuses.Count: > 0 }) - { - if (_retries > 1) - { - if (EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) - { - lock (seqReqStatus!.AnsiRequest._responseLock) - { - EscSeqRequests.Statuses.TryDequeue (out _); - - seqReqStatus.AnsiRequest.Response = string.Empty; - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); - } - } - - _retries = 0; - } - else - { - _retries++; - } - } - else - { - _retries = 0; - } - - if (!_forceRead) - { - Task.Delay (100, cancellationToken).Wait (cancellationToken); - } - } - - cancellationToken.ThrowIfCancellationRequested (); - - return default (ConsoleKeyInfo); - } - - internal bool _forceRead; - private int _retries; - - private void ProcessInputQueue () - { - while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false }) - { - try - { - if (!_forceRead) - { - _waitForStart.Wait (_inputReadyCancellationTokenSource.Token); - } - } - catch (OperationCanceledException) - { - return; - } - - _waitForStart.Reset (); - - if (_inputQueue.Count == 0 || _forceRead) - { - ConsoleKey key = 0; - ConsoleModifiers mod = 0; - ConsoleKeyInfo newConsoleKeyInfo = default; - - while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false }) - { - ConsoleKeyInfo consoleKeyInfo; - - try - { - consoleKeyInfo = ReadConsoleKeyInfo (_inputReadyCancellationTokenSource.Token); - } - catch (OperationCanceledException) - { - return; - } - - if (EscSeqUtils.IncompleteCkInfos is { }) - { - EscSeqUtils.InsertArray (EscSeqUtils.IncompleteCkInfos, _cki); - } - - if ((consoleKeyInfo.KeyChar == (char)KeyCode.Esc && !_isEscSeq) - || (consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq)) - { - if (_cki is null && consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq) - { - _cki = EscSeqUtils.ResizeArray ( - new ConsoleKeyInfo ( - (char)KeyCode.Esc, - 0, - false, - false, - false - ), - _cki - ); - } - - _isEscSeq = true; - - if ((_cki is { } && _cki [^1].KeyChar != Key.Esc && consoleKeyInfo.KeyChar != Key.Esc && consoleKeyInfo.KeyChar <= Key.Space) - || (_cki is { } && _cki [^1].KeyChar != '\u001B' && consoleKeyInfo.KeyChar == 127) - || (_cki is { } && char.IsLetter (_cki [^1].KeyChar) && char.IsLower (consoleKeyInfo.KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar)) - || (_cki is { Length: > 2 } && char.IsLetter (_cki [^1].KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar))) - { - ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); - _cki = null; - _isEscSeq = false; - - ProcessMapConsoleKeyInfo (consoleKeyInfo); - } - else - { - newConsoleKeyInfo = consoleKeyInfo; - _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki); - - if (Console.KeyAvailable) - { - continue; - } - - ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); - _cki = null; - _isEscSeq = false; - } - - break; - } - - if (consoleKeyInfo.KeyChar == (char)KeyCode.Esc && _isEscSeq && _cki is { }) - { - ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); - _cki = null; - - if (Console.KeyAvailable) - { - _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki); - } - else - { - ProcessMapConsoleKeyInfo (consoleKeyInfo); - } - - break; - } - - ProcessMapConsoleKeyInfo (consoleKeyInfo); - - if (_retries > 0) - { - _retries = 0; - } - - break; - } - } - - _inputReady.Set (); - } - - void ProcessMapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) - { - _inputQueue.Enqueue ( - new InputResult - { - EventType = EventType.Key, ConsoleKeyInfo = EscSeqUtils.MapConsoleKeyInfo (consoleKeyInfo) - } - ); - _isEscSeq = false; - } - } - - private void CheckWindowSizeChange () - { - void RequestWindowSize (CancellationToken cancellationToken) - { - while (!cancellationToken.IsCancellationRequested) - { - // Wait for a while then check if screen has changed sizes - Task.Delay (500, cancellationToken).Wait (cancellationToken); - - int buffHeight, buffWidth; - - if (((NetDriver)_consoleDriver).IsWinPlatform) - { - buffHeight = Math.Max (Console.BufferHeight, 0); - buffWidth = Math.Max (Console.BufferWidth, 0); - } - else - { - buffHeight = _consoleDriver.Rows; - buffWidth = _consoleDriver.Cols; - } - - if (EnqueueWindowSizeEvent ( - Math.Max (Console.WindowHeight, 0), - Math.Max (Console.WindowWidth, 0), - buffHeight, - buffWidth - )) - { - return; - } - } - - cancellationToken.ThrowIfCancellationRequested (); - } - - while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false }) - { - try - { - _winChange.Wait (_inputReadyCancellationTokenSource.Token); - _winChange.Reset (); - - RequestWindowSize (_inputReadyCancellationTokenSource.Token); - } - catch (OperationCanceledException) - { - return; - } - - _inputReady.Set (); - } - } - - /// Enqueue a window size event if the window size has changed. - /// - /// - /// - /// - /// - private bool EnqueueWindowSizeEvent (int winHeight, int winWidth, int buffHeight, int buffWidth) - { - if (winWidth == _consoleDriver.Cols && winHeight == _consoleDriver.Rows) - { - return false; - } - - int w = Math.Max (winWidth, 0); - int h = Math.Max (winHeight, 0); - - _inputQueue.Enqueue ( - new InputResult - { - EventType = EventType.WindowSize, WindowSizeEvent = new WindowSizeEvent { Size = new (w, h) } - } - ); - - return true; - } - - // Process a CSI sequence received by the driver (key pressed, mouse event, or request/response event) - private void ProcessRequestResponse ( - ref ConsoleKeyInfo newConsoleKeyInfo, - ref ConsoleKey key, - ConsoleKeyInfo [] cki, - ref ConsoleModifiers mod - ) - { - // isMouse is true if it's CSI<, false otherwise - EscSeqUtils.DecodeEscSeq ( - EscSeqRequests, - ref newConsoleKeyInfo, - ref key, - cki, - ref mod, - out string c1Control, - out string code, - out string [] values, - out string terminating, - out bool isMouse, - out List mouseFlags, - out Point pos, - out EscSeqReqStatus seqReqStatus, - (f, p) => HandleMouseEvent (MapMouseFlags (f), p) - ); - - if (isMouse) - { - foreach (MouseFlags mf in mouseFlags) - { - HandleMouseEvent (MapMouseFlags (mf), pos); - } - - return; - } - - if (seqReqStatus is { }) - { - //HandleRequestResponseEvent (c1Control, code, values, terminating); - - var ckiString = EscSeqUtils.ToString (cki); - - lock (seqReqStatus.AnsiRequest._responseLock) - { - seqReqStatus.AnsiRequest.Response = ckiString; - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, ckiString); - } - - return; - } - - if (!string.IsNullOrEmpty (EscSeqUtils.InvalidRequestTerminator)) - { - if (EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus result)) - { - lock (result.AnsiRequest._responseLock) - { - result.AnsiRequest.Response = EscSeqUtils.InvalidRequestTerminator; - result.AnsiRequest.RaiseResponseFromInput (result.AnsiRequest, EscSeqUtils.InvalidRequestTerminator); - - EscSeqUtils.InvalidRequestTerminator = null; - } - } - - return; - } - - if (newConsoleKeyInfo != default) - { - HandleKeyboardEvent (newConsoleKeyInfo); - } - } - - [UnconditionalSuppressMessage ("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "")] - private MouseButtonState MapMouseFlags (MouseFlags mouseFlags) - { - MouseButtonState mbs = default; - - foreach (object flag in Enum.GetValues (mouseFlags.GetType ())) - { - if (mouseFlags.HasFlag ((MouseFlags)flag)) - { - switch (flag) - { - case MouseFlags.Button1Pressed: - mbs |= MouseButtonState.Button1Pressed; - - break; - case MouseFlags.Button1Released: - mbs |= MouseButtonState.Button1Released; - - break; - case MouseFlags.Button1Clicked: - mbs |= MouseButtonState.Button1Clicked; - - break; - case MouseFlags.Button1DoubleClicked: - mbs |= MouseButtonState.Button1DoubleClicked; - - break; - case MouseFlags.Button1TripleClicked: - mbs |= MouseButtonState.Button1TripleClicked; - - break; - case MouseFlags.Button2Pressed: - mbs |= MouseButtonState.Button2Pressed; - - break; - case MouseFlags.Button2Released: - mbs |= MouseButtonState.Button2Released; - - break; - case MouseFlags.Button2Clicked: - mbs |= MouseButtonState.Button2Clicked; - - break; - case MouseFlags.Button2DoubleClicked: - mbs |= MouseButtonState.Button2DoubleClicked; - - break; - case MouseFlags.Button2TripleClicked: - mbs |= MouseButtonState.Button2TripleClicked; - - break; - case MouseFlags.Button3Pressed: - mbs |= MouseButtonState.Button3Pressed; - - break; - case MouseFlags.Button3Released: - mbs |= MouseButtonState.Button3Released; - - break; - case MouseFlags.Button3Clicked: - mbs |= MouseButtonState.Button3Clicked; - - break; - case MouseFlags.Button3DoubleClicked: - mbs |= MouseButtonState.Button3DoubleClicked; - - break; - case MouseFlags.Button3TripleClicked: - mbs |= MouseButtonState.Button3TripleClicked; - - break; - case MouseFlags.WheeledUp: - mbs |= MouseButtonState.ButtonWheeledUp; - - break; - case MouseFlags.WheeledDown: - mbs |= MouseButtonState.ButtonWheeledDown; - - break; - case MouseFlags.WheeledLeft: - mbs |= MouseButtonState.ButtonWheeledLeft; - - break; - case MouseFlags.WheeledRight: - mbs |= MouseButtonState.ButtonWheeledRight; - - break; - case MouseFlags.Button4Pressed: - mbs |= MouseButtonState.Button4Pressed; - - break; - case MouseFlags.Button4Released: - mbs |= MouseButtonState.Button4Released; - - break; - case MouseFlags.Button4Clicked: - mbs |= MouseButtonState.Button4Clicked; - - break; - case MouseFlags.Button4DoubleClicked: - mbs |= MouseButtonState.Button4DoubleClicked; - - break; - case MouseFlags.Button4TripleClicked: - mbs |= MouseButtonState.Button4TripleClicked; - - break; - case MouseFlags.ButtonShift: - mbs |= MouseButtonState.ButtonShift; - - break; - case MouseFlags.ButtonCtrl: - mbs |= MouseButtonState.ButtonCtrl; - - break; - case MouseFlags.ButtonAlt: - mbs |= MouseButtonState.ButtonAlt; - - break; - case MouseFlags.ReportMousePosition: - mbs |= MouseButtonState.ReportMousePosition; - - break; - case MouseFlags.AllEvents: - mbs |= MouseButtonState.AllEvents; - - break; - } - } - } - - return mbs; - } - - private Point _lastCursorPosition; - - //private void HandleRequestResponseEvent (string c1Control, string code, string [] values, string terminating) - //{ - // if (terminating == - - // // BUGBUG: I can't find where we send a request for cursor position (ESC[?6n), so I'm not sure if this is needed. - // // The observation is correct because the response isn't immediate and this is useless - // EscSeqUtils.CSI_RequestCursorPositionReport.Terminator) - // { - // var point = new Point { X = int.Parse (values [1]) - 1, Y = int.Parse (values [0]) - 1 }; - - // if (_lastCursorPosition.Y != point.Y) - // { - // _lastCursorPosition = point; - // var eventType = EventType.WindowPosition; - // var winPositionEv = new WindowPositionEvent { CursorPosition = point }; - - // _inputQueue.Enqueue ( - // new InputResult { EventType = eventType, WindowPositionEvent = winPositionEv } - // ); - // } - // else - // { - // return; - // } - // } - // else if (terminating == EscSeqUtils.CSI_ReportTerminalSizeInChars.Terminator) - // { - // if (values [0] == EscSeqUtils.CSI_ReportTerminalSizeInChars.Value) - // { - // EnqueueWindowSizeEvent ( - // Math.Max (int.Parse (values [1]), 0), - // Math.Max (int.Parse (values [2]), 0), - // Math.Max (int.Parse (values [1]), 0), - // Math.Max (int.Parse (values [2]), 0) - // ); - // } - // else - // { - // EnqueueRequestResponseEvent (c1Control, code, values, terminating); - // } - // } - // else - // { - // EnqueueRequestResponseEvent (c1Control, code, values, terminating); - // } - - // _inputReady.Set (); - //} - - //private void EnqueueRequestResponseEvent (string c1Control, string code, string [] values, string terminating) - //{ - // var eventType = EventType.RequestResponse; - // var requestRespEv = new RequestResponseEvent { ResultTuple = (c1Control, code, values, terminating) }; - - // _inputQueue.Enqueue ( - // new InputResult { EventType = eventType, RequestResponseEvent = requestRespEv } - // ); - //} - - private void HandleMouseEvent (MouseButtonState buttonState, Point pos) - { - var mouseEvent = new MouseEvent { Position = pos, ButtonState = buttonState }; - - _inputQueue.Enqueue ( - new InputResult { EventType = EventType.Mouse, MouseEvent = mouseEvent } - ); - - _inputReady.Set (); - } - - public enum EventType - { - Key = 1, - Mouse = 2, - WindowSize = 3, - WindowPosition = 4, - RequestResponse = 5 - } - - [Flags] - public enum MouseButtonState - { - Button1Pressed = 0x1, - Button1Released = 0x2, - Button1Clicked = 0x4, - Button1DoubleClicked = 0x8, - Button1TripleClicked = 0x10, - Button2Pressed = 0x20, - Button2Released = 0x40, - Button2Clicked = 0x80, - Button2DoubleClicked = 0x100, - Button2TripleClicked = 0x200, - Button3Pressed = 0x400, - Button3Released = 0x800, - Button3Clicked = 0x1000, - Button3DoubleClicked = 0x2000, - Button3TripleClicked = 0x4000, - ButtonWheeledUp = 0x8000, - ButtonWheeledDown = 0x10000, - ButtonWheeledLeft = 0x20000, - ButtonWheeledRight = 0x40000, - Button4Pressed = 0x80000, - Button4Released = 0x100000, - Button4Clicked = 0x200000, - Button4DoubleClicked = 0x400000, - Button4TripleClicked = 0x800000, - ButtonShift = 0x1000000, - ButtonCtrl = 0x2000000, - ButtonAlt = 0x4000000, - ReportMousePosition = 0x8000000, - AllEvents = -1 - } - - public struct MouseEvent - { - public Point Position; - public MouseButtonState ButtonState; - } - - public struct WindowSizeEvent - { - public Size Size; - } - - public struct WindowPositionEvent - { - public int Top; - public int Left; - public Point CursorPosition; - } - - public struct RequestResponseEvent - { - public (string c1Control, string code, string [] values, string terminating) ResultTuple; - } - - public struct InputResult - { - public EventType EventType; - public ConsoleKeyInfo ConsoleKeyInfo; - public MouseEvent MouseEvent; - public WindowSizeEvent WindowSizeEvent; - public WindowPositionEvent WindowPositionEvent; - public RequestResponseEvent RequestResponseEvent; - - public readonly override string ToString () - { - return EventType switch - { - EventType.Key => ToString (ConsoleKeyInfo), - EventType.Mouse => MouseEvent.ToString (), - - //EventType.WindowSize => WindowSize.ToString (), - //EventType.RequestResponse => RequestResponse.ToString (), - _ => "Unknown event type: " + EventType - }; - } - - /// Prints a ConsoleKeyInfoEx structure - /// - /// - public readonly string ToString (ConsoleKeyInfo cki) - { - var ke = new Key ((KeyCode)cki.KeyChar); - var sb = new StringBuilder (); - sb.Append ($"Key: {(KeyCode)cki.Key} ({cki.Key})"); - sb.Append ((cki.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty); - sb.Append ((cki.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty); - sb.Append ((cki.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty); - sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)cki.KeyChar}) "); - string s = sb.ToString ().TrimEnd (',').TrimEnd (' '); - - return $"[ConsoleKeyInfo({s})]"; - } - } - - private void HandleKeyboardEvent (ConsoleKeyInfo cki) - { - var inputResult = new InputResult { EventType = EventType.Key, ConsoleKeyInfo = cki }; - - _inputQueue.Enqueue (inputResult); - } - - public void Dispose () - { - _inputReadyCancellationTokenSource?.Cancel (); - _inputReadyCancellationTokenSource?.Dispose (); - _inputReadyCancellationTokenSource = null; - - try - { - // throws away any typeahead that has been typed by - // the user and has not yet been read by the program. - while (Console.KeyAvailable) - { - Console.ReadKey (true); - } - } - catch (InvalidOperationException) - { - // Ignore - Console input has already been closed - } - } -} - -internal class NetDriver : ConsoleDriver -{ - private const int COLOR_BLACK = 30; - private const int COLOR_BLUE = 34; - private const int COLOR_BRIGHT_BLACK = 90; - private const int COLOR_BRIGHT_BLUE = 94; - private const int COLOR_BRIGHT_CYAN = 96; - private const int COLOR_BRIGHT_GREEN = 92; - private const int COLOR_BRIGHT_MAGENTA = 95; - private const int COLOR_BRIGHT_RED = 91; - private const int COLOR_BRIGHT_WHITE = 97; - private const int COLOR_BRIGHT_YELLOW = 93; - private const int COLOR_CYAN = 36; - private const int COLOR_GREEN = 32; - private const int COLOR_MAGENTA = 35; - private const int COLOR_RED = 31; - private const int COLOR_WHITE = 37; - private const int COLOR_YELLOW = 33; - internal NetMainLoop _mainLoopDriver; - public bool IsWinPlatform { get; private set; } - public NetWinVTConsole NetWinConsole { get; private set; } - - public override bool SupportsTrueColor => Environment.OSVersion.Platform == PlatformID.Unix - || (IsWinPlatform && Environment.OSVersion.Version.Build >= 14931); - - public override void Refresh () - { - UpdateScreen (); - UpdateCursor (); - } - - public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control) - { - var input = new InputResult - { - EventType = EventType.Key, ConsoleKeyInfo = new ConsoleKeyInfo (keyChar, key, shift, alt, control) - }; - - try - { - ProcessInput (input); - } - catch (OverflowException) - { } - } - - public override void Suspend () - { - if (Environment.OSVersion.Platform != PlatformID.Unix) - { - return; - } - - StopReportingMouseMoves (); - - if (!RunningUnitTests) - { - 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); - - SetContentsAsDirty (); - Refresh (); - } - - StartReportingMouseMoves (); - } - - public override void UpdateScreen () - { - if (RunningUnitTests - || _winSizeChanging - || Console.WindowHeight < 1 - || Contents.Length != Rows * Cols - || Rows != Console.WindowHeight) - { - return; - } - - var top = 0; - var left = 0; - int rows = Rows; - int cols = Cols; - var output = new StringBuilder (); - Attribute? redrawAttr = null; - int lastCol = -1; - - CursorVisibility? savedVisibility = _cachedCursorVisibility; - SetCursorVisibility (CursorVisibility.Invisible); - - for (int row = top; row < rows; row++) - { - if (Console.WindowHeight < 1) - { - return; - } - - if (!_dirtyLines [row]) - { - continue; - } - - if (!SetCursorPosition (0, row)) - { - return; - } - - _dirtyLines [row] = false; - output.Clear (); - - for (int col = left; col < cols; col++) - { - lastCol = -1; - var outputWidth = 0; - - for (; col < cols; col++) - { - if (!Contents [row, col].IsDirty) - { - if (output.Length > 0) - { - WriteToConsole (output, ref lastCol, row, ref outputWidth); - } - else if (lastCol == -1) - { - lastCol = col; - } - - if (lastCol + 1 < cols) - { - lastCol++; - } - - continue; - } - - if (lastCol == -1) - { - lastCol = col; - } - - Attribute attr = Contents [row, col].Attribute.Value; - - // Performance: Only send the escape sequence if the attribute has changed. - if (attr != redrawAttr) - { - redrawAttr = attr; - - if (Force16Colors) - { - output.Append ( - EscSeqUtils.CSI_SetGraphicsRendition ( - MapColors ( - (ConsoleColor)attr.Background.GetClosestNamedColor16 (), - false - ), - MapColors ((ConsoleColor)attr.Foreground.GetClosestNamedColor16 ()) - ) - ); - } - else - { - output.Append ( - EscSeqUtils.CSI_SetForegroundColorRGB ( - attr.Foreground.R, - attr.Foreground.G, - attr.Foreground.B - ) - ); - - output.Append ( - EscSeqUtils.CSI_SetBackgroundColorRGB ( - attr.Background.R, - attr.Background.G, - attr.Background.B - ) - ); - } - } - - outputWidth++; - Rune rune = Contents [row, col].Rune; - output.Append (rune); - - if (Contents [row, col].CombiningMarks.Count > 0) - { - // 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 `[é ]`. - // - // For now, we just ignore the list of CMs. - //foreach (var combMark in Contents [row, col].CombiningMarks) { - // output.Append (combMark); - //} - // WriteToConsole (output, ref lastCol, row, ref outputWidth); - } - else if (rune.IsSurrogatePair () && rune.GetColumns () < 2) - { - WriteToConsole (output, ref lastCol, row, ref outputWidth); - SetCursorPosition (col - 1, row); - } - - Contents [row, col].IsDirty = false; - } - } - - if (output.Length > 0) - { - SetCursorPosition (lastCol, row); - Console.Write (output); - } - - foreach (var s in Application.Sixel) - { - if (!string.IsNullOrWhiteSpace (s.SixelData)) - { - SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y); - Console.Write (s.SixelData); - } - } - } - - SetCursorPosition (0, 0); - - _cachedCursorVisibility = savedVisibility; - - void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth) - { - SetCursorPosition (lastCol, row); - Console.Write (output); - output.Clear (); - lastCol += outputWidth; - outputWidth = 0; - } - } - - internal override void End () - { - if (IsWinPlatform) - { - NetWinConsole?.Cleanup (); - } - - StopReportingMouseMoves (); - - _ansiResponseTokenSource?.Cancel (); - _ansiResponseTokenSource?.Dispose (); - - _waitAnsiResponse?.Dispose (); - - if (!RunningUnitTests) - { - Console.ResetColor (); - - //Disable alternative screen buffer. - Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll); - - //Set cursor key to cursor. - Console.Out.Write (EscSeqUtils.CSI_ShowCursor); - Console.Out.Close (); - } - } - - internal override MainLoop Init () - { - PlatformID p = Environment.OSVersion.Platform; - - if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) - { - IsWinPlatform = true; - - try - { - NetWinConsole = new NetWinVTConsole (); - } - catch (ApplicationException) - { - // Likely running as a unit test, or in a non-interactive session. - } - } - - if (IsWinPlatform) - { - Clipboard = new WindowsClipboard (); - } - else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) - { - Clipboard = new MacOSXClipboard (); - } - else - { - if (CursesDriver.Is_WSL_Platform ()) - { - Clipboard = new WSLClipboard (); - } - else - { - Clipboard = new CursesClipboard (); - } - } - - if (!RunningUnitTests) - { - Console.TreatControlCAsInput = true; - - Cols = Console.WindowWidth; - Rows = Console.WindowHeight; - - //Enable alternative screen buffer. - Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll); - - //Set cursor key to application. - Console.Out.Write (EscSeqUtils.CSI_HideCursor); - } - else - { - // We are being run in an environment that does not support a console - // such as a unit test, or a pipe. - Cols = 80; - Rows = 24; - } - - ResizeScreen (); - ClearContents (); - CurrentAttribute = new Attribute (Color.White, Color.Black); - - StartReportingMouseMoves (); - - _mainLoopDriver = new NetMainLoop (this); - _mainLoopDriver.ProcessInput = ProcessInput; - - - return new MainLoop (_mainLoopDriver); - } - - private void ProcessInput (InputResult inputEvent) - { - switch (inputEvent.EventType) - { - case EventType.Key: - ConsoleKeyInfo consoleKeyInfo = inputEvent.ConsoleKeyInfo; - - //if (consoleKeyInfo.Key == ConsoleKey.Packet) { - // consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo); - //} - - //Debug.WriteLine ($"event: {inputEvent}"); - - KeyCode map = MapKey (consoleKeyInfo); - - if (map == KeyCode.Null) - { - break; - } - - OnKeyDown (new Key (map)); - OnKeyUp (new Key (map)); - - break; - case EventType.Mouse: - MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent); - //Debug.WriteLine ($"NetDriver: ({me.X},{me.Y}) - {me.Flags}"); - OnMouseEvent (me); - - break; - case EventType.WindowSize: - _winSizeChanging = true; - Top = 0; - Left = 0; - Cols = inputEvent.WindowSizeEvent.Size.Width; - Rows = Math.Max (inputEvent.WindowSizeEvent.Size.Height, 0); - ; - ResizeScreen (); - ClearContents (); - _winSizeChanging = false; - OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows))); - - break; - case EventType.RequestResponse: - break; - case EventType.WindowPosition: - break; - default: - throw new ArgumentOutOfRangeException (); - } - } - - #region Size and Position Handling - - private volatile bool _winSizeChanging; - - private void SetWindowPosition (int col, int row) - { - if (!RunningUnitTests) - { - Top = Console.WindowTop; - Left = Console.WindowLeft; - } - else - { - Top = row; - Left = col; - } - } - - public virtual void ResizeScreen () - { - // Not supported on Unix. - if (IsWinPlatform) - { - // Can raise an exception while is still resizing. - try - { -#pragma warning disable CA1416 - if (Console.WindowHeight > 0) - { - Console.CursorTop = 0; - Console.CursorLeft = 0; - Console.WindowTop = 0; - Console.WindowLeft = 0; - - if (Console.WindowHeight > Rows) - { - Console.SetWindowSize (Cols, Rows); - } - - Console.SetBufferSize (Cols, Rows); - } -#pragma warning restore CA1416 - } - // INTENT: Why are these eating the exceptions? - // Comments would be good here. - catch (IOException) - { - // CONCURRENCY: Unsynchronized access to Clip is not safe. - Clip = new (0, 0, Cols, Rows); - } - catch (ArgumentOutOfRangeException) - { - // CONCURRENCY: Unsynchronized access to Clip is not safe. - Clip = new (0, 0, Cols, Rows); - } - } - else - { - Console.Out.Write (EscSeqUtils.CSI_SetTerminalWindowSize (Rows, Cols)); - } - - // CONCURRENCY: Unsynchronized access to Clip is not safe. - Clip = new (0, 0, Cols, Rows); - } - - #endregion - - #region Color Handling - - // Cache the list of ConsoleColor values. - [UnconditionalSuppressMessage ("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "")] - private static readonly HashSet ConsoleColorValues = new ( - Enum.GetValues (typeof (ConsoleColor)) - .OfType () - .Select (c => (int)c) - ); - - // Dictionary for mapping ConsoleColor values to the values used by System.Net.Console. - private static readonly Dictionary colorMap = new () - { - { ConsoleColor.Black, COLOR_BLACK }, - { ConsoleColor.DarkBlue, COLOR_BLUE }, - { ConsoleColor.DarkGreen, COLOR_GREEN }, - { ConsoleColor.DarkCyan, COLOR_CYAN }, - { ConsoleColor.DarkRed, COLOR_RED }, - { ConsoleColor.DarkMagenta, COLOR_MAGENTA }, - { ConsoleColor.DarkYellow, COLOR_YELLOW }, - { ConsoleColor.Gray, COLOR_WHITE }, - { ConsoleColor.DarkGray, COLOR_BRIGHT_BLACK }, - { ConsoleColor.Blue, COLOR_BRIGHT_BLUE }, - { ConsoleColor.Green, COLOR_BRIGHT_GREEN }, - { ConsoleColor.Cyan, COLOR_BRIGHT_CYAN }, - { ConsoleColor.Red, COLOR_BRIGHT_RED }, - { ConsoleColor.Magenta, COLOR_BRIGHT_MAGENTA }, - { ConsoleColor.Yellow, COLOR_BRIGHT_YELLOW }, - { ConsoleColor.White, COLOR_BRIGHT_WHITE } - }; - - // Map a ConsoleColor to a platform dependent value. - private int MapColors (ConsoleColor color, bool isForeground = true) - { - return colorMap.TryGetValue (color, out int colorValue) ? colorValue + (isForeground ? 0 : 10) : 0; - } - - ///// - ///// In the NetDriver, colors are encoded as an int. - ///// However, the foreground color is stored in the most significant 16 bits, - ///// and the background color is stored in the least significant 16 bits. - ///// - //public override Attribute MakeColor (Color foreground, Color background) - //{ - // // Encode the colors into the int value. - // return new Attribute ( - // platformColor: ((((int)foreground.ColorName) & 0xffff) << 16) | (((int)background.ColorName) & 0xffff), - // foreground: foreground, - // background: background - // ); - //} - - #endregion - - #region Cursor Handling - - private bool SetCursorPosition (int col, int row) - { - if (IsWinPlatform) - { - // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth. - try - { - Console.SetCursorPosition (col, row); - - return true; - } - catch (Exception) - { - return false; - } - } - - // + 1 is needed because non-Windows is based on 1 instead of 0 and - // Console.CursorTop/CursorLeft isn't reliable. - Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1)); - - return true; - } - - private CursorVisibility? _cachedCursorVisibility; - - public override void UpdateCursor () - { - EnsureCursorVisibility (); - - if (Col >= 0 && Col < Cols && Row >= 0 && Row <= Rows) - { - SetCursorPosition (Col, Row); - SetWindowPosition (0, Row); - } - } - - public override bool GetCursorVisibility (out CursorVisibility visibility) - { - visibility = _cachedCursorVisibility ?? CursorVisibility.Default; - - return visibility == CursorVisibility.Default; - } - - public override bool SetCursorVisibility (CursorVisibility visibility) - { - _cachedCursorVisibility = visibility; - - Console.Out.Write (visibility == CursorVisibility.Default ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor); - - return visibility == CursorVisibility.Default; - } - - public override bool EnsureCursorVisibility () - { - if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) - { - GetCursorVisibility (out CursorVisibility cursorVisibility); - _cachedCursorVisibility = cursorVisibility; - SetCursorVisibility (CursorVisibility.Invisible); - - return false; - } - - SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default); - - return _cachedCursorVisibility == CursorVisibility.Default; - } - - #endregion - - #region Mouse Handling - - public void StartReportingMouseMoves () - { - if (!RunningUnitTests) - { - Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); - } - } - - public void StopReportingMouseMoves () - { - if (!RunningUnitTests) - { - Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); - } - } - - private readonly ManualResetEventSlim _waitAnsiResponse = new (false); - private readonly CancellationTokenSource _ansiResponseTokenSource = new (); - - /// - public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) - { - if (_mainLoopDriver is null) - { - return string.Empty; - } - - try - { - lock (ansiRequest._responseLock) - { - ansiRequest.ResponseFromInput += (s, e) => - { - Debug.Assert (s == ansiRequest); - Debug.Assert (e == ansiRequest.Response); - - _waitAnsiResponse.Set (); - }; - - _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest); - - _mainLoopDriver._netEvents._forceRead = true; - } - - if (!_ansiResponseTokenSource.IsCancellationRequested) - { - _mainLoopDriver._netEvents._waitForStart.Set (); - - if (!_mainLoopDriver._waitForProbe.IsSet) - { - _mainLoopDriver._waitForProbe.Set (); - } - - _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); - } - } - catch (OperationCanceledException) - { - return string.Empty; - } - - lock (ansiRequest._responseLock) - { - _mainLoopDriver._netEvents._forceRead = false; - - if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) - { - if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0 - && string.IsNullOrEmpty (request.AnsiRequest.Response)) - { - lock (request!.AnsiRequest._responseLock) - { - // Bad request or no response at all - _mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryDequeue (out _); - } - } - } - - _waitAnsiResponse.Reset (); - - return ansiRequest.Response; - } - } - - /// - public override void WriteRaw (string ansi) { throw new NotImplementedException (); } - - private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me) - { - //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}"); - - MouseFlags mouseFlag = 0; - - if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0) - { - mouseFlag |= MouseFlags.Button1Pressed; - } - - if ((me.ButtonState & MouseButtonState.Button1Released) != 0) - { - mouseFlag |= MouseFlags.Button1Released; - } - - if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0) - { - mouseFlag |= MouseFlags.Button1Clicked; - } - - if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0) - { - mouseFlag |= MouseFlags.Button1DoubleClicked; - } - - if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0) - { - mouseFlag |= MouseFlags.Button1TripleClicked; - } - - if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0) - { - mouseFlag |= MouseFlags.Button2Pressed; - } - - if ((me.ButtonState & MouseButtonState.Button2Released) != 0) - { - mouseFlag |= MouseFlags.Button2Released; - } - - if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0) - { - mouseFlag |= MouseFlags.Button2Clicked; - } - - if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0) - { - mouseFlag |= MouseFlags.Button2DoubleClicked; - } - - if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0) - { - mouseFlag |= MouseFlags.Button2TripleClicked; - } - - if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0) - { - mouseFlag |= MouseFlags.Button3Pressed; - } - - if ((me.ButtonState & MouseButtonState.Button3Released) != 0) - { - mouseFlag |= MouseFlags.Button3Released; - } - - if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0) - { - mouseFlag |= MouseFlags.Button3Clicked; - } - - if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0) - { - mouseFlag |= MouseFlags.Button3DoubleClicked; - } - - if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0) - { - mouseFlag |= MouseFlags.Button3TripleClicked; - } - - if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0) - { - mouseFlag |= MouseFlags.WheeledUp; - } - - if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0) - { - mouseFlag |= MouseFlags.WheeledDown; - } - - if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0) - { - mouseFlag |= MouseFlags.WheeledLeft; - } - - if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0) - { - mouseFlag |= MouseFlags.WheeledRight; - } - - if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0) - { - mouseFlag |= MouseFlags.Button4Pressed; - } - - if ((me.ButtonState & MouseButtonState.Button4Released) != 0) - { - mouseFlag |= MouseFlags.Button4Released; - } - - if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0) - { - mouseFlag |= MouseFlags.Button4Clicked; - } - - if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0) - { - mouseFlag |= MouseFlags.Button4DoubleClicked; - } - - if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0) - { - mouseFlag |= MouseFlags.Button4TripleClicked; - } - - if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0) - { - mouseFlag |= MouseFlags.ReportMousePosition; - } - - if ((me.ButtonState & MouseButtonState.ButtonShift) != 0) - { - mouseFlag |= MouseFlags.ButtonShift; - } - - if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0) - { - mouseFlag |= MouseFlags.ButtonCtrl; - } - - if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0) - { - mouseFlag |= MouseFlags.ButtonAlt; - } - - return new MouseEventArgs { Position = me.Position, Flags = mouseFlag }; - } - - #endregion Mouse Handling - - #region Keyboard Handling - - private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) - { - if (consoleKeyInfo.Key != ConsoleKey.Packet) - { - return consoleKeyInfo; - } - - ConsoleModifiers mod = consoleKeyInfo.Modifiers; - bool shift = (mod & ConsoleModifiers.Shift) != 0; - bool alt = (mod & ConsoleModifiers.Alt) != 0; - bool control = (mod & ConsoleModifiers.Control) != 0; - - ConsoleKeyInfo cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo); - - return new ConsoleKeyInfo (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control); - } - - private KeyCode MapKey (ConsoleKeyInfo keyInfo) - { - switch (keyInfo.Key) - { - case ConsoleKey.OemPeriod: - case ConsoleKey.OemComma: - case ConsoleKey.OemPlus: - case ConsoleKey.OemMinus: - case ConsoleKey.Packet: - case ConsoleKey.Oem1: - case ConsoleKey.Oem2: - case ConsoleKey.Oem3: - case ConsoleKey.Oem4: - case ConsoleKey.Oem5: - case ConsoleKey.Oem6: - case ConsoleKey.Oem7: - case ConsoleKey.Oem8: - case ConsoleKey.Oem102: - if (keyInfo.KeyChar == 0) - { - // If the keyChar is 0, keyInfo.Key value is not a printable character. - - return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key); - } - - if (keyInfo.Modifiers != ConsoleModifiers.Shift) - { - // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar - return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar); - } - - // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç") - // and passing on Shift would be redundant. - return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar); - } - - // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC - if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key)) - { - if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I) - { - return KeyCode.Tab; - } - - return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key)); - } - - // Handle control keys (e.g. CursorUp) - if (keyInfo.Key != ConsoleKey.None - && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint)) - { - return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint)); - } - - if (((ConsoleKey)keyInfo.KeyChar) is >= ConsoleKey.A and <= ConsoleKey.Z) - { - // Shifted - keyInfo = new ConsoleKeyInfo ( - keyInfo.KeyChar, - (ConsoleKey)keyInfo.KeyChar, - true, - keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt), - keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)); - } - - if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z) - { - // Unshifted - keyInfo = new ConsoleKeyInfo ( - keyInfo.KeyChar, - (ConsoleKey)(keyInfo.KeyChar - 32), - false, - keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt), - keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)); - } - - if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z ) - { - if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) - || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) - { - // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos - return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key); - } - - if (keyInfo.Modifiers == ConsoleModifiers.Shift) - { - // If ShiftMask is on add the ShiftMask - if (char.IsUpper (keyInfo.KeyChar)) - { - return (KeyCode)keyInfo.Key | KeyCode.ShiftMask; - } - } - - return (KeyCode)keyInfo.Key; - } - - - return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.KeyChar)); - } - - #endregion Keyboard Handling -} - -/// -/// Mainloop intended to be used with the .NET System.Console API, and can be used on Windows and Unix, it is -/// cross-platform but lacks things like file descriptor monitoring. -/// -/// This implementation is used for NetDriver. -internal class NetMainLoop : IMainLoopDriver -{ - internal NetEvents _netEvents; - - /// Invoked when a Key is pressed. - internal Action ProcessInput; - - private readonly ManualResetEventSlim _eventReady = new (false); - private readonly CancellationTokenSource _inputHandlerTokenSource = new (); - private readonly ConcurrentQueue _resultQueue = new (); - internal readonly ManualResetEventSlim _waitForProbe = new (false); - private readonly CancellationTokenSource _eventReadyTokenSource = new (); - private MainLoop _mainLoop; - - /// Initializes the class with the console driver. - /// Passing a consoleDriver is provided to capture windows resizing. - /// The console driver used by this Net main loop. - /// - public NetMainLoop (ConsoleDriver consoleDriver = null) - { - if (consoleDriver is null) - { - throw new ArgumentNullException (nameof (consoleDriver)); - } - - _netEvents = new NetEvents (consoleDriver); - } - - void IMainLoopDriver.Setup (MainLoop mainLoop) - { - _mainLoop = mainLoop; - - if (ConsoleDriver.RunningUnitTests) - { - return; - } - - Task.Run (NetInputHandler, _inputHandlerTokenSource.Token); - } - - void IMainLoopDriver.Wakeup () { _eventReady.Set (); } - - bool IMainLoopDriver.EventsPending () - { - _waitForProbe.Set (); - - if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) - { - return true; - } - - try - { - if (!_eventReadyTokenSource.IsCancellationRequested) - { - // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there - // are no timers, but there IS an idle handler waiting. - _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token); - } - } - catch (OperationCanceledException) - { - return true; - } - finally - { - _eventReady.Reset (); - } - - _eventReadyTokenSource.Token.ThrowIfCancellationRequested (); - - if (!_eventReadyTokenSource.IsCancellationRequested) - { - return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _); - } - - return true; - } - - void IMainLoopDriver.Iteration () - { - while (_resultQueue.Count > 0) - { - // Always dequeue even if it's null and invoke if isn't null - if (_resultQueue.TryDequeue (out InputResult? dequeueResult)) - { - if (dequeueResult is { }) - { - ProcessInput?.Invoke (dequeueResult.Value); - } - } - } - } - - void IMainLoopDriver.TearDown () - { - _inputHandlerTokenSource?.Cancel (); - _inputHandlerTokenSource?.Dispose (); - _eventReadyTokenSource?.Cancel (); - _eventReadyTokenSource?.Dispose (); - - _eventReady?.Dispose (); - - _resultQueue?.Clear (); - _waitForProbe?.Dispose (); - _netEvents?.Dispose (); - _netEvents = null; - - _mainLoop = null; - } - - private void NetInputHandler () - { - while (_mainLoop is { }) - { - try - { - if (!_netEvents._forceRead && !_inputHandlerTokenSource.IsCancellationRequested) - { - _waitForProbe.Wait (_inputHandlerTokenSource.Token); - } - } - catch (OperationCanceledException) - { - return; - } - finally - { - if (_waitForProbe.IsSet) - { - _waitForProbe.Reset (); - } - } - - if (_inputHandlerTokenSource.IsCancellationRequested) - { - return; - } - - _inputHandlerTokenSource.Token.ThrowIfCancellationRequested (); - - if (_resultQueue.Count == 0) - { - _resultQueue.Enqueue (_netEvents.DequeueInput ()); - } - - try - { - while (_resultQueue.Count > 0 && _resultQueue.TryPeek (out InputResult? result) && result is null) - { - // Dequeue null values - _resultQueue.TryDequeue (out _); - } - } - catch (InvalidOperationException) // Peek can raise an exception - { } - - if (_resultQueue.Count > 0) - { - _eventReady.Set (); - } - } - } -} diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs new file mode 100644 index 0000000000..e4103d8c36 --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs @@ -0,0 +1,965 @@ +// TODO: #nullable enable +// +// NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient. +// + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping; +using static Terminal.Gui.NetEvents; + +namespace Terminal.Gui; + +internal class NetDriver : ConsoleDriver +{ + public bool IsWinPlatform { get; private set; } + public NetWinVTConsole NetWinConsole { get; private set; } + + public override void Refresh () + { + UpdateScreen (); + UpdateCursor (); + } + + public override void Suspend () + { + if (Environment.OSVersion.Platform != PlatformID.Unix) + { + return; + } + + StopReportingMouseMoves (); + + if (!RunningUnitTests) + { + 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); + + SetContentsAsDirty (); + Refresh (); + } + + StartReportingMouseMoves (); + } + + #region Screen and Contents + + public override void UpdateScreen () + { + if (RunningUnitTests + || _winSizeChanging + || Console.WindowHeight < 1 + || Contents.Length != Rows * Cols + || Rows != Console.WindowHeight) + { + return; + } + + var top = 0; + var left = 0; + int rows = Rows; + int cols = Cols; + var output = new StringBuilder (); + Attribute? redrawAttr = null; + int lastCol = -1; + + CursorVisibility? savedVisibility = _cachedCursorVisibility; + SetCursorVisibility (CursorVisibility.Invisible); + + for (int row = top; row < rows; row++) + { + if (Console.WindowHeight < 1) + { + return; + } + + if (!_dirtyLines [row]) + { + continue; + } + + if (!SetCursorPosition (0, row)) + { + return; + } + + _dirtyLines [row] = false; + output.Clear (); + + for (int col = left; col < cols; col++) + { + lastCol = -1; + var outputWidth = 0; + + for (; col < cols; col++) + { + if (!Contents [row, col].IsDirty) + { + if (output.Length > 0) + { + WriteToConsole (output, ref lastCol, row, ref outputWidth); + } + else if (lastCol == -1) + { + lastCol = col; + } + + if (lastCol + 1 < cols) + { + lastCol++; + } + + continue; + } + + if (lastCol == -1) + { + lastCol = col; + } + + Attribute attr = Contents [row, col].Attribute.Value; + + // Performance: Only send the escape sequence if the attribute has changed. + if (attr != redrawAttr) + { + redrawAttr = attr; + + if (Force16Colors) + { + output.Append ( + EscSeqUtils.CSI_SetGraphicsRendition ( + MapColors ( + (ConsoleColor)attr.Background.GetClosestNamedColor16 (), + false + ), + MapColors ((ConsoleColor)attr.Foreground.GetClosestNamedColor16 ()) + ) + ); + } + else + { + output.Append ( + EscSeqUtils.CSI_SetForegroundColorRGB ( + attr.Foreground.R, + attr.Foreground.G, + attr.Foreground.B + ) + ); + + output.Append ( + EscSeqUtils.CSI_SetBackgroundColorRGB ( + attr.Background.R, + attr.Background.G, + attr.Background.B + ) + ); + } + } + + outputWidth++; + Rune rune = Contents [row, col].Rune; + output.Append (rune); + + if (Contents [row, col].CombiningMarks.Count > 0) + { + // 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 `[é ]`. + // + // For now, we just ignore the list of CMs. + //foreach (var combMark in Contents [row, col].CombiningMarks) { + // output.Append (combMark); + //} + // WriteToConsole (output, ref lastCol, row, ref outputWidth); + } + else if (rune.IsSurrogatePair () && rune.GetColumns () < 2) + { + WriteToConsole (output, ref lastCol, row, ref outputWidth); + SetCursorPosition (col - 1, row); + } + + Contents [row, col].IsDirty = false; + } + } + + if (output.Length > 0) + { + SetCursorPosition (lastCol, row); + Console.Write (output); + } + + foreach (SixelToRender s in Application.Sixel) + { + if (!string.IsNullOrWhiteSpace (s.SixelData)) + { + SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y); + Console.Write (s.SixelData); + } + } + } + + SetCursorPosition (0, 0); + + _cachedCursorVisibility = savedVisibility; + + void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth) + { + SetCursorPosition (lastCol, row); + Console.Write (output); + output.Clear (); + lastCol += outputWidth; + outputWidth = 0; + } + } + + #endregion Screen and Contents + + #region Init/End/MainLoop + + internal NetMainLoop _mainLoopDriver; + + internal override MainLoop Init () + { + PlatformID p = Environment.OSVersion.Platform; + + if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) + { + IsWinPlatform = true; + + try + { + NetWinConsole = new (); + } + catch (ApplicationException) + { + // Likely running as a unit test, or in a non-interactive session. + } + } + + if (IsWinPlatform) + { + Clipboard = new WindowsClipboard (); + } + else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) + { + Clipboard = new MacOSXClipboard (); + } + else + { + if (CursesDriver.Is_WSL_Platform ()) + { + Clipboard = new WSLClipboard (); + } + else + { + Clipboard = new CursesClipboard (); + } + } + + if (!RunningUnitTests) + { + Console.TreatControlCAsInput = true; + + Cols = Console.WindowWidth; + Rows = Console.WindowHeight; + + //Enable alternative screen buffer. + Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll); + + //Set cursor key to application. + Console.Out.Write (EscSeqUtils.CSI_HideCursor); + } + else + { + // We are being run in an environment that does not support a console + // such as a unit test, or a pipe. + Cols = 80; + Rows = 24; + } + + ResizeScreen (); + ClearContents (); + CurrentAttribute = new (Color.White, Color.Black); + + StartReportingMouseMoves (); + + _mainLoopDriver = new (this); + _mainLoopDriver.ProcessInput = ProcessInput; + + return new (_mainLoopDriver); + } + + private void ProcessInput (InputResult inputEvent) + { + switch (inputEvent.EventType) + { + case EventType.Key: + ConsoleKeyInfo consoleKeyInfo = inputEvent.ConsoleKeyInfo; + + //if (consoleKeyInfo.Key == ConsoleKey.Packet) { + // consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo); + //} + + //Debug.WriteLine ($"event: {inputEvent}"); + + KeyCode map = MapKey (consoleKeyInfo); + + if (map == KeyCode.Null) + { + break; + } + + OnKeyDown (new (map)); + OnKeyUp (new (map)); + + break; + case EventType.Mouse: + MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent); + + //Debug.WriteLine ($"NetDriver: ({me.X},{me.Y}) - {me.Flags}"); + OnMouseEvent (me); + + break; + case EventType.WindowSize: + _winSizeChanging = true; + Top = 0; + Left = 0; + Cols = inputEvent.WindowSizeEvent.Size.Width; + Rows = Math.Max (inputEvent.WindowSizeEvent.Size.Height, 0); + ; + ResizeScreen (); + ClearContents (); + _winSizeChanging = false; + OnSizeChanged (new (new (Cols, Rows))); + + break; + case EventType.RequestResponse: + break; + case EventType.WindowPosition: + break; + default: + throw new ArgumentOutOfRangeException (); + } + } + + internal override void End () + { + if (IsWinPlatform) + { + NetWinConsole?.Cleanup (); + } + + StopReportingMouseMoves (); + + _ansiResponseTokenSource?.Cancel (); + _ansiResponseTokenSource?.Dispose (); + + _waitAnsiResponse?.Dispose (); + + if (!RunningUnitTests) + { + Console.ResetColor (); + + //Disable alternative screen buffer. + Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll); + + //Set cursor key to cursor. + Console.Out.Write (EscSeqUtils.CSI_ShowCursor); + Console.Out.Close (); + } + } + + #endregion Init/End/MainLoop + + #region Color Handling + + public override bool SupportsTrueColor => Environment.OSVersion.Platform == PlatformID.Unix + || (IsWinPlatform && Environment.OSVersion.Version.Build >= 14931); + + private const int COLOR_BLACK = 30; + private const int COLOR_BLUE = 34; + private const int COLOR_BRIGHT_BLACK = 90; + private const int COLOR_BRIGHT_BLUE = 94; + private const int COLOR_BRIGHT_CYAN = 96; + private const int COLOR_BRIGHT_GREEN = 92; + private const int COLOR_BRIGHT_MAGENTA = 95; + private const int COLOR_BRIGHT_RED = 91; + private const int COLOR_BRIGHT_WHITE = 97; + private const int COLOR_BRIGHT_YELLOW = 93; + private const int COLOR_CYAN = 36; + private const int COLOR_GREEN = 32; + private const int COLOR_MAGENTA = 35; + private const int COLOR_RED = 31; + private const int COLOR_WHITE = 37; + private const int COLOR_YELLOW = 33; + + // Cache the list of ConsoleColor values. + [UnconditionalSuppressMessage ( + "AOT", + "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", + Justification = "")] + private static readonly HashSet ConsoleColorValues = new ( + Enum.GetValues (typeof (ConsoleColor)) + .OfType () + .Select (c => (int)c) + ); + + // Dictionary for mapping ConsoleColor values to the values used by System.Net.Console. + private static readonly Dictionary colorMap = new () + { + { ConsoleColor.Black, COLOR_BLACK }, + { ConsoleColor.DarkBlue, COLOR_BLUE }, + { ConsoleColor.DarkGreen, COLOR_GREEN }, + { ConsoleColor.DarkCyan, COLOR_CYAN }, + { ConsoleColor.DarkRed, COLOR_RED }, + { ConsoleColor.DarkMagenta, COLOR_MAGENTA }, + { ConsoleColor.DarkYellow, COLOR_YELLOW }, + { ConsoleColor.Gray, COLOR_WHITE }, + { ConsoleColor.DarkGray, COLOR_BRIGHT_BLACK }, + { ConsoleColor.Blue, COLOR_BRIGHT_BLUE }, + { ConsoleColor.Green, COLOR_BRIGHT_GREEN }, + { ConsoleColor.Cyan, COLOR_BRIGHT_CYAN }, + { ConsoleColor.Red, COLOR_BRIGHT_RED }, + { ConsoleColor.Magenta, COLOR_BRIGHT_MAGENTA }, + { ConsoleColor.Yellow, COLOR_BRIGHT_YELLOW }, + { ConsoleColor.White, COLOR_BRIGHT_WHITE } + }; + + // Map a ConsoleColor to a platform dependent value. + private int MapColors (ConsoleColor color, bool isForeground = true) + { + return colorMap.TryGetValue (color, out int colorValue) ? colorValue + (isForeground ? 0 : 10) : 0; + } + + #endregion + + #region Cursor Handling + + private bool SetCursorPosition (int col, int row) + { + if (IsWinPlatform) + { + // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth. + try + { + Console.SetCursorPosition (col, row); + + return true; + } + catch (Exception) + { + return false; + } + } + + // + 1 is needed because non-Windows is based on 1 instead of 0 and + // Console.CursorTop/CursorLeft isn't reliable. + Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1)); + + return true; + } + + private CursorVisibility? _cachedCursorVisibility; + + public override void UpdateCursor () + { + EnsureCursorVisibility (); + + if (Col >= 0 && Col < Cols && Row >= 0 && Row <= Rows) + { + SetCursorPosition (Col, Row); + SetWindowPosition (0, Row); + } + } + + public override bool GetCursorVisibility (out CursorVisibility visibility) + { + visibility = _cachedCursorVisibility ?? CursorVisibility.Default; + + return visibility == CursorVisibility.Default; + } + + public override bool SetCursorVisibility (CursorVisibility visibility) + { + _cachedCursorVisibility = visibility; + + Console.Out.Write (visibility == CursorVisibility.Default ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor); + + return visibility == CursorVisibility.Default; + } + + public override bool EnsureCursorVisibility () + { + if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows)) + { + GetCursorVisibility (out CursorVisibility cursorVisibility); + _cachedCursorVisibility = cursorVisibility; + SetCursorVisibility (CursorVisibility.Invisible); + + return false; + } + + SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default); + + return _cachedCursorVisibility == CursorVisibility.Default; + } + + #endregion + + #region Mouse Handling + + public void StartReportingMouseMoves () + { + if (!RunningUnitTests) + { + Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); + } + } + + public void StopReportingMouseMoves () + { + if (!RunningUnitTests) + { + Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); + } + } + + private MouseEventArgs ToDriverMouse (MouseEvent me) + { + //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}"); + + MouseFlags mouseFlag = 0; + + if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0) + { + mouseFlag |= MouseFlags.Button1Pressed; + } + + if ((me.ButtonState & MouseButtonState.Button1Released) != 0) + { + mouseFlag |= MouseFlags.Button1Released; + } + + if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0) + { + mouseFlag |= MouseFlags.Button1Clicked; + } + + if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0) + { + mouseFlag |= MouseFlags.Button1DoubleClicked; + } + + if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0) + { + mouseFlag |= MouseFlags.Button1TripleClicked; + } + + if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0) + { + mouseFlag |= MouseFlags.Button2Pressed; + } + + if ((me.ButtonState & MouseButtonState.Button2Released) != 0) + { + mouseFlag |= MouseFlags.Button2Released; + } + + if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0) + { + mouseFlag |= MouseFlags.Button2Clicked; + } + + if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0) + { + mouseFlag |= MouseFlags.Button2DoubleClicked; + } + + if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0) + { + mouseFlag |= MouseFlags.Button2TripleClicked; + } + + if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0) + { + mouseFlag |= MouseFlags.Button3Pressed; + } + + if ((me.ButtonState & MouseButtonState.Button3Released) != 0) + { + mouseFlag |= MouseFlags.Button3Released; + } + + if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0) + { + mouseFlag |= MouseFlags.Button3Clicked; + } + + if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0) + { + mouseFlag |= MouseFlags.Button3DoubleClicked; + } + + if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0) + { + mouseFlag |= MouseFlags.Button3TripleClicked; + } + + if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0) + { + mouseFlag |= MouseFlags.WheeledUp; + } + + if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0) + { + mouseFlag |= MouseFlags.WheeledDown; + } + + if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0) + { + mouseFlag |= MouseFlags.WheeledLeft; + } + + if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0) + { + mouseFlag |= MouseFlags.WheeledRight; + } + + if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0) + { + mouseFlag |= MouseFlags.Button4Pressed; + } + + if ((me.ButtonState & MouseButtonState.Button4Released) != 0) + { + mouseFlag |= MouseFlags.Button4Released; + } + + if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0) + { + mouseFlag |= MouseFlags.Button4Clicked; + } + + if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0) + { + mouseFlag |= MouseFlags.Button4DoubleClicked; + } + + if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0) + { + mouseFlag |= MouseFlags.Button4TripleClicked; + } + + if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0) + { + mouseFlag |= MouseFlags.ReportMousePosition; + } + + if ((me.ButtonState & MouseButtonState.ButtonShift) != 0) + { + mouseFlag |= MouseFlags.ButtonShift; + } + + if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0) + { + mouseFlag |= MouseFlags.ButtonCtrl; + } + + if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0) + { + mouseFlag |= MouseFlags.ButtonAlt; + } + + return new() { Position = me.Position, Flags = mouseFlag }; + } + + #endregion Mouse Handling + + #region Keyboard Handling + + public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control) + { + var input = new InputResult + { + EventType = EventType.Key, ConsoleKeyInfo = new (keyChar, key, shift, alt, control) + }; + + try + { + ProcessInput (input); + } + catch (OverflowException) + { } + } + + private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) + { + if (consoleKeyInfo.Key != ConsoleKey.Packet) + { + return consoleKeyInfo; + } + + ConsoleModifiers mod = consoleKeyInfo.Modifiers; + bool shift = (mod & ConsoleModifiers.Shift) != 0; + bool alt = (mod & ConsoleModifiers.Alt) != 0; + bool control = (mod & ConsoleModifiers.Control) != 0; + + ConsoleKeyInfo cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo); + + return new (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control); + } + + private KeyCode MapKey (ConsoleKeyInfo keyInfo) + { + switch (keyInfo.Key) + { + case ConsoleKey.OemPeriod: + case ConsoleKey.OemComma: + case ConsoleKey.OemPlus: + case ConsoleKey.OemMinus: + case ConsoleKey.Packet: + case ConsoleKey.Oem1: + case ConsoleKey.Oem2: + case ConsoleKey.Oem3: + case ConsoleKey.Oem4: + case ConsoleKey.Oem5: + case ConsoleKey.Oem6: + case ConsoleKey.Oem7: + case ConsoleKey.Oem8: + case ConsoleKey.Oem102: + if (keyInfo.KeyChar == 0) + { + // If the keyChar is 0, keyInfo.Key value is not a printable character. + + return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key); + } + + if (keyInfo.Modifiers != ConsoleModifiers.Shift) + { + // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar + return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar); + } + + // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç") + // and passing on Shift would be redundant. + return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar); + } + + // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC + if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key)) + { + if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I) + { + return KeyCode.Tab; + } + + return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key); + } + + // Handle control keys (e.g. CursorUp) + if (keyInfo.Key != ConsoleKey.None + && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint)) + { + return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint)); + } + + if ((ConsoleKey)keyInfo.KeyChar is >= ConsoleKey.A and <= ConsoleKey.Z) + { + // Shifted + keyInfo = new ( + keyInfo.KeyChar, + (ConsoleKey)keyInfo.KeyChar, + true, + keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt), + keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)); + } + + if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z) + { + // Unshifted + keyInfo = new ( + keyInfo.KeyChar, + (ConsoleKey)(keyInfo.KeyChar - 32), + false, + keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt), + keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)); + } + + if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z) + { + if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) + || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) + { + // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos + return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key); + } + + if (keyInfo.Modifiers == ConsoleModifiers.Shift) + { + // If ShiftMask is on add the ShiftMask + if (char.IsUpper (keyInfo.KeyChar)) + { + return (KeyCode)keyInfo.Key | KeyCode.ShiftMask; + } + } + + return (KeyCode)keyInfo.Key; + } + + return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar); + } + + #endregion Keyboard Handling + + #region Low-Level DotNet tuff + + private readonly ManualResetEventSlim _waitAnsiResponse = new (false); + private readonly CancellationTokenSource _ansiResponseTokenSource = new (); + + /// + public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) + { + if (_mainLoopDriver is null) + { + return string.Empty; + } + + try + { + lock (ansiRequest._responseLock) + { + ansiRequest.ResponseFromInput += (s, e) => + { + Debug.Assert (s == ansiRequest); + Debug.Assert (e == ansiRequest.Response); + + _waitAnsiResponse.Set (); + }; + + _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest); + + _mainLoopDriver._netEvents._forceRead = true; + } + + if (!_ansiResponseTokenSource.IsCancellationRequested) + { + _mainLoopDriver._netEvents._waitForStart.Set (); + + if (!_mainLoopDriver._waitForProbe.IsSet) + { + _mainLoopDriver._waitForProbe.Set (); + } + + _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); + } + } + catch (OperationCanceledException) + { + return string.Empty; + } + + lock (ansiRequest._responseLock) + { + _mainLoopDriver._netEvents._forceRead = false; + + if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) + { + if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0 + && string.IsNullOrEmpty (request.AnsiRequest.Response)) + { + lock (request!.AnsiRequest._responseLock) + { + // Bad request or no response at all + _mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryDequeue (out _); + } + } + } + + _waitAnsiResponse.Reset (); + + return ansiRequest.Response; + } + } + + /// + public override void WriteRaw (string ansi) { throw new NotImplementedException (); } + + private volatile bool _winSizeChanging; + + private void SetWindowPosition (int col, int row) + { + if (!RunningUnitTests) + { + Top = Console.WindowTop; + Left = Console.WindowLeft; + } + else + { + Top = row; + Left = col; + } + } + + private void ResizeScreen () + { + // Not supported on Unix. + if (IsWinPlatform) + { + // Can raise an exception while is still resizing. + try + { +#pragma warning disable CA1416 + if (Console.WindowHeight > 0) + { + Console.CursorTop = 0; + Console.CursorLeft = 0; + Console.WindowTop = 0; + Console.WindowLeft = 0; + + if (Console.WindowHeight > Rows) + { + Console.SetWindowSize (Cols, Rows); + } + + Console.SetBufferSize (Cols, Rows); + } +#pragma warning restore CA1416 + } + + // INTENT: Why are these eating the exceptions? + // Comments would be good here. + catch (IOException) + { + // CONCURRENCY: Unsynchronized access to Clip is not safe. + Clip = new (0, 0, Cols, Rows); + } + catch (ArgumentOutOfRangeException) + { + // CONCURRENCY: Unsynchronized access to Clip is not safe. + Clip = new (0, 0, Cols, Rows); + } + } + else + { + Console.Out.Write (EscSeqUtils.CSI_SetTerminalWindowSize (Rows, Cols)); + } + + // CONCURRENCY: Unsynchronized access to Clip is not safe. + Clip = new (0, 0, Cols, Rows); + } + + #endregion Low-Level DotNet tuff +} diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs new file mode 100644 index 0000000000..939ed0d2d5 --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs @@ -0,0 +1,753 @@ +// TODO: #nullable enable +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; + +namespace Terminal.Gui; + +internal class NetEvents : IDisposable +{ + private readonly ManualResetEventSlim _inputReady = new (false); + private CancellationTokenSource _inputReadyCancellationTokenSource; + internal readonly ManualResetEventSlim _waitForStart = new (false); + + //CancellationTokenSource _waitForStartCancellationTokenSource; + private readonly ManualResetEventSlim _winChange = new (false); + private readonly ConcurrentQueue _inputQueue = new (); + private readonly ConsoleDriver _consoleDriver; + private ConsoleKeyInfo [] _cki; + private bool _isEscSeq; +#if PROCESS_REQUEST + bool _neededProcessRequest; +#endif + public EscSeqRequests EscSeqRequests { get; } = new (); + + public NetEvents (ConsoleDriver consoleDriver) + { + _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver)); + _inputReadyCancellationTokenSource = new CancellationTokenSource (); + + Task.Run (ProcessInputQueue, _inputReadyCancellationTokenSource.Token); + + Task.Run (CheckWindowSizeChange, _inputReadyCancellationTokenSource.Token); + } + + public InputResult? DequeueInput () + { + while (_inputReadyCancellationTokenSource != null + && !_inputReadyCancellationTokenSource.Token.IsCancellationRequested) + { + _waitForStart.Set (); + _winChange.Set (); + + try + { + if (!_inputReadyCancellationTokenSource.Token.IsCancellationRequested) + { + if (_inputQueue.Count == 0) + { + _inputReady.Wait (_inputReadyCancellationTokenSource.Token); + } + } + } + catch (OperationCanceledException) + { + return null; + } + finally + { + _inputReady.Reset (); + } + +#if PROCESS_REQUEST + _neededProcessRequest = false; +#endif + if (_inputQueue.Count > 0) + { + if (_inputQueue.TryDequeue (out InputResult? result)) + { + return result; + } + } + } + + return null; + } + + private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, bool intercept = true) + { + while (!cancellationToken.IsCancellationRequested) + { + // if there is a key available, return it without waiting + // (or dispatching work to the thread queue) + if (Console.KeyAvailable) + { + return Console.ReadKey (intercept); + } + + if (EscSeqUtils.IncompleteCkInfos is null && EscSeqRequests is { Statuses.Count: > 0 }) + { + if (_retries > 1) + { + if (EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) + { + lock (seqReqStatus!.AnsiRequest._responseLock) + { + EscSeqRequests.Statuses.TryDequeue (out _); + + seqReqStatus.AnsiRequest.Response = string.Empty; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + } + } + + _retries = 0; + } + else + { + _retries++; + } + } + else + { + _retries = 0; + } + + if (!_forceRead) + { + Task.Delay (100, cancellationToken).Wait (cancellationToken); + } + } + + cancellationToken.ThrowIfCancellationRequested (); + + return default (ConsoleKeyInfo); + } + + internal bool _forceRead; + private int _retries; + + private void ProcessInputQueue () + { + while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false }) + { + try + { + if (!_forceRead) + { + _waitForStart.Wait (_inputReadyCancellationTokenSource.Token); + } + } + catch (OperationCanceledException) + { + return; + } + + _waitForStart.Reset (); + + if (_inputQueue.Count == 0 || _forceRead) + { + ConsoleKey key = 0; + ConsoleModifiers mod = 0; + ConsoleKeyInfo newConsoleKeyInfo = default; + + while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false }) + { + ConsoleKeyInfo consoleKeyInfo; + + try + { + consoleKeyInfo = ReadConsoleKeyInfo (_inputReadyCancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + return; + } + + if (EscSeqUtils.IncompleteCkInfos is { }) + { + EscSeqUtils.InsertArray (EscSeqUtils.IncompleteCkInfos, _cki); + } + + if ((consoleKeyInfo.KeyChar == (char)KeyCode.Esc && !_isEscSeq) + || (consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq)) + { + if (_cki is null && consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq) + { + _cki = EscSeqUtils.ResizeArray ( + new ConsoleKeyInfo ( + (char)KeyCode.Esc, + 0, + false, + false, + false + ), + _cki + ); + } + + _isEscSeq = true; + + if ((_cki is { } && _cki [^1].KeyChar != Key.Esc && consoleKeyInfo.KeyChar != Key.Esc && consoleKeyInfo.KeyChar <= Key.Space) + || (_cki is { } && _cki [^1].KeyChar != '\u001B' && consoleKeyInfo.KeyChar == 127) + || (_cki is { } && char.IsLetter (_cki [^1].KeyChar) && char.IsLower (consoleKeyInfo.KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar)) + || (_cki is { Length: > 2 } && char.IsLetter (_cki [^1].KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar))) + { + ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); + _cki = null; + _isEscSeq = false; + + ProcessMapConsoleKeyInfo (consoleKeyInfo); + } + else + { + newConsoleKeyInfo = consoleKeyInfo; + _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki); + + if (Console.KeyAvailable) + { + continue; + } + + ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); + _cki = null; + _isEscSeq = false; + } + + break; + } + + if (consoleKeyInfo.KeyChar == (char)KeyCode.Esc && _isEscSeq && _cki is { }) + { + ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); + _cki = null; + + if (Console.KeyAvailable) + { + _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki); + } + else + { + ProcessMapConsoleKeyInfo (consoleKeyInfo); + } + + break; + } + + ProcessMapConsoleKeyInfo (consoleKeyInfo); + + if (_retries > 0) + { + _retries = 0; + } + + break; + } + } + + _inputReady.Set (); + } + + void ProcessMapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) + { + _inputQueue.Enqueue ( + new InputResult + { + EventType = EventType.Key, ConsoleKeyInfo = EscSeqUtils.MapConsoleKeyInfo (consoleKeyInfo) + } + ); + _isEscSeq = false; + } + } + + private void CheckWindowSizeChange () + { + void RequestWindowSize (CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + // Wait for a while then check if screen has changed sizes + Task.Delay (500, cancellationToken).Wait (cancellationToken); + + int buffHeight, buffWidth; + + if (((NetDriver)_consoleDriver).IsWinPlatform) + { + buffHeight = Math.Max (Console.BufferHeight, 0); + buffWidth = Math.Max (Console.BufferWidth, 0); + } + else + { + buffHeight = _consoleDriver.Rows; + buffWidth = _consoleDriver.Cols; + } + + if (EnqueueWindowSizeEvent ( + Math.Max (Console.WindowHeight, 0), + Math.Max (Console.WindowWidth, 0), + buffHeight, + buffWidth + )) + { + return; + } + } + + cancellationToken.ThrowIfCancellationRequested (); + } + + while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false }) + { + try + { + _winChange.Wait (_inputReadyCancellationTokenSource.Token); + _winChange.Reset (); + + RequestWindowSize (_inputReadyCancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + return; + } + + _inputReady.Set (); + } + } + + /// Enqueue a window size event if the window size has changed. + /// + /// + /// + /// + /// + private bool EnqueueWindowSizeEvent (int winHeight, int winWidth, int buffHeight, int buffWidth) + { + if (winWidth == _consoleDriver.Cols && winHeight == _consoleDriver.Rows) + { + return false; + } + + int w = Math.Max (winWidth, 0); + int h = Math.Max (winHeight, 0); + + _inputQueue.Enqueue ( + new InputResult + { + EventType = EventType.WindowSize, WindowSizeEvent = new WindowSizeEvent { Size = new (w, h) } + } + ); + + return true; + } + + // Process a CSI sequence received by the driver (key pressed, mouse event, or request/response event) + private void ProcessRequestResponse ( + ref ConsoleKeyInfo newConsoleKeyInfo, + ref ConsoleKey key, + ConsoleKeyInfo [] cki, + ref ConsoleModifiers mod + ) + { + // isMouse is true if it's CSI<, false otherwise + EscSeqUtils.DecodeEscSeq ( + EscSeqRequests, + ref newConsoleKeyInfo, + ref key, + cki, + ref mod, + out string c1Control, + out string code, + out string [] values, + out string terminating, + out bool isMouse, + out List mouseFlags, + out Point pos, + out EscSeqReqStatus seqReqStatus, + (f, p) => HandleMouseEvent (MapMouseFlags (f), p) + ); + + if (isMouse) + { + foreach (MouseFlags mf in mouseFlags) + { + HandleMouseEvent (MapMouseFlags (mf), pos); + } + + return; + } + + if (seqReqStatus is { }) + { + //HandleRequestResponseEvent (c1Control, code, values, terminating); + + var ckiString = EscSeqUtils.ToString (cki); + + lock (seqReqStatus.AnsiRequest._responseLock) + { + seqReqStatus.AnsiRequest.Response = ckiString; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, ckiString); + } + + return; + } + + if (!string.IsNullOrEmpty (EscSeqUtils.InvalidRequestTerminator)) + { + if (EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus result)) + { + lock (result.AnsiRequest._responseLock) + { + result.AnsiRequest.Response = EscSeqUtils.InvalidRequestTerminator; + result.AnsiRequest.RaiseResponseFromInput (result.AnsiRequest, EscSeqUtils.InvalidRequestTerminator); + + EscSeqUtils.InvalidRequestTerminator = null; + } + } + + return; + } + + if (newConsoleKeyInfo != default) + { + HandleKeyboardEvent (newConsoleKeyInfo); + } + } + + [UnconditionalSuppressMessage ("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "")] + private MouseButtonState MapMouseFlags (MouseFlags mouseFlags) + { + MouseButtonState mbs = default; + + foreach (object flag in Enum.GetValues (mouseFlags.GetType ())) + { + if (mouseFlags.HasFlag ((MouseFlags)flag)) + { + switch (flag) + { + case MouseFlags.Button1Pressed: + mbs |= MouseButtonState.Button1Pressed; + + break; + case MouseFlags.Button1Released: + mbs |= MouseButtonState.Button1Released; + + break; + case MouseFlags.Button1Clicked: + mbs |= MouseButtonState.Button1Clicked; + + break; + case MouseFlags.Button1DoubleClicked: + mbs |= MouseButtonState.Button1DoubleClicked; + + break; + case MouseFlags.Button1TripleClicked: + mbs |= MouseButtonState.Button1TripleClicked; + + break; + case MouseFlags.Button2Pressed: + mbs |= MouseButtonState.Button2Pressed; + + break; + case MouseFlags.Button2Released: + mbs |= MouseButtonState.Button2Released; + + break; + case MouseFlags.Button2Clicked: + mbs |= MouseButtonState.Button2Clicked; + + break; + case MouseFlags.Button2DoubleClicked: + mbs |= MouseButtonState.Button2DoubleClicked; + + break; + case MouseFlags.Button2TripleClicked: + mbs |= MouseButtonState.Button2TripleClicked; + + break; + case MouseFlags.Button3Pressed: + mbs |= MouseButtonState.Button3Pressed; + + break; + case MouseFlags.Button3Released: + mbs |= MouseButtonState.Button3Released; + + break; + case MouseFlags.Button3Clicked: + mbs |= MouseButtonState.Button3Clicked; + + break; + case MouseFlags.Button3DoubleClicked: + mbs |= MouseButtonState.Button3DoubleClicked; + + break; + case MouseFlags.Button3TripleClicked: + mbs |= MouseButtonState.Button3TripleClicked; + + break; + case MouseFlags.WheeledUp: + mbs |= MouseButtonState.ButtonWheeledUp; + + break; + case MouseFlags.WheeledDown: + mbs |= MouseButtonState.ButtonWheeledDown; + + break; + case MouseFlags.WheeledLeft: + mbs |= MouseButtonState.ButtonWheeledLeft; + + break; + case MouseFlags.WheeledRight: + mbs |= MouseButtonState.ButtonWheeledRight; + + break; + case MouseFlags.Button4Pressed: + mbs |= MouseButtonState.Button4Pressed; + + break; + case MouseFlags.Button4Released: + mbs |= MouseButtonState.Button4Released; + + break; + case MouseFlags.Button4Clicked: + mbs |= MouseButtonState.Button4Clicked; + + break; + case MouseFlags.Button4DoubleClicked: + mbs |= MouseButtonState.Button4DoubleClicked; + + break; + case MouseFlags.Button4TripleClicked: + mbs |= MouseButtonState.Button4TripleClicked; + + break; + case MouseFlags.ButtonShift: + mbs |= MouseButtonState.ButtonShift; + + break; + case MouseFlags.ButtonCtrl: + mbs |= MouseButtonState.ButtonCtrl; + + break; + case MouseFlags.ButtonAlt: + mbs |= MouseButtonState.ButtonAlt; + + break; + case MouseFlags.ReportMousePosition: + mbs |= MouseButtonState.ReportMousePosition; + + break; + case MouseFlags.AllEvents: + mbs |= MouseButtonState.AllEvents; + + break; + } + } + } + + return mbs; + } + + private Point _lastCursorPosition; + + //private void HandleRequestResponseEvent (string c1Control, string code, string [] values, string terminating) + //{ + // if (terminating == + + // // BUGBUG: I can't find where we send a request for cursor position (ESC[?6n), so I'm not sure if this is needed. + // // The observation is correct because the response isn't immediate and this is useless + // EscSeqUtils.CSI_RequestCursorPositionReport.Terminator) + // { + // var point = new Point { X = int.Parse (values [1]) - 1, Y = int.Parse (values [0]) - 1 }; + + // if (_lastCursorPosition.Y != point.Y) + // { + // _lastCursorPosition = point; + // var eventType = EventType.WindowPosition; + // var winPositionEv = new WindowPositionEvent { CursorPosition = point }; + + // _inputQueue.Enqueue ( + // new InputResult { EventType = eventType, WindowPositionEvent = winPositionEv } + // ); + // } + // else + // { + // return; + // } + // } + // else if (terminating == EscSeqUtils.CSI_ReportTerminalSizeInChars.Terminator) + // { + // if (values [0] == EscSeqUtils.CSI_ReportTerminalSizeInChars.Value) + // { + // EnqueueWindowSizeEvent ( + // Math.Max (int.Parse (values [1]), 0), + // Math.Max (int.Parse (values [2]), 0), + // Math.Max (int.Parse (values [1]), 0), + // Math.Max (int.Parse (values [2]), 0) + // ); + // } + // else + // { + // EnqueueRequestResponseEvent (c1Control, code, values, terminating); + // } + // } + // else + // { + // EnqueueRequestResponseEvent (c1Control, code, values, terminating); + // } + + // _inputReady.Set (); + //} + + //private void EnqueueRequestResponseEvent (string c1Control, string code, string [] values, string terminating) + //{ + // var eventType = EventType.RequestResponse; + // var requestRespEv = new RequestResponseEvent { ResultTuple = (c1Control, code, values, terminating) }; + + // _inputQueue.Enqueue ( + // new InputResult { EventType = eventType, RequestResponseEvent = requestRespEv } + // ); + //} + + private void HandleMouseEvent (MouseButtonState buttonState, Point pos) + { + var mouseEvent = new MouseEvent { Position = pos, ButtonState = buttonState }; + + _inputQueue.Enqueue ( + new InputResult { EventType = EventType.Mouse, MouseEvent = mouseEvent } + ); + + _inputReady.Set (); + } + + public enum EventType + { + Key = 1, + Mouse = 2, + WindowSize = 3, + WindowPosition = 4, + RequestResponse = 5 + } + + [Flags] + public enum MouseButtonState + { + Button1Pressed = 0x1, + Button1Released = 0x2, + Button1Clicked = 0x4, + Button1DoubleClicked = 0x8, + Button1TripleClicked = 0x10, + Button2Pressed = 0x20, + Button2Released = 0x40, + Button2Clicked = 0x80, + Button2DoubleClicked = 0x100, + Button2TripleClicked = 0x200, + Button3Pressed = 0x400, + Button3Released = 0x800, + Button3Clicked = 0x1000, + Button3DoubleClicked = 0x2000, + Button3TripleClicked = 0x4000, + ButtonWheeledUp = 0x8000, + ButtonWheeledDown = 0x10000, + ButtonWheeledLeft = 0x20000, + ButtonWheeledRight = 0x40000, + Button4Pressed = 0x80000, + Button4Released = 0x100000, + Button4Clicked = 0x200000, + Button4DoubleClicked = 0x400000, + Button4TripleClicked = 0x800000, + ButtonShift = 0x1000000, + ButtonCtrl = 0x2000000, + ButtonAlt = 0x4000000, + ReportMousePosition = 0x8000000, + AllEvents = -1 + } + + public struct MouseEvent + { + public Point Position; + public MouseButtonState ButtonState; + } + + public struct WindowSizeEvent + { + public Size Size; + } + + public struct WindowPositionEvent + { + public int Top; + public int Left; + public Point CursorPosition; + } + + public struct RequestResponseEvent + { + public (string c1Control, string code, string [] values, string terminating) ResultTuple; + } + + public struct InputResult + { + public EventType EventType; + public ConsoleKeyInfo ConsoleKeyInfo; + public MouseEvent MouseEvent; + public WindowSizeEvent WindowSizeEvent; + public WindowPositionEvent WindowPositionEvent; + public RequestResponseEvent RequestResponseEvent; + + public readonly override string ToString () + { + return EventType switch + { + EventType.Key => ToString (ConsoleKeyInfo), + EventType.Mouse => MouseEvent.ToString (), + + //EventType.WindowSize => WindowSize.ToString (), + //EventType.RequestResponse => RequestResponse.ToString (), + _ => "Unknown event type: " + EventType + }; + } + + /// Prints a ConsoleKeyInfoEx structure + /// + /// + public readonly string ToString (ConsoleKeyInfo cki) + { + var ke = new Key ((KeyCode)cki.KeyChar); + var sb = new StringBuilder (); + sb.Append ($"Key: {(KeyCode)cki.Key} ({cki.Key})"); + sb.Append ((cki.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty); + sb.Append ((cki.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty); + sb.Append ((cki.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty); + sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)cki.KeyChar}) "); + string s = sb.ToString ().TrimEnd (',').TrimEnd (' '); + + return $"[ConsoleKeyInfo({s})]"; + } + } + + private void HandleKeyboardEvent (ConsoleKeyInfo cki) + { + var inputResult = new InputResult { EventType = EventType.Key, ConsoleKeyInfo = cki }; + + _inputQueue.Enqueue (inputResult); + } + + public void Dispose () + { + _inputReadyCancellationTokenSource?.Cancel (); + _inputReadyCancellationTokenSource?.Dispose (); + _inputReadyCancellationTokenSource = null; + + try + { + // throws away any typeahead that has been typed by + // the user and has not yet been read by the program. + while (Console.KeyAvailable) + { + Console.ReadKey (true); + } + } + catch (InvalidOperationException) + { + // Ignore - Console input has already been closed + } + } +} diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs new file mode 100644 index 0000000000..d876ef0cbb --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs @@ -0,0 +1,173 @@ +using System.Collections.Concurrent; + +namespace Terminal.Gui; + +/// +/// Mainloop intended to be used with the .NET System.Console API, and can be used on Windows and Unix, it is +/// cross-platform but lacks things like file descriptor monitoring. +/// +/// This implementation is used for NetDriver. +internal class NetMainLoop : IMainLoopDriver +{ + internal NetEvents _netEvents; + + /// Invoked when a Key is pressed. + internal Action ProcessInput; + + private readonly ManualResetEventSlim _eventReady = new (false); + private readonly CancellationTokenSource _inputHandlerTokenSource = new (); + private readonly ConcurrentQueue _resultQueue = new (); + internal readonly ManualResetEventSlim _waitForProbe = new (false); + private readonly CancellationTokenSource _eventReadyTokenSource = new (); + private MainLoop _mainLoop; + + /// Initializes the class with the console driver. + /// Passing a consoleDriver is provided to capture windows resizing. + /// The console driver used by this Net main loop. + /// + public NetMainLoop (ConsoleDriver consoleDriver = null) + { + if (consoleDriver is null) + { + throw new ArgumentNullException (nameof (consoleDriver)); + } + + _netEvents = new NetEvents (consoleDriver); + } + + void IMainLoopDriver.Setup (MainLoop mainLoop) + { + _mainLoop = mainLoop; + + if (ConsoleDriver.RunningUnitTests) + { + return; + } + + Task.Run (NetInputHandler, _inputHandlerTokenSource.Token); + } + + void IMainLoopDriver.Wakeup () { _eventReady.Set (); } + + bool IMainLoopDriver.EventsPending () + { + _waitForProbe.Set (); + + if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) + { + return true; + } + + try + { + if (!_eventReadyTokenSource.IsCancellationRequested) + { + // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there + // are no timers, but there IS an idle handler waiting. + _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token); + } + } + catch (OperationCanceledException) + { + return true; + } + finally + { + _eventReady.Reset (); + } + + _eventReadyTokenSource.Token.ThrowIfCancellationRequested (); + + if (!_eventReadyTokenSource.IsCancellationRequested) + { + return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _); + } + + return true; + } + + void IMainLoopDriver.Iteration () + { + while (_resultQueue.Count > 0) + { + // Always dequeue even if it's null and invoke if isn't null + if (_resultQueue.TryDequeue (out NetEvents.InputResult? dequeueResult)) + { + if (dequeueResult is { }) + { + ProcessInput?.Invoke (dequeueResult.Value); + } + } + } + } + + void IMainLoopDriver.TearDown () + { + _inputHandlerTokenSource?.Cancel (); + _inputHandlerTokenSource?.Dispose (); + _eventReadyTokenSource?.Cancel (); + _eventReadyTokenSource?.Dispose (); + + _eventReady?.Dispose (); + + _resultQueue?.Clear (); + _waitForProbe?.Dispose (); + _netEvents?.Dispose (); + _netEvents = null; + + _mainLoop = null; + } + + private void NetInputHandler () + { + while (_mainLoop is { }) + { + try + { + if (!_netEvents._forceRead && !_inputHandlerTokenSource.IsCancellationRequested) + { + _waitForProbe.Wait (_inputHandlerTokenSource.Token); + } + } + catch (OperationCanceledException) + { + return; + } + finally + { + if (_waitForProbe.IsSet) + { + _waitForProbe.Reset (); + } + } + + if (_inputHandlerTokenSource.IsCancellationRequested) + { + return; + } + + _inputHandlerTokenSource.Token.ThrowIfCancellationRequested (); + + if (_resultQueue.Count == 0) + { + _resultQueue.Enqueue (_netEvents.DequeueInput ()); + } + + try + { + while (_resultQueue.Count > 0 && _resultQueue.TryPeek (out NetEvents.InputResult? result) && result is null) + { + // Dequeue null values + _resultQueue.TryDequeue (out _); + } + } + catch (InvalidOperationException) // Peek can raise an exception + { } + + if (_resultQueue.Count > 0) + { + _eventReady.Set (); + } + } + } +} diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetWinVTConsole.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetWinVTConsole.cs new file mode 100644 index 0000000000..81a9f6b68b --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetWinVTConsole.cs @@ -0,0 +1,125 @@ +using System.Runtime.InteropServices; + +namespace Terminal.Gui; + +internal class NetWinVTConsole +{ + private const uint DISABLE_NEWLINE_AUTO_RETURN = 8; + private const uint ENABLE_ECHO_INPUT = 4; + private const uint ENABLE_EXTENDED_FLAGS = 128; + private const uint ENABLE_INSERT_MODE = 32; + private const uint ENABLE_LINE_INPUT = 2; + private const uint ENABLE_LVB_GRID_WORLDWIDE = 10; + private const uint ENABLE_MOUSE_INPUT = 16; + + // Input modes. + private const uint ENABLE_PROCESSED_INPUT = 1; + + // Output modes. + private const uint ENABLE_PROCESSED_OUTPUT = 1; + private const uint ENABLE_QUICK_EDIT_MODE = 64; + private const uint ENABLE_VIRTUAL_TERMINAL_INPUT = 512; + private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4; + private const uint ENABLE_WINDOW_INPUT = 8; + private const uint ENABLE_WRAP_AT_EOL_OUTPUT = 2; + private const int STD_ERROR_HANDLE = -12; + private const int STD_INPUT_HANDLE = -10; + private const int STD_OUTPUT_HANDLE = -11; + + private readonly nint _errorHandle; + private readonly nint _inputHandle; + private readonly uint _originalErrorConsoleMode; + private readonly uint _originalInputConsoleMode; + private readonly uint _originalOutputConsoleMode; + private readonly nint _outputHandle; + + public NetWinVTConsole () + { + _inputHandle = GetStdHandle (STD_INPUT_HANDLE); + + if (!GetConsoleMode (_inputHandle, out uint mode)) + { + throw new ApplicationException ($"Failed to get input console mode, error code: {GetLastError ()}."); + } + + _originalInputConsoleMode = mode; + + if ((mode & ENABLE_VIRTUAL_TERMINAL_INPUT) < ENABLE_VIRTUAL_TERMINAL_INPUT) + { + mode |= ENABLE_VIRTUAL_TERMINAL_INPUT; + + if (!SetConsoleMode (_inputHandle, mode)) + { + throw new ApplicationException ($"Failed to set input console mode, error code: {GetLastError ()}."); + } + } + + _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE); + + if (!GetConsoleMode (_outputHandle, out mode)) + { + throw new ApplicationException ($"Failed to get output console mode, error code: {GetLastError ()}."); + } + + _originalOutputConsoleMode = mode; + + if ((mode & (ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN) + { + mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN; + + if (!SetConsoleMode (_outputHandle, mode)) + { + throw new ApplicationException ($"Failed to set output console mode, error code: {GetLastError ()}."); + } + } + + _errorHandle = GetStdHandle (STD_ERROR_HANDLE); + + if (!GetConsoleMode (_errorHandle, out mode)) + { + throw new ApplicationException ($"Failed to get error console mode, error code: {GetLastError ()}."); + } + + _originalErrorConsoleMode = mode; + + if ((mode & DISABLE_NEWLINE_AUTO_RETURN) < DISABLE_NEWLINE_AUTO_RETURN) + { + mode |= DISABLE_NEWLINE_AUTO_RETURN; + + if (!SetConsoleMode (_errorHandle, mode)) + { + throw new ApplicationException ($"Failed to set error console mode, error code: {GetLastError ()}."); + } + } + } + + public void Cleanup () + { + if (!SetConsoleMode (_inputHandle, _originalInputConsoleMode)) + { + throw new ApplicationException ($"Failed to restore input console mode, error code: {GetLastError ()}."); + } + + if (!SetConsoleMode (_outputHandle, _originalOutputConsoleMode)) + { + throw new ApplicationException ($"Failed to restore output console mode, error code: {GetLastError ()}."); + } + + if (!SetConsoleMode (_errorHandle, _originalErrorConsoleMode)) + { + throw new ApplicationException ($"Failed to restore error console mode, error code: {GetLastError ()}."); + } + } + + [DllImport ("kernel32.dll")] + private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode); + + [DllImport ("kernel32.dll")] + private static extern uint GetLastError (); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern nint GetStdHandle (int nStdHandle); + + [DllImport ("kernel32.dll")] + private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode); +} diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs new file mode 100644 index 0000000000..22c0e10357 --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs @@ -0,0 +1,1109 @@ +// TODO: #nullable enable +using System.ComponentModel; +using System.Runtime.InteropServices; +using Terminal.Gui.ConsoleDrivers; + +namespace Terminal.Gui; + +internal class WindowsConsole +{ + internal WindowsMainLoop _mainLoop; + + public const int STD_OUTPUT_HANDLE = -11; + public const int STD_INPUT_HANDLE = -10; + + private readonly nint _inputHandle; + private nint _outputHandle; + //private nint _screenBuffer; + private readonly uint _originalConsoleMode; + private CursorVisibility? _initialCursorVisibility; + private CursorVisibility? _currentCursorVisibility; + private CursorVisibility? _pendingCursorVisibility; + private readonly StringBuilder _stringBuilder = new (256 * 1024); + private string _lastWrite = string.Empty; + + public WindowsConsole () + { + _inputHandle = GetStdHandle (STD_INPUT_HANDLE); + _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE); + _originalConsoleMode = ConsoleMode; + uint newConsoleMode = _originalConsoleMode; + newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags); + newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode; + newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput; + ConsoleMode = newConsoleMode; + } + + private CharInfo [] _originalStdOutChars; + + public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord bufferSize, SmallRect window, bool force16Colors) + { + //Debug.WriteLine ("WriteToConsole"); + + //if (_screenBuffer == nint.Zero) + //{ + // ReadFromConsoleOutput (size, bufferSize, ref window); + //} + + var result = false; + + if (force16Colors) + { + var i = 0; + CharInfo [] ci = new CharInfo [charInfoBuffer.Length]; + + foreach (ExtendedCharInfo info in charInfoBuffer) + { + ci [i++] = new CharInfo + { + Char = new CharUnion { UnicodeChar = info.Char }, + Attributes = + (ushort)((int)info.Attribute.Foreground.GetClosestNamedColor16 () | ((int)info.Attribute.Background.GetClosestNamedColor16 () << 4)) + }; + } + + result = WriteConsoleOutput (_outputHandle, ci, bufferSize, new Coord { X = window.Left, Y = window.Top }, ref window); + } + else + { + _stringBuilder.Clear (); + + _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition); + _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0)); + + Attribute? prev = null; + + foreach (ExtendedCharInfo info in charInfoBuffer) + { + Attribute attr = info.Attribute; + + if (attr != prev) + { + prev = attr; + _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B)); + _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B)); + } + + if (info.Char != '\x1b') + { + if (!info.Empty) + { + _stringBuilder.Append (info.Char); + } + } + else + { + _stringBuilder.Append (' '); + } + } + + _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition); + _stringBuilder.Append (EscSeqUtils.CSI_HideCursor); + + var s = _stringBuilder.ToString (); + + // TODO: requires extensive testing if we go down this route + // If console output has changed + if (s != _lastWrite) + { + // supply console with the new content + result = WriteConsole (_outputHandle, s, (uint)s.Length, out uint _, nint.Zero); + } + + _lastWrite = s; + + foreach (var sixel in Application.Sixel) + { + SetCursorPosition (new Coord ((short)sixel.ScreenPosition.X, (short)sixel.ScreenPosition.Y)); + WriteConsole (_outputHandle, sixel.SixelData, (uint)sixel.SixelData.Length, out uint _, nint.Zero); + } + } + + if (!result) + { + int err = Marshal.GetLastWin32Error (); + + if (err != 0) + { + throw new Win32Exception (err); + } + } + + return result; + } + + internal bool WriteANSI (string ansi) + { + if (WriteConsole (_outputHandle, ansi, (uint)ansi.Length, out uint _, nint.Zero)) + { + // Flush the output to make sure it's sent immediately + return FlushFileBuffers (_outputHandle); + } + + return false; + } + + public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window) + { + //_screenBuffer = CreateConsoleScreenBuffer ( + // DesiredAccess.GenericRead | DesiredAccess.GenericWrite, + // ShareMode.FileShareRead | ShareMode.FileShareWrite, + // nint.Zero, + // 1, + // nint.Zero + // ); + + //if (_screenBuffer == INVALID_HANDLE_VALUE) + //{ + // int err = Marshal.GetLastWin32Error (); + + // if (err != 0) + // { + // throw new Win32Exception (err); + // } + //} + + SetInitialCursorVisibility (); + + //if (!SetConsoleActiveScreenBuffer (_screenBuffer)) + //{ + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + //} + + _originalStdOutChars = new CharInfo [size.Height * size.Width]; + + if (!ReadConsoleOutput (_outputHandle, _originalStdOutChars, coords, new Coord { X = 0, Y = 0 }, ref window)) + { + throw new Win32Exception (Marshal.GetLastWin32Error ()); + } + } + + public bool SetCursorPosition (Coord position) + { + return SetConsoleCursorPosition (_outputHandle, position); + } + + public void SetInitialCursorVisibility () + { + if (_initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility)) + { + _initialCursorVisibility = visibility; + } + } + + public bool GetCursorVisibility (out CursorVisibility visibility) + { + if (_outputHandle == nint.Zero) + { + visibility = CursorVisibility.Invisible; + + return false; + } + + if (!GetConsoleCursorInfo (_outputHandle, out ConsoleCursorInfo info)) + { + int err = Marshal.GetLastWin32Error (); + + if (err != 0) + { + throw new Win32Exception (err); + } + + visibility = CursorVisibility.Default; + + return false; + } + + if (!info.bVisible) + { + visibility = CursorVisibility.Invisible; + } + else if (info.dwSize > 50) + { + visibility = CursorVisibility.Default; + } + else + { + visibility = CursorVisibility.Default; + } + + return true; + } + + public bool EnsureCursorVisibility () + { + if (_initialCursorVisibility.HasValue && _pendingCursorVisibility.HasValue && SetCursorVisibility (_pendingCursorVisibility.Value)) + { + _pendingCursorVisibility = null; + + return true; + } + + return false; + } + + public void ForceRefreshCursorVisibility () + { + if (_currentCursorVisibility.HasValue) + { + _pendingCursorVisibility = _currentCursorVisibility; + _currentCursorVisibility = null; + } + } + + public bool SetCursorVisibility (CursorVisibility visibility) + { + if (_initialCursorVisibility.HasValue == false) + { + _pendingCursorVisibility = visibility; + + return false; + } + + if (_currentCursorVisibility.HasValue == false || _currentCursorVisibility.Value != visibility) + { + var info = new ConsoleCursorInfo + { + dwSize = (uint)visibility & 0x00FF, + bVisible = ((uint)visibility & 0xFF00) != 0 + }; + + if (!SetConsoleCursorInfo (_outputHandle, ref info)) + { + return false; + } + + _currentCursorVisibility = visibility; + } + + return true; + } + + public void Cleanup () + { + if (_initialCursorVisibility.HasValue) + { + SetCursorVisibility (_initialCursorVisibility.Value); + } + + //SetConsoleOutputWindow (out _); + + ConsoleMode = _originalConsoleMode; + + _outputHandle = CreateConsoleScreenBuffer ( + DesiredAccess.GenericRead | DesiredAccess.GenericWrite, + ShareMode.FileShareRead | ShareMode.FileShareWrite, + nint.Zero, + 1, + nint.Zero + ); + + if (!SetConsoleActiveScreenBuffer (_outputHandle)) + { + int err = Marshal.GetLastWin32Error (); + Console.WriteLine ("Error: {0}", err); + } + + //if (_screenBuffer != nint.Zero) + //{ + // CloseHandle (_screenBuffer); + //} + + //_screenBuffer = nint.Zero; + } + + //internal Size GetConsoleBufferWindow (out Point position) + //{ + // if (_screenBuffer == nint.Zero) + // { + // position = Point.Empty; + + // return Size.Empty; + // } + + // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); + // csbi.cbSize = (uint)Marshal.SizeOf (csbi); + + // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ()); + // position = Point.Empty; + + // return Size.Empty; + // } + + // Size sz = new ( + // csbi.srWindow.Right - csbi.srWindow.Left + 1, + // csbi.srWindow.Bottom - csbi.srWindow.Top + 1); + // position = new (csbi.srWindow.Left, csbi.srWindow.Top); + + // return sz; + //} + + internal Size GetConsoleOutputWindow (out Point position) + { + var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); + csbi.cbSize = (uint)Marshal.SizeOf (csbi); + + if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) + { + throw new Win32Exception (Marshal.GetLastWin32Error ()); + } + + Size sz = new ( + csbi.srWindow.Right - csbi.srWindow.Left + 1, + csbi.srWindow.Bottom - csbi.srWindow.Top + 1); + position = new (csbi.srWindow.Left, csbi.srWindow.Top); + + return sz; + } + + //internal Size SetConsoleWindow (short cols, short rows) + //{ + // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); + // csbi.cbSize = (uint)Marshal.SizeOf (csbi); + + // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // Coord maxWinSize = GetLargestConsoleWindowSize (_screenBuffer); + // short newCols = Math.Min (cols, maxWinSize.X); + // short newRows = Math.Min (rows, maxWinSize.Y); + // csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1)); + // csbi.srWindow = new SmallRect (0, 0, newCols, newRows); + // csbi.dwMaximumWindowSize = new Coord (newCols, newRows); + + // if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0)); + + // if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) + // { + // //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ()); + // return new (cols, rows); + // } + + // SetConsoleOutputWindow (csbi); + + // return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1); + //} + + //private void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi) + //{ + // if (_screenBuffer != nint.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + //} + + //internal Size SetConsoleOutputWindow (out Point position) + //{ + // if (_screenBuffer == nint.Zero) + // { + // position = Point.Empty; + + // return Size.Empty; + // } + + // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); + // csbi.cbSize = (uint)Marshal.SizeOf (csbi); + + // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // Size sz = new ( + // csbi.srWindow.Right - csbi.srWindow.Left + 1, + // Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0)); + // position = new (csbi.srWindow.Left, csbi.srWindow.Top); + // SetConsoleOutputWindow (csbi); + // var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0)); + + // if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) + // { + // throw new Win32Exception (Marshal.GetLastWin32Error ()); + // } + + // return sz; + //} + + private uint ConsoleMode + { + get + { + GetConsoleMode (_inputHandle, out uint v); + + return v; + } + set => SetConsoleMode (_inputHandle, value); + } + + [Flags] + public enum ConsoleModes : uint + { + EnableProcessedInput = 1, + EnableMouseInput = 16, + EnableQuickEditMode = 64, + EnableExtendedFlags = 128 + } + + [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)] + public struct KeyEventRecord + { + [FieldOffset (0)] + [MarshalAs (UnmanagedType.Bool)] + public bool bKeyDown; + + [FieldOffset (4)] + [MarshalAs (UnmanagedType.U2)] + public ushort wRepeatCount; + + [FieldOffset (6)] + [MarshalAs (UnmanagedType.U2)] + public ConsoleKeyMapping.VK wVirtualKeyCode; + + [FieldOffset (8)] + [MarshalAs (UnmanagedType.U2)] + public ushort wVirtualScanCode; + + [FieldOffset (10)] + public char UnicodeChar; + + [FieldOffset (12)] + [MarshalAs (UnmanagedType.U4)] + public ControlKeyState dwControlKeyState; + + public readonly override string ToString () + { + return + $"[KeyEventRecord({(bKeyDown ? "down" : "up")},{wRepeatCount},{wVirtualKeyCode},{wVirtualScanCode},{new Rune (UnicodeChar).MakePrintable ()},{dwControlKeyState})]"; + } + } + + [Flags] + public enum ButtonState + { + NoButtonPressed = 0, + Button1Pressed = 1, + Button2Pressed = 4, + Button3Pressed = 8, + Button4Pressed = 16, + RightmostButtonPressed = 2 + } + + [Flags] + public enum ControlKeyState + { + NoControlKeyPressed = 0, + RightAltPressed = 1, + LeftAltPressed = 2, + RightControlPressed = 4, + LeftControlPressed = 8, + ShiftPressed = 16, + NumlockOn = 32, + ScrolllockOn = 64, + CapslockOn = 128, + EnhancedKey = 256 + } + + [Flags] + public enum EventFlags + { + NoEvent = 0, + MouseMoved = 1, + DoubleClick = 2, + MouseWheeled = 4, + MouseHorizontalWheeled = 8 + } + + [StructLayout (LayoutKind.Explicit)] + public struct MouseEventRecord + { + [FieldOffset (0)] + public Coord MousePosition; + + [FieldOffset (4)] + public ButtonState ButtonState; + + [FieldOffset (8)] + public ControlKeyState ControlKeyState; + + [FieldOffset (12)] + public EventFlags EventFlags; + + public readonly override string ToString () { return $"[Mouse{MousePosition},{ButtonState},{ControlKeyState},{EventFlags}]"; } + } + + public struct WindowBufferSizeRecord + { + public Coord _size; + + public WindowBufferSizeRecord (short x, short y) { _size = new Coord (x, y); } + + public readonly override string ToString () { return $"[WindowBufferSize{_size}"; } + } + + [StructLayout (LayoutKind.Sequential)] + public struct MenuEventRecord + { + public uint dwCommandId; + } + + [StructLayout (LayoutKind.Sequential)] + public struct FocusEventRecord + { + public uint bSetFocus; + } + + public enum EventType : ushort + { + Focus = 0x10, + Key = 0x1, + Menu = 0x8, + Mouse = 2, + WindowBufferSize = 4 + } + + [StructLayout (LayoutKind.Explicit)] + public struct InputRecord + { + [FieldOffset (0)] + public EventType EventType; + + [FieldOffset (4)] + public KeyEventRecord KeyEvent; + + [FieldOffset (4)] + public MouseEventRecord MouseEvent; + + [FieldOffset (4)] + public WindowBufferSizeRecord WindowBufferSizeEvent; + + [FieldOffset (4)] + public MenuEventRecord MenuEvent; + + [FieldOffset (4)] + public FocusEventRecord FocusEvent; + + public readonly override string ToString () + { + return EventType switch + { + EventType.Focus => FocusEvent.ToString (), + EventType.Key => KeyEvent.ToString (), + EventType.Menu => MenuEvent.ToString (), + EventType.Mouse => MouseEvent.ToString (), + EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (), + _ => "Unknown event type: " + EventType + }; + } + } + + [Flags] + private enum ShareMode : uint + { + FileShareRead = 1, + FileShareWrite = 2 + } + + [Flags] + private enum DesiredAccess : uint + { + GenericRead = 2147483648, + GenericWrite = 1073741824 + } + + [StructLayout (LayoutKind.Sequential)] + public struct ConsoleScreenBufferInfo + { + public Coord dwSize; + public Coord dwCursorPosition; + public ushort wAttributes; + public SmallRect srWindow; + public Coord dwMaximumWindowSize; + } + + [StructLayout (LayoutKind.Sequential)] + public struct Coord + { + public short X; + public short Y; + + public Coord (short x, short y) + { + X = x; + Y = y; + } + + public readonly override string ToString () { return $"({X},{Y})"; } + } + + [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)] + public struct CharUnion + { + [FieldOffset (0)] + public char UnicodeChar; + + [FieldOffset (0)] + public byte AsciiChar; + } + + [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)] + public struct CharInfo + { + [FieldOffset (0)] + public CharUnion Char; + + [FieldOffset (2)] + public ushort Attributes; + } + + public struct ExtendedCharInfo + { + public char Char { get; set; } + public Attribute Attribute { get; set; } + public bool Empty { get; set; } // TODO: Temp hack until virtual terminal sequences + + public ExtendedCharInfo (char character, Attribute attribute) + { + Char = character; + Attribute = attribute; + Empty = false; + } + } + + [StructLayout (LayoutKind.Sequential)] + public struct SmallRect + { + public short Left; + public short Top; + public short Right; + public short Bottom; + + public SmallRect (short left, short top, short right, short bottom) + { + Left = left; + Top = top; + Right = right; + Bottom = bottom; + } + + public static void MakeEmpty (ref SmallRect rect) { rect.Left = -1; } + + public static void Update (ref SmallRect rect, short col, short row) + { + if (rect.Left == -1) + { + rect.Left = rect.Right = col; + rect.Bottom = rect.Top = row; + + return; + } + + if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom) + { + return; + } + + if (col < rect.Left) + { + rect.Left = col; + } + + if (col > rect.Right) + { + rect.Right = col; + } + + if (row < rect.Top) + { + rect.Top = row; + } + + if (row > rect.Bottom) + { + rect.Bottom = row; + } + } + + public readonly override string ToString () { return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}"; } + } + + [StructLayout (LayoutKind.Sequential)] + public struct ConsoleKeyInfoEx + { + public ConsoleKeyInfo ConsoleKeyInfo; + public bool CapsLock; + public bool NumLock; + public bool ScrollLock; + + public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock) + { + ConsoleKeyInfo = consoleKeyInfo; + CapsLock = capslock; + NumLock = numlock; + ScrollLock = scrolllock; + } + + /// + /// Prints a ConsoleKeyInfoEx structure + /// + /// + /// + public readonly string ToString (ConsoleKeyInfoEx ex) + { + var ke = new Key ((KeyCode)ex.ConsoleKeyInfo.KeyChar); + var sb = new StringBuilder (); + sb.Append ($"Key: {(KeyCode)ex.ConsoleKeyInfo.Key} ({ex.ConsoleKeyInfo.Key})"); + sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty); + sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty); + sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty); + sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)ex.ConsoleKeyInfo.KeyChar}) "); + sb.Append (ex.CapsLock ? "caps," : string.Empty); + sb.Append (ex.NumLock ? "num," : string.Empty); + sb.Append (ex.ScrollLock ? "scroll," : string.Empty); + string s = sb.ToString ().TrimEnd (',').TrimEnd (' '); + + return $"[ConsoleKeyInfoEx({s})]"; + } + } + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern nint GetStdHandle (int nStdHandle); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern bool CloseHandle (nint handle); + + [DllImport ("kernel32.dll", SetLastError = true)] + public static extern bool PeekConsoleInput (nint hConsoleInput, out InputRecord lpBuffer, uint nLength, out uint lpNumberOfEventsRead); + + [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)] + public static extern bool ReadConsoleInput ( + nint hConsoleInput, + out InputRecord lpBuffer, + uint nLength, + out uint lpNumberOfEventsRead + ); + + [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern bool ReadConsoleOutput ( + nint hConsoleOutput, + [Out] CharInfo [] lpBuffer, + Coord dwBufferSize, + Coord dwBufferCoord, + ref SmallRect lpReadRegion + ); + + // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput + [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern bool WriteConsoleOutput ( + nint hConsoleOutput, + CharInfo [] lpBuffer, + Coord dwBufferSize, + Coord dwBufferCoord, + ref SmallRect lpWriteRegion + ); + + [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern bool WriteConsole ( + nint hConsoleOutput, + string lpbufer, + uint NumberOfCharsToWriten, + out uint lpNumberOfCharsWritten, + nint lpReserved + ); + + [DllImport ("kernel32.dll", SetLastError = true)] + static extern bool FlushFileBuffers (nint hFile); + + [DllImport ("kernel32.dll")] + private static extern bool SetConsoleCursorPosition (nint hConsoleOutput, Coord dwCursorPosition); + + [StructLayout (LayoutKind.Sequential)] + public struct ConsoleCursorInfo + { + /// + /// The percentage of the character cell that is filled by the cursor.This value is between 1 and 100. + /// The cursor appearance varies, ranging from completely filling the cell to showing up as a horizontal + /// line at the bottom of the cell. + /// + public uint dwSize; + public bool bVisible; + } + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern bool SetConsoleCursorInfo (nint hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern bool GetConsoleCursorInfo (nint hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo); + + [DllImport ("kernel32.dll")] + private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode); + + [DllImport ("kernel32.dll")] + private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern nint CreateConsoleScreenBuffer ( + DesiredAccess dwDesiredAccess, + ShareMode dwShareMode, + nint secutiryAttributes, + uint flags, + nint screenBufferData + ); + + internal static nint INVALID_HANDLE_VALUE = new (-1); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern bool SetConsoleActiveScreenBuffer (nint Handle); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern bool GetNumberOfConsoleInputEvents (nint handle, out uint lpcNumberOfEvents); + + internal uint GetNumberOfConsoleInputEvents () + { + if (!GetNumberOfConsoleInputEvents (_inputHandle, out uint numOfEvents)) + { + Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}"); + + return 0; + } + + return numOfEvents; + } + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern bool FlushConsoleInputBuffer (nint handle); + + internal void FlushConsoleInputBuffer () + { + if (!FlushConsoleInputBuffer (_inputHandle)) + { + Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}"); + } + } + + private int _retries; + + public InputRecord [] ReadConsoleInput () + { + const int bufferSize = 1; + InputRecord inputRecord = default; + uint numberEventsRead = 0; + StringBuilder ansiSequence = new StringBuilder (); + bool readingSequence = false; + bool raisedResponse = false; + + while (true) + { + try + { + // Peek to check if there is any input available + if (PeekConsoleInput (_inputHandle, out _, bufferSize, out uint eventsRead) && eventsRead > 0) + { + // Read the input since it is available + ReadConsoleInput ( + _inputHandle, + out inputRecord, + bufferSize, + out numberEventsRead); + + if (inputRecord.EventType == EventType.Key) + { + KeyEventRecord keyEvent = inputRecord.KeyEvent; + + if (keyEvent.bKeyDown) + { + char inputChar = keyEvent.UnicodeChar; + + // Check if input is part of an ANSI escape sequence + if (inputChar == '\u001B') // Escape character + { + // Peek to check if there is any input available with key event and bKeyDown + if (PeekConsoleInput (_inputHandle, out InputRecord peekRecord, bufferSize, out eventsRead) && eventsRead > 0) + { + if (peekRecord is { EventType: EventType.Key, KeyEvent.bKeyDown: true }) + { + // It's really an ANSI request response + readingSequence = true; + ansiSequence.Clear (); // Start a new sequence + ansiSequence.Append (inputChar); + + continue; + } + } + } + else if (readingSequence) + { + ansiSequence.Append (inputChar); + + // Check if the sequence has ended with an expected command terminator + if (_mainLoop.EscSeqRequests is { } && _mainLoop.EscSeqRequests.HasResponse (inputChar.ToString (), out EscSeqReqStatus seqReqStatus)) + { + // Finished reading the sequence and remove the enqueued request + _mainLoop.EscSeqRequests.Remove (seqReqStatus); + + lock (seqReqStatus!.AnsiRequest._responseLock) + { + raisedResponse = true; + seqReqStatus.AnsiRequest.Response = ansiSequence.ToString (); + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response); + // Clear the terminator for not be enqueued + inputRecord = default (InputRecord); + } + } + + continue; + } + } + } + } + + if (readingSequence && !raisedResponse && EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) + { + _mainLoop.EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); + + lock (seqReqStatus!.AnsiRequest._responseLock) + { + seqReqStatus.AnsiRequest.Response = ansiSequence.ToString (); + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response); + } + + _retries = 0; + } + else if (EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) + { + if (_retries > 1) + { + if (_mainLoop.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) + { + lock (seqReqStatus!.AnsiRequest._responseLock) + { + _mainLoop.EscSeqRequests.Statuses.TryDequeue (out _); + + seqReqStatus.AnsiRequest.Response = string.Empty; + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + } + } + + _retries = 0; + } + else + { + _retries++; + } + } + else + { + _retries = 0; + } + + return numberEventsRead == 0 + ? null + : [inputRecord]; + } + catch (Exception) + { + return null; + } + } + } + +#if false // Not needed on the constructor. Perhaps could be used on resizing. To study. + [DllImport ("kernel32.dll", ExactSpelling = true)] + static extern IntPtr GetConsoleWindow (); + + [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + static extern bool ShowWindow (IntPtr hWnd, int nCmdShow); + + public const int HIDE = 0; + public const int MAXIMIZE = 3; + public const int MINIMIZE = 6; + public const int RESTORE = 9; + + internal void ShowWindow (int state) + { + IntPtr thisConsole = GetConsoleWindow (); + ShowWindow (thisConsole, state); + } +#endif + + // See: https://github.com/gui-cs/Terminal.Gui/issues/357 + + [StructLayout (LayoutKind.Sequential)] + public struct CONSOLE_SCREEN_BUFFER_INFOEX + { + public uint cbSize; + public Coord dwSize; + public Coord dwCursorPosition; + public ushort wAttributes; + public SmallRect srWindow; + public Coord dwMaximumWindowSize; + public ushort wPopupAttributes; + public bool bFullscreenSupported; + + [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)] + public COLORREF [] ColorTable; + } + + [StructLayout (LayoutKind.Explicit, Size = 4)] + public struct COLORREF + { + public COLORREF (byte r, byte g, byte b) + { + Value = 0; + R = r; + G = g; + B = b; + } + + public COLORREF (uint value) + { + R = 0; + G = 0; + B = 0; + Value = value & 0x00FFFFFF; + } + + [FieldOffset (0)] + public byte R; + + [FieldOffset (1)] + public byte G; + + [FieldOffset (2)] + public byte B; + + [FieldOffset (0)] + public uint Value; + } + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern bool SetConsoleWindowInfo ( + nint hConsoleOutput, + bool bAbsolute, + [In] ref SmallRect lpConsoleWindow + ); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern Coord GetLargestConsoleWindowSize ( + nint hConsoleOutput + ); +} diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs similarity index 60% rename from Terminal.Gui/ConsoleDrivers/WindowsDriver.cs rename to Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs index 83763e0818..6f20539d8d 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs @@ -1,4 +1,5 @@ -// +// TODO: #nullable enable +// // WindowsDriver.cs: Windows specific driver // @@ -23,1109 +24,6 @@ namespace Terminal.Gui; -internal class WindowsConsole -{ - internal WindowsMainLoop _mainLoop; - - public const int STD_OUTPUT_HANDLE = -11; - public const int STD_INPUT_HANDLE = -10; - - private readonly nint _inputHandle; - private nint _outputHandle; - //private nint _screenBuffer; - private readonly uint _originalConsoleMode; - private CursorVisibility? _initialCursorVisibility; - private CursorVisibility? _currentCursorVisibility; - private CursorVisibility? _pendingCursorVisibility; - private readonly StringBuilder _stringBuilder = new (256 * 1024); - private string _lastWrite = string.Empty; - - public WindowsConsole () - { - _inputHandle = GetStdHandle (STD_INPUT_HANDLE); - _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE); - _originalConsoleMode = ConsoleMode; - uint newConsoleMode = _originalConsoleMode; - newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags); - newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode; - newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput; - ConsoleMode = newConsoleMode; - } - - private CharInfo [] _originalStdOutChars; - - public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord bufferSize, SmallRect window, bool force16Colors) - { - //Debug.WriteLine ("WriteToConsole"); - - //if (_screenBuffer == nint.Zero) - //{ - // ReadFromConsoleOutput (size, bufferSize, ref window); - //} - - var result = false; - - if (force16Colors) - { - var i = 0; - CharInfo [] ci = new CharInfo [charInfoBuffer.Length]; - - foreach (ExtendedCharInfo info in charInfoBuffer) - { - ci [i++] = new CharInfo - { - Char = new CharUnion { UnicodeChar = info.Char }, - Attributes = - (ushort)((int)info.Attribute.Foreground.GetClosestNamedColor16 () | ((int)info.Attribute.Background.GetClosestNamedColor16 () << 4)) - }; - } - - result = WriteConsoleOutput (_outputHandle, ci, bufferSize, new Coord { X = window.Left, Y = window.Top }, ref window); - } - else - { - _stringBuilder.Clear (); - - _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition); - _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0)); - - Attribute? prev = null; - - foreach (ExtendedCharInfo info in charInfoBuffer) - { - Attribute attr = info.Attribute; - - if (attr != prev) - { - prev = attr; - _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B)); - _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B)); - } - - if (info.Char != '\x1b') - { - if (!info.Empty) - { - _stringBuilder.Append (info.Char); - } - } - else - { - _stringBuilder.Append (' '); - } - } - - _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition); - _stringBuilder.Append (EscSeqUtils.CSI_HideCursor); - - var s = _stringBuilder.ToString (); - - // TODO: requires extensive testing if we go down this route - // If console output has changed - if (s != _lastWrite) - { - // supply console with the new content - result = WriteConsole (_outputHandle, s, (uint)s.Length, out uint _, nint.Zero); - } - - _lastWrite = s; - - foreach (var sixel in Application.Sixel) - { - SetCursorPosition (new Coord ((short)sixel.ScreenPosition.X, (short)sixel.ScreenPosition.Y)); - WriteConsole (_outputHandle, sixel.SixelData, (uint)sixel.SixelData.Length, out uint _, nint.Zero); - } - } - - if (!result) - { - int err = Marshal.GetLastWin32Error (); - - if (err != 0) - { - throw new Win32Exception (err); - } - } - - return result; - } - - internal bool WriteANSI (string ansi) - { - if (WriteConsole (_outputHandle, ansi, (uint)ansi.Length, out uint _, nint.Zero)) - { - // Flush the output to make sure it's sent immediately - return FlushFileBuffers (_outputHandle); - } - - return false; - } - - public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window) - { - //_screenBuffer = CreateConsoleScreenBuffer ( - // DesiredAccess.GenericRead | DesiredAccess.GenericWrite, - // ShareMode.FileShareRead | ShareMode.FileShareWrite, - // nint.Zero, - // 1, - // nint.Zero - // ); - - //if (_screenBuffer == INVALID_HANDLE_VALUE) - //{ - // int err = Marshal.GetLastWin32Error (); - - // if (err != 0) - // { - // throw new Win32Exception (err); - // } - //} - - SetInitialCursorVisibility (); - - //if (!SetConsoleActiveScreenBuffer (_screenBuffer)) - //{ - // throw new Win32Exception (Marshal.GetLastWin32Error ()); - //} - - _originalStdOutChars = new CharInfo [size.Height * size.Width]; - - if (!ReadConsoleOutput (_outputHandle, _originalStdOutChars, coords, new Coord { X = 0, Y = 0 }, ref window)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } - } - - public bool SetCursorPosition (Coord position) - { - return SetConsoleCursorPosition (_outputHandle, position); - } - - public void SetInitialCursorVisibility () - { - if (_initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility)) - { - _initialCursorVisibility = visibility; - } - } - - public bool GetCursorVisibility (out CursorVisibility visibility) - { - if (_outputHandle == nint.Zero) - { - visibility = CursorVisibility.Invisible; - - return false; - } - - if (!GetConsoleCursorInfo (_outputHandle, out ConsoleCursorInfo info)) - { - int err = Marshal.GetLastWin32Error (); - - if (err != 0) - { - throw new Win32Exception (err); - } - - visibility = CursorVisibility.Default; - - return false; - } - - if (!info.bVisible) - { - visibility = CursorVisibility.Invisible; - } - else if (info.dwSize > 50) - { - visibility = CursorVisibility.Default; - } - else - { - visibility = CursorVisibility.Default; - } - - return true; - } - - public bool EnsureCursorVisibility () - { - if (_initialCursorVisibility.HasValue && _pendingCursorVisibility.HasValue && SetCursorVisibility (_pendingCursorVisibility.Value)) - { - _pendingCursorVisibility = null; - - return true; - } - - return false; - } - - public void ForceRefreshCursorVisibility () - { - if (_currentCursorVisibility.HasValue) - { - _pendingCursorVisibility = _currentCursorVisibility; - _currentCursorVisibility = null; - } - } - - public bool SetCursorVisibility (CursorVisibility visibility) - { - if (_initialCursorVisibility.HasValue == false) - { - _pendingCursorVisibility = visibility; - - return false; - } - - if (_currentCursorVisibility.HasValue == false || _currentCursorVisibility.Value != visibility) - { - var info = new ConsoleCursorInfo - { - dwSize = (uint)visibility & 0x00FF, - bVisible = ((uint)visibility & 0xFF00) != 0 - }; - - if (!SetConsoleCursorInfo (_outputHandle, ref info)) - { - return false; - } - - _currentCursorVisibility = visibility; - } - - return true; - } - - public void Cleanup () - { - if (_initialCursorVisibility.HasValue) - { - SetCursorVisibility (_initialCursorVisibility.Value); - } - - //SetConsoleOutputWindow (out _); - - ConsoleMode = _originalConsoleMode; - - _outputHandle = CreateConsoleScreenBuffer ( - DesiredAccess.GenericRead | DesiredAccess.GenericWrite, - ShareMode.FileShareRead | ShareMode.FileShareWrite, - nint.Zero, - 1, - nint.Zero - ); - - if (!SetConsoleActiveScreenBuffer (_outputHandle)) - { - int err = Marshal.GetLastWin32Error (); - Console.WriteLine ("Error: {0}", err); - } - - //if (_screenBuffer != nint.Zero) - //{ - // CloseHandle (_screenBuffer); - //} - - //_screenBuffer = nint.Zero; - } - - //internal Size GetConsoleBufferWindow (out Point position) - //{ - // if (_screenBuffer == nint.Zero) - // { - // position = Point.Empty; - - // return Size.Empty; - // } - - // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); - // csbi.cbSize = (uint)Marshal.SizeOf (csbi); - - // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - // { - // //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ()); - // position = Point.Empty; - - // return Size.Empty; - // } - - // Size sz = new ( - // csbi.srWindow.Right - csbi.srWindow.Left + 1, - // csbi.srWindow.Bottom - csbi.srWindow.Top + 1); - // position = new (csbi.srWindow.Left, csbi.srWindow.Top); - - // return sz; - //} - - internal Size GetConsoleOutputWindow (out Point position) - { - var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); - csbi.cbSize = (uint)Marshal.SizeOf (csbi); - - if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) - { - throw new Win32Exception (Marshal.GetLastWin32Error ()); - } - - Size sz = new ( - csbi.srWindow.Right - csbi.srWindow.Left + 1, - csbi.srWindow.Bottom - csbi.srWindow.Top + 1); - position = new (csbi.srWindow.Left, csbi.srWindow.Top); - - return sz; - } - - //internal Size SetConsoleWindow (short cols, short rows) - //{ - // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); - // csbi.cbSize = (uint)Marshal.SizeOf (csbi); - - // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - // { - // throw new Win32Exception (Marshal.GetLastWin32Error ()); - // } - - // Coord maxWinSize = GetLargestConsoleWindowSize (_screenBuffer); - // short newCols = Math.Min (cols, maxWinSize.X); - // short newRows = Math.Min (rows, maxWinSize.Y); - // csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1)); - // csbi.srWindow = new SmallRect (0, 0, newCols, newRows); - // csbi.dwMaximumWindowSize = new Coord (newCols, newRows); - - // if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - // { - // throw new Win32Exception (Marshal.GetLastWin32Error ()); - // } - - // var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0)); - - // if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) - // { - // //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ()); - // return new (cols, rows); - // } - - // SetConsoleOutputWindow (csbi); - - // return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1); - //} - - //private void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi) - //{ - // if (_screenBuffer != nint.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - // { - // throw new Win32Exception (Marshal.GetLastWin32Error ()); - // } - //} - - //internal Size SetConsoleOutputWindow (out Point position) - //{ - // if (_screenBuffer == nint.Zero) - // { - // position = Point.Empty; - - // return Size.Empty; - // } - - // var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX (); - // csbi.cbSize = (uint)Marshal.SizeOf (csbi); - - // if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi)) - // { - // throw new Win32Exception (Marshal.GetLastWin32Error ()); - // } - - // Size sz = new ( - // csbi.srWindow.Right - csbi.srWindow.Left + 1, - // Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0)); - // position = new (csbi.srWindow.Left, csbi.srWindow.Top); - // SetConsoleOutputWindow (csbi); - // var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0)); - - // if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi)) - // { - // throw new Win32Exception (Marshal.GetLastWin32Error ()); - // } - - // if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect)) - // { - // throw new Win32Exception (Marshal.GetLastWin32Error ()); - // } - - // return sz; - //} - - private uint ConsoleMode - { - get - { - GetConsoleMode (_inputHandle, out uint v); - - return v; - } - set => SetConsoleMode (_inputHandle, value); - } - - [Flags] - public enum ConsoleModes : uint - { - EnableProcessedInput = 1, - EnableMouseInput = 16, - EnableQuickEditMode = 64, - EnableExtendedFlags = 128 - } - - [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)] - public struct KeyEventRecord - { - [FieldOffset (0)] - [MarshalAs (UnmanagedType.Bool)] - public bool bKeyDown; - - [FieldOffset (4)] - [MarshalAs (UnmanagedType.U2)] - public ushort wRepeatCount; - - [FieldOffset (6)] - [MarshalAs (UnmanagedType.U2)] - public VK wVirtualKeyCode; - - [FieldOffset (8)] - [MarshalAs (UnmanagedType.U2)] - public ushort wVirtualScanCode; - - [FieldOffset (10)] - public char UnicodeChar; - - [FieldOffset (12)] - [MarshalAs (UnmanagedType.U4)] - public ControlKeyState dwControlKeyState; - - public readonly override string ToString () - { - return - $"[KeyEventRecord({(bKeyDown ? "down" : "up")},{wRepeatCount},{wVirtualKeyCode},{wVirtualScanCode},{new Rune (UnicodeChar).MakePrintable ()},{dwControlKeyState})]"; - } - } - - [Flags] - public enum ButtonState - { - NoButtonPressed = 0, - Button1Pressed = 1, - Button2Pressed = 4, - Button3Pressed = 8, - Button4Pressed = 16, - RightmostButtonPressed = 2 - } - - [Flags] - public enum ControlKeyState - { - NoControlKeyPressed = 0, - RightAltPressed = 1, - LeftAltPressed = 2, - RightControlPressed = 4, - LeftControlPressed = 8, - ShiftPressed = 16, - NumlockOn = 32, - ScrolllockOn = 64, - CapslockOn = 128, - EnhancedKey = 256 - } - - [Flags] - public enum EventFlags - { - NoEvent = 0, - MouseMoved = 1, - DoubleClick = 2, - MouseWheeled = 4, - MouseHorizontalWheeled = 8 - } - - [StructLayout (LayoutKind.Explicit)] - public struct MouseEventRecord - { - [FieldOffset (0)] - public Coord MousePosition; - - [FieldOffset (4)] - public ButtonState ButtonState; - - [FieldOffset (8)] - public ControlKeyState ControlKeyState; - - [FieldOffset (12)] - public EventFlags EventFlags; - - public readonly override string ToString () { return $"[Mouse{MousePosition},{ButtonState},{ControlKeyState},{EventFlags}]"; } - } - - public struct WindowBufferSizeRecord - { - public Coord _size; - - public WindowBufferSizeRecord (short x, short y) { _size = new Coord (x, y); } - - public readonly override string ToString () { return $"[WindowBufferSize{_size}"; } - } - - [StructLayout (LayoutKind.Sequential)] - public struct MenuEventRecord - { - public uint dwCommandId; - } - - [StructLayout (LayoutKind.Sequential)] - public struct FocusEventRecord - { - public uint bSetFocus; - } - - public enum EventType : ushort - { - Focus = 0x10, - Key = 0x1, - Menu = 0x8, - Mouse = 2, - WindowBufferSize = 4 - } - - [StructLayout (LayoutKind.Explicit)] - public struct InputRecord - { - [FieldOffset (0)] - public EventType EventType; - - [FieldOffset (4)] - public KeyEventRecord KeyEvent; - - [FieldOffset (4)] - public MouseEventRecord MouseEvent; - - [FieldOffset (4)] - public WindowBufferSizeRecord WindowBufferSizeEvent; - - [FieldOffset (4)] - public MenuEventRecord MenuEvent; - - [FieldOffset (4)] - public FocusEventRecord FocusEvent; - - public readonly override string ToString () - { - return EventType switch - { - EventType.Focus => FocusEvent.ToString (), - EventType.Key => KeyEvent.ToString (), - EventType.Menu => MenuEvent.ToString (), - EventType.Mouse => MouseEvent.ToString (), - EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (), - _ => "Unknown event type: " + EventType - }; - } - } - - [Flags] - private enum ShareMode : uint - { - FileShareRead = 1, - FileShareWrite = 2 - } - - [Flags] - private enum DesiredAccess : uint - { - GenericRead = 2147483648, - GenericWrite = 1073741824 - } - - [StructLayout (LayoutKind.Sequential)] - public struct ConsoleScreenBufferInfo - { - public Coord dwSize; - public Coord dwCursorPosition; - public ushort wAttributes; - public SmallRect srWindow; - public Coord dwMaximumWindowSize; - } - - [StructLayout (LayoutKind.Sequential)] - public struct Coord - { - public short X; - public short Y; - - public Coord (short x, short y) - { - X = x; - Y = y; - } - - public readonly override string ToString () { return $"({X},{Y})"; } - } - - [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)] - public struct CharUnion - { - [FieldOffset (0)] - public char UnicodeChar; - - [FieldOffset (0)] - public byte AsciiChar; - } - - [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)] - public struct CharInfo - { - [FieldOffset (0)] - public CharUnion Char; - - [FieldOffset (2)] - public ushort Attributes; - } - - public struct ExtendedCharInfo - { - public char Char { get; set; } - public Attribute Attribute { get; set; } - public bool Empty { get; set; } // TODO: Temp hack until virtual terminal sequences - - public ExtendedCharInfo (char character, Attribute attribute) - { - Char = character; - Attribute = attribute; - Empty = false; - } - } - - [StructLayout (LayoutKind.Sequential)] - public struct SmallRect - { - public short Left; - public short Top; - public short Right; - public short Bottom; - - public SmallRect (short left, short top, short right, short bottom) - { - Left = left; - Top = top; - Right = right; - Bottom = bottom; - } - - public static void MakeEmpty (ref SmallRect rect) { rect.Left = -1; } - - public static void Update (ref SmallRect rect, short col, short row) - { - if (rect.Left == -1) - { - rect.Left = rect.Right = col; - rect.Bottom = rect.Top = row; - - return; - } - - if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom) - { - return; - } - - if (col < rect.Left) - { - rect.Left = col; - } - - if (col > rect.Right) - { - rect.Right = col; - } - - if (row < rect.Top) - { - rect.Top = row; - } - - if (row > rect.Bottom) - { - rect.Bottom = row; - } - } - - public readonly override string ToString () { return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}"; } - } - - [StructLayout (LayoutKind.Sequential)] - public struct ConsoleKeyInfoEx - { - public ConsoleKeyInfo ConsoleKeyInfo; - public bool CapsLock; - public bool NumLock; - public bool ScrollLock; - - public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock) - { - ConsoleKeyInfo = consoleKeyInfo; - CapsLock = capslock; - NumLock = numlock; - ScrollLock = scrolllock; - } - - /// - /// Prints a ConsoleKeyInfoEx structure - /// - /// - /// - public readonly string ToString (ConsoleKeyInfoEx ex) - { - var ke = new Key ((KeyCode)ex.ConsoleKeyInfo.KeyChar); - var sb = new StringBuilder (); - sb.Append ($"Key: {(KeyCode)ex.ConsoleKeyInfo.Key} ({ex.ConsoleKeyInfo.Key})"); - sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty); - sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty); - sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty); - sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)ex.ConsoleKeyInfo.KeyChar}) "); - sb.Append (ex.CapsLock ? "caps," : string.Empty); - sb.Append (ex.NumLock ? "num," : string.Empty); - sb.Append (ex.ScrollLock ? "scroll," : string.Empty); - string s = sb.ToString ().TrimEnd (',').TrimEnd (' '); - - return $"[ConsoleKeyInfoEx({s})]"; - } - } - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern nint GetStdHandle (int nStdHandle); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool CloseHandle (nint handle); - - [DllImport ("kernel32.dll", SetLastError = true)] - public static extern bool PeekConsoleInput (nint hConsoleInput, out InputRecord lpBuffer, uint nLength, out uint lpNumberOfEventsRead); - - [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)] - public static extern bool ReadConsoleInput ( - nint hConsoleInput, - out InputRecord lpBuffer, - uint nLength, - out uint lpNumberOfEventsRead - ); - - [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - private static extern bool ReadConsoleOutput ( - nint hConsoleOutput, - [Out] CharInfo [] lpBuffer, - Coord dwBufferSize, - Coord dwBufferCoord, - ref SmallRect lpReadRegion - ); - - // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput - [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)] - private static extern bool WriteConsoleOutput ( - nint hConsoleOutput, - CharInfo [] lpBuffer, - Coord dwBufferSize, - Coord dwBufferCoord, - ref SmallRect lpWriteRegion - ); - - [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)] - private static extern bool WriteConsole ( - nint hConsoleOutput, - string lpbufer, - uint NumberOfCharsToWriten, - out uint lpNumberOfCharsWritten, - nint lpReserved - ); - - [DllImport ("kernel32.dll", SetLastError = true)] - static extern bool FlushFileBuffers (nint hFile); - - [DllImport ("kernel32.dll")] - private static extern bool SetConsoleCursorPosition (nint hConsoleOutput, Coord dwCursorPosition); - - [StructLayout (LayoutKind.Sequential)] - public struct ConsoleCursorInfo - { - /// - /// The percentage of the character cell that is filled by the cursor.This value is between 1 and 100. - /// The cursor appearance varies, ranging from completely filling the cell to showing up as a horizontal - /// line at the bottom of the cell. - /// - public uint dwSize; - public bool bVisible; - } - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool SetConsoleCursorInfo (nint hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool GetConsoleCursorInfo (nint hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo); - - [DllImport ("kernel32.dll")] - private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode); - - [DllImport ("kernel32.dll")] - private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern nint CreateConsoleScreenBuffer ( - DesiredAccess dwDesiredAccess, - ShareMode dwShareMode, - nint secutiryAttributes, - uint flags, - nint screenBufferData - ); - - internal static nint INVALID_HANDLE_VALUE = new (-1); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool SetConsoleActiveScreenBuffer (nint Handle); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool GetNumberOfConsoleInputEvents (nint handle, out uint lpcNumberOfEvents); - - internal uint GetNumberOfConsoleInputEvents () - { - if (!GetNumberOfConsoleInputEvents (_inputHandle, out uint numOfEvents)) - { - Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}"); - - return 0; - } - - return numOfEvents; - } - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool FlushConsoleInputBuffer (nint handle); - - internal void FlushConsoleInputBuffer () - { - if (!FlushConsoleInputBuffer (_inputHandle)) - { - Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}"); - } - } - - private int _retries; - - public InputRecord [] ReadConsoleInput () - { - const int bufferSize = 1; - InputRecord inputRecord = default; - uint numberEventsRead = 0; - StringBuilder ansiSequence = new StringBuilder (); - bool readingSequence = false; - bool raisedResponse = false; - - while (true) - { - try - { - // Peek to check if there is any input available - if (PeekConsoleInput (_inputHandle, out _, bufferSize, out uint eventsRead) && eventsRead > 0) - { - // Read the input since it is available - ReadConsoleInput ( - _inputHandle, - out inputRecord, - bufferSize, - out numberEventsRead); - - if (inputRecord.EventType == EventType.Key) - { - KeyEventRecord keyEvent = inputRecord.KeyEvent; - - if (keyEvent.bKeyDown) - { - char inputChar = keyEvent.UnicodeChar; - - // Check if input is part of an ANSI escape sequence - if (inputChar == '\u001B') // Escape character - { - // Peek to check if there is any input available with key event and bKeyDown - if (PeekConsoleInput (_inputHandle, out InputRecord peekRecord, bufferSize, out eventsRead) && eventsRead > 0) - { - if (peekRecord is { EventType: EventType.Key, KeyEvent.bKeyDown: true }) - { - // It's really an ANSI request response - readingSequence = true; - ansiSequence.Clear (); // Start a new sequence - ansiSequence.Append (inputChar); - - continue; - } - } - } - else if (readingSequence) - { - ansiSequence.Append (inputChar); - - // Check if the sequence has ended with an expected command terminator - if (_mainLoop.EscSeqRequests is { } && _mainLoop.EscSeqRequests.HasResponse (inputChar.ToString (), out EscSeqReqStatus seqReqStatus)) - { - // Finished reading the sequence and remove the enqueued request - _mainLoop.EscSeqRequests.Remove (seqReqStatus); - - lock (seqReqStatus!.AnsiRequest._responseLock) - { - raisedResponse = true; - seqReqStatus.AnsiRequest.Response = ansiSequence.ToString (); - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response); - // Clear the terminator for not be enqueued - inputRecord = default (InputRecord); - } - } - - continue; - } - } - } - } - - if (readingSequence && !raisedResponse && EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) - { - _mainLoop.EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); - - lock (seqReqStatus!.AnsiRequest._responseLock) - { - seqReqStatus.AnsiRequest.Response = ansiSequence.ToString (); - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response); - } - - _retries = 0; - } - else if (EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) - { - if (_retries > 1) - { - if (_mainLoop.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) - { - lock (seqReqStatus!.AnsiRequest._responseLock) - { - _mainLoop.EscSeqRequests.Statuses.TryDequeue (out _); - - seqReqStatus.AnsiRequest.Response = string.Empty; - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); - } - } - - _retries = 0; - } - else - { - _retries++; - } - } - else - { - _retries = 0; - } - - return numberEventsRead == 0 - ? null - : [inputRecord]; - } - catch (Exception) - { - return null; - } - } - } - -#if false // Not needed on the constructor. Perhaps could be used on resizing. To study. - [DllImport ("kernel32.dll", ExactSpelling = true)] - static extern IntPtr GetConsoleWindow (); - - [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] - static extern bool ShowWindow (IntPtr hWnd, int nCmdShow); - - public const int HIDE = 0; - public const int MAXIMIZE = 3; - public const int MINIMIZE = 6; - public const int RESTORE = 9; - - internal void ShowWindow (int state) - { - IntPtr thisConsole = GetConsoleWindow (); - ShowWindow (thisConsole, state); - } -#endif - - // See: https://github.com/gui-cs/Terminal.Gui/issues/357 - - [StructLayout (LayoutKind.Sequential)] - public struct CONSOLE_SCREEN_BUFFER_INFOEX - { - public uint cbSize; - public Coord dwSize; - public Coord dwCursorPosition; - public ushort wAttributes; - public SmallRect srWindow; - public Coord dwMaximumWindowSize; - public ushort wPopupAttributes; - public bool bFullscreenSupported; - - [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)] - public COLORREF [] ColorTable; - } - - [StructLayout (LayoutKind.Explicit, Size = 4)] - public struct COLORREF - { - public COLORREF (byte r, byte g, byte b) - { - Value = 0; - R = r; - G = g; - B = b; - } - - public COLORREF (uint value) - { - R = 0; - G = 0; - B = 0; - Value = value & 0x00FFFFFF; - } - - [FieldOffset (0)] - public byte R; - - [FieldOffset (1)] - public byte G; - - [FieldOffset (2)] - public byte B; - - [FieldOffset (0)] - public uint Value; - } - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool SetConsoleWindowInfo ( - nint hConsoleOutput, - bool bAbsolute, - [In] ref SmallRect lpConsoleWindow - ); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern Coord GetLargestConsoleWindowSize ( - nint hConsoleOutput - ); -} - internal class WindowsDriver : ConsoleDriver { private readonly bool _isWindowsTerminal; diff --git a/Terminal.Gui/Terminal.Gui.csproj b/Terminal.Gui/Terminal.Gui.csproj index 88d57c26be..abf668f259 100644 --- a/Terminal.Gui/Terminal.Gui.csproj +++ b/Terminal.Gui/Terminal.Gui.csproj @@ -164,8 +164,7 @@ - + diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index 321af7c2ed..f88c80820a 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using Terminal.Gui; namespace UICatalog.Scenarios; @@ -12,14 +11,13 @@ public sealed class AnsiEscapeSequenceRequests : Scenario { private GraphView _graphView; - private DateTime start = DateTime.Now; private ScatterSeries _sentSeries; private ScatterSeries _answeredSeries; - private List sends = new (); + private readonly List _sends = new (); - private object lockAnswers = new object (); - private Dictionary answers = new (); + private readonly object _lockAnswers = new (); + private readonly Dictionary _answers = new (); private Label _lblSummary; public override void Main () @@ -27,18 +25,18 @@ public override void Main () // Init Application.Init (); - TabView tv = new TabView + var tv = new TabView { Width = Dim.Fill (), Height = Dim.Fill () }; - Tab single = new Tab (); - single.DisplayText = "Single"; + var single = new Tab (); + single.DisplayText = "_Single"; single.View = BuildSingleTab (); Tab bulk = new (); - bulk.DisplayText = "Multi"; + bulk.DisplayText = "_Multi"; bulk.View = BuildBulkTab (); tv.AddTab (single, true); @@ -47,7 +45,7 @@ public override void Main () // Setup - Create a top-level application window and configure it. Window appWindow = new () { - Title = GetQuitKeyAndName (), + Title = GetQuitKeyAndName () }; appWindow.Add (tv); @@ -61,18 +59,20 @@ public override void Main () // Shutdown - Calling Application.Shutdown is required. Application.Shutdown (); } + private View BuildSingleTab () { - View w = new View () + var w = new View { - Width = Dim.Fill(), + Width = Dim.Fill (), Height = Dim.Fill (), CanFocus = true }; w.Padding.Thickness = new (1); - var scrRequests = new List + // TODO: This hackery is why I think the EscSeqUtils class should be refactored and the CSI's made type safe. + List scrRequests = new () { "CSI_SendDeviceAttributes", "CSI_ReportTerminalSizeInChars", @@ -80,18 +80,19 @@ private View BuildSingleTab () "CSI_SendDeviceAttributes2" }; - var cbRequests = new ComboBox () { Width = 40, Height = 5, ReadOnly = true, Source = new ListWrapper (new (scrRequests)) }; + var cbRequests = new ComboBox { Width = 40, Height = 5, ReadOnly = true, Source = new ListWrapper (new (scrRequests)) }; w.Add (cbRequests); - var label = new Label { Y = Pos.Bottom (cbRequests) + 1, Text = "Request:" }; + // TODO: Use Pos.Align and Dim.Func so these hardcoded widths aren't needed. + var label = new Label { Y = Pos.Bottom (cbRequests) + 1, Text = "_Request:" }; var tfRequest = new TextField { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 20 }; w.Add (label, tfRequest); - label = new Label { X = Pos.Right (tfRequest) + 1, Y = Pos.Top (tfRequest) - 1, Text = "Value:" }; + label = new () { X = Pos.Right (tfRequest) + 1, Y = Pos.Top (tfRequest) - 1, Text = "E_xpectedResponseValue:" }; var tfValue = new TextField { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 6 }; w.Add (label, tfValue); - label = new Label { X = Pos.Right (tfValue) + 1, Y = Pos.Top (tfValue) - 1, Text = "Terminator:" }; + label = new () { X = Pos.Right (tfValue) + 1, Y = Pos.Top (tfValue) - 1, Text = "_Terminator:" }; var tfTerminator = new TextField { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 4 }; w.Add (label, tfTerminator); @@ -102,101 +103,111 @@ private View BuildSingleTab () return; } - var selAnsiEscapeSequenceRequestName = scrRequests [cbRequests.SelectedItem]; + string selAnsiEscapeSequenceRequestName = scrRequests [cbRequests.SelectedItem]; AnsiEscapeSequenceRequest selAnsiEscapeSequenceRequest = null; + switch (selAnsiEscapeSequenceRequestName) { case "CSI_SendDeviceAttributes": selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_SendDeviceAttributes; + break; case "CSI_ReportTerminalSizeInChars": selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_ReportTerminalSizeInChars; + break; case "CSI_RequestCursorPositionReport": selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_RequestCursorPositionReport; + break; case "CSI_SendDeviceAttributes2": selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_SendDeviceAttributes2; + break; } tfRequest.Text = selAnsiEscapeSequenceRequest is { } ? selAnsiEscapeSequenceRequest.Request : ""; - tfValue.Text = selAnsiEscapeSequenceRequest is { } ? selAnsiEscapeSequenceRequest.Value ?? "" : ""; + + tfValue.Text = selAnsiEscapeSequenceRequest is { } + ? selAnsiEscapeSequenceRequest.ExpectedResponseValue ?? "" + : ""; tfTerminator.Text = selAnsiEscapeSequenceRequest is { } ? selAnsiEscapeSequenceRequest.Terminator : ""; }; + // Forces raise cbRequests.SelectedItemChanged to update TextFields cbRequests.SelectedItem = 0; - label = new Label { Y = Pos.Bottom (tfRequest) + 2, Text = "Response:" }; + label = new () { Y = Pos.Bottom (tfRequest) + 2, Text = "_Response:" }; var tvResponse = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 40, Height = 4, ReadOnly = true }; w.Add (label, tvResponse); - label = new Label { X = Pos.Right (tvResponse) + 1, Y = Pos.Top (tvResponse) - 1, Text = "Error:" }; + label = new () { X = Pos.Right (tvResponse) + 1, Y = Pos.Top (tvResponse) - 1, Text = "_Error:" }; var tvError = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 40, Height = 4, ReadOnly = true }; w.Add (label, tvError); - label = new Label { X = Pos.Right (tvError) + 1, Y = Pos.Top (tvError) - 1, Text = "Value:" }; + label = new () { X = Pos.Right (tvError) + 1, Y = Pos.Top (tvError) - 1, Text = "E_xpectedResponseValue:" }; var tvValue = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 6, Height = 4, ReadOnly = true }; w.Add (label, tvValue); - label = new Label { X = Pos.Right (tvValue) + 1, Y = Pos.Top (tvValue) - 1, Text = "Terminator:" }; + label = new () { X = Pos.Right (tvValue) + 1, Y = Pos.Top (tvValue) - 1, Text = "_Terminator:" }; var tvTerminator = new TextView { X = Pos.Left (label), Y = Pos.Bottom (label), Width = 4, Height = 4, ReadOnly = true }; w.Add (label, tvTerminator); - var btnResponse = new Button { X = Pos.Center (), Y = Pos.Bottom (tvResponse) + 2, Text = "Send Request", IsDefault = true }; + var btnResponse = new Button { X = Pos.Center (), Y = Pos.Bottom (tvResponse) + 2, Text = "_Send Request", IsDefault = true }; var lblSuccess = new Label { X = Pos.Center (), Y = Pos.Bottom (btnResponse) + 1 }; w.Add (lblSuccess); btnResponse.Accepting += (s, e) => - { - var ansiEscapeSequenceRequest = new AnsiEscapeSequenceRequest - { - Request = tfRequest.Text, - Terminator = tfTerminator.Text, - Value = string.IsNullOrEmpty (tfValue.Text) ? null : tfValue.Text - }; - - var success = AnsiEscapeSequenceRequest.TryExecuteAnsiRequest ( - ansiEscapeSequenceRequest, - out AnsiEscapeSequenceResponse ansiEscapeSequenceResponse - ); - - tvResponse.Text = ansiEscapeSequenceResponse.Response; - tvError.Text = ansiEscapeSequenceResponse.Error; - tvValue.Text = ansiEscapeSequenceResponse.Value ?? ""; - tvTerminator.Text = ansiEscapeSequenceResponse.Terminator; - - if (success) - { - lblSuccess.ColorScheme = Colors.ColorSchemes ["Base"]; - lblSuccess.Text = "Successful"; - } - else - { - lblSuccess.ColorScheme = Colors.ColorSchemes ["Error"]; - lblSuccess.Text = "Error"; - } - }; + { + var ansiEscapeSequenceRequest = new AnsiEscapeSequenceRequest + { + Request = tfRequest.Text, + Terminator = tfTerminator.Text, + ExpectedResponseValue = string.IsNullOrEmpty (tfValue.Text) ? null : tfValue.Text + }; + + bool success = AnsiEscapeSequenceRequest.TryRequest ( + ansiEscapeSequenceRequest, + out AnsiEscapeSequenceResponse ansiEscapeSequenceResponse + ); + + tvResponse.Text = ansiEscapeSequenceResponse.Response; + tvError.Text = ansiEscapeSequenceResponse.Error; + tvValue.Text = ansiEscapeSequenceResponse.ExpectedResponseValue ?? ""; + tvTerminator.Text = ansiEscapeSequenceResponse.Terminator; + + if (success) + { + lblSuccess.ColorScheme = Colors.ColorSchemes ["Base"]; + lblSuccess.Text = "Success"; + } + else + { + lblSuccess.ColorScheme = Colors.ColorSchemes ["Error"]; + lblSuccess.Text = "Error"; + } + }; w.Add (btnResponse); - w.Add (new Label { Y = Pos.Bottom (lblSuccess) + 2, Text = "You can send other requests by editing the TextFields." }); + w.Add (new Label { Y = Pos.Bottom (lblSuccess) + 2, Text = "Send other requests by editing the TextFields." }); return w; } private View BuildBulkTab () { - View w = new View () + var w = new View { Width = Dim.Fill (), Height = Dim.Fill (), CanFocus = true }; - var lbl = new Label () + var lbl = new Label { - Text = "This scenario tests Ansi request/response processing. Use the TextView to ensure regular user interaction continues as normal during sends. Responses are in red, queued messages are in green.", + Text = + "_This scenario tests Ansi request/response processing. Use the TextView to ensure regular user interaction continues as normal during sends. Responses are in red, queued messages are in green.", Height = 2, Width = Dim.Fill () }; @@ -205,50 +216,49 @@ private View BuildBulkTab () TimeSpan.FromMilliseconds (1000), () => { - lock (lockAnswers) + lock (_lockAnswers) { UpdateGraph (); UpdateResponses (); } - - return true; }); - var tv = new TextView () + var tv = new TextView { Y = Pos.Bottom (lbl), Width = Dim.Percent (50), Height = Dim.Fill () }; - - var lblDar = new Label () + var lblDar = new Label { Y = Pos.Bottom (lbl), X = Pos.Right (tv) + 1, - Text = "DAR per second", + Text = "_DAR per second: " }; - var cbDar = new NumericUpDown () + + var cbDar = new NumericUpDown { X = Pos.Right (lblDar), Y = Pos.Bottom (lbl), - Value = 0, + Value = 0 }; cbDar.ValueChanging += (s, e) => - { - if (e.NewValue < 0 || e.NewValue > 20) - { - e.Cancel = true; - } - }; + { + if (e.NewValue < 0 || e.NewValue > 20) + { + e.Cancel = true; + } + }; w.Add (cbDar); int lastSendTime = Environment.TickCount; - object lockObj = new object (); + var lockObj = new object (); + Application.AddTimeout ( TimeSpan.FromMilliseconds (50), () => @@ -272,8 +282,7 @@ private View BuildBulkTab () return true; }); - - _graphView = new GraphView () + _graphView = new () { Y = Pos.Bottom (cbDar), X = Pos.Right (tv), @@ -281,7 +290,7 @@ private View BuildBulkTab () Height = Dim.Fill (1) }; - _lblSummary = new Label () + _lblSummary = new () { Y = Pos.Bottom (_graphView), X = Pos.Right (tv), @@ -299,6 +308,7 @@ private View BuildBulkTab () return w; } + private void UpdateResponses () { _lblSummary.Text = GetSummary (); @@ -307,32 +317,31 @@ private void UpdateResponses () private string GetSummary () { - if (answers.Count == 0) + if (_answers.Count == 0) { return "No requests sent yet"; } - var last = answers.Last ().Value; + string last = _answers.Last ().Value; - var unique = answers.Values.Distinct ().Count (); - var total = answers.Count; + int unique = _answers.Values.Distinct ().Count (); + int total = _answers.Count; return $"Last:{last} U:{unique} T:{total}"; } private void SetupGraph () { + _graphView.Series.Add (_sentSeries = new ()); + _graphView.Series.Add (_answeredSeries = new ()); - _graphView.Series.Add (_sentSeries = new ScatterSeries ()); - _graphView.Series.Add (_answeredSeries = new ScatterSeries ()); - - _sentSeries.Fill = new GraphCellToRender (new Rune ('.'), new Attribute (ColorName16.BrightGreen, ColorName16.Black)); - _answeredSeries.Fill = new GraphCellToRender (new Rune ('.'), new Attribute (ColorName16.BrightRed, ColorName16.Black)); + _sentSeries.Fill = new (new ('.'), new (ColorName16.BrightGreen, ColorName16.Black)); + _answeredSeries.Fill = new (new ('.'), new (ColorName16.BrightRed, ColorName16.Black)); // Todo: // _graphView.Annotations.Add (_sentSeries new PathAnnotation {}); - _graphView.CellSize = new PointF (1, 1); + _graphView.CellSize = new (1, 1); _graphView.MarginBottom = 2; _graphView.AxisX.Increment = 1; _graphView.AxisX.Text = "Seconds"; @@ -341,40 +350,37 @@ private void SetupGraph () private void UpdateGraph () { - _sentSeries.Points = sends + _sentSeries.Points = _sends .GroupBy (ToSeconds) .Select (g => new PointF (g.Key, g.Count ())) .ToList (); - _answeredSeries.Points = answers.Keys + _answeredSeries.Points = _answers.Keys .GroupBy (ToSeconds) .Select (g => new PointF (g.Key, g.Count ())) .ToList (); + // _graphView.ScrollOffset = new PointF(,0); if (_sentSeries.Points.Count > 0 || _answeredSeries.Points.Count > 0) { _graphView.SetNeedsDisplay (); } - } - private int ToSeconds (DateTime t) - { - return (int)(DateTime.Now - t).TotalSeconds; - } + private int ToSeconds (DateTime t) { return (int)(DateTime.Now - t).TotalSeconds; } private void SendDar () { - sends.Add (DateTime.Now); - var result = Application.Driver.WriteAnsiRequest (EscSeqUtils.CSI_SendDeviceAttributes); + _sends.Add (DateTime.Now); + string result = Application.Driver.WriteAnsiRequest (EscSeqUtils.CSI_SendDeviceAttributes); HandleResponse (result); } private void HandleResponse (string response) { - lock (lockAnswers) + lock (_lockAnswers) { - answers.Add (DateTime.Now, response); + _answers.Add (DateTime.Now, response); } } } From 7d9ae7f341bfab731b5582631b2e2f78f0cf3d95 Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 6 Nov 2024 20:48:08 +0000 Subject: [PATCH 76/89] Ad more unit test to handling with IsLetterOrDigit, IsPunctuation and IsSymbol. --- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 4 +- UnitTests/Input/EscSeqUtilsTests.cs | 46 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 99e5bce8f9..7b6fe1cf62 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -1448,7 +1448,9 @@ public static List SplitEscapeRawString (string rawData) } else if ((previousChar != '\u001B' && c <= Key.Space) || (previousChar != '\u001B' && c == 127) || (char.IsLetter (previousChar) && char.IsLower (c) && char.IsLetter (c)) - || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsLetter (c))) + || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsLetterOrDigit (c)) + || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsPunctuation (c)) + || (!string.IsNullOrEmpty (split) && split.Length > 2 && char.IsLetter (previousChar) && char.IsSymbol (c))) { isEscSeq = false; split = AddAndClearSplit (); diff --git a/UnitTests/Input/EscSeqUtilsTests.cs b/UnitTests/Input/EscSeqUtilsTests.cs index 3b028b60e4..7cc225971b 100644 --- a/UnitTests/Input/EscSeqUtilsTests.cs +++ b/UnitTests/Input/EscSeqUtilsTests.cs @@ -1441,11 +1441,57 @@ public void ResizeArray_ConsoleKeyInfo () } [Theory] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\b", "\b")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\t", "\t")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\n", "\n")] [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\r", "\r")] [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOCe", "e")] [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOCV", "V")] [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\u007f", "\u007f")] [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC ", " ")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\\", "\\")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC|", "|")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC1", "1")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC!", "!")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC\"", "\"")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC@", "@")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC#", "#")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC£", "£")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC$", "$")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC§", "§")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC%", "%")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC€", "€")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC&", "&")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC/", "/")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC{", "{")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC(", "(")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC[", "[")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC)", ")")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC]", "]")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC=", "=")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC}", "}")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC'", "'")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC?", "?")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC«", "«")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC»", "»")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC+", "+")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC*", "*")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC¨", "¨")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC´", "´")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC`", "`")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOCç", "ç")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOCº", "º")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOCª", "ª")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC~", "~")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC^", "^")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC<", "<")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC>", ">")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC,", ",")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC;", ";")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC.", ".")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC:", ":")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC-", "-")] + [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC_", "_")] public void SplitEscapeRawString_Multiple_Tests (string rawData, string expectedLast) { List splitList = EscSeqUtils.SplitEscapeRawString (rawData); From eb987071c864a3a0e381c20e89fced21e1aed830 Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 6 Nov 2024 22:05:46 +0000 Subject: [PATCH 77/89] Revert Key class changes. --- .../WindowsDriver/WindowsDriver.cs | 12 ++++++++- Terminal.Gui/Input/Key.cs | 25 +++++++------------ UnitTests/Input/KeyTests.cs | 10 ++++---- 3 files changed, 25 insertions(+), 22 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs index 6f20539d8d..656043f70c 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs @@ -817,11 +817,21 @@ private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx) // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask if (char.IsUpper (keyInfo.KeyChar)) { + if (keyInfo.KeyChar <= 'Z') + { + return (KeyCode)keyInfo.Key | KeyCode.ShiftMask; + } + // Always return the KeyChar because it may be an Á, À with Oem1, etc - return (KeyCode)keyInfo.KeyChar | KeyCode.ShiftMask; + return (KeyCode)keyInfo.KeyChar; } } + if (keyInfo.KeyChar <= 'z') + { + return (KeyCode)keyInfo.Key; + } + // Always return the KeyChar because it may be an á, à with Oem1, etc return (KeyCode)keyInfo.KeyChar; } diff --git a/Terminal.Gui/Input/Key.cs b/Terminal.Gui/Input/Key.cs index 3c8b75d94d..f5cd3e8bc2 100644 --- a/Terminal.Gui/Input/Key.cs +++ b/Terminal.Gui/Input/Key.cs @@ -1,6 +1,5 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; -using Terminal.Gui.ConsoleDrivers; namespace Terminal.Gui; @@ -209,13 +208,13 @@ public KeyCode KeyCode get => _keyCode; init { -//#if DEBUG -// if (GetIsKeyCodeAtoZ (value) && (value & KeyCode.Space) != 0) -// { -// throw new ArgumentException ($"Invalid KeyCode: {value} is invalid.", nameof (value)); -// } +#if DEBUG + if (GetIsKeyCodeAtoZ (value) && (value & KeyCode.Space) != 0) + { + throw new ArgumentException ($"Invalid KeyCode: {value} is invalid.", nameof (value)); + } -//#endif +#endif _keyCode = value; } } @@ -289,10 +288,7 @@ public static bool GetIsKeyCodeAtoZ (KeyCode keyCode) return false; } - // A to Z may have , , , , with Oem1, etc - ConsoleKeyInfo cki = ConsoleKeyMapping.GetConsoleKeyInfoFromKeyCode (keyCode); - - if (cki.Key is >= ConsoleKey.A and <= ConsoleKey.Z) + if ((keyCode & ~KeyCode.Space & ~KeyCode.ShiftMask) is >= KeyCode.A and <= KeyCode.Z) { return true; } @@ -525,12 +521,9 @@ public static string ToString (KeyCode key, Rune separator) // Handle special cases and modifiers on their own if (key != KeyCode.SpecialMask && (baseKey != KeyCode.Null || hasModifiers)) { - // A to Z may have , , , , with Oem1, etc - ConsoleKeyInfo cki = ConsoleKeyMapping.GetConsoleKeyInfoFromKeyCode (baseKey); - - if ((key & KeyCode.SpecialMask) != 0 && cki.Key is >= ConsoleKey.A and <= ConsoleKey.Z) + if ((key & KeyCode.SpecialMask) != 0 && (baseKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z) { - sb.Append (((char)(baseKey & ~KeyCode.Space)).ToString ()); + sb.Append (baseKey & ~KeyCode.Space); } else { diff --git a/UnitTests/Input/KeyTests.cs b/UnitTests/Input/KeyTests.cs index 1916c1d9bf..cf4cb78585 100644 --- a/UnitTests/Input/KeyTests.cs +++ b/UnitTests/Input/KeyTests.cs @@ -17,7 +17,7 @@ public class KeyTests { "Alt+A", Key.A.WithAlt }, { "Shift+A", Key.A.WithShift }, { "A", Key.A.WithShift }, - { "â", new ((KeyCode)'Â') }, + { "â", new ((KeyCode)'â') }, { "Shift+â", new ((KeyCode)'â' | KeyCode.ShiftMask) }, { "Shift+Â", new ((KeyCode)'Â' | KeyCode.ShiftMask) }, { "Ctrl+Shift+CursorUp", Key.CursorUp.WithShift.WithCtrl }, @@ -342,10 +342,10 @@ public void Standard_Keys_Should_Equal_KeyCode () [InlineData ((KeyCode)'{', "{")] [InlineData ((KeyCode)'\'', "\'")] [InlineData ((KeyCode)'ó', "ó")] - [InlineData ((KeyCode)'Ó' | KeyCode.ShiftMask, "Ó")] - [InlineData ((KeyCode)'ó' | KeyCode.ShiftMask, "Ó")] + [InlineData ((KeyCode)'Ó' | KeyCode.ShiftMask, "Shift+Ó")] + [InlineData ((KeyCode)'ó' | KeyCode.ShiftMask, "Shift+ó")] [InlineData ((KeyCode)'Ó', "Ó")] - [InlineData ((KeyCode)'ç' | KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.CtrlMask, "Ctrl+Alt+Shift+Ç")] + [InlineData ((KeyCode)'ç' | KeyCode.ShiftMask | KeyCode.AltMask | KeyCode.CtrlMask, "Ctrl+Alt+Shift+ç")] [InlineData ((KeyCode)'a', "a")] // 97 or Key.Space | Key.A [InlineData ((KeyCode)'A', "a")] // 65 or equivalent to Key.A, but A-Z are mapped to lower case by drivers [InlineData (KeyCode.ShiftMask | KeyCode.A, "A")] @@ -468,7 +468,7 @@ public void ToStringWithSeparator_ShouldReturnFormattedString (KeyCode key, char [InlineData ("Alt+A", KeyCode.A | KeyCode.AltMask)] [InlineData ("Shift+A", KeyCode.A | KeyCode.ShiftMask)] [InlineData ("A", KeyCode.A | KeyCode.ShiftMask)] - [InlineData ("â", (KeyCode)'Â')] + [InlineData ("â", (KeyCode)'â')] [InlineData ("Shift+â", (KeyCode)'â' | KeyCode.ShiftMask)] [InlineData ("Shift+Â", (KeyCode)'Â' | KeyCode.ShiftMask)] [InlineData ("Ctrl+Shift+CursorUp", KeyCode.ShiftMask | KeyCode.CtrlMask | KeyCode.CursorUp)] From 0b11e20e2fadb34c524f165a1de881997b2bb44b Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 6 Nov 2024 22:36:58 +0000 Subject: [PATCH 78/89] Change Response to a nullable string. --- .../AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs | 2 +- Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs | 2 +- Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs | 1 - Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs | 1 - Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs | 1 - 5 files changed, 2 insertions(+), 5 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 2e8da6bfed..0d35d4a920 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -24,7 +24,7 @@ public class AnsiEscapeSequenceRequest /// /// Gets the response received from the request. /// - public string Response { get; internal set; } = string.Empty; + public string? Response { get; internal set; } /// /// Raised when the console responds with an ANSI response code that matches the diff --git a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs index d6ccf99914..885f907a0c 100644 --- a/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/ConsoleDriver.cs @@ -45,7 +45,7 @@ public abstract class ConsoleDriver /// /// The object. /// The request response. - public abstract string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest); + public abstract string? WriteAnsiRequest (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? diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs index 52014cb55a..4410b799d1 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs @@ -248,7 +248,6 @@ private void CursesInputHandler () { EscSeqRequests.Statuses.TryDequeue (out _); - seqReqStatus.AnsiRequest.Response = string.Empty; seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); } } diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs index 939ed0d2d5..ed2ddd7f57 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs @@ -94,7 +94,6 @@ private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, { EscSeqRequests.Statuses.TryDequeue (out _); - seqReqStatus.AnsiRequest.Response = string.Empty; seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); } } diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs index 22c0e10357..d031817ee9 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs @@ -992,7 +992,6 @@ public InputRecord [] ReadConsoleInput () { _mainLoop.EscSeqRequests.Statuses.TryDequeue (out _); - seqReqStatus.AnsiRequest.Response = string.Empty; seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); } } From bdcc0ff6d43b6e0a6ea91aeb7388340ed838102c Mon Sep 17 00:00:00 2001 From: BDisp Date: Wed, 6 Nov 2024 23:36:21 +0000 Subject: [PATCH 79/89] Return null instead if empty and fix a bug that was returning the terminator as input. --- .../AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs | 4 ++-- Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs | 2 +- Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs | 2 +- Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs | 6 +++++- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 0d35d4a920..4c1636bf02 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -126,8 +126,8 @@ public static bool TryRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEs /// public string? ExpectedResponseValue { get; init; } - internal void RaiseResponseFromInput (AnsiEscapeSequenceRequest ansiRequest, string response) { ResponseFromInput?.Invoke (ansiRequest, response); } + internal void RaiseResponseFromInput (AnsiEscapeSequenceRequest ansiRequest, string? response) { ResponseFromInput?.Invoke (ansiRequest, response); } // QUESTION: What is this for? Please provide a descriptive comment. - internal event EventHandler? ResponseFromInput; + internal event EventHandler? ResponseFromInput; } diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs index 4410b799d1..9152296ff5 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs @@ -248,7 +248,7 @@ private void CursesInputHandler () { EscSeqRequests.Statuses.TryDequeue (out _); - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, null); } } diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs index ed2ddd7f57..6c4c24d1fb 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs @@ -94,7 +94,7 @@ private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, { EscSeqRequests.Statuses.TryDequeue (out _); - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, null); } } diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs index d031817ee9..1507ed4f43 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs @@ -978,6 +978,8 @@ public InputRecord [] ReadConsoleInput () { seqReqStatus.AnsiRequest.Response = ansiSequence.ToString (); seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response); + // Clear the terminator for not be enqueued + inputRecord = default (InputRecord); } _retries = 0; @@ -992,7 +994,9 @@ public InputRecord [] ReadConsoleInput () { _mainLoop.EscSeqRequests.Statuses.TryDequeue (out _); - seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty); + seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, null); + // Clear the terminator for not be enqueued + inputRecord = default (InputRecord); } } From 629cea841d4eb93138e6d2b77e1f93b30e474b6c Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 00:05:43 +0000 Subject: [PATCH 80/89] Handling null response. --- .../AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs | 7 ++++++- .../AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs | 2 +- UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index 4c1636bf02..a820ce9448 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -83,7 +83,12 @@ public static bool TryRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEs throw new InvalidOperationException ("Terminator request is empty."); } - if (!ansiRequest.Response.EndsWith (ansiRequest.Terminator [^1])) + if (string.IsNullOrEmpty (ansiRequest.Response)) + { + throw new InvalidOperationException ("Response request is null."); + } + + if (!string.IsNullOrEmpty (ansiRequest.Response) && !ansiRequest.Response.EndsWith (ansiRequest.Terminator [^1])) { string resp = string.IsNullOrEmpty (ansiRequest.Response) ? "" : ansiRequest.Response.Last ().ToString (); diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs index 2cc8208015..9a5a2ec8d4 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceResponse.cs @@ -24,7 +24,7 @@ public class AnsiEscapeSequenceResponse /// /// . /// - public required string Response { get; init; } + public required string? Response { get; init; } // QUESTION: Does string.Empty indicate no terminator expected? If not, perhaps make this property nullable? /// diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index f88c80820a..62fd1ef603 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -172,7 +172,7 @@ private View BuildSingleTab () out AnsiEscapeSequenceResponse ansiEscapeSequenceResponse ); - tvResponse.Text = ansiEscapeSequenceResponse.Response; + tvResponse.Text = ansiEscapeSequenceResponse.Response ?? ""; tvError.Text = ansiEscapeSequenceResponse.Error; tvValue.Text = ansiEscapeSequenceResponse.ExpectedResponseValue ?? ""; tvTerminator.Text = ansiEscapeSequenceResponse.Terminator; From f87c2b1e835235062f5a4001437584918d3cbc07 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 00:37:33 +0000 Subject: [PATCH 81/89] Rename EscSeq to AnsiEscapeSequence and move to his folder. --- .../AnsiEscapeSequenceRequest.cs | 4 +- .../AnsiEscapeSequenceRequestStatus.cs} | 6 +- .../AnsiEscapeSequenceRequestUtils.cs} | 6 +- .../AnsiEscapeSequenceRequests.cs} | 22 +- .../CursesDriver/CursesDriver.cs | 18 +- .../CursesDriver/UnixMainLoop.cs | 38 +-- .../ConsoleDrivers/NetDriver/NetDriver.cs | 32 +-- .../ConsoleDrivers/NetDriver/NetEvents.cs | 34 +-- .../WindowsDriver/WindowsConsole.cs | 22 +- .../WindowsDriver/WindowsDriver.cs | 14 +- .../Scenarios/AnsiEscapeSequenceRequests.cs | 10 +- ...=> AnsiEscapeSequenceRequestUtilsTests.cs} | 262 +++++++++--------- ....cs => AnsiEscapeSequenceRequestsTests.cs} | 14 +- 13 files changed, 241 insertions(+), 241 deletions(-) rename Terminal.Gui/ConsoleDrivers/{EscSeqUtils/EscSeqReqStatus.cs => AnsiEscapeSequence/AnsiEscapeSequenceRequestStatus.cs} (71%) rename Terminal.Gui/ConsoleDrivers/{EscSeqUtils/EscSeqUtils.cs => AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs} (99%) rename Terminal.Gui/ConsoleDrivers/{EscSeqUtils/EscSeqReq.cs => AnsiEscapeSequence/AnsiEscapeSequenceRequests.cs} (72%) rename UnitTests/Input/{EscSeqUtilsTests.cs => AnsiEscapeSequenceRequestUtilsTests.cs} (84%) rename UnitTests/Input/{EscSeqReqTests.cs => AnsiEscapeSequenceRequestsTests.cs} (82%) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs index a820ce9448..1159ae37da 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequest.cs @@ -73,7 +73,7 @@ public static bool TryRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEs // Send the ANSI escape sequence ansiRequest.Response = driver?.WriteAnsiRequest (ansiRequest)!; - if (!string.IsNullOrEmpty (ansiRequest.Response) && !ansiRequest.Response.StartsWith (EscSeqUtils.KeyEsc)) + if (!string.IsNullOrEmpty (ansiRequest.Response) && !ansiRequest.Response.StartsWith (AnsiEscapeSequenceRequestUtils.KeyEsc)) { throw new InvalidOperationException ($"Invalid Response: {ansiRequest.Response}"); } @@ -103,7 +103,7 @@ public static bool TryRequest (AnsiEscapeSequenceRequest ansiRequest, out AnsiEs { if (string.IsNullOrEmpty (error.ToString ())) { - (string? _, string? _, values, string? _) = EscSeqUtils.GetEscapeResult (ansiRequest.Response.ToCharArray ()); + (string? _, string? _, values, string? _) = AnsiEscapeSequenceRequestUtils.GetEscapeResult (ansiRequest.Response.ToCharArray ()); } } diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReqStatus.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestStatus.cs similarity index 71% rename from Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReqStatus.cs rename to Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestStatus.cs index c9561ec7bf..b07d482366 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReqStatus.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestStatus.cs @@ -3,14 +3,14 @@ namespace Terminal.Gui; /// /// Represents the status of an ANSI escape sequence request made to the terminal using -/// . +/// . /// /// -public class EscSeqReqStatus +public class AnsiEscapeSequenceRequestStatus { /// Creates a new state of escape sequence request. /// The object. - public EscSeqReqStatus (AnsiEscapeSequenceRequest ansiRequest) { AnsiRequest = ansiRequest; } + public AnsiEscapeSequenceRequestStatus (AnsiEscapeSequenceRequest ansiRequest) { AnsiRequest = ansiRequest; } /// Gets the Escape Sequence Terminator (e.g. ESC[8t ... t is the terminator). public AnsiEscapeSequenceRequest AnsiRequest { get; } diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs similarity index 99% rename from Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs rename to Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs index 7b6fe1cf62..844112d650 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs @@ -19,7 +19,7 @@ namespace Terminal.Gui; /// * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html /// * https://vt100.net/ /// -public static class EscSeqUtils +public static class AnsiEscapeSequenceRequestUtils { // TODO: One type per file - Move this enum to a separate file. /// @@ -197,7 +197,7 @@ public enum ClearScreenOptions /// The object. /// The handler that will process the event. public static void DecodeEscSeq ( - EscSeqRequests? escSeqRequests, + AnsiEscapeSequenceRequests? escSeqRequests, ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ConsoleKeyInfo [] cki, @@ -209,7 +209,7 @@ public static void DecodeEscSeq ( out bool isMouse, out List buttonState, out Point pos, - out EscSeqReqStatus? seqReqStatus, + out AnsiEscapeSequenceRequestStatus? seqReqStatus, Action continuousButtonPressedHandler ) { diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequests.cs similarity index 72% rename from Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs rename to Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequests.cs index 280f3f9e71..8cc9845235 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqReq.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequests.cs @@ -8,14 +8,14 @@ namespace Terminal.Gui; // TODO: This class is a singleton. It should use the singleton pattern. /// -/// Manages ANSI Escape Sequence requests and responses. The list of contains the +/// Manages ANSI Escape Sequence requests and responses. The list of contains the /// status of the request. Each request is identified by the terminator (e.g. ESC[8t ... t is the terminator). /// -public class EscSeqRequests +public class AnsiEscapeSequenceRequests { /// /// Adds a new request for the ANSI Escape Sequence defined by . Adds a - /// instance to list. + /// instance to list. /// /// The object. /// The driver in use. @@ -38,13 +38,13 @@ public void Add (AnsiEscapeSequenceRequest ansiRequest, ConsoleDriver? driver = } /// - /// Indicates if a with the exists in the + /// Indicates if a with the exists in the /// list. /// /// /// /// if exist, otherwise. - public bool HasResponse (string terminator, out EscSeqReqStatus? seqReqStatus) + public bool HasResponse (string terminator, out AnsiEscapeSequenceRequestStatus? seqReqStatus) { lock (Statuses) { @@ -64,13 +64,13 @@ public bool HasResponse (string terminator, out EscSeqReqStatus? seqReqStatus) } /// - /// Removes a request defined by . If a matching is + /// Removes a request defined by . If a matching is /// found and the number of outstanding requests is greater than 0, the number of outstanding requests is decremented. - /// If the number of outstanding requests is 0, the is removed from + /// If the number of outstanding requests is 0, the is removed from /// . /// - /// The object. - public void Remove (EscSeqReqStatus? seqReqStatus) + /// The object. + public void Remove (AnsiEscapeSequenceRequestStatus? seqReqStatus) { lock (Statuses) { @@ -83,6 +83,6 @@ public void Remove (EscSeqReqStatus? seqReqStatus) } } - /// Gets the list. - public ConcurrentQueue Statuses { get; } = new (); + /// Gets the list. + public ConcurrentQueue Statuses { get; } = new (); } diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index e0225b3aae..80b74edf69 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -230,7 +230,7 @@ public override void UpdateScreen () redrawAttr = attr; output.Append ( - EscSeqUtils.CSI_SetForegroundColorRGB ( + AnsiEscapeSequenceRequestUtils.CSI_SetForegroundColorRGB ( attr.Foreground.R, attr.Foreground.G, attr.Foreground.B @@ -238,7 +238,7 @@ public override void UpdateScreen () ); output.Append ( - EscSeqUtils.CSI_SetBackgroundColorRGB ( + AnsiEscapeSequenceRequestUtils.CSI_SetBackgroundColorRGB ( attr.Background.R, attr.Background.G, attr.Background.B @@ -487,8 +487,8 @@ public override bool SetCursorVisibility (CursorVisibility visibility) if (visibility != CursorVisibility.Invisible) { Console.Out.Write ( - EscSeqUtils.CSI_SetCursorStyle ( - (EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) + AnsiEscapeSequenceRequestUtils.CSI_SetCursorStyle ( + (AnsiEscapeSequenceRequestUtils.DECSCUSR_Style)(((int)visibility >> 24) & 0xFF) ) ); @@ -515,7 +515,7 @@ public override void UpdateCursor () } else { - _mainLoopDriver.WriteRaw (EscSeqUtils.CSI_SetCursorPosition (Row + 1, Col + 1)); + _mainLoopDriver.WriteRaw (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (Row + 1, Col + 1)); } } } @@ -647,7 +647,7 @@ public void StartReportingMouseMoves () { if (!RunningUnitTests) { - Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_EnableMouseEvents); } } @@ -655,7 +655,7 @@ public void StopReportingMouseMoves () { if (!RunningUnitTests) { - Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_DisableMouseEvents); } } @@ -665,7 +665,7 @@ private bool SetCursorPosition (int col, int row) { // + 1 is needed because non-Windows is based on 1 instead of 0 and // Console.CursorTop/CursorLeft isn't reliable. - Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1)); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (row + 1, col + 1)); return true; } @@ -903,7 +903,7 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { _mainLoopDriver._forceRead = false; - if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) + if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus request)) { if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0 && string.IsNullOrEmpty (request.AnsiRequest.Response)) diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs index 9152296ff5..68d6df13ad 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/UnixMainLoop.cs @@ -52,7 +52,7 @@ public UnixMainLoop (ConsoleDriver consoleDriver = null) _cursesDriver = (CursesDriver)consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver)); } - public EscSeqRequests EscSeqRequests { get; } = new (); + public AnsiEscapeSequenceRequests EscSeqRequests { get; } = new (); void IMainLoopDriver.Wakeup () { _eventReady.Set (); } @@ -77,7 +77,7 @@ void IMainLoopDriver.Setup (MainLoop mainLoop) throw new NotSupportedException ("libc not found", e); } - EscSeqUtils.ContinuousButtonPressed += EscSeqUtils_ContinuousButtonPressed; + AnsiEscapeSequenceRequestUtils.ContinuousButtonPressed += EscSeqUtils_ContinuousButtonPressed; Task.Run (CursesInputHandler, _inputHandlerTokenSource.Token); Task.Run (WindowSizeHandler, _inputHandlerTokenSource.Token); @@ -213,10 +213,10 @@ private void CursesInputHandler () // Convert the byte array to a string (assuming UTF-8 encoding) string data = Encoding.UTF8.GetString (buffer); - if (EscSeqUtils.IncompleteCkInfos is { }) + if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is { }) { - data = data.Insert (0, EscSeqUtils.ToString (EscSeqUtils.IncompleteCkInfos)); - EscSeqUtils.IncompleteCkInfos = null; + data = data.Insert (0, AnsiEscapeSequenceRequestUtils.ToString (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos)); + AnsiEscapeSequenceRequestUtils.IncompleteCkInfos = null; } // Enqueue the data @@ -238,11 +238,11 @@ private void CursesInputHandler () break; } - if (EscSeqUtils.IncompleteCkInfos is null && EscSeqRequests is { Statuses.Count: > 0 }) + if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && EscSeqRequests is { Statuses.Count: > 0 }) { if (_retries > 1) { - if (EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) + if (EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) { lock (seqReqStatus!.AnsiRequest._responseLock) { @@ -284,7 +284,7 @@ private void CursesInputHandler () private void ProcessEnqueuePollData (string pollData) { - foreach (string split in EscSeqUtils.SplitEscapeRawString (pollData)) + foreach (string split in AnsiEscapeSequenceRequestUtils.SplitEscapeRawString (pollData)) { EnqueuePollData (split); } @@ -292,13 +292,13 @@ private void ProcessEnqueuePollData (string pollData) private void EnqueuePollData (string pollDataPart) { - ConsoleKeyInfo [] cki = EscSeqUtils.ToConsoleKeyInfoArray (pollDataPart); + ConsoleKeyInfo [] cki = AnsiEscapeSequenceRequestUtils.ToConsoleKeyInfoArray (pollDataPart); ConsoleKey key = 0; ConsoleModifiers mod = 0; ConsoleKeyInfo newConsoleKeyInfo = default; - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( EscSeqRequests, ref newConsoleKeyInfo, ref key, @@ -311,8 +311,8 @@ private void EnqueuePollData (string pollDataPart) out bool isMouse, out List mouseFlags, out Point pos, - out EscSeqReqStatus seqReqStatus, - EscSeqUtils.ProcessMouseEvent + out AnsiEscapeSequenceRequestStatus seqReqStatus, + AnsiEscapeSequenceRequestUtils.ProcessMouseEvent ); if (isMouse) @@ -327,7 +327,7 @@ private void EnqueuePollData (string pollDataPart) if (seqReqStatus is { }) { - var ckiString = EscSeqUtils.ToString (cki); + var ckiString = AnsiEscapeSequenceRequestUtils.ToString (cki); lock (seqReqStatus.AnsiRequest._responseLock) { @@ -338,16 +338,16 @@ private void EnqueuePollData (string pollDataPart) return; } - if (!string.IsNullOrEmpty (EscSeqUtils.InvalidRequestTerminator)) + if (!string.IsNullOrEmpty (AnsiEscapeSequenceRequestUtils.InvalidRequestTerminator)) { - if (EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus result)) + if (EscSeqRequests.Statuses.TryDequeue (out AnsiEscapeSequenceRequestStatus result)) { lock (result.AnsiRequest._responseLock) { - result.AnsiRequest.Response = EscSeqUtils.InvalidRequestTerminator; - result.AnsiRequest.RaiseResponseFromInput (result.AnsiRequest, EscSeqUtils.InvalidRequestTerminator); + result.AnsiRequest.Response = AnsiEscapeSequenceRequestUtils.InvalidRequestTerminator; + result.AnsiRequest.RaiseResponseFromInput (result.AnsiRequest, AnsiEscapeSequenceRequestUtils.InvalidRequestTerminator); - EscSeqUtils.InvalidRequestTerminator = null; + AnsiEscapeSequenceRequestUtils.InvalidRequestTerminator = null; } } @@ -425,7 +425,7 @@ void IMainLoopDriver.Iteration () void IMainLoopDriver.TearDown () { - EscSeqUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed; + AnsiEscapeSequenceRequestUtils.ContinuousButtonPressed -= EscSeqUtils_ContinuousButtonPressed; _inputHandlerTokenSource?.Cancel (); _inputHandlerTokenSource?.Dispose (); diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs index e4103d8c36..d650c91f04 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs @@ -37,15 +37,15 @@ public override void Suspend () Console.Clear (); //Disable alternative screen buffer. - Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll); //Set cursor key to cursor. - Console.Out.Write (EscSeqUtils.CSI_ShowCursor); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_ShowCursor); Platform.Suspend (); //Enable alternative screen buffer. - Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll); SetContentsAsDirty (); Refresh (); @@ -139,7 +139,7 @@ public override void UpdateScreen () if (Force16Colors) { output.Append ( - EscSeqUtils.CSI_SetGraphicsRendition ( + AnsiEscapeSequenceRequestUtils.CSI_SetGraphicsRendition ( MapColors ( (ConsoleColor)attr.Background.GetClosestNamedColor16 (), false @@ -151,7 +151,7 @@ public override void UpdateScreen () else { output.Append ( - EscSeqUtils.CSI_SetForegroundColorRGB ( + AnsiEscapeSequenceRequestUtils.CSI_SetForegroundColorRGB ( attr.Foreground.R, attr.Foreground.G, attr.Foreground.B @@ -159,7 +159,7 @@ public override void UpdateScreen () ); output.Append ( - EscSeqUtils.CSI_SetBackgroundColorRGB ( + AnsiEscapeSequenceRequestUtils.CSI_SetBackgroundColorRGB ( attr.Background.R, attr.Background.G, attr.Background.B @@ -277,10 +277,10 @@ internal override MainLoop Init () Rows = Console.WindowHeight; //Enable alternative screen buffer. - Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll); //Set cursor key to application. - Console.Out.Write (EscSeqUtils.CSI_HideCursor); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_HideCursor); } else { @@ -374,10 +374,10 @@ internal override void End () Console.ResetColor (); //Disable alternative screen buffer. - Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll); //Set cursor key to cursor. - Console.Out.Write (EscSeqUtils.CSI_ShowCursor); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_ShowCursor); Console.Out.Close (); } } @@ -467,7 +467,7 @@ private bool SetCursorPosition (int col, int row) // + 1 is needed because non-Windows is based on 1 instead of 0 and // Console.CursorTop/CursorLeft isn't reliable. - Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1)); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (row + 1, col + 1)); return true; } @@ -496,7 +496,7 @@ public override bool SetCursorVisibility (CursorVisibility visibility) { _cachedCursorVisibility = visibility; - Console.Out.Write (visibility == CursorVisibility.Default ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor); + Console.Out.Write (visibility == CursorVisibility.Default ? AnsiEscapeSequenceRequestUtils.CSI_ShowCursor : AnsiEscapeSequenceRequestUtils.CSI_HideCursor); return visibility == CursorVisibility.Default; } @@ -525,7 +525,7 @@ public void StartReportingMouseMoves () { if (!RunningUnitTests) { - Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_EnableMouseEvents); } } @@ -533,7 +533,7 @@ public void StopReportingMouseMoves () { if (!RunningUnitTests) { - Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_DisableMouseEvents); } } @@ -875,7 +875,7 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { _mainLoopDriver._netEvents._forceRead = false; - if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) + if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus request)) { if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0 && string.IsNullOrEmpty (request.AnsiRequest.Response)) @@ -954,7 +954,7 @@ private void ResizeScreen () } else { - Console.Out.Write (EscSeqUtils.CSI_SetTerminalWindowSize (Rows, Cols)); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SetTerminalWindowSize (Rows, Cols)); } // CONCURRENCY: Unsynchronized access to Clip is not safe. diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs index 6c4c24d1fb..3e5414241b 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs @@ -19,7 +19,7 @@ internal class NetEvents : IDisposable #if PROCESS_REQUEST bool _neededProcessRequest; #endif - public EscSeqRequests EscSeqRequests { get; } = new (); + public AnsiEscapeSequenceRequests EscSeqRequests { get; } = new (); public NetEvents (ConsoleDriver consoleDriver) { @@ -84,11 +84,11 @@ private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, return Console.ReadKey (intercept); } - if (EscSeqUtils.IncompleteCkInfos is null && EscSeqRequests is { Statuses.Count: > 0 }) + if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && EscSeqRequests is { Statuses.Count: > 0 }) { if (_retries > 1) { - if (EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) + if (EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) { lock (seqReqStatus!.AnsiRequest._responseLock) { @@ -161,9 +161,9 @@ private void ProcessInputQueue () return; } - if (EscSeqUtils.IncompleteCkInfos is { }) + if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is { }) { - EscSeqUtils.InsertArray (EscSeqUtils.IncompleteCkInfos, _cki); + AnsiEscapeSequenceRequestUtils.InsertArray (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos, _cki); } if ((consoleKeyInfo.KeyChar == (char)KeyCode.Esc && !_isEscSeq) @@ -171,7 +171,7 @@ private void ProcessInputQueue () { if (_cki is null && consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq) { - _cki = EscSeqUtils.ResizeArray ( + _cki = AnsiEscapeSequenceRequestUtils.ResizeArray ( new ConsoleKeyInfo ( (char)KeyCode.Esc, 0, @@ -199,7 +199,7 @@ private void ProcessInputQueue () else { newConsoleKeyInfo = consoleKeyInfo; - _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki); + _cki = AnsiEscapeSequenceRequestUtils.ResizeArray (consoleKeyInfo, _cki); if (Console.KeyAvailable) { @@ -221,7 +221,7 @@ private void ProcessInputQueue () if (Console.KeyAvailable) { - _cki = EscSeqUtils.ResizeArray (consoleKeyInfo, _cki); + _cki = AnsiEscapeSequenceRequestUtils.ResizeArray (consoleKeyInfo, _cki); } else { @@ -250,7 +250,7 @@ void ProcessMapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) _inputQueue.Enqueue ( new InputResult { - EventType = EventType.Key, ConsoleKeyInfo = EscSeqUtils.MapConsoleKeyInfo (consoleKeyInfo) + EventType = EventType.Key, ConsoleKeyInfo = AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (consoleKeyInfo) } ); _isEscSeq = false; @@ -346,7 +346,7 @@ ref ConsoleModifiers mod ) { // isMouse is true if it's CSI<, false otherwise - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( EscSeqRequests, ref newConsoleKeyInfo, ref key, @@ -359,7 +359,7 @@ ref ConsoleModifiers mod out bool isMouse, out List mouseFlags, out Point pos, - out EscSeqReqStatus seqReqStatus, + out AnsiEscapeSequenceRequestStatus seqReqStatus, (f, p) => HandleMouseEvent (MapMouseFlags (f), p) ); @@ -377,7 +377,7 @@ ref ConsoleModifiers mod { //HandleRequestResponseEvent (c1Control, code, values, terminating); - var ckiString = EscSeqUtils.ToString (cki); + var ckiString = AnsiEscapeSequenceRequestUtils.ToString (cki); lock (seqReqStatus.AnsiRequest._responseLock) { @@ -388,16 +388,16 @@ ref ConsoleModifiers mod return; } - if (!string.IsNullOrEmpty (EscSeqUtils.InvalidRequestTerminator)) + if (!string.IsNullOrEmpty (AnsiEscapeSequenceRequestUtils.InvalidRequestTerminator)) { - if (EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus result)) + if (EscSeqRequests.Statuses.TryDequeue (out AnsiEscapeSequenceRequestStatus result)) { lock (result.AnsiRequest._responseLock) { - result.AnsiRequest.Response = EscSeqUtils.InvalidRequestTerminator; - result.AnsiRequest.RaiseResponseFromInput (result.AnsiRequest, EscSeqUtils.InvalidRequestTerminator); + result.AnsiRequest.Response = AnsiEscapeSequenceRequestUtils.InvalidRequestTerminator; + result.AnsiRequest.RaiseResponseFromInput (result.AnsiRequest, AnsiEscapeSequenceRequestUtils.InvalidRequestTerminator); - EscSeqUtils.InvalidRequestTerminator = null; + AnsiEscapeSequenceRequestUtils.InvalidRequestTerminator = null; } } diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs index 1507ed4f43..430085a2aa 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs @@ -68,8 +68,8 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord { _stringBuilder.Clear (); - _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition); - _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0)); + _stringBuilder.Append (AnsiEscapeSequenceRequestUtils.CSI_SaveCursorPosition); + _stringBuilder.Append (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (0, 0)); Attribute? prev = null; @@ -80,8 +80,8 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord if (attr != prev) { prev = attr; - _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B)); - _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B)); + _stringBuilder.Append (AnsiEscapeSequenceRequestUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B)); + _stringBuilder.Append (AnsiEscapeSequenceRequestUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B)); } if (info.Char != '\x1b') @@ -97,8 +97,8 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord } } - _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition); - _stringBuilder.Append (EscSeqUtils.CSI_HideCursor); + _stringBuilder.Append (AnsiEscapeSequenceRequestUtils.CSI_RestoreCursorPosition); + _stringBuilder.Append (AnsiEscapeSequenceRequestUtils.CSI_HideCursor); var s = _stringBuilder.ToString (); @@ -949,7 +949,7 @@ public InputRecord [] ReadConsoleInput () ansiSequence.Append (inputChar); // Check if the sequence has ended with an expected command terminator - if (_mainLoop.EscSeqRequests is { } && _mainLoop.EscSeqRequests.HasResponse (inputChar.ToString (), out EscSeqReqStatus seqReqStatus)) + if (_mainLoop.EscSeqRequests is { } && _mainLoop.EscSeqRequests.HasResponse (inputChar.ToString (), out AnsiEscapeSequenceRequestStatus seqReqStatus)) { // Finished reading the sequence and remove the enqueued request _mainLoop.EscSeqRequests.Remove (seqReqStatus); @@ -970,9 +970,9 @@ public InputRecord [] ReadConsoleInput () } } - if (readingSequence && !raisedResponse && EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) + if (readingSequence && !raisedResponse && AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) { - _mainLoop.EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus); + _mainLoop.EscSeqRequests.Statuses.TryDequeue (out AnsiEscapeSequenceRequestStatus seqReqStatus); lock (seqReqStatus!.AnsiRequest._responseLock) { @@ -984,11 +984,11 @@ public InputRecord [] ReadConsoleInput () _retries = 0; } - else if (EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) + else if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) { if (_retries > 1) { - if (_mainLoop.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) + if (_mainLoop.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) { lock (seqReqStatus!.AnsiRequest._responseLock) { diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs index 656043f70c..9372fcb046 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs @@ -242,7 +242,7 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { _mainLoopDriver._forceRead = false; - if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request)) + if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus request)) { if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0 && string.IsNullOrEmpty (request.AnsiRequest.Response)) @@ -316,7 +316,7 @@ public override void UpdateCursor () else { var sb = new StringBuilder (); - sb.Append (EscSeqUtils.CSI_SetCursorPosition (position.Y + 1, position.X + 1)); + sb.Append (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (position.Y + 1, position.X + 1)); WinConsole?.WriteANSI (sb.ToString ()); } @@ -352,7 +352,7 @@ public override bool SetCursorVisibility (CursorVisibility visibility) else { var sb = new StringBuilder (); - sb.Append (visibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor); + sb.Append (visibility != CursorVisibility.Invisible ? AnsiEscapeSequenceRequestUtils.CSI_ShowCursor : AnsiEscapeSequenceRequestUtils.CSI_HideCursor); return WinConsole?.WriteANSI (sb.ToString ()) ?? false; } } @@ -367,7 +367,7 @@ public override bool EnsureCursorVisibility () else { var sb = new StringBuilder (); - sb.Append (_cachedCursorVisibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor); + sb.Append (_cachedCursorVisibility != CursorVisibility.Invisible ? AnsiEscapeSequenceRequestUtils.CSI_ShowCursor : AnsiEscapeSequenceRequestUtils.CSI_HideCursor); return WinConsole?.WriteANSI (sb.ToString ()) ?? false; } @@ -488,7 +488,7 @@ internal override void End () if (!RunningUnitTests && _isWindowsTerminal) { // Disable alternative screen buffer. - Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll); } } @@ -513,7 +513,7 @@ internal override MainLoop Init () if (_isWindowsTerminal) { - Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll); + Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll); } } catch (Win32Exception e) @@ -1291,7 +1291,7 @@ public WindowsMainLoop (ConsoleDriver consoleDriver = null) } } - public EscSeqRequests EscSeqRequests { get; } = new (); + public AnsiEscapeSequenceRequests EscSeqRequests { get; } = new (); void IMainLoopDriver.Setup (MainLoop mainLoop) { diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index 62fd1ef603..af8b0d8688 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -109,19 +109,19 @@ private View BuildSingleTab () switch (selAnsiEscapeSequenceRequestName) { case "CSI_SendDeviceAttributes": - selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_SendDeviceAttributes; + selAnsiEscapeSequenceRequest = AnsiEscapeSequenceRequestUtils.CSI_SendDeviceAttributes; break; case "CSI_ReportTerminalSizeInChars": - selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_ReportTerminalSizeInChars; + selAnsiEscapeSequenceRequest = AnsiEscapeSequenceRequestUtils.CSI_ReportTerminalSizeInChars; break; case "CSI_RequestCursorPositionReport": - selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_RequestCursorPositionReport; + selAnsiEscapeSequenceRequest = AnsiEscapeSequenceRequestUtils.CSI_RequestCursorPositionReport; break; case "CSI_SendDeviceAttributes2": - selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_SendDeviceAttributes2; + selAnsiEscapeSequenceRequest = AnsiEscapeSequenceRequestUtils.CSI_SendDeviceAttributes2; break; } @@ -372,7 +372,7 @@ private void UpdateGraph () private void SendDar () { _sends.Add (DateTime.Now); - string result = Application.Driver.WriteAnsiRequest (EscSeqUtils.CSI_SendDeviceAttributes); + string result = Application.Driver.WriteAnsiRequest (AnsiEscapeSequenceRequestUtils.CSI_SendDeviceAttributes); HandleResponse (result); } diff --git a/UnitTests/Input/EscSeqUtilsTests.cs b/UnitTests/Input/AnsiEscapeSequenceRequestUtilsTests.cs similarity index 84% rename from UnitTests/Input/EscSeqUtilsTests.cs rename to UnitTests/Input/AnsiEscapeSequenceRequestUtilsTests.cs index 7cc225971b..dbfc5286e3 100644 --- a/UnitTests/Input/EscSeqUtilsTests.cs +++ b/UnitTests/Input/AnsiEscapeSequenceRequestUtilsTests.cs @@ -3,17 +3,17 @@ namespace Terminal.Gui.InputTests; -public class EscSeqUtilsTests +public class AnsiEscapeSequenceRequestUtilsTests { private bool _actionStarted; private MouseFlags _arg1; private Point _arg2; private string _c1Control, _code, _terminating; private ConsoleKeyInfo [] _cki; - private EscSeqRequests _escSeqReqProc; + private AnsiEscapeSequenceRequests _escSeqReqProc; private bool _isKeyMouse; [CanBeNull] - private EscSeqReqStatus _seqReqStatus; + private AnsiEscapeSequenceRequestStatus _seqReqStatus; private ConsoleKey _key; private ConsoleModifiers _mod; private List _mouseFlags; @@ -29,7 +29,7 @@ public void DecodeEscSeq_Multiple_Tests () _cki = new ConsoleKeyInfo [] { new ('\u001b', 0, false, false, false) }; var expectedCki = new ConsoleKeyInfo ('\u001b', ConsoleKey.Escape, false, false, false); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -64,7 +64,7 @@ public void DecodeEscSeq_Multiple_Tests () _cki = new ConsoleKeyInfo [] { new ('\u001b', 0, false, false, false), new ('\u0012', 0, false, false, false) }; expectedCki = new ('\u0012', ConsoleKey.R, false, true, true); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -99,7 +99,7 @@ public void DecodeEscSeq_Multiple_Tests () _cki = new ConsoleKeyInfo [] { new ('\u001b', 0, false, false, false), new ('r', 0, false, false, false) }; expectedCki = new ('r', ConsoleKey.R, false, true, false); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -139,7 +139,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = new ('\0', ConsoleKey.F3, false, false, false); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -185,7 +185,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = new ('\0', ConsoleKey.F3, true, false, false); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -231,7 +231,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = new ('\0', ConsoleKey.F3, false, true, false); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -277,7 +277,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = new ('\0', ConsoleKey.F3, true, true, false); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -323,7 +323,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = new ('\0', ConsoleKey.F3, false, false, true); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -369,7 +369,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = new ('\0', ConsoleKey.F3, true, false, true); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -415,7 +415,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = new ('\0', ConsoleKey.F3, false, true, true); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -461,7 +461,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = new ('\0', ConsoleKey.F3, true, true, true); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -510,7 +510,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = default (ConsoleKeyInfo); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -560,7 +560,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = default (ConsoleKeyInfo); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -615,7 +615,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = default (ConsoleKeyInfo); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -663,7 +663,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = default (ConsoleKeyInfo); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -718,7 +718,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = default (ConsoleKeyInfo); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -787,7 +787,7 @@ public void DecodeEscSeq_Multiple_Tests () }; expectedCki = default (ConsoleKeyInfo); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -844,7 +844,7 @@ public void DecodeEscSeq_Multiple_Tests () Assert.Single (_escSeqReqProc.Statuses); Assert.Equal ("t", _escSeqReqProc.Statuses.ToArray () [^1].AnsiRequest.Terminator); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -908,7 +908,7 @@ params char [] kChars var expectedCki = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -975,7 +975,7 @@ public void DecodeEscSeq_IncompleteCKInfos () ConsoleKeyInfo expectedCki = default; - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -1005,10 +1005,10 @@ public void DecodeEscSeq_IncompleteCKInfos () Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); - Assert.Equal (_cki, EscSeqUtils.IncompleteCkInfos); + Assert.Equal (_cki, AnsiEscapeSequenceRequestUtils.IncompleteCkInfos); - _cki = EscSeqUtils.InsertArray ( - EscSeqUtils.IncompleteCkInfos, + _cki = AnsiEscapeSequenceRequestUtils.InsertArray ( + AnsiEscapeSequenceRequestUtils.IncompleteCkInfos, [ new ('0', 0, false, false, false), new (';', 0, false, false, false), @@ -1019,7 +1019,7 @@ public void DecodeEscSeq_IncompleteCKInfos () expectedCki = default; - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -1050,8 +1050,8 @@ public void DecodeEscSeq_IncompleteCKInfos () Assert.Null (_seqReqStatus); Assert.Equal (0, (int)_arg1); Assert.Equal (Point.Empty, _arg2); - Assert.NotEqual (_cki, EscSeqUtils.IncompleteCkInfos); - Assert.Contains (EscSeqUtils.ToString (EscSeqUtils.IncompleteCkInfos), EscSeqUtils.ToString (_cki)); + Assert.NotEqual (_cki, AnsiEscapeSequenceRequestUtils.IncompleteCkInfos); + Assert.Contains (AnsiEscapeSequenceRequestUtils.ToString (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos), AnsiEscapeSequenceRequestUtils.ToString (_cki)); ClearAll (); } @@ -1072,7 +1072,7 @@ public void DecodeEscSeq_Single_Tests (char keyChar, ConsoleKey consoleKey, bool _cki = [new (keyChar, 0, false, false, false)]; var expectedCki = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control); - EscSeqUtils.DecodeEscSeq ( + AnsiEscapeSequenceRequestUtils.DecodeEscSeq ( _escSeqReqProc, ref _newConsoleKeyInfo, ref _key, @@ -1136,38 +1136,38 @@ public void DecodeEscSeq_Single_Tests (char keyChar, ConsoleKey consoleKey, bool [Fact] public void Defaults_Values () { - Assert.Equal ('\x1b', EscSeqUtils.KeyEsc); - Assert.Equal ("\x1b[", EscSeqUtils.CSI); - Assert.Equal ("\x1b[?1003h", EscSeqUtils.CSI_EnableAnyEventMouse); - Assert.Equal ("\x1b[?1006h", EscSeqUtils.CSI_EnableSgrExtModeMouse); - Assert.Equal ("\x1b[?1015h", EscSeqUtils.CSI_EnableUrxvtExtModeMouse); - Assert.Equal ("\x1b[?1003l", EscSeqUtils.CSI_DisableAnyEventMouse); - Assert.Equal ("\x1b[?1006l", EscSeqUtils.CSI_DisableSgrExtModeMouse); - Assert.Equal ("\x1b[?1015l", EscSeqUtils.CSI_DisableUrxvtExtModeMouse); - Assert.Equal ("\x1b[?1003h\x1b[?1015h\u001b[?1006h", EscSeqUtils.CSI_EnableMouseEvents); - Assert.Equal ("\x1b[?1003l\x1b[?1015l\u001b[?1006l", EscSeqUtils.CSI_DisableMouseEvents); + Assert.Equal ('\x1b', AnsiEscapeSequenceRequestUtils.KeyEsc); + Assert.Equal ("\x1b[", AnsiEscapeSequenceRequestUtils.CSI); + Assert.Equal ("\x1b[?1003h", AnsiEscapeSequenceRequestUtils.CSI_EnableAnyEventMouse); + Assert.Equal ("\x1b[?1006h", AnsiEscapeSequenceRequestUtils.CSI_EnableSgrExtModeMouse); + Assert.Equal ("\x1b[?1015h", AnsiEscapeSequenceRequestUtils.CSI_EnableUrxvtExtModeMouse); + Assert.Equal ("\x1b[?1003l", AnsiEscapeSequenceRequestUtils.CSI_DisableAnyEventMouse); + Assert.Equal ("\x1b[?1006l", AnsiEscapeSequenceRequestUtils.CSI_DisableSgrExtModeMouse); + Assert.Equal ("\x1b[?1015l", AnsiEscapeSequenceRequestUtils.CSI_DisableUrxvtExtModeMouse); + Assert.Equal ("\x1b[?1003h\x1b[?1015h\u001b[?1006h", AnsiEscapeSequenceRequestUtils.CSI_EnableMouseEvents); + Assert.Equal ("\x1b[?1003l\x1b[?1015l\u001b[?1006l", AnsiEscapeSequenceRequestUtils.CSI_DisableMouseEvents); } [Fact] public void GetC1ControlChar_Tests () { - Assert.Equal ("IND", EscSeqUtils.GetC1ControlChar ('D')); - Assert.Equal ("NEL", EscSeqUtils.GetC1ControlChar ('E')); - Assert.Equal ("HTS", EscSeqUtils.GetC1ControlChar ('H')); - Assert.Equal ("RI", EscSeqUtils.GetC1ControlChar ('M')); - Assert.Equal ("SS2", EscSeqUtils.GetC1ControlChar ('N')); - Assert.Equal ("SS3", EscSeqUtils.GetC1ControlChar ('O')); - Assert.Equal ("DCS", EscSeqUtils.GetC1ControlChar ('P')); - Assert.Equal ("SPA", EscSeqUtils.GetC1ControlChar ('V')); - Assert.Equal ("EPA", EscSeqUtils.GetC1ControlChar ('W')); - Assert.Equal ("SOS", EscSeqUtils.GetC1ControlChar ('X')); - Assert.Equal ("DECID", EscSeqUtils.GetC1ControlChar ('Z')); - Assert.Equal ("CSI", EscSeqUtils.GetC1ControlChar ('[')); - Assert.Equal ("ST", EscSeqUtils.GetC1ControlChar ('\\')); - Assert.Equal ("OSC", EscSeqUtils.GetC1ControlChar (']')); - Assert.Equal ("PM", EscSeqUtils.GetC1ControlChar ('^')); - Assert.Equal ("APC", EscSeqUtils.GetC1ControlChar ('_')); - Assert.Equal ("", EscSeqUtils.GetC1ControlChar ('\0')); + Assert.Equal ("IND", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('D')); + Assert.Equal ("NEL", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('E')); + Assert.Equal ("HTS", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('H')); + Assert.Equal ("RI", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('M')); + Assert.Equal ("SS2", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('N')); + Assert.Equal ("SS3", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('O')); + Assert.Equal ("DCS", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('P')); + Assert.Equal ("SPA", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('V')); + Assert.Equal ("EPA", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('W')); + Assert.Equal ("SOS", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('X')); + Assert.Equal ("DECID", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('Z')); + Assert.Equal ("CSI", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('[')); + Assert.Equal ("ST", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('\\')); + Assert.Equal ("OSC", AnsiEscapeSequenceRequestUtils.GetC1ControlChar (']')); + Assert.Equal ("PM", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('^')); + Assert.Equal ("APC", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('_')); + Assert.Equal ("", AnsiEscapeSequenceRequestUtils.GetC1ControlChar ('\0')); } [Fact] @@ -1175,51 +1175,51 @@ public void GetConsoleInputKey_ConsoleKeyInfo () { var cki = new ConsoleKeyInfo ('r', 0, false, false, false); var expectedCki = new ConsoleKeyInfo ('r', ConsoleKey.R, false, false, false); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, true, false, false); expectedCki = new ('r', ConsoleKey.R, true, false, false); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, false, true, false); expectedCki = new ('r', ConsoleKey.R, false, true, false); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, false, false, true); expectedCki = new ('r', ConsoleKey.R, false, false, true); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, true, true, false); expectedCki = new ('r', ConsoleKey.R, true, true, false); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, false, true, true); expectedCki = new ('r', ConsoleKey.R, false, true, true); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('r', 0, true, true, true); expectedCki = new ('r', ConsoleKey.R, true, true, true); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('\u0012', 0, false, false, false); expectedCki = new ('\u0012', ConsoleKey.R, false, false, true); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('\0', (ConsoleKey)64, false, false, true); expectedCki = new ('\0', ConsoleKey.Spacebar, false, false, true); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('\r', 0, false, false, false); expectedCki = new ('\r', ConsoleKey.Enter, false, false, false); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('\u007f', 0, false, false, false); expectedCki = new ('\u007f', ConsoleKey.Backspace, false, false, false); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); cki = new ('R', 0, false, false, false); expectedCki = new ('R', ConsoleKey.R, true, false, false); - Assert.Equal (expectedCki, EscSeqUtils.MapConsoleKeyInfo (cki)); + Assert.Equal (expectedCki, AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (cki)); } [Fact] @@ -1227,69 +1227,69 @@ public void GetConsoleKey_Tests () { ConsoleModifiers mod = 0; char keyChar = '\0'; - Assert.Equal (ConsoleKey.UpArrow, EscSeqUtils.GetConsoleKey ('A', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.DownArrow, EscSeqUtils.GetConsoleKey ('B', "", ref mod, ref keyChar)); - Assert.Equal (_key = ConsoleKey.RightArrow, EscSeqUtils.GetConsoleKey ('C', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.LeftArrow, EscSeqUtils.GetConsoleKey ('D', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.End, EscSeqUtils.GetConsoleKey ('F', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Home, EscSeqUtils.GetConsoleKey ('H', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F1, EscSeqUtils.GetConsoleKey ('P', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F2, EscSeqUtils.GetConsoleKey ('Q', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F3, EscSeqUtils.GetConsoleKey ('R', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F4, EscSeqUtils.GetConsoleKey ('S', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Tab, EscSeqUtils.GetConsoleKey ('Z', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.UpArrow, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('A', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.DownArrow, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('B', "", ref mod, ref keyChar)); + Assert.Equal (_key = ConsoleKey.RightArrow, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('C', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.LeftArrow, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('D', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.End, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('F', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Home, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('H', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F1, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('P', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F2, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('Q', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F3, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('R', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F4, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('S', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Tab, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('Z', "", ref mod, ref keyChar)); Assert.Equal (ConsoleModifiers.Shift, mod); - Assert.Equal (0, (int)EscSeqUtils.GetConsoleKey ('\0', "", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Insert, EscSeqUtils.GetConsoleKey ('~', "2", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Delete, EscSeqUtils.GetConsoleKey ('~', "3", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.PageUp, EscSeqUtils.GetConsoleKey ('~', "5", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.PageDown, EscSeqUtils.GetConsoleKey ('~', "6", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F5, EscSeqUtils.GetConsoleKey ('~', "15", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F6, EscSeqUtils.GetConsoleKey ('~', "17", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F7, EscSeqUtils.GetConsoleKey ('~', "18", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F8, EscSeqUtils.GetConsoleKey ('~', "19", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F9, EscSeqUtils.GetConsoleKey ('~', "20", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F10, EscSeqUtils.GetConsoleKey ('~', "21", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F11, EscSeqUtils.GetConsoleKey ('~', "23", ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.F12, EscSeqUtils.GetConsoleKey ('~', "24", ref mod, ref keyChar)); - Assert.Equal (0, (int)EscSeqUtils.GetConsoleKey ('~', "", ref mod, ref keyChar)); + Assert.Equal (0, (int)AnsiEscapeSequenceRequestUtils.GetConsoleKey ('\0', "", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Insert, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "2", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Delete, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "3", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.PageUp, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "5", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.PageDown, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "6", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F5, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "15", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F6, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "17", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F7, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "18", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F8, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "19", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F9, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "20", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F10, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "21", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F11, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "23", ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.F12, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "24", ref mod, ref keyChar)); + Assert.Equal (0, (int)AnsiEscapeSequenceRequestUtils.GetConsoleKey ('~', "", ref mod, ref keyChar)); // These terminators are used by macOS on a numeric keypad without keys modifiers - Assert.Equal (ConsoleKey.Add, EscSeqUtils.GetConsoleKey ('l', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Subtract, EscSeqUtils.GetConsoleKey ('m', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Insert, EscSeqUtils.GetConsoleKey ('p', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.End, EscSeqUtils.GetConsoleKey ('q', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.DownArrow, EscSeqUtils.GetConsoleKey ('r', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.PageDown, EscSeqUtils.GetConsoleKey ('s', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.LeftArrow, EscSeqUtils.GetConsoleKey ('t', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Clear, EscSeqUtils.GetConsoleKey ('u', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.RightArrow, EscSeqUtils.GetConsoleKey ('v', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.Home, EscSeqUtils.GetConsoleKey ('w', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.UpArrow, EscSeqUtils.GetConsoleKey ('x', null, ref mod, ref keyChar)); - Assert.Equal (ConsoleKey.PageUp, EscSeqUtils.GetConsoleKey ('y', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Add, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('l', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Subtract, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('m', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Insert, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('p', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.End, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('q', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.DownArrow, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('r', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.PageDown, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('s', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.LeftArrow, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('t', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Clear, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('u', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.RightArrow, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('v', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.Home, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('w', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.UpArrow, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('x', null, ref mod, ref keyChar)); + Assert.Equal (ConsoleKey.PageUp, AnsiEscapeSequenceRequestUtils.GetConsoleKey ('y', null, ref mod, ref keyChar)); } [Fact] public void GetConsoleModifiers_Tests () { - Assert.Equal (ConsoleModifiers.Shift, EscSeqUtils.GetConsoleModifiers ("2")); - Assert.Equal (ConsoleModifiers.Alt, EscSeqUtils.GetConsoleModifiers ("3")); - Assert.Equal (ConsoleModifiers.Shift | ConsoleModifiers.Alt, EscSeqUtils.GetConsoleModifiers ("4")); - Assert.Equal (ConsoleModifiers.Control, EscSeqUtils.GetConsoleModifiers ("5")); - Assert.Equal (ConsoleModifiers.Shift | ConsoleModifiers.Control, EscSeqUtils.GetConsoleModifiers ("6")); - Assert.Equal (ConsoleModifiers.Alt | ConsoleModifiers.Control, EscSeqUtils.GetConsoleModifiers ("7")); + Assert.Equal (ConsoleModifiers.Shift, AnsiEscapeSequenceRequestUtils.GetConsoleModifiers ("2")); + Assert.Equal (ConsoleModifiers.Alt, AnsiEscapeSequenceRequestUtils.GetConsoleModifiers ("3")); + Assert.Equal (ConsoleModifiers.Shift | ConsoleModifiers.Alt, AnsiEscapeSequenceRequestUtils.GetConsoleModifiers ("4")); + Assert.Equal (ConsoleModifiers.Control, AnsiEscapeSequenceRequestUtils.GetConsoleModifiers ("5")); + Assert.Equal (ConsoleModifiers.Shift | ConsoleModifiers.Control, AnsiEscapeSequenceRequestUtils.GetConsoleModifiers ("6")); + Assert.Equal (ConsoleModifiers.Alt | ConsoleModifiers.Control, AnsiEscapeSequenceRequestUtils.GetConsoleModifiers ("7")); Assert.Equal ( ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control, - EscSeqUtils.GetConsoleModifiers ("8") + AnsiEscapeSequenceRequestUtils.GetConsoleModifiers ("8") ); - Assert.Equal (0, (int)EscSeqUtils.GetConsoleModifiers ("")); + Assert.Equal (0, (int)AnsiEscapeSequenceRequestUtils.GetConsoleModifiers ("")); } [Fact] public void GetEscapeResult_Multiple_Tests () { char [] kChars = ['\u001b', '[', '5', ';', '1', '0', 'r']; - (_c1Control, _code, _values, _terminating) = EscSeqUtils.GetEscapeResult (kChars); + (_c1Control, _code, _values, _terminating) = AnsiEscapeSequenceRequestUtils.GetEscapeResult (kChars); Assert.Equal ("CSI", _c1Control); Assert.Null (_code); Assert.Equal (2, _values.Length); @@ -1307,7 +1307,7 @@ public void GetEscapeResult_Multiple_Tests () [InlineData (['A'])] public void GetEscapeResult_Single_Tests (params char [] kChars) { - (_c1Control, _code, _values, _terminating) = EscSeqUtils.GetEscapeResult (kChars); + (_c1Control, _code, _values, _terminating) = AnsiEscapeSequenceRequestUtils.GetEscapeResult (kChars); if (kChars [0] == '\u001B') { @@ -1337,7 +1337,7 @@ public void GetKeyCharArray_Tests () new ('r', 0, false, false, false) }; - Assert.Equal (new [] { '\u001b', '[', '5', ';', '1', '0', 'r' }, EscSeqUtils.GetKeyCharArray (cki)); + Assert.Equal (new [] { '\u001b', '[', '5', ';', '1', '0', 'r' }, AnsiEscapeSequenceRequestUtils.GetKeyCharArray (cki)); } [Fact] @@ -1356,7 +1356,7 @@ public void GetMouse_Tests () new ('3', 0, false, false, false), new ('M', 0, false, false, false) }; - EscSeqUtils.GetMouse (cki, out List mouseFlags, out Point pos, ProcessContinuousButtonPressed); + AnsiEscapeSequenceRequestUtils.GetMouse (cki, out List mouseFlags, out Point pos, ProcessContinuousButtonPressed); Assert.Equal (new () { MouseFlags.Button1Pressed }, mouseFlags); Assert.Equal (new (1, 2), pos); @@ -1372,7 +1372,7 @@ public void GetMouse_Tests () new ('3', 0, false, false, false), new ('m', 0, false, false, false) }; - EscSeqUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); + AnsiEscapeSequenceRequestUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); Assert.Equal (2, mouseFlags.Count); Assert.Equal ( @@ -1393,7 +1393,7 @@ public void GetMouse_Tests () new ('3', 0, false, false, false), new ('M', 0, false, false, false) }; - EscSeqUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); + AnsiEscapeSequenceRequestUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); Assert.Equal (new () { MouseFlags.Button1DoubleClicked }, mouseFlags); Assert.Equal (new (1, 2), pos); @@ -1409,7 +1409,7 @@ public void GetMouse_Tests () new ('3', 0, false, false, false), new ('M', 0, false, false, false) }; - EscSeqUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); + AnsiEscapeSequenceRequestUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); Assert.Equal (new () { MouseFlags.Button1TripleClicked }, mouseFlags); Assert.Equal (new (1, 2), pos); @@ -1425,7 +1425,7 @@ public void GetMouse_Tests () new ('3', 0, false, false, false), new ('m', 0, false, false, false) }; - EscSeqUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); + AnsiEscapeSequenceRequestUtils.GetMouse (cki, out mouseFlags, out pos, ProcessContinuousButtonPressed); Assert.Equal (new () { MouseFlags.Button1Released }, mouseFlags); Assert.Equal (new (1, 2), pos); } @@ -1435,7 +1435,7 @@ public void ResizeArray_ConsoleKeyInfo () { ConsoleKeyInfo [] expectedCkInfos = null; var cki = new ConsoleKeyInfo ('\u001b', ConsoleKey.Escape, false, false, false); - expectedCkInfos = EscSeqUtils.ResizeArray (cki, expectedCkInfos); + expectedCkInfos = AnsiEscapeSequenceRequestUtils.ResizeArray (cki, expectedCkInfos); Assert.Single (expectedCkInfos); Assert.Equal (cki, expectedCkInfos [0]); } @@ -1494,7 +1494,7 @@ public void ResizeArray_ConsoleKeyInfo () [InlineData ("\r[<35;50;1m[<35;49;1m[<35;47;1m[<35;46;1m[<35;45;2m[<35;44;2m[<35;43;3m[<35;42;3m[<35;41;4m[<35;40;5m[<35;39;6m[<35;49;1m[<35;48;2m[<0;33;6M[<0;33;6mOC_", "_")] public void SplitEscapeRawString_Multiple_Tests (string rawData, string expectedLast) { - List splitList = EscSeqUtils.SplitEscapeRawString (rawData); + List splitList = AnsiEscapeSequenceRequestUtils.SplitEscapeRawString (rawData); Assert.Equal (18, splitList.Count); Assert.Equal ("\r", splitList [0]); Assert.Equal ("\u001b[<35;50;1m", splitList [1]); @@ -1525,7 +1525,7 @@ public void SplitEscapeRawString_Multiple_Tests (string rawData, string expected [InlineData ("A")] public void SplitEscapeRawString_Single_Tests (string rawData) { - List splitList = EscSeqUtils.SplitEscapeRawString (rawData); + List splitList = AnsiEscapeSequenceRequestUtils.SplitEscapeRawString (rawData); Assert.Single (splitList); Assert.Equal (rawData, splitList [0]); } @@ -1541,23 +1541,23 @@ public void SplitEscapeRawString_Single_Tests (string rawData) [InlineData ("0;20t", "\u001b[8;1", 3, "\u001b[80;20t;1")] public void InsertArray_Tests (string toInsert, string current, int? index, string expected) { - ConsoleKeyInfo [] toIns = EscSeqUtils.ToConsoleKeyInfoArray (toInsert); - ConsoleKeyInfo [] cki = EscSeqUtils.ToConsoleKeyInfoArray (current); - ConsoleKeyInfo [] result = EscSeqUtils.ToConsoleKeyInfoArray (expected); + ConsoleKeyInfo [] toIns = AnsiEscapeSequenceRequestUtils.ToConsoleKeyInfoArray (toInsert); + ConsoleKeyInfo [] cki = AnsiEscapeSequenceRequestUtils.ToConsoleKeyInfoArray (current); + ConsoleKeyInfo [] result = AnsiEscapeSequenceRequestUtils.ToConsoleKeyInfoArray (expected); if (index is null) { - Assert.Equal (result, EscSeqUtils.InsertArray (toIns, cki)); + Assert.Equal (result, AnsiEscapeSequenceRequestUtils.InsertArray (toIns, cki)); } else { - Assert.Equal (result, EscSeqUtils.InsertArray (toIns, cki, (int)index)); + Assert.Equal (result, AnsiEscapeSequenceRequestUtils.InsertArray (toIns, cki, (int)index)); } } private void ClearAll () { - _escSeqReqProc = default (EscSeqRequests); + _escSeqReqProc = default (AnsiEscapeSequenceRequests); _newConsoleKeyInfo = default (ConsoleKeyInfo); _key = default (ConsoleKey); _cki = default (ConsoleKeyInfo []); diff --git a/UnitTests/Input/EscSeqReqTests.cs b/UnitTests/Input/AnsiEscapeSequenceRequestsTests.cs similarity index 82% rename from UnitTests/Input/EscSeqReqTests.cs rename to UnitTests/Input/AnsiEscapeSequenceRequestsTests.cs index 9f6921796f..0184ab1229 100644 --- a/UnitTests/Input/EscSeqReqTests.cs +++ b/UnitTests/Input/AnsiEscapeSequenceRequestsTests.cs @@ -1,11 +1,11 @@ namespace Terminal.Gui.InputTests; -public class EscSeqReqTests +public class AnsiEscapeSequenceRequestsTests { [Fact] public void Add_Tests () { - var escSeqReq = new EscSeqRequests (); + var escSeqReq = new AnsiEscapeSequenceRequests (); escSeqReq.Add (new () { Request = "", Terminator = "t" }); Assert.Single (escSeqReq.Statuses); Assert.Equal ("t", escSeqReq.Statuses.ToArray () [^1].AnsiRequest.Terminator); @@ -28,7 +28,7 @@ public void Add_Tests () [Fact] public void Constructor_Defaults () { - var escSeqReq = new EscSeqRequests (); + var escSeqReq = new AnsiEscapeSequenceRequests (); Assert.NotNull (escSeqReq.Statuses); Assert.Empty (escSeqReq.Statuses); } @@ -36,9 +36,9 @@ public void Constructor_Defaults () [Fact] public void Remove_Tests () { - var escSeqReq = new EscSeqRequests (); + var escSeqReq = new AnsiEscapeSequenceRequests (); escSeqReq.Add (new () { Request = "", Terminator = "t" }); - escSeqReq.HasResponse ("t", out EscSeqReqStatus seqReqStatus); + escSeqReq.HasResponse ("t", out AnsiEscapeSequenceRequestStatus seqReqStatus); escSeqReq.Remove (seqReqStatus); Assert.Empty (escSeqReq.Statuses); @@ -57,8 +57,8 @@ public void Remove_Tests () [Fact] public void Requested_Tests () { - var escSeqReq = new EscSeqRequests (); - Assert.False (escSeqReq.HasResponse ("t", out EscSeqReqStatus seqReqStatus)); + var escSeqReq = new AnsiEscapeSequenceRequests (); + Assert.False (escSeqReq.HasResponse ("t", out AnsiEscapeSequenceRequestStatus seqReqStatus)); Assert.Null (seqReqStatus); escSeqReq.Add (new () { Request = "", Terminator = "t" }); From dba089fda01dc0bc0ff42daa1a37208981e716c7 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 00:42:22 +0000 Subject: [PATCH 82/89] Change category. --- UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index af8b0d8688..e7485da62e 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -6,7 +6,7 @@ namespace UICatalog.Scenarios; [ScenarioMetadata ("AnsiEscapeSequenceRequest", "Ansi Escape Sequence Request")] -[ScenarioCategory ("Ansi Escape Sequence")] +[ScenarioCategory ("Tests")] public sealed class AnsiEscapeSequenceRequests : Scenario { private GraphView _graphView; From 5efba6a5bc9e05679f5cc7b1f734cf9a1a6ed3e7 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 00:44:02 +0000 Subject: [PATCH 83/89] Code cleanup. --- .../Scenarios/AnsiEscapeSequenceRequests.cs | 283 +++++++++--------- 1 file changed, 141 insertions(+), 142 deletions(-) diff --git a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs index e7485da62e..6fbc445c46 100644 --- a/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs +++ b/UICatalog/Scenarios/AnsiEscapeSequenceRequests.cs @@ -9,15 +9,14 @@ namespace UICatalog.Scenarios; [ScenarioCategory ("Tests")] public sealed class AnsiEscapeSequenceRequests : Scenario { - private GraphView _graphView; - - private ScatterSeries _sentSeries; - private ScatterSeries _answeredSeries; - private readonly List _sends = new (); private readonly object _lockAnswers = new (); private readonly Dictionary _answers = new (); + private GraphView _graphView; + + private ScatterSeries _sentSeries; + private ScatterSeries _answeredSeries; private Label _lblSummary; public override void Main () @@ -60,6 +59,120 @@ public override void Main () Application.Shutdown (); } + private View BuildBulkTab () + { + var w = new View + { + Width = Dim.Fill (), + Height = Dim.Fill (), + CanFocus = true + }; + + var lbl = new Label + { + Text = + "_This scenario tests Ansi request/response processing. Use the TextView to ensure regular user interaction continues as normal during sends. Responses are in red, queued messages are in green.", + Height = 2, + Width = Dim.Fill () + }; + + Application.AddTimeout ( + TimeSpan.FromMilliseconds (1000), + () => + { + lock (_lockAnswers) + { + UpdateGraph (); + + UpdateResponses (); + } + + return true; + }); + + var tv = new TextView + { + Y = Pos.Bottom (lbl), + Width = Dim.Percent (50), + Height = Dim.Fill () + }; + + var lblDar = new Label + { + Y = Pos.Bottom (lbl), + X = Pos.Right (tv) + 1, + Text = "_DAR per second: " + }; + + var cbDar = new NumericUpDown + { + X = Pos.Right (lblDar), + Y = Pos.Bottom (lbl), + Value = 0 + }; + + cbDar.ValueChanging += (s, e) => + { + if (e.NewValue < 0 || e.NewValue > 20) + { + e.Cancel = true; + } + }; + w.Add (cbDar); + + int lastSendTime = Environment.TickCount; + var lockObj = new object (); + + Application.AddTimeout ( + TimeSpan.FromMilliseconds (50), + () => + { + lock (lockObj) + { + if (cbDar.Value > 0) + { + int interval = 1000 / cbDar.Value; // Calculate the desired interval in milliseconds + int currentTime = Environment.TickCount; // Current system time in milliseconds + + // Check if the time elapsed since the last send is greater than the interval + if (currentTime - lastSendTime >= interval) + { + SendDar (); // Send the request + lastSendTime = currentTime; // Update the last send time + } + } + } + + return true; + }); + + _graphView = new () + { + Y = Pos.Bottom (cbDar), + X = Pos.Right (tv), + Width = Dim.Fill (), + Height = Dim.Fill (1) + }; + + _lblSummary = new () + { + Y = Pos.Bottom (_graphView), + X = Pos.Right (tv), + Width = Dim.Fill () + }; + + SetupGraph (); + + w.Add (lbl); + w.Add (lblDar); + w.Add (cbDar); + w.Add (tv); + w.Add (_graphView); + w.Add (_lblSummary); + + return w; + } + private View BuildSingleTab () { var w = new View @@ -195,126 +308,6 @@ out AnsiEscapeSequenceResponse ansiEscapeSequenceResponse return w; } - private View BuildBulkTab () - { - var w = new View - { - Width = Dim.Fill (), - Height = Dim.Fill (), - CanFocus = true - }; - - var lbl = new Label - { - Text = - "_This scenario tests Ansi request/response processing. Use the TextView to ensure regular user interaction continues as normal during sends. Responses are in red, queued messages are in green.", - Height = 2, - Width = Dim.Fill () - }; - - Application.AddTimeout ( - TimeSpan.FromMilliseconds (1000), - () => - { - lock (_lockAnswers) - { - UpdateGraph (); - - UpdateResponses (); - } - - return true; - }); - - var tv = new TextView - { - Y = Pos.Bottom (lbl), - Width = Dim.Percent (50), - Height = Dim.Fill () - }; - - var lblDar = new Label - { - Y = Pos.Bottom (lbl), - X = Pos.Right (tv) + 1, - Text = "_DAR per second: " - }; - - var cbDar = new NumericUpDown - { - X = Pos.Right (lblDar), - Y = Pos.Bottom (lbl), - Value = 0 - }; - - cbDar.ValueChanging += (s, e) => - { - if (e.NewValue < 0 || e.NewValue > 20) - { - e.Cancel = true; - } - }; - w.Add (cbDar); - - int lastSendTime = Environment.TickCount; - var lockObj = new object (); - - Application.AddTimeout ( - TimeSpan.FromMilliseconds (50), - () => - { - lock (lockObj) - { - if (cbDar.Value > 0) - { - int interval = 1000 / cbDar.Value; // Calculate the desired interval in milliseconds - int currentTime = Environment.TickCount; // Current system time in milliseconds - - // Check if the time elapsed since the last send is greater than the interval - if (currentTime - lastSendTime >= interval) - { - SendDar (); // Send the request - lastSendTime = currentTime; // Update the last send time - } - } - } - - return true; - }); - - _graphView = new () - { - Y = Pos.Bottom (cbDar), - X = Pos.Right (tv), - Width = Dim.Fill (), - Height = Dim.Fill (1) - }; - - _lblSummary = new () - { - Y = Pos.Bottom (_graphView), - X = Pos.Right (tv), - Width = Dim.Fill () - }; - - SetupGraph (); - - w.Add (lbl); - w.Add (lblDar); - w.Add (cbDar); - w.Add (tv); - w.Add (_graphView); - w.Add (_lblSummary); - - return w; - } - - private void UpdateResponses () - { - _lblSummary.Text = GetSummary (); - _lblSummary.SetNeedsDisplay (); - } - private string GetSummary () { if (_answers.Count == 0) @@ -330,6 +323,21 @@ private string GetSummary () return $"Last:{last} U:{unique} T:{total}"; } + private void HandleResponse (string response) + { + lock (_lockAnswers) + { + _answers.Add (DateTime.Now, response); + } + } + + private void SendDar () + { + _sends.Add (DateTime.Now); + string result = Application.Driver.WriteAnsiRequest (AnsiEscapeSequenceRequestUtils.CSI_SendDeviceAttributes); + HandleResponse (result); + } + private void SetupGraph () { _graphView.Series.Add (_sentSeries = new ()); @@ -348,6 +356,8 @@ private void SetupGraph () _graphView.GraphColor = new Attribute (Color.Green, Color.Black); } + private int ToSeconds (DateTime t) { return (int)(DateTime.Now - t).TotalSeconds; } + private void UpdateGraph () { _sentSeries.Points = _sends @@ -356,9 +366,9 @@ private void UpdateGraph () .ToList (); _answeredSeries.Points = _answers.Keys - .GroupBy (ToSeconds) - .Select (g => new PointF (g.Key, g.Count ())) - .ToList (); + .GroupBy (ToSeconds) + .Select (g => new PointF (g.Key, g.Count ())) + .ToList (); // _graphView.ScrollOffset = new PointF(,0); if (_sentSeries.Points.Count > 0 || _answeredSeries.Points.Count > 0) @@ -367,20 +377,9 @@ private void UpdateGraph () } } - private int ToSeconds (DateTime t) { return (int)(DateTime.Now - t).TotalSeconds; } - - private void SendDar () - { - _sends.Add (DateTime.Now); - string result = Application.Driver.WriteAnsiRequest (AnsiEscapeSequenceRequestUtils.CSI_SendDeviceAttributes); - HandleResponse (result); - } - - private void HandleResponse (string response) + private void UpdateResponses () { - lock (_lockAnswers) - { - _answers.Add (DateTime.Now, response); - } + _lblSummary.Text = GetSummary (); + _lblSummary.SetNeedsDisplay (); } } From b7b9e015026bf2b067f0fc0775628a305c009920 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 01:11:52 +0000 Subject: [PATCH 84/89] Fix error with Key.Space using lowercase letters. --- .../AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs index 844112d650..75a5937c64 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs @@ -1140,10 +1140,11 @@ public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) if (isConsoleKey) { key = (ConsoleKey)ck; + keyChar = (char)ck; } newConsoleKeyInfo = new ( - consoleKeyInfo.KeyChar, + keyChar, key, GetShiftMod (consoleKeyInfo.Modifiers), (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, From a64f68ca7f353770b2d0ccef1800576a85ccfc9c Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 02:00:44 +0000 Subject: [PATCH 85/89] Moving MapKey method to the AnsiEscapeSequenceRequestUtils class. --- .../AnsiEscapeSequenceRequestUtils.cs | 104 +++++++++++++++++- .../CursesDriver/CursesDriver.cs | 2 +- .../ConsoleDrivers/NetDriver/NetDriver.cs | 102 +---------------- 3 files changed, 104 insertions(+), 104 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs index 75a5937c64..0cef28e803 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs @@ -1,5 +1,6 @@ #nullable enable using Terminal.Gui.ConsoleDrivers; +using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping; namespace Terminal.Gui; @@ -1135,12 +1136,11 @@ public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) break; default: - uint ck = ConsoleKeyMapping.MapKeyCodeToConsoleKey ((KeyCode)consoleKeyInfo.KeyChar, out bool isConsoleKey); + uint ck = MapKeyCodeToConsoleKey ((KeyCode)consoleKeyInfo.KeyChar, out bool isConsoleKey); if (isConsoleKey) { key = (ConsoleKey)ck; - keyChar = (char)ck; } newConsoleKeyInfo = new ( @@ -1363,6 +1363,106 @@ private static MouseFlags GetButtonTripleClicked (MouseFlags mouseFlag) return mf; } + internal static KeyCode MapKey (ConsoleKeyInfo keyInfo) + { + switch (keyInfo.Key) + { + case ConsoleKey.OemPeriod: + case ConsoleKey.OemComma: + case ConsoleKey.OemPlus: + case ConsoleKey.OemMinus: + case ConsoleKey.Packet: + case ConsoleKey.Oem1: + case ConsoleKey.Oem2: + case ConsoleKey.Oem3: + case ConsoleKey.Oem4: + case ConsoleKey.Oem5: + case ConsoleKey.Oem6: + case ConsoleKey.Oem7: + case ConsoleKey.Oem8: + case ConsoleKey.Oem102: + if (keyInfo.KeyChar == 0) + { + // If the keyChar is 0, keyInfo.Key value is not a printable character. + + return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key); + } + + if (keyInfo.Modifiers != ConsoleModifiers.Shift) + { + // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar + return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar); + } + + // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç") + // and passing on Shift would be redundant. + return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar); + } + + // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC + if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key)) + { + if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I) + { + return KeyCode.Tab; + } + + return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key); + } + + // Handle control keys (e.g. CursorUp) + if (keyInfo.Key != ConsoleKey.None + && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint)) + { + return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint)); + } + + if ((ConsoleKey)keyInfo.KeyChar is >= ConsoleKey.A and <= ConsoleKey.Z) + { + // Shifted + keyInfo = new ( + keyInfo.KeyChar, + (ConsoleKey)keyInfo.KeyChar, + true, + keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt), + keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)); + } + + if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z) + { + // Unshifted + keyInfo = new ( + keyInfo.KeyChar, + (ConsoleKey)(keyInfo.KeyChar - 32), + false, + keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt), + keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)); + } + + if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z) + { + if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) + || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) + { + // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos + return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key); + } + + if (keyInfo.Modifiers == ConsoleModifiers.Shift) + { + // If ShiftMask is on add the ShiftMask + if (char.IsUpper (keyInfo.KeyChar)) + { + return (KeyCode)keyInfo.Key | KeyCode.ShiftMask; + } + } + + return (KeyCode)keyInfo.Key; + } + + return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar); + } + private static async Task ProcessButtonClickedAsync () { await Task.Delay (300); diff --git a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs index 80b74edf69..866bfa496c 100644 --- a/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs @@ -783,7 +783,7 @@ internal void ProcessInput (UnixMainLoop.PollData inputEvent) case UnixMainLoop.EventType.Key: ConsoleKeyInfo consoleKeyInfo = inputEvent.KeyEvent; - KeyCode map = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (consoleKeyInfo); + KeyCode map = AnsiEscapeSequenceRequestUtils.MapKey (consoleKeyInfo); if (map == KeyCode.Null) { diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs index d650c91f04..69fb782538 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs @@ -315,7 +315,7 @@ private void ProcessInput (InputResult inputEvent) //Debug.WriteLine ($"event: {inputEvent}"); - KeyCode map = MapKey (consoleKeyInfo); + KeyCode map = AnsiEscapeSequenceRequestUtils.MapKey (consoleKeyInfo); if (map == KeyCode.Null) { @@ -722,106 +722,6 @@ private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyI return new (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control); } - private KeyCode MapKey (ConsoleKeyInfo keyInfo) - { - switch (keyInfo.Key) - { - case ConsoleKey.OemPeriod: - case ConsoleKey.OemComma: - case ConsoleKey.OemPlus: - case ConsoleKey.OemMinus: - case ConsoleKey.Packet: - case ConsoleKey.Oem1: - case ConsoleKey.Oem2: - case ConsoleKey.Oem3: - case ConsoleKey.Oem4: - case ConsoleKey.Oem5: - case ConsoleKey.Oem6: - case ConsoleKey.Oem7: - case ConsoleKey.Oem8: - case ConsoleKey.Oem102: - if (keyInfo.KeyChar == 0) - { - // If the keyChar is 0, keyInfo.Key value is not a printable character. - - return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key); - } - - if (keyInfo.Modifiers != ConsoleModifiers.Shift) - { - // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar - return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar); - } - - // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç") - // and passing on Shift would be redundant. - return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar); - } - - // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC - if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key)) - { - if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I) - { - return KeyCode.Tab; - } - - return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key); - } - - // Handle control keys (e.g. CursorUp) - if (keyInfo.Key != ConsoleKey.None - && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint)) - { - return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint)); - } - - if ((ConsoleKey)keyInfo.KeyChar is >= ConsoleKey.A and <= ConsoleKey.Z) - { - // Shifted - keyInfo = new ( - keyInfo.KeyChar, - (ConsoleKey)keyInfo.KeyChar, - true, - keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt), - keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)); - } - - if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z) - { - // Unshifted - keyInfo = new ( - keyInfo.KeyChar, - (ConsoleKey)(keyInfo.KeyChar - 32), - false, - keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt), - keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)); - } - - if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z) - { - if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) - || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control)) - { - // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos - return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key); - } - - if (keyInfo.Modifiers == ConsoleModifiers.Shift) - { - // If ShiftMask is on add the ShiftMask - if (char.IsUpper (keyInfo.KeyChar)) - { - return (KeyCode)keyInfo.Key | KeyCode.ShiftMask; - } - } - - return (KeyCode)keyInfo.Key; - } - - return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar); - } - #endregion Keyboard Handling #region Low-Level DotNet tuff From cc21bd461dcfe8f31bb2f6c63e07380b23753dc3 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 13:01:03 +0000 Subject: [PATCH 86/89] Fix a bug where a esc key was ignored. --- .../AnsiEscapeSequenceRequestUtils.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs index 0cef28e803..ca8533f77c 100644 --- a/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/AnsiEscapeSequence/AnsiEscapeSequenceRequestUtils.cs @@ -1078,7 +1078,18 @@ public static ConsoleKeyInfo MapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) break; case uint n when n is > 0 and <= KeyEsc: - if (consoleKeyInfo is { Key: 0, KeyChar: '\t' }) + if (consoleKeyInfo is { Key: 0, KeyChar: '\u001B' }) + { + key = ConsoleKey.Escape; + + newConsoleKeyInfo = new ( + consoleKeyInfo.KeyChar, + key, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0, + (consoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0); + } + else if (consoleKeyInfo is { Key: 0, KeyChar: '\t' }) { key = ConsoleKey.Tab; From 3e952df5f7b3341f31b3f862ead1712ea270f20a Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 13:04:11 +0000 Subject: [PATCH 87/89] Change to BlockingCollection, thanks to @tznind. --- .../ConsoleDrivers/NetDriver/NetDriver.cs | 12 +- .../ConsoleDrivers/NetDriver/NetEvents.cs | 234 +++++++----------- .../ConsoleDrivers/NetDriver/NetMainLoop.cs | 70 ++---- 3 files changed, 119 insertions(+), 197 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs index 69fb782538..0422f548f9 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs @@ -754,17 +754,7 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) _mainLoopDriver._netEvents._forceRead = true; } - if (!_ansiResponseTokenSource.IsCancellationRequested) - { - _mainLoopDriver._netEvents._waitForStart.Set (); - - if (!_mainLoopDriver._waitForProbe.IsSet) - { - _mainLoopDriver._waitForProbe.Set (); - } - - _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); - } + _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token); } catch (OperationCanceledException) { diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs index 3e5414241b..9976c01369 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs @@ -6,13 +6,8 @@ namespace Terminal.Gui; internal class NetEvents : IDisposable { - private readonly ManualResetEventSlim _inputReady = new (false); private CancellationTokenSource _inputReadyCancellationTokenSource; - internal readonly ManualResetEventSlim _waitForStart = new (false); - - //CancellationTokenSource _waitForStartCancellationTokenSource; - private readonly ManualResetEventSlim _winChange = new (false); - private readonly ConcurrentQueue _inputQueue = new (); + private readonly BlockingCollection _inputQueue = new (new ConcurrentQueue ()); private readonly ConsoleDriver _consoleDriver; private ConsoleKeyInfo [] _cki; private bool _isEscSeq; @@ -33,41 +28,20 @@ public NetEvents (ConsoleDriver consoleDriver) public InputResult? DequeueInput () { - while (_inputReadyCancellationTokenSource != null - && !_inputReadyCancellationTokenSource.Token.IsCancellationRequested) + while (_inputReadyCancellationTokenSource is { }) { - _waitForStart.Set (); - _winChange.Set (); - try { - if (!_inputReadyCancellationTokenSource.Token.IsCancellationRequested) - { - if (_inputQueue.Count == 0) - { - _inputReady.Wait (_inputReadyCancellationTokenSource.Token); - } - } + return _inputQueue.Take (_inputReadyCancellationTokenSource.Token); } catch (OperationCanceledException) { return null; } - finally - { - _inputReady.Reset (); - } #if PROCESS_REQUEST _neededProcessRequest = false; #endif - if (_inputQueue.Count > 0) - { - if (_inputQueue.TryDequeue (out InputResult? result)) - { - return result; - } - } } return null; @@ -130,129 +104,120 @@ private void ProcessInputQueue () { try { - if (!_forceRead) - { - _waitForStart.Wait (_inputReadyCancellationTokenSource.Token); - } - } - catch (OperationCanceledException) - { - return; - } - - _waitForStart.Reset (); - - if (_inputQueue.Count == 0 || _forceRead) - { - ConsoleKey key = 0; - ConsoleModifiers mod = 0; - ConsoleKeyInfo newConsoleKeyInfo = default; - - while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false }) + if (_inputQueue.Count == 0 || _forceRead) { - ConsoleKeyInfo consoleKeyInfo; - - try - { - consoleKeyInfo = ReadConsoleKeyInfo (_inputReadyCancellationTokenSource.Token); - } - catch (OperationCanceledException) - { - return; - } + ConsoleKey key = 0; + ConsoleModifiers mod = 0; + ConsoleKeyInfo newConsoleKeyInfo = default; - if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is { }) + while (_inputReadyCancellationTokenSource is { IsCancellationRequested: false }) { - AnsiEscapeSequenceRequestUtils.InsertArray (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos, _cki); - } + ConsoleKeyInfo consoleKeyInfo; - if ((consoleKeyInfo.KeyChar == (char)KeyCode.Esc && !_isEscSeq) - || (consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq)) - { - if (_cki is null && consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq) + try { - _cki = AnsiEscapeSequenceRequestUtils.ResizeArray ( - new ConsoleKeyInfo ( - (char)KeyCode.Esc, - 0, - false, - false, - false - ), - _cki - ); + consoleKeyInfo = ReadConsoleKeyInfo (_inputReadyCancellationTokenSource.Token); + } + catch (OperationCanceledException) + { + return; } - _isEscSeq = true; + if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is { }) + { + AnsiEscapeSequenceRequestUtils.InsertArray (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos, _cki); + } - if ((_cki is { } && _cki [^1].KeyChar != Key.Esc && consoleKeyInfo.KeyChar != Key.Esc && consoleKeyInfo.KeyChar <= Key.Space) - || (_cki is { } && _cki [^1].KeyChar != '\u001B' && consoleKeyInfo.KeyChar == 127) - || (_cki is { } && char.IsLetter (_cki [^1].KeyChar) && char.IsLower (consoleKeyInfo.KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar)) - || (_cki is { Length: > 2 } && char.IsLetter (_cki [^1].KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar))) + if ((consoleKeyInfo.KeyChar == (char)KeyCode.Esc && !_isEscSeq) + || (consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq)) { - ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); - _cki = null; - _isEscSeq = false; + if (_cki is null && consoleKeyInfo.KeyChar != (char)KeyCode.Esc && _isEscSeq) + { + _cki = AnsiEscapeSequenceRequestUtils.ResizeArray ( + new ( + (char)KeyCode.Esc, + 0, + false, + false, + false + ), + _cki + ); + } + + _isEscSeq = true; + + if ((_cki is { } && _cki [^1].KeyChar != Key.Esc && consoleKeyInfo.KeyChar != Key.Esc && consoleKeyInfo.KeyChar <= Key.Space) + || (_cki is { } && _cki [^1].KeyChar != '\u001B' && consoleKeyInfo.KeyChar == 127) + || (_cki is { } && char.IsLetter (_cki [^1].KeyChar) && char.IsLower (consoleKeyInfo.KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar)) + || (_cki is { Length: > 2 } && char.IsLetter (_cki [^1].KeyChar) && char.IsLetter (consoleKeyInfo.KeyChar))) + { + ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); + _cki = null; + _isEscSeq = false; + + ProcessMapConsoleKeyInfo (consoleKeyInfo); + } + else + { + newConsoleKeyInfo = consoleKeyInfo; + _cki = AnsiEscapeSequenceRequestUtils.ResizeArray (consoleKeyInfo, _cki); + + if (Console.KeyAvailable) + { + continue; + } - ProcessMapConsoleKeyInfo (consoleKeyInfo); + ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); + _cki = null; + _isEscSeq = false; + } + + break; } - else + + if (consoleKeyInfo.KeyChar == (char)KeyCode.Esc && _isEscSeq && _cki is { }) { - newConsoleKeyInfo = consoleKeyInfo; - _cki = AnsiEscapeSequenceRequestUtils.ResizeArray (consoleKeyInfo, _cki); + ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); + _cki = null; if (Console.KeyAvailable) { - continue; + _cki = AnsiEscapeSequenceRequestUtils.ResizeArray (consoleKeyInfo, _cki); + } + else + { + ProcessMapConsoleKeyInfo (consoleKeyInfo); } - ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); - _cki = null; - _isEscSeq = false; + break; } - break; - } - - if (consoleKeyInfo.KeyChar == (char)KeyCode.Esc && _isEscSeq && _cki is { }) - { - ProcessRequestResponse (ref newConsoleKeyInfo, ref key, _cki, ref mod); - _cki = null; + ProcessMapConsoleKeyInfo (consoleKeyInfo); - if (Console.KeyAvailable) - { - _cki = AnsiEscapeSequenceRequestUtils.ResizeArray (consoleKeyInfo, _cki); - } - else + if (_retries > 0) { - ProcessMapConsoleKeyInfo (consoleKeyInfo); + _retries = 0; } break; } - - ProcessMapConsoleKeyInfo (consoleKeyInfo); - - if (_retries > 0) - { - _retries = 0; - } - - break; } } - - _inputReady.Set (); + catch (OperationCanceledException) + { + return; + } } void ProcessMapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo) { - _inputQueue.Enqueue ( - new InputResult - { - EventType = EventType.Key, ConsoleKeyInfo = AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (consoleKeyInfo) - } - ); + _inputQueue.Add ( + new () + { + EventType = EventType.Key, ConsoleKeyInfo = AnsiEscapeSequenceRequestUtils.MapConsoleKeyInfo (consoleKeyInfo) + } + ); _isEscSeq = false; } } @@ -297,17 +262,12 @@ void RequestWindowSize (CancellationToken cancellationToken) { try { - _winChange.Wait (_inputReadyCancellationTokenSource.Token); - _winChange.Reset (); - RequestWindowSize (_inputReadyCancellationTokenSource.Token); } catch (OperationCanceledException) { return; } - - _inputReady.Set (); } } @@ -327,12 +287,12 @@ private bool EnqueueWindowSizeEvent (int winHeight, int winWidth, int buffHeight int w = Math.Max (winWidth, 0); int h = Math.Max (winHeight, 0); - _inputQueue.Enqueue ( - new InputResult - { - EventType = EventType.WindowSize, WindowSizeEvent = new WindowSizeEvent { Size = new (w, h) } - } - ); + _inputQueue.Add ( + new () + { + EventType = EventType.WindowSize, WindowSizeEvent = new () { Size = new (w, h) } + } + ); return true; } @@ -609,11 +569,9 @@ private void HandleMouseEvent (MouseButtonState buttonState, Point pos) { var mouseEvent = new MouseEvent { Position = pos, ButtonState = buttonState }; - _inputQueue.Enqueue ( - new InputResult { EventType = EventType.Mouse, MouseEvent = mouseEvent } - ); - - _inputReady.Set (); + _inputQueue.Add ( + new () { EventType = EventType.Mouse, MouseEvent = mouseEvent } + ); } public enum EventType @@ -726,7 +684,7 @@ private void HandleKeyboardEvent (ConsoleKeyInfo cki) { var inputResult = new InputResult { EventType = EventType.Key, ConsoleKeyInfo = cki }; - _inputQueue.Enqueue (inputResult); + _inputQueue.Add (inputResult); } public void Dispose () diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs index d876ef0cbb..6e68bf8d5b 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs @@ -16,8 +16,7 @@ internal class NetMainLoop : IMainLoopDriver private readonly ManualResetEventSlim _eventReady = new (false); private readonly CancellationTokenSource _inputHandlerTokenSource = new (); - private readonly ConcurrentQueue _resultQueue = new (); - internal readonly ManualResetEventSlim _waitForProbe = new (false); + private readonly BlockingCollection _resultQueue = new (new ConcurrentQueue ()); private readonly CancellationTokenSource _eventReadyTokenSource = new (); private MainLoop _mainLoop; @@ -27,12 +26,9 @@ internal class NetMainLoop : IMainLoopDriver /// public NetMainLoop (ConsoleDriver consoleDriver = null) { - if (consoleDriver is null) - { - throw new ArgumentNullException (nameof (consoleDriver)); - } + ArgumentNullException.ThrowIfNull (consoleDriver); - _netEvents = new NetEvents (consoleDriver); + _netEvents = new (consoleDriver); } void IMainLoopDriver.Setup (MainLoop mainLoop) @@ -51,9 +47,7 @@ void IMainLoopDriver.Setup (MainLoop mainLoop) bool IMainLoopDriver.EventsPending () { - _waitForProbe.Set (); - - if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) + if (_resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) { return true; } @@ -83,6 +77,7 @@ bool IMainLoopDriver.EventsPending () return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _); } + // If cancellation was requested then always return true return true; } @@ -91,11 +86,11 @@ void IMainLoopDriver.Iteration () while (_resultQueue.Count > 0) { // Always dequeue even if it's null and invoke if isn't null - if (_resultQueue.TryDequeue (out NetEvents.InputResult? dequeueResult)) + if (_resultQueue.TryTake (out NetEvents.InputResult dequeueResult)) { if (dequeueResult is { }) { - ProcessInput?.Invoke (dequeueResult.Value); + ProcessInput?.Invoke (dequeueResult); } } } @@ -110,8 +105,7 @@ void IMainLoopDriver.TearDown () _eventReady?.Dispose (); - _resultQueue?.Clear (); - _waitForProbe?.Dispose (); + _resultQueue?.Dispose(); _netEvents?.Dispose (); _netEvents = null; @@ -124,49 +118,29 @@ private void NetInputHandler () { try { - if (!_netEvents._forceRead && !_inputHandlerTokenSource.IsCancellationRequested) + if (_inputHandlerTokenSource.IsCancellationRequested) { - _waitForProbe.Wait (_inputHandlerTokenSource.Token); + return; } - } - catch (OperationCanceledException) - { - return; - } - finally - { - if (_waitForProbe.IsSet) - { - _waitForProbe.Reset (); - } - } - if (_inputHandlerTokenSource.IsCancellationRequested) - { - return; - } - - _inputHandlerTokenSource.Token.ThrowIfCancellationRequested (); + if (_resultQueue?.Count == 0 || _netEvents._forceRead) + { + NetEvents.InputResult? result = _netEvents.DequeueInput (); - if (_resultQueue.Count == 0) - { - _resultQueue.Enqueue (_netEvents.DequeueInput ()); - } + if (result.HasValue) + { + _resultQueue?.Add (result.Value); + } + } - try - { - while (_resultQueue.Count > 0 && _resultQueue.TryPeek (out NetEvents.InputResult? result) && result is null) + if (!_inputHandlerTokenSource.IsCancellationRequested && _resultQueue?.Count > 0) { - // Dequeue null values - _resultQueue.TryDequeue (out _); + _eventReady.Set (); } } - catch (InvalidOperationException) // Peek can raise an exception - { } - - if (_resultQueue.Count > 0) + catch (OperationCanceledException) { - _eventReady.Set (); + return; } } } From 44d59974606098575bf039642f2eabe28f6e5f37 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 14:46:27 +0000 Subject: [PATCH 88/89] Split more WindowDriver classes and #nullable enable. --- .../WindowsDriver/ClipboardImpl.cs | 179 +++++++ .../WindowsDriver/WindowsConsole.cs | 56 +- .../WindowsDriver/WindowsDriver.cs | 492 ++---------------- .../WindowsDriver/WindowsMainLoop.cs | 248 +++++++++ 4 files changed, 492 insertions(+), 483 deletions(-) create mode 100644 Terminal.Gui/ConsoleDrivers/WindowsDriver/ClipboardImpl.cs create mode 100644 Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsMainLoop.cs diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/ClipboardImpl.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/ClipboardImpl.cs new file mode 100644 index 0000000000..d38ffb4082 --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/ClipboardImpl.cs @@ -0,0 +1,179 @@ +#nullable enable +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace Terminal.Gui; + +internal class WindowsClipboard : ClipboardBase +{ + private const uint CF_UNICODE_TEXT = 13; + + public override bool IsSupported { get; } = CheckClipboardIsAvailable (); + + private static bool CheckClipboardIsAvailable () + { + // Attempt to open the clipboard + if (OpenClipboard (nint.Zero)) + { + // Clipboard is available + // Close the clipboard after use + CloseClipboard (); + + return true; + } + // Clipboard is not available + return false; + } + + protected override string GetClipboardDataImpl () + { + try + { + if (!OpenClipboard (nint.Zero)) + { + return string.Empty; + } + + nint handle = GetClipboardData (CF_UNICODE_TEXT); + + if (handle == nint.Zero) + { + return string.Empty; + } + + nint pointer = nint.Zero; + + try + { + pointer = GlobalLock (handle); + + if (pointer == nint.Zero) + { + return string.Empty; + } + + int size = GlobalSize (handle); + var buff = new byte [size]; + + Marshal.Copy (pointer, buff, 0, size); + + return Encoding.Unicode.GetString (buff).TrimEnd ('\0'); + } + finally + { + if (pointer != nint.Zero) + { + GlobalUnlock (handle); + } + } + } + finally + { + CloseClipboard (); + } + } + + protected override void SetClipboardDataImpl (string text) + { + OpenClipboard (); + + EmptyClipboard (); + nint hGlobal = default; + + try + { + int bytes = (text.Length + 1) * 2; + hGlobal = Marshal.AllocHGlobal (bytes); + + if (hGlobal == default (nint)) + { + ThrowWin32 (); + } + + nint target = GlobalLock (hGlobal); + + if (target == default (nint)) + { + ThrowWin32 (); + } + + try + { + Marshal.Copy (text.ToCharArray (), 0, target, text.Length); + } + finally + { + GlobalUnlock (target); + } + + if (SetClipboardData (CF_UNICODE_TEXT, hGlobal) == default (nint)) + { + ThrowWin32 (); + } + + hGlobal = default (nint); + } + finally + { + if (hGlobal != default (nint)) + { + Marshal.FreeHGlobal (hGlobal); + } + + CloseClipboard (); + } + } + + [DllImport ("user32.dll", SetLastError = true)] + [return: MarshalAs (UnmanagedType.Bool)] + private static extern bool CloseClipboard (); + + [DllImport ("user32.dll")] + private static extern bool EmptyClipboard (); + + [DllImport ("user32.dll", SetLastError = true)] + private static extern nint GetClipboardData (uint uFormat); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern nint GlobalLock (nint hMem); + + [DllImport ("kernel32.dll", SetLastError = true)] + private static extern int GlobalSize (nint handle); + + [DllImport ("kernel32.dll", SetLastError = true)] + [return: MarshalAs (UnmanagedType.Bool)] + private static extern bool GlobalUnlock (nint hMem); + + [DllImport ("User32.dll", SetLastError = true)] + [return: MarshalAs (UnmanagedType.Bool)] + private static extern bool IsClipboardFormatAvailable (uint format); + + private void OpenClipboard () + { + var num = 10; + + while (true) + { + if (OpenClipboard (default (nint))) + { + break; + } + + if (--num == 0) + { + ThrowWin32 (); + } + + Thread.Sleep (100); + } + } + + [DllImport ("user32.dll", SetLastError = true)] + [return: MarshalAs (UnmanagedType.Bool)] + private static extern bool OpenClipboard (nint hWndNewOwner); + + [DllImport ("user32.dll", SetLastError = true)] + private static extern nint SetClipboardData (uint uFormat, nint data); + + private void ThrowWin32 () { throw new Win32Exception (Marshal.GetLastWin32Error ()); } +} diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs index 430085a2aa..ff8d155b78 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsConsole.cs @@ -1,4 +1,4 @@ -// TODO: #nullable enable +#nullable enable using System.ComponentModel; using System.Runtime.InteropServices; using Terminal.Gui.ConsoleDrivers; @@ -7,7 +7,7 @@ namespace Terminal.Gui; internal class WindowsConsole { - internal WindowsMainLoop _mainLoop; + internal WindowsMainLoop? _mainLoop; public const int STD_OUTPUT_HANDLE = -11; public const int STD_INPUT_HANDLE = -10; @@ -34,7 +34,7 @@ public WindowsConsole () ConsoleMode = newConsoleMode; } - private CharInfo [] _originalStdOutChars; + private CharInfo []? _originalStdOutChars; public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord bufferSize, SmallRect window, bool force16Colors) { @@ -598,15 +598,15 @@ public struct InputRecord public readonly override string ToString () { - return EventType switch - { - EventType.Focus => FocusEvent.ToString (), - EventType.Key => KeyEvent.ToString (), - EventType.Menu => MenuEvent.ToString (), - EventType.Mouse => MouseEvent.ToString (), - EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (), - _ => "Unknown event type: " + EventType - }; + return (EventType switch + { + EventType.Focus => FocusEvent.ToString (), + EventType.Key => KeyEvent.ToString (), + EventType.Menu => MenuEvent.ToString (), + EventType.Mouse => MouseEvent.ToString (), + EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (), + _ => "Unknown event type: " + EventType + })!; } } @@ -866,7 +866,7 @@ nint screenBufferData internal static nint INVALID_HANDLE_VALUE = new (-1); [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool SetConsoleActiveScreenBuffer (nint Handle); + private static extern bool SetConsoleActiveScreenBuffer (nint handle); [DllImport ("kernel32.dll", SetLastError = true)] private static extern bool GetNumberOfConsoleInputEvents (nint handle, out uint lpcNumberOfEvents); @@ -896,9 +896,9 @@ internal void FlushConsoleInputBuffer () private int _retries; - public InputRecord [] ReadConsoleInput () + public InputRecord []? ReadConsoleInput () { - const int bufferSize = 1; + const int BUFFER_SIZE = 1; InputRecord inputRecord = default; uint numberEventsRead = 0; StringBuilder ansiSequence = new StringBuilder (); @@ -910,13 +910,13 @@ public InputRecord [] ReadConsoleInput () try { // Peek to check if there is any input available - if (PeekConsoleInput (_inputHandle, out _, bufferSize, out uint eventsRead) && eventsRead > 0) + if (PeekConsoleInput (_inputHandle, out _, BUFFER_SIZE, out uint eventsRead) && eventsRead > 0) { // Read the input since it is available ReadConsoleInput ( _inputHandle, out inputRecord, - bufferSize, + BUFFER_SIZE, out numberEventsRead); if (inputRecord.EventType == EventType.Key) @@ -931,7 +931,7 @@ public InputRecord [] ReadConsoleInput () if (inputChar == '\u001B') // Escape character { // Peek to check if there is any input available with key event and bKeyDown - if (PeekConsoleInput (_inputHandle, out InputRecord peekRecord, bufferSize, out eventsRead) && eventsRead > 0) + if (PeekConsoleInput (_inputHandle, out InputRecord peekRecord, BUFFER_SIZE, out eventsRead) && eventsRead > 0) { if (peekRecord is { EventType: EventType.Key, KeyEvent.bKeyDown: true }) { @@ -949,7 +949,7 @@ public InputRecord [] ReadConsoleInput () ansiSequence.Append (inputChar); // Check if the sequence has ended with an expected command terminator - if (_mainLoop.EscSeqRequests is { } && _mainLoop.EscSeqRequests.HasResponse (inputChar.ToString (), out AnsiEscapeSequenceRequestStatus seqReqStatus)) + if (_mainLoop?.EscSeqRequests is { } && _mainLoop.EscSeqRequests.HasResponse (inputChar.ToString (), out AnsiEscapeSequenceRequestStatus? seqReqStatus)) { // Finished reading the sequence and remove the enqueued request _mainLoop.EscSeqRequests.Remove (seqReqStatus); @@ -970,9 +970,9 @@ public InputRecord [] ReadConsoleInput () } } - if (readingSequence && !raisedResponse && AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) + if (readingSequence && !raisedResponse && AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && _mainLoop?.EscSeqRequests is { Statuses.Count: > 0 }) { - _mainLoop.EscSeqRequests.Statuses.TryDequeue (out AnsiEscapeSequenceRequestStatus seqReqStatus); + _mainLoop.EscSeqRequests.Statuses.TryDequeue (out AnsiEscapeSequenceRequestStatus? seqReqStatus); lock (seqReqStatus!.AnsiRequest._responseLock) { @@ -984,13 +984,13 @@ public InputRecord [] ReadConsoleInput () _retries = 0; } - else if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 }) + else if (AnsiEscapeSequenceRequestUtils.IncompleteCkInfos is null && _mainLoop?.EscSeqRequests is { Statuses.Count: > 0 }) { if (_retries > 1) { - if (_mainLoop.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) + if (_mainLoop.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) { - lock (seqReqStatus!.AnsiRequest._responseLock) + lock (seqReqStatus.AnsiRequest._responseLock) { _mainLoop.EscSeqRequests.Statuses.TryDequeue (out _); @@ -1012,9 +1012,9 @@ public InputRecord [] ReadConsoleInput () _retries = 0; } - return numberEventsRead == 0 - ? null - : [inputRecord]; + return (numberEventsRead == 0 + ? null + : [inputRecord])!; } catch (Exception) { @@ -1096,7 +1096,7 @@ public COLORREF (uint value) private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi); [DllImport ("kernel32.dll", SetLastError = true)] - private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo); + private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX consoleScreenBufferInfo); [DllImport ("kernel32.dll", SetLastError = true)] private static extern bool SetConsoleWindowInfo ( diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs index 9372fcb046..616dc9fb0c 100644 --- a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsDriver.cs @@ -1,4 +1,4 @@ -// TODO: #nullable enable +#nullable enable // // WindowsDriver.cs: Windows specific driver // @@ -9,14 +9,13 @@ // 2) The values provided during Init (and the first WindowsConsole.EventType.WindowBufferSize) are not correct. // // If HACK_CHECK_WINCHANGED is defined then we ignore WindowsConsole.EventType.WindowBufferSize events -// and instead check the console size every 500ms in a thread in WidowsMainLoop. -// As of Windows 11 23H2 25947.1000 and/or WT 1.19.2682 tearing no longer occurs when using +// and instead check the console size every 500ms in a thread in WidowsMainLoop. +// As of Windows 11 23H2 25947.1000 and/or WT 1.19.2682 tearing no longer occurs when using // the WindowsConsole.EventType.WindowBufferSize event. However, on Init the window size is // still incorrect so we still need this hack. //#define HACK_CHECK_WINCHANGED -using System.Collections.Concurrent; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; @@ -35,7 +34,7 @@ internal class WindowsDriver : ConsoleDriver private bool _isOneFingerDoubleClicked; private WindowsConsole.ButtonState? _lastMouseButtonPressed; - private WindowsMainLoop _mainLoopDriver; + private WindowsMainLoop? _mainLoopDriver; private WindowsConsole.ExtendedCharInfo [] _outputBuffer; private Point? _point; private Point _pointMove; @@ -45,7 +44,7 @@ public WindowsDriver () { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { - WinConsole = new WindowsConsole (); + WinConsole = new (); // otherwise we're probably running in unit tests Clipboard = new WindowsClipboard (); @@ -68,7 +67,7 @@ public WindowsDriver () public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal); - public WindowsConsole WinConsole { get; private set; } + public WindowsConsole? WinConsole { get; private set; } public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent) { @@ -202,7 +201,7 @@ public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool al private readonly CancellationTokenSource _ansiResponseTokenSource = new (); /// - public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) + public override string? WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { if (_mainLoopDriver is null) { @@ -242,12 +241,12 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { _mainLoopDriver._forceRead = false; - if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus request)) + if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? request)) { if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0 && string.IsNullOrEmpty (request.AnsiRequest.Response)) { - lock (request!.AnsiRequest._responseLock) + lock (request.AnsiRequest._responseLock) { // Bad request or no response at all _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _); @@ -404,7 +403,7 @@ public override void UpdateScreen () for (var row = 0; row < Rows; row++) { - if (!_dirtyLines [row]) + if (!_dirtyLines! [row]) { continue; } @@ -414,7 +413,7 @@ public override void UpdateScreen () for (var col = 0; col < Cols; col++) { int position = row * Cols + col; - _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault (); + _outputBuffer [position].Attribute = Contents! [row, col].Attribute.GetValueOrDefault (); if (Contents [row, col].IsDirty == false) { @@ -504,7 +503,7 @@ internal override MainLoop Init () { // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED - Size winSize = WinConsole.GetConsoleOutputWindow (out Point pos); + Size winSize = WinConsole.GetConsoleOutputWindow (out Point _); Cols = winSize.Width; Rows = winSize.Height; } @@ -592,7 +591,7 @@ internal void ProcessInput (WindowsConsole.InputRecord inputEvent) case WindowsConsole.EventType.Mouse: MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent); - if (me is null || me.Flags == MouseFlags.None) + if (me.Flags == MouseFlags.None) { break; } @@ -717,7 +716,7 @@ private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx) if (mapResult == 0) { // There is no mapping - this should not happen - Debug.Assert (mapResult != 0, $@"Unable to map the virtual key code {keyInfo.Key}."); + Debug.Assert (true, $@"Unable to map the virtual key code {keyInfo.Key}."); return KeyCode.Null; } @@ -727,13 +726,13 @@ private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx) if (keyInfo.KeyChar == 0) { - // If the keyChar is 0, keyInfo.Key value is not a printable character. + // If the keyChar is 0, keyInfo.Key value is not a printable character. - // Dead keys (diacritics) are indicated by setting the top bit of the return value. + // Dead keys (diacritics) are indicated by setting the top bit of the return value. if ((mapResult & 0x80000000) != 0) { // Dead key (e.g. Oem2 '~'/'^' on POR keyboard) - // Option 1: Throw it out. + // Option 1: Throw it out. // - Apps will never see the dead keys // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see '�'). // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a'). @@ -754,7 +753,7 @@ private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx) if (keyInfo.Modifiers != 0) { // These Oem keys have well-defined chars. We ensure the representative char is used. - // If we don't do this, then on some keyboard layouts the wrong char is + // If we don't do this, then on some keyboard layouts the wrong char is // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important // for key persistence ("Ctrl++" vs. "Ctrl+="). mappedChar = keyInfo.Key switch @@ -925,25 +924,25 @@ private async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag) { // When a user presses-and-holds, start generating pressed events every `startDelay` // After `iterationsUntilFast` iterations, speed them up to `fastDelay` ms - const int startDelay = 500; - const int iterationsUntilFast = 4; - const int fastDelay = 50; + const int START_DELAY = 500; + const int ITERATIONS_UNTIL_FAST = 4; + const int FAST_DELAY = 50; int iterations = 0; - int delay = startDelay; + int delay = START_DELAY; while (_isButtonPressed) { // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application. - View view = Application.WantContinuousButtonPressedView; + View? view = Application.WantContinuousButtonPressedView; if (view is null) { break; } - if (iterations++ >= iterationsUntilFast) + if (iterations++ >= ITERATIONS_UNTIL_FAST) { - delay = fastDelay; + delay = FAST_DELAY; } await Task.Delay (delay); @@ -1012,13 +1011,13 @@ private MouseEventArgs ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent if (_isButtonDoubleClicked || _isOneFingerDoubleClicked) { // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application. - Application.MainLoop.AddIdle ( - () => - { - Task.Run (async () => await ProcessButtonDoubleClickedAsync ()); + Application.MainLoop!.AddIdle ( + () => + { + Task.Run (async () => await ProcessButtonDoubleClickedAsync ()); - return false; - }); + return false; + }); } // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button. @@ -1084,13 +1083,13 @@ private MouseEventArgs ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) { // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application. - Application.MainLoop.AddIdle ( - () => - { - Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag)); + Application.MainLoop!.AddIdle ( + () => + { + Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag)); - return false; - }); + return false; + }); } } else if (_lastMouseButtonPressed != null @@ -1254,420 +1253,3 @@ private MouseEventArgs ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent }; } } - -/// -/// Mainloop intended to be used with the , and can -/// only be used on Windows. -/// -/// -/// This implementation is used for WindowsDriver. -/// -internal class WindowsMainLoop : IMainLoopDriver -{ - /// - /// Invoked when the window is changed. - /// - public EventHandler WinChanged; - - private readonly ConsoleDriver _consoleDriver; - private readonly ManualResetEventSlim _eventReady = new (false); - - // The records that we keep fetching - private readonly ConcurrentQueue _resultQueue = new (); - internal readonly ManualResetEventSlim _waitForProbe = new (false); - private readonly WindowsConsole _winConsole; - private CancellationTokenSource _eventReadyTokenSource = new (); - private readonly CancellationTokenSource _inputHandlerTokenSource = new (); - private MainLoop _mainLoop; - - public WindowsMainLoop (ConsoleDriver consoleDriver = null) - { - _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver)); - - if (!ConsoleDriver.RunningUnitTests) - { - _winConsole = ((WindowsDriver)consoleDriver).WinConsole; - _winConsole._mainLoop = this; - } - } - - public AnsiEscapeSequenceRequests EscSeqRequests { get; } = new (); - - void IMainLoopDriver.Setup (MainLoop mainLoop) - { - _mainLoop = mainLoop; - - if (ConsoleDriver.RunningUnitTests) - { - return; - } - - Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token); -#if HACK_CHECK_WINCHANGED - Task.Run (CheckWinChange); -#endif - } - - void IMainLoopDriver.Wakeup () { _eventReady.Set (); } - - bool IMainLoopDriver.EventsPending () - { - _waitForProbe.Set (); -#if HACK_CHECK_WINCHANGED - _winChange.Set (); -#endif - if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) - { - return true; - } - - try - { - if (!_eventReadyTokenSource.IsCancellationRequested) - { - // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there - // are no timers, but there IS an idle handler waiting. - _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token); - } - } - catch (OperationCanceledException) - { - return true; - } - finally - { - _eventReady.Reset (); - } - - if (!_eventReadyTokenSource.IsCancellationRequested) - { -#if HACK_CHECK_WINCHANGED - return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged; -#else - return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _); -#endif - } - - _eventReadyTokenSource.Dispose (); - _eventReadyTokenSource = new CancellationTokenSource (); - - return true; - } - - void IMainLoopDriver.Iteration () - { - while (_resultQueue.Count > 0) - { - if (_resultQueue.TryDequeue (out WindowsConsole.InputRecord [] inputRecords)) - { - if (inputRecords is { Length: > 0 }) - { - ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]); - } - } - } -#if HACK_CHECK_WINCHANGED - if (_winChanged) - { - _winChanged = false; - WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize)); - } -#endif - } - - void IMainLoopDriver.TearDown () - { - _inputHandlerTokenSource?.Cancel (); - _inputHandlerTokenSource?.Dispose (); - - if (_winConsole is { }) - { - var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents (); - - if (numOfEvents > 0) - { - _winConsole.FlushConsoleInputBuffer (); - //Debug.WriteLine ($"Flushed {numOfEvents} events."); - } - } - - _waitForProbe?.Dispose (); - - _resultQueue?.Clear (); - - _eventReadyTokenSource?.Cancel (); - _eventReadyTokenSource?.Dispose (); - _eventReady?.Dispose (); - -#if HACK_CHECK_WINCHANGED - _winChange?.Dispose (); -#endif - - _mainLoop = null; - } - - internal bool _forceRead; - - private void WindowsInputHandler () - { - while (_mainLoop is { }) - { - try - { - if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead) - { - _waitForProbe.Wait (_inputHandlerTokenSource.Token); - } - } - catch (OperationCanceledException) - { - // Wakes the _waitForProbe if it's waiting - _waitForProbe.Set (); - - return; - } - finally - { - // If IsCancellationRequested is true the code after - // the `finally` block will not be executed. - if (!_inputHandlerTokenSource.IsCancellationRequested) - { - _waitForProbe.Reset (); - } - } - - if (_resultQueue?.Count == 0 || _forceRead) - { - while (!_inputHandlerTokenSource.IsCancellationRequested) - { - WindowsConsole.InputRecord [] inpRec = _winConsole.ReadConsoleInput (); - - if (inpRec is { }) - { - _resultQueue!.Enqueue (inpRec); - - break; - } - - if (!_forceRead) - { - try - { - Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); - } - catch (OperationCanceledException) - { } - } - } - } - - _eventReady.Set (); - } - } - -#if HACK_CHECK_WINCHANGED - private readonly ManualResetEventSlim _winChange = new (false); - private bool _winChanged; - private Size _windowSize; - private void CheckWinChange () - { - while (_mainLoop is { }) - { - _winChange.Wait (); - _winChange.Reset (); - - // Check if the window size changed every half second. - // We do this to minimize the weird tearing seen on Windows when resizing the console - while (_mainLoop is { }) - { - Task.Delay (500).Wait (); - _windowSize = _winConsole.GetConsoleBufferWindow (out _); - - if (_windowSize != Size.Empty - && (_windowSize.Width != _consoleDriver.Cols - || _windowSize.Height != _consoleDriver.Rows)) - { - break; - } - } - - _winChanged = true; - _eventReady.Set (); - } - } -#endif -} - -internal class WindowsClipboard : ClipboardBase -{ - private const uint CF_UNICODE_TEXT = 13; - - public override bool IsSupported { get; } = CheckClipboardIsAvailable (); - - private static bool CheckClipboardIsAvailable () - { - // Attempt to open the clipboard - if (OpenClipboard (nint.Zero)) - { - // Clipboard is available - // Close the clipboard after use - CloseClipboard (); - - return true; - } - // Clipboard is not available - return false; - } - - protected override string GetClipboardDataImpl () - { - try - { - if (!OpenClipboard (nint.Zero)) - { - return string.Empty; - } - - nint handle = GetClipboardData (CF_UNICODE_TEXT); - - if (handle == nint.Zero) - { - return string.Empty; - } - - nint pointer = nint.Zero; - - try - { - pointer = GlobalLock (handle); - - if (pointer == nint.Zero) - { - return string.Empty; - } - - int size = GlobalSize (handle); - var buff = new byte [size]; - - Marshal.Copy (pointer, buff, 0, size); - - return Encoding.Unicode.GetString (buff).TrimEnd ('\0'); - } - finally - { - if (pointer != nint.Zero) - { - GlobalUnlock (handle); - } - } - } - finally - { - CloseClipboard (); - } - } - - protected override void SetClipboardDataImpl (string text) - { - OpenClipboard (); - - EmptyClipboard (); - nint hGlobal = default; - - try - { - int bytes = (text.Length + 1) * 2; - hGlobal = Marshal.AllocHGlobal (bytes); - - if (hGlobal == default (nint)) - { - ThrowWin32 (); - } - - nint target = GlobalLock (hGlobal); - - if (target == default (nint)) - { - ThrowWin32 (); - } - - try - { - Marshal.Copy (text.ToCharArray (), 0, target, text.Length); - } - finally - { - GlobalUnlock (target); - } - - if (SetClipboardData (CF_UNICODE_TEXT, hGlobal) == default (nint)) - { - ThrowWin32 (); - } - - hGlobal = default (nint); - } - finally - { - if (hGlobal != default (nint)) - { - Marshal.FreeHGlobal (hGlobal); - } - - CloseClipboard (); - } - } - - [DllImport ("user32.dll", SetLastError = true)] - [return: MarshalAs (UnmanagedType.Bool)] - private static extern bool CloseClipboard (); - - [DllImport ("user32.dll")] - private static extern bool EmptyClipboard (); - - [DllImport ("user32.dll", SetLastError = true)] - private static extern nint GetClipboardData (uint uFormat); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern nint GlobalLock (nint hMem); - - [DllImport ("kernel32.dll", SetLastError = true)] - private static extern int GlobalSize (nint handle); - - [DllImport ("kernel32.dll", SetLastError = true)] - [return: MarshalAs (UnmanagedType.Bool)] - private static extern bool GlobalUnlock (nint hMem); - - [DllImport ("User32.dll", SetLastError = true)] - [return: MarshalAs (UnmanagedType.Bool)] - private static extern bool IsClipboardFormatAvailable (uint format); - - private void OpenClipboard () - { - var num = 10; - - while (true) - { - if (OpenClipboard (default (nint))) - { - break; - } - - if (--num == 0) - { - ThrowWin32 (); - } - - Thread.Sleep (100); - } - } - - [DllImport ("user32.dll", SetLastError = true)] - [return: MarshalAs (UnmanagedType.Bool)] - private static extern bool OpenClipboard (nint hWndNewOwner); - - [DllImport ("user32.dll", SetLastError = true)] - private static extern nint SetClipboardData (uint uFormat, nint data); - - private void ThrowWin32 () { throw new Win32Exception (Marshal.GetLastWin32Error ()); } -} diff --git a/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsMainLoop.cs b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsMainLoop.cs new file mode 100644 index 0000000000..33aca97048 --- /dev/null +++ b/Terminal.Gui/ConsoleDrivers/WindowsDriver/WindowsMainLoop.cs @@ -0,0 +1,248 @@ +#nullable enable +using System.Collections.Concurrent; + +namespace Terminal.Gui; + +/// +/// Mainloop intended to be used with the , and can +/// only be used on Windows. +/// +/// +/// This implementation is used for WindowsDriver. +/// +internal class WindowsMainLoop : IMainLoopDriver +{ + /// + /// Invoked when the window is changed. + /// + public EventHandler? WinChanged; + + private readonly ConsoleDriver _consoleDriver; + private readonly ManualResetEventSlim _eventReady = new (false); + + // The records that we keep fetching + private readonly ConcurrentQueue _resultQueue = new (); + internal readonly ManualResetEventSlim _waitForProbe = new (false); + private readonly WindowsConsole? _winConsole; + private CancellationTokenSource _eventReadyTokenSource = new (); + private readonly CancellationTokenSource _inputHandlerTokenSource = new (); + private MainLoop? _mainLoop; + + public WindowsMainLoop (ConsoleDriver consoleDriver) + { + _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver)); + + if (!ConsoleDriver.RunningUnitTests) + { + _winConsole = ((WindowsDriver)consoleDriver).WinConsole; + _winConsole!._mainLoop = this; + } + } + + public AnsiEscapeSequenceRequests EscSeqRequests { get; } = new (); + + void IMainLoopDriver.Setup (MainLoop mainLoop) + { + _mainLoop = mainLoop; + + if (ConsoleDriver.RunningUnitTests) + { + return; + } + + Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token); +#if HACK_CHECK_WINCHANGED + Task.Run (CheckWinChange); +#endif + } + + void IMainLoopDriver.Wakeup () { _eventReady.Set (); } + + bool IMainLoopDriver.EventsPending () + { + _waitForProbe.Set (); +#if HACK_CHECK_WINCHANGED + _winChange.Set (); +#endif + if (_mainLoop!.CheckTimersAndIdleHandlers (out int waitTimeout)) + { + return true; + } + + try + { + if (!_eventReadyTokenSource.IsCancellationRequested) + { + // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there + // are no timers, but there IS an idle handler waiting. + _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token); + } + } + catch (OperationCanceledException) + { + return true; + } + finally + { + _eventReady.Reset (); + } + + if (!_eventReadyTokenSource.IsCancellationRequested) + { +#if HACK_CHECK_WINCHANGED + return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged; +#else + return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _); +#endif + } + + _eventReadyTokenSource.Dispose (); + _eventReadyTokenSource = new CancellationTokenSource (); + + return true; + } + + void IMainLoopDriver.Iteration () + { + while (_resultQueue.Count > 0) + { + if (_resultQueue.TryDequeue (out WindowsConsole.InputRecord []? inputRecords)) + { + if (inputRecords is { Length: > 0 }) + { + ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]); + } + } + } +#if HACK_CHECK_WINCHANGED + if (_winChanged) + { + _winChanged = false; + WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize)); + } +#endif + } + + void IMainLoopDriver.TearDown () + { + _inputHandlerTokenSource.Cancel (); + _inputHandlerTokenSource.Dispose (); + + if (_winConsole is { }) + { + var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents (); + + if (numOfEvents > 0) + { + _winConsole.FlushConsoleInputBuffer (); + //Debug.WriteLine ($"Flushed {numOfEvents} events."); + } + } + + _waitForProbe.Dispose (); + + _resultQueue.Clear (); + + _eventReadyTokenSource.Cancel (); + _eventReadyTokenSource.Dispose (); + _eventReady.Dispose (); + +#if HACK_CHECK_WINCHANGED + _winChange?.Dispose (); +#endif + + _mainLoop = null; + } + + internal bool _forceRead; + + private void WindowsInputHandler () + { + while (_mainLoop is { }) + { + try + { + if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead) + { + _waitForProbe.Wait (_inputHandlerTokenSource.Token); + } + } + catch (OperationCanceledException) + { + // Wakes the _waitForProbe if it's waiting + _waitForProbe.Set (); + + return; + } + finally + { + // If IsCancellationRequested is true the code after + // the `finally` block will not be executed. + if (!_inputHandlerTokenSource.IsCancellationRequested) + { + _waitForProbe.Reset (); + } + } + + if (_resultQueue?.Count == 0 || _forceRead) + { + while (!_inputHandlerTokenSource.IsCancellationRequested) + { + WindowsConsole.InputRecord [] inpRec = _winConsole.ReadConsoleInput (); + + if (inpRec is { }) + { + _resultQueue!.Enqueue (inpRec); + + break; + } + + if (!_forceRead) + { + try + { + Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token); + } + catch (OperationCanceledException) + { } + } + } + } + + _eventReady.Set (); + } + } + +#if HACK_CHECK_WINCHANGED + private readonly ManualResetEventSlim _winChange = new (false); + private bool _winChanged; + private Size _windowSize; + private void CheckWinChange () + { + while (_mainLoop is { }) + { + _winChange.Wait (); + _winChange.Reset (); + + // Check if the window size changed every half second. + // We do this to minimize the weird tearing seen on Windows when resizing the console + while (_mainLoop is { }) + { + Task.Delay (500).Wait (); + _windowSize = _winConsole.GetConsoleBufferWindow (out _); + + if (_windowSize != Size.Empty + && (_windowSize.Width != _consoleDriver.Cols + || _windowSize.Height != _consoleDriver.Rows)) + { + break; + } + } + + _winChanged = true; + _eventReady.Set (); + } + } +#endif +} + From 873b5783ef162da7212d1df2c358b30baee17f11 Mon Sep 17 00:00:00 2001 From: BDisp Date: Thu, 7 Nov 2024 15:41:58 +0000 Subject: [PATCH 89/89] #nullable enable. --- .../ConsoleDrivers/NetDriver/NetDriver.cs | 31 ++++++++++------- .../ConsoleDrivers/NetDriver/NetEvents.cs | 34 +++++++++---------- .../ConsoleDrivers/NetDriver/NetMainLoop.cs | 34 +++++++++---------- .../NetDriver/NetWinVTConsole.cs | 3 +- 4 files changed, 53 insertions(+), 49 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs index 0422f548f9..73ec87d41c 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetDriver.cs @@ -1,4 +1,4 @@ -// TODO: #nullable enable +#nullable enable // // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient. // @@ -14,7 +14,7 @@ namespace Terminal.Gui; internal class NetDriver : ConsoleDriver { public bool IsWinPlatform { get; private set; } - public NetWinVTConsole NetWinConsole { get; private set; } + public NetWinVTConsole? NetWinConsole { get; private set; } public override void Refresh () { @@ -61,7 +61,7 @@ public override void UpdateScreen () if (RunningUnitTests || _winSizeChanging || Console.WindowHeight < 1 - || Contents.Length != Rows * Cols + || Contents?.Length != Rows * Cols || Rows != Console.WindowHeight) { return; @@ -85,7 +85,7 @@ public override void UpdateScreen () return; } - if (!_dirtyLines [row]) + if (!_dirtyLines! [row]) { continue; } @@ -129,7 +129,7 @@ public override void UpdateScreen () lastCol = col; } - Attribute attr = Contents [row, col].Attribute.Value; + Attribute attr = Contents [row, col].Attribute!.Value; // Performance: Only send the escape sequence if the attribute has changed. if (attr != redrawAttr) @@ -229,7 +229,7 @@ void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int out #region Init/End/MainLoop - internal NetMainLoop _mainLoopDriver; + internal NetMainLoop? _mainLoopDriver; internal override MainLoop Init () { @@ -339,7 +339,7 @@ private void ProcessInput (InputResult inputEvent) Left = 0; Cols = inputEvent.WindowSizeEvent.Size.Width; Rows = Math.Max (inputEvent.WindowSizeEvent.Size.Height, 0); - ; + ResizeScreen (); ClearContents (); _winSizeChanging = false; @@ -727,16 +727,21 @@ private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyI #region Low-Level DotNet tuff private readonly ManualResetEventSlim _waitAnsiResponse = new (false); - private readonly CancellationTokenSource _ansiResponseTokenSource = new (); + private CancellationTokenSource? _ansiResponseTokenSource; /// - public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) + public override string? WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { - if (_mainLoopDriver is null) + lock (ansiRequest._responseLock) { - return string.Empty; + if (_mainLoopDriver is null) + { + return string.Empty; + } } + _ansiResponseTokenSource ??= new (); + try { lock (ansiRequest._responseLock) @@ -765,12 +770,12 @@ public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest) { _mainLoopDriver._netEvents._forceRead = false; - if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus request)) + if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? request)) { if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0 && string.IsNullOrEmpty (request.AnsiRequest.Response)) { - lock (request!.AnsiRequest._responseLock) + lock (request.AnsiRequest._responseLock) { // Bad request or no response at all _mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryDequeue (out _); diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs index 9976c01369..6ce0bbe26a 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetEvents.cs @@ -1,4 +1,4 @@ -// TODO: #nullable enable +#nullable enable using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; @@ -6,10 +6,10 @@ namespace Terminal.Gui; internal class NetEvents : IDisposable { - private CancellationTokenSource _inputReadyCancellationTokenSource; + private CancellationTokenSource? _inputReadyCancellationTokenSource; private readonly BlockingCollection _inputQueue = new (new ConcurrentQueue ()); private readonly ConsoleDriver _consoleDriver; - private ConsoleKeyInfo [] _cki; + private ConsoleKeyInfo []? _cki; private bool _isEscSeq; #if PROCESS_REQUEST bool _neededProcessRequest; @@ -62,9 +62,9 @@ private ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, { if (_retries > 1) { - if (EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) + if (EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus? seqReqStatus) && string.IsNullOrEmpty (seqReqStatus.AnsiRequest.Response)) { - lock (seqReqStatus!.AnsiRequest._responseLock) + lock (seqReqStatus.AnsiRequest._responseLock) { EscSeqRequests.Statuses.TryDequeue (out _); @@ -319,7 +319,7 @@ ref ConsoleModifiers mod out bool isMouse, out List mouseFlags, out Point pos, - out AnsiEscapeSequenceRequestStatus seqReqStatus, + out AnsiEscapeSequenceRequestStatus? seqReqStatus, (f, p) => HandleMouseEvent (MapMouseFlags (f), p) ); @@ -350,7 +350,7 @@ ref ConsoleModifiers mod if (!string.IsNullOrEmpty (AnsiEscapeSequenceRequestUtils.InvalidRequestTerminator)) { - if (EscSeqRequests.Statuses.TryDequeue (out AnsiEscapeSequenceRequestStatus result)) + if (EscSeqRequests.Statuses.TryDequeue (out AnsiEscapeSequenceRequestStatus? result)) { lock (result.AnsiRequest._responseLock) { @@ -504,7 +504,7 @@ private MouseButtonState MapMouseFlags (MouseFlags mouseFlags) return mbs; } - private Point _lastCursorPosition; + //private Point _lastCursorPosition; //private void HandleRequestResponseEvent (string c1Control, string code, string [] values, string terminating) //{ @@ -651,15 +651,15 @@ public struct InputResult public readonly override string ToString () { - return EventType switch - { - EventType.Key => ToString (ConsoleKeyInfo), - EventType.Mouse => MouseEvent.ToString (), - - //EventType.WindowSize => WindowSize.ToString (), - //EventType.RequestResponse => RequestResponse.ToString (), - _ => "Unknown event type: " + EventType - }; + return (EventType switch + { + EventType.Key => ToString (ConsoleKeyInfo), + EventType.Mouse => MouseEvent.ToString (), + + //EventType.WindowSize => WindowSize.ToString (), + //EventType.RequestResponse => RequestResponse.ToString (), + _ => "Unknown event type: " + EventType + })!; } /// Prints a ConsoleKeyInfoEx structure diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs index 6e68bf8d5b..df6b63203d 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetMainLoop.cs @@ -1,4 +1,5 @@ -using System.Collections.Concurrent; +#nullable enable +using System.Collections.Concurrent; namespace Terminal.Gui; @@ -9,22 +10,22 @@ namespace Terminal.Gui; /// This implementation is used for NetDriver. internal class NetMainLoop : IMainLoopDriver { - internal NetEvents _netEvents; + internal NetEvents? _netEvents; /// Invoked when a Key is pressed. - internal Action ProcessInput; + internal Action? ProcessInput; private readonly ManualResetEventSlim _eventReady = new (false); private readonly CancellationTokenSource _inputHandlerTokenSource = new (); private readonly BlockingCollection _resultQueue = new (new ConcurrentQueue ()); private readonly CancellationTokenSource _eventReadyTokenSource = new (); - private MainLoop _mainLoop; + private MainLoop? _mainLoop; /// Initializes the class with the console driver. /// Passing a consoleDriver is provided to capture windows resizing. /// The console driver used by this Net main loop. /// - public NetMainLoop (ConsoleDriver consoleDriver = null) + public NetMainLoop (ConsoleDriver consoleDriver) { ArgumentNullException.ThrowIfNull (consoleDriver); @@ -47,7 +48,7 @@ void IMainLoopDriver.Setup (MainLoop mainLoop) bool IMainLoopDriver.EventsPending () { - if (_resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout)) + if (_resultQueue.Count > 0 || _mainLoop!.CheckTimersAndIdleHandlers (out int waitTimeout)) { return true; } @@ -88,24 +89,21 @@ void IMainLoopDriver.Iteration () // Always dequeue even if it's null and invoke if isn't null if (_resultQueue.TryTake (out NetEvents.InputResult dequeueResult)) { - if (dequeueResult is { }) - { - ProcessInput?.Invoke (dequeueResult); - } + ProcessInput?.Invoke (dequeueResult); } } } void IMainLoopDriver.TearDown () { - _inputHandlerTokenSource?.Cancel (); - _inputHandlerTokenSource?.Dispose (); - _eventReadyTokenSource?.Cancel (); - _eventReadyTokenSource?.Dispose (); + _inputHandlerTokenSource.Cancel (); + _inputHandlerTokenSource.Dispose (); + _eventReadyTokenSource.Cancel (); + _eventReadyTokenSource.Dispose (); - _eventReady?.Dispose (); + _eventReady.Dispose (); - _resultQueue?.Dispose(); + _resultQueue.Dispose(); _netEvents?.Dispose (); _netEvents = null; @@ -123,9 +121,9 @@ private void NetInputHandler () return; } - if (_resultQueue?.Count == 0 || _netEvents._forceRead) + if (_resultQueue?.Count == 0 || _netEvents!._forceRead) { - NetEvents.InputResult? result = _netEvents.DequeueInput (); + NetEvents.InputResult? result = _netEvents!.DequeueInput (); if (result.HasValue) { diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver/NetWinVTConsole.cs b/Terminal.Gui/ConsoleDrivers/NetDriver/NetWinVTConsole.cs index 81a9f6b68b..98666f4609 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver/NetWinVTConsole.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver/NetWinVTConsole.cs @@ -1,4 +1,5 @@ -using System.Runtime.InteropServices; +#nullable enable +using System.Runtime.InteropServices; namespace Terminal.Gui;