Files
Terminal.Gui/Examples/UICatalog/Scenarios/AnsiRequestsScenario.cs
Copilot e6a0ec64ca Fixes #4361 - Consolidate FakeDriver into library and refactor driver architecture (#4362)
* Initial plan

* Add ScreenChanged event, SetScreenSize method, and fix FakeDriver buffer initialization

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Add comprehensive tests for ScreenChanged event and buffer integrity

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Replace obsolete SizeChanged usage with ScreenChanged in core and tests

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Refactor terminal size event handling

Replaced `ScreenChanged` with `SizeChanged` across the codebase to standardize naming and improve clarity. Updated event handling logic, including subscriptions, unsubscriptions, and raising methods. Removed deprecated `ScreenChanged` event and backward compatibility code.

Refactored driver initialization to handle legacy `IConsoleDriver` types separately. Updated tests and mock implementations to align with the new `SizeChanged` event. Improved documentation and comments to reflect these changes.

These updates enhance maintainability, consistency, and modernize the architecture.

* Refactor & Code Cleanup: Replace IWindowSizeMonitor with IConsoleSizeMonitor

Renamed `IWindowSizeMonitor` to `IConsoleSizeMonitor` across the codebase, updating all references, method signatures, and event handlers. Replaced the `WindowSizeMonitor` class with the new `ConsoleSizeMonitor` implementation, which includes improved terminal size change handling via the `Poll` method.

Enabled nullable reference types in several files to enhance code safety. Updated test cases to reflect the new `IConsoleSizeMonitor` interface. Removed redundant code, simplified null checks, and corrected minor typos in comments. Streamlined the codebase by removing the obsolete `WindowSizeMonitor` class and its interface.

* Code cleanup - Refactor and enhance ShadowView and FakeDriverTests

Updated ShadowView.cs to use null-conditional operators and added null checks for safer access to `ScreenContents`. Refined XML documentation in View.Layout.cs for clarity and consistency.

Refactored FakeDriverTests.cs to leverage modern C# features, including shorthand object instantiation, inline lambdas, and tuple-like syntax for `Size` and `Rectangle`. Removed redundant tests and improved test readability and reliability.

Enhanced error handling with null checks and ensured backward compatibility for deprecated events. Improved test coverage for resizing, clipboard operations, and invalid coordinates. Verified buffer integrity and screen updates after resizing.

General improvements include replacing explicit type declarations with `var`, removing unused imports, and aligning code formatting for better readability.

Refactor and improve code quality and test coverage

Updated `ShadowView` for null safety using null-conditional operators. Simplified object initializations and modernized syntax across the codebase, including shorthand initializations and inline lambdas. Enhanced event handling logic and ensured compatibility with obsolete members.

Refactored `FakeDriverTests` by removing redundant code, standardizing formatting, and improving test setup. Suppressed obsolete warnings where necessary. Improved XML documentation in `View.Layout.cs` for clarity and removed outdated references.

Performed general cleanup, including removing unused namespaces, redundant comments, and ensuring consistent formatting. These changes enhance readability, maintainability, and runtime safety.

* Code cleanup

Refactor TimedEventsTests for readability and consistency

Improved code readability and maintainability:
- Enabled nullable reference types with `#nullable enable`.
- Removed unused `using System.Diagnostics;`.
- Updated namespace to `UnitTests.ApplicationTests`.
- Replaced `Terminal.Gui.App.TimedEvents` with `TimedEvents`.
- Reformatted XML documentation comments for alignment.
- Used `var` and target-typed new expressions for consistency.
- Reformatted `Parallel.For` loops and lambdas for clarity.
- Added `Thread.Sleep(10)` to prevent excessive CPU usage in tests.
- Improved assertions and event handler formatting in tests.

Aligned with modern C# coding practices.

* Code Cleanup - No more driver warnings.

Refactor codebase and introduce FakeClipboard

- Adjusted `.editorconfig` to change severity levels for CS0612, CS0618, and CS0672 diagnostics.
- Replaced `FakeDriver.FakeClipboard` with a new `FakeClipboard` class for testing purposes, supporting exception handling and clipboard data manipulation.
- Removed redundant methods (`MakeColor`, `MapKey`) and unused classes (`MockConsoleDriver`) to streamline the codebase.
- Refactored `ConsoleDriverFacade` and `FakeDriver` to simplify logic and improve maintainability.
- Updated tests to use `CreateFakeDriver` and removed or commented out obsolete tests.
- Reformatted and cleaned up code for readability across multiple files.

* Refactor FakeDriver - Code Cleanup

Standardized console size management by replacing `WindowSizeMonitor` with `ConsoleSizeMonitor` across the codebase. Updated methods `GetWindowSize` and `SetWindowSize` to `GetSize` and `SetSize` for consistency.

Refactored `FakeDriver` to use `SetScreenSize` and removed redundant methods. Simplified driver initialization by removing legacy `InternalInit` logic.

Standardized ANSI escape sequences by replacing `CSI_ReportTerminalSizeInChars` with `CSI_ReportWindowSizeInChars`.

Updated test cases to align with the new `ConsoleSizeMonitor` and `SetScreenSize` methods. Removed obsolete test utilities like `FakeSizeMonitor` and `FakeWindowSizeMonitor`.

Performed general code cleanup, including removing unused classes, redundant code, and improving formatting. Fixed resizing logic issues and improved exception handling in driver methods.

* Update Terminal.Gui/Drivers/OutputBuffer.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Terminal.Gui/Drivers/MouseButtonStateEx.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Terminal.Gui/App/MainLoop/IApplicationMainLoop.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Tests/UnitTests/Views/ToplevelTests.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Terminal.Gui/ViewBase/View.Layout.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Moved all Drawing tests to Paralleizable - proving Fakedriver works

Enhanced `Ruler` and `Thickness` classes by adding an optional `IConsoleDriver? driver` parameter to decouple rendering from the default `Application.Driver`, improving flexibility and testability. Updated `DriverAssert` to support nullable drivers and added defensive checks.

Refactored and expanded test cases for `Ruler`, `Thickness`, `LineCanvas`, and `StraightLineExtensions` to ensure comprehensive coverage, including zero-length intersections, line rendering, and exclusion logic. Migrated rendering-dependent tests to a parallelizable namespace.

Removed redundant tests, improved naming conventions, and updated documentation for better maintainability and clarity.

* Fixed Run<T> startup hang.

Refactor: Simplify driver logic and update SetSize methods

Removed FakeDriver safeguard in unit tests to simplify
CreateDriver logic. Updated SetSize methods in NetOutput,
UnixOutput, and WindowsOutput to do nothing instead of
throwing NotImplementedException. Modified SizeChanged
event in ConsoleDriverFacade to call SetScreenSize directly.
Commented out unnecessary debug validation in DimAuto.
These changes improve maintainability and reduce complexity.

* Fixed intermittent unit test bug.

Refactored `_cachedRunStateToplevel` to `CachedRunStateToplevel` as an internal static property, delegating its management to `ApplicationImpl` for improved encapsulation. Updated all references to use the new property and centralized its handling in `ApplicationImpl`.

Removed the `MouseGrabHandler` property from `ApplicationImpl` and simplified driver-related assignments by replacing `Application.ForceDriver` and `Application.Screen` with direct references.

Reset `CachedRunStateToplevel` during cleanup to ensure proper state management. Updated the `Invoke` method to use `Top` directly, aligning with the refactored design. Improved debug assertions and performed general cleanup to enhance code readability and maintainability.

* Fixed intermittent bug an massive code cleanup of warnings.

Refactor and enhance codebase for maintainability

- Applied null-conditional operator (`!`) to improve null-safety.
- Refactored tests for clarity, added new cases, and removed redundancies.
- Introduced `FakeApplicationFactory` and `FakeSizeMonitor` for testing.
- Removed unused code, including legacy `DecodeEscSeq` logic.
- Reformatted code for readability and consistency.
- Updated assertions for more accurate validation in tests.
- Fixed potential null reference issues across multiple files.
- Improved event handling with proper null checks.
- Enhanced documentation for new classes and methods.
- Modernized code with C# features like `record struct` and `nullable enable`.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: tig <585482+tig@users.noreply.github.com>
Co-authored-by: Tig <tig@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-27 23:34:14 -06:00

400 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UICatalog.Scenarios;
[ScenarioMetadata ("AnsiEscapeSequenceRequest", "Ansi Escape Sequence Request")]
[ScenarioCategory ("Tests")]
public sealed class AnsiEscapeSequenceRequests : Scenario
{
private GraphView _graphView;
private ScatterSeries _sentSeries;
private ScatterSeries _answeredSeries;
private readonly List<DateTime> _sends = new ();
private readonly object _lockAnswers = new object ();
private readonly Dictionary<DateTime, string> _answers = new ();
private Label _lblSummary;
public override void Main ()
{
// Init
Application.Init ();
TabView tv = new TabView
{
Width = Dim.Fill (),
Height = Dim.Fill (),
CanFocus = true
};
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.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 (),
CanFocus = true
};
w.Padding.Thickness = new (1);
var scrRequests = new List<string>
{
"CSI_SendDeviceAttributes",
"CSI_ReportTerminalSizeInChars",
"CSI_RequestCursorPositionReport",
"CSI_SendDeviceAttributes2"
};
// TODO: This UI would be cleaner/less rigid if Pos.Align were used
var cbRequests = new ComboBox () { Width = 40, Height = 5, ReadOnly = true, Source = new ListWrapper<string> (new (scrRequests)) };
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 };
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 };
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 };
w.Add (label, tfTerminator);
cbRequests.SelectedItemChanged += (s, e) =>
{
if (cbRequests.SelectedItem == -1)
{
return;
}
var selAnsiEscapeSequenceRequestName = scrRequests [cbRequests.SelectedItem];
AnsiEscapeSequence selAnsiEscapeSequenceRequest = null;
switch (selAnsiEscapeSequenceRequestName)
{
case "CSI_SendDeviceAttributes":
selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_SendDeviceAttributes;
break;
case "CSI_ReportTerminalSizeInChars":
selAnsiEscapeSequenceRequest = EscSeqUtils.CSI_ReportWindowSizeInChars;
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.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:" };
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:" };
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:" };
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 lblSuccess = new Label { X = Pos.Center (), Y = Pos.Bottom (btnResponse) + 1 };
w.Add (lblSuccess);
btnResponse.Accepting += (s, e) =>
{
var ansiEscapeSequenceRequest = new AnsiEscapeSequence
{
Request = tfRequest.Text,
Terminator = tfTerminator.Text,
Value = string.IsNullOrEmpty (tfValue.Text) ? null : tfValue.Text
};
Application.Driver.QueueAnsiRequest (
new ()
{
Request = ansiEscapeSequenceRequest.Request,
Terminator = ansiEscapeSequenceRequest.Terminator,
ResponseReceived = (s) => OnSuccess (s, tvResponse, tvError, tvValue, tvTerminator, lblSuccess),
Abandoned = () => OnFail (tvResponse, tvError, tvValue, tvTerminator, lblSuccess)
});
};
w.Add (btnResponse);
w.Add (new Label { Y = Pos.Bottom (lblSuccess) + 2, Text = "You can send other requests by editing the TextFields." });
return w;
}
private void OnSuccess (string response, TextView tvResponse, TextView tvError, TextView tvValue, TextView tvTerminator, Label lblSuccess)
{
tvResponse.Text = response;
tvError.Text = string.Empty;
tvValue.Text = string.Empty;
tvTerminator.Text = string.Empty;
lblSuccess.SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Base);
lblSuccess.Text = "Successful";
}
private void OnFail (TextView tvResponse, TextView tvError, TextView tvValue, TextView tvTerminator, Label lblSuccess)
{
tvResponse.Text = string.Empty;
tvError.Text = "No Response";
tvValue.Text = string.Empty;
tvTerminator.Text = string.Empty;
lblSuccess.SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Error);
lblSuccess.Text = "Error";
}
private View BuildBulkTab ()
{
View 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",
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.SetNeedsDraw ();
}
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.SetNeedsDraw ();
}
private int ToSeconds (DateTime t)
{
return (int)(DateTime.Now - t).TotalSeconds;
}
private void SendDar ()
{
Application.Driver.QueueAnsiRequest (
new ()
{
Request = EscSeqUtils.CSI_SendDeviceAttributes.Request,
Terminator = EscSeqUtils.CSI_SendDeviceAttributes.Terminator,
ResponseReceived = HandleResponse
});
_sends.Add (DateTime.Now);
}
private void HandleResponse (string response)
{
lock (_lockAnswers)
{
_answers.Add (DateTime.Now, response);
}
}
}