Commit Graph

8188 Commits

Author SHA1 Message Date
Copilot
aab90e1fbc Fixes #4463 - Adds LineCanvas.GetRegion() - 10x performance regression in RenderLineCanvas (#4464)
* Initial plan

* Revert xunit maxParallelThreads to default to fix performance issue

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

* Fix 10x performance regression in RenderLineCanvas

Found via binary search of 51 commits that commit 027018368 introduced
the slowdown by calling context.AddDrawnRectangle() for every cell in
the LineCanvas (thousands of times per frame).

Fixed by reporting the entire LineCanvas.Bounds once instead of per-cell.

Test results:
- Before: 1m 33s (10x slower than v2_release)
- After: 9s (same as v2_release)

Fixes the performance issue in AllViews_Draw_Does_Not_Layout test.

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

* Add comment clarifying LineCanvas coordinate system

Addresses code review feedback about coordinate system conversion.
LineCanvas.Bounds is already in screen-relative coordinates since
cells are stored with screen positions (used with Driver.Move).

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

* Build non-rectangular Region from LineCanvas cells efficiently

Instead of reporting entire LineCanvas.Bounds (which includes empty space),
efficiently build a Region that encompasses only the actual line cells.

Algorithm groups contiguous horizontal cells into spans per row, avoiding
per-cell overhead while accurately representing the non-rectangular shape.

Performance maintained: 10s (same as v2_release)
All tests pass: 5695 drawing tests, 200 LineCanvas tests, 33 transparency tests

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

* Address code review feedback - improve robustness

- Remove redundant empty check (caller already verifies)
- Add safety check for empty row groups to prevent IndexOutOfRangeException
- Update documentation to clarify precondition

Tests still pass with 9s performance.

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

* Optimize BuildRegionFromLineCells - eliminate redundant sort

Remove redundant OrderBy since X values are already sorted from the
initial OrderBy().ThenBy() operation. Also remove unreachable empty
check since GroupBy guarantees non-empty groups.

Performance maintained at 9s.

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

* Final code review fixes - improve comments and add defensive check

- Clarify comment about sorting behavior
- Add defensive empty check for edge cases
- Performance maintained at 10s

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

* Move BuildRegionFromCells to LineCanvas class

Moved the BuildRegionFromCells method from View.Drawing.cs to LineCanvas
where it logically belongs as a public static method.

Updated View.Drawing.cs to call Drawing.LineCanvas.BuildRegionFromCells.

Performance maintained at 9s. All tests pass.

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

* Update documentation for BuildRegionFromCells

- Clarify that method handles empty cellMap gracefully
- Improve comment explaining the defensive empty check
- Performance maintained at 10s

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

* Rename BuildRegionFromCells to GetRegion

Renamed the method as requested to have a more concise name.

Performance maintained at 10s. All tests pass.

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

* Add GetCellMapWithRegion optimization for single-pass iteration

Implemented optimized method that builds both cell map and Region in a
single pass through the canvas bounds, eliminating the need for separate
GetCellMap() and GetRegion() calls.

Benefits:
- Reduces from 2 iterations to 1 (GetCellMap then GetRegion -> single pass)
- Eliminates sorting overhead (O(n log n) -> O(n))
- X values already sorted due to inner loop order
- Builds Region incrementally per row as cells are discovered

Performance maintained at 10s. All tests pass:
- AllViews_Draw_Does_Not_Layout: 10s
- 5695 drawing tests passed
- 200 LineCanvas tests passed
- 33 transparency tests passed

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

* Add comprehensive unit tests for GetRegion and GetCellMapWithRegion

Added 15 new unit tests covering:

GetRegion tests:
- Empty cell map handling
- Single cell regions
- Horizontal and vertical lines
- L-shaped regions
- Discontiguous cells creating separate spans
- Intersecting lines

GetCellMapWithRegion tests:
- Empty canvas handling
- Single horizontal/vertical lines
- Intersecting lines with proper intersection handling
- Complex shapes (boxes)
- Consistency with separate GetCellMap + GetRegion calls
- Negative coordinate handling
- Exclusion region support

All 215 LineCanvas tests pass. Performance maintained at 9s.

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

* Fix code style violations per CONTRIBUTING.md

- Replace var with explicit types (Dictionary<Point, Cell?>, LineCanvas, Region, etc.)
- Replace new TypeName() with target-typed new () where type is declared
- Fix foreach loop to use explicit IGrouping<int, Point> type
- Use StraightLine instead of var in foreach

All style violations fixed per CONTRIBUTING.md coding conventions.
Tests still pass: 215 LineCanvas tests, 9s performance maintained.

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

* Code cleanup.

* Upgrades Transparent Scenario to demonstrate LineCanvas transparency. "dotnet" is drawn using LineCanvas.

* Comment out debug assertions in View drawing logic

The debug assertions in the `View` class, which validated the relationships between `Margin`, `Border`, `Padding`, and their parent objects, as well as their `SubViewNeedsDraw` and `NeedsDraw` states, have been commented out. These assertions were conditionally executed when the current object and its `SuperView` were not of type `Adornment`.

The code has been retained as comments for potential future reference or debugging purposes, but the assertions are no longer active in the current implementation.

---------

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>
2025-12-08 17:13:58 -07:00
Tig
3ae28bbf5a Makes timeout tests more robust to slow GH runners (#4461)
* Fixed MouseGrabView bug.

Added extensive test coverage for `Keyboard`, `Mouse`, `Timeout`, and `Popover` functionalities, including edge cases and concurrent access. Introduced parameterized and data-driven tests to reduce redundancy and improve clarity.

Refactored codebase for modularity and maintainability,
introducing new namespaces and reorganizing classes. Enhanced `MouseImpl`, `KeyboardImpl`, and `Runnable` implementations with improved event handling, thread safety, and support for the Terminal.Gui Cancellable Work Pattern (CWP).

Removed deprecated code and legacy tests, such as `LogarithmicTimeout` and `SmoothAcceleratingTimeout`. Fixed bugs related to mouse grabbing during drag operations and unbalanced `ApplicationImpl.Begin/End` calls. Improved documentation and code readability with modern C# features.

* Modified assertion logic to conditionally skip checks when the safety timeout fires, preventing false negatives. Improved comments to clarify the purpose of the safety timeout and assertion changes.
2025-12-08 12:52:13 -07:00
Tig
f548059a27 Fixes #4258 - Glyphs drawn at mid-point of wide glyphs don't get drawn with clipping (#4462)
* Enhanced `View.Drawing.cs` with improved comments, a new
`DoDrawComplete` method for clip region updates, and
clarified terminology. Added detailed remarks for the
`OnDrawComplete` method and `DrawComplete` event.

Refactored `ViewDrawingClippingTests` to simplify driver
setup, use target-typed `new`, and add a new test for wide
glyph clipping with bordered subviews. Improved handling of
edge cases like empty viewports and nested clips.

Added `WideGlyphs.DrawFlow.md` and
`ViewDrawingClippingTests.DrawFlow.md` to document the draw
flow, clipping behavior, and coordinate systems for both the
scenario and the test.

Commented out redundant `Driver.Clip` initialization in
`ApplicationImpl`. Added a `BUGBUG` comment in `Border` to
highlight missing redraw logic for `LineStyle` changes.

* Uncomment Driver.Clip initialization in Screen redraw

* Fixed it!

* Fixes #4258 - Correct wide glyph and border rendering

Refactored `OutputBufferImpl.AddStr` to improve handling of wide glyphs:
- Wide glyphs now modify only the first column they occupy, leaving the second column untouched.
- Removed redundant code that set replacement characters and marked cells as not dirty.
- Synchronized cursor updates (`Col` and `Row`) with the buffer lock to prevent race conditions.
- Modularized logic with helper methods for better readability and maintainability.

Updated `WideGlyphs.cs`:
- Removed dashed `BorderStyle` and added border thickness and subview for `arrangeableViewAtEven`.
- Removed unused `superView` initialization.

Enhanced tests:
- Added unit tests to verify correct rendering of borders and content at odd columns overlapping wide glyphs.
- Updated existing tests to reflect the new behavior of wide glyph handling.
- Introduced `DriverAssert.AssertDriverOutputIs` to validate raw ANSI output.

Improved documentation:
- Expanded problem description and root cause analysis in `WideGlyphBorderBugFix.md`.
- Detailed the fix and its impact, ensuring proper layering of content at any column position.

General cleanup:
- Removed unused imports and redundant code.
- Improved code readability and maintainability.

* Code cleanup

* Update Tests/UnitTestsParallelizable/ViewBase/Draw/ViewDrawingClippingTests.cs

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

* Update Terminal.Gui/Drivers/OutputBufferImpl.cs

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

* Update Tests/UnitTestsParallelizable/ViewBase/Draw/ViewDrawingClippingTests.cs

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

* Update Tests/UnitTestsParallelizable/ViewBase/Draw/ViewDrawingClippingTests.cs

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

* Fixed test slowness problem

* Simplified

* Rmoved temp .md files

* Refactor I/O handling and improve testability

Refactored `InputProcessor` and `Output` access by replacing direct property usage with `GetInputProcessor()` and `GetOutput()` methods to enhance encapsulation. Introduced `GetLastOutput()` and `GetLastBuffer()` methods for better debugging and testability.

Centralized `StringBuilder` usage in `OutputBase` implementations to ensure consistency. Improved exception handling with clearer messages. Updated tests to align with the refactored structure and added a new test for wide glyph handling.

Enhanced ANSI sequence handling and simplified cursor visibility logic to prevent flickering. Standardized method naming for consistency. Cleaned up redundant code and improved documentation for better developer clarity.

* Refactored `NetOutput`, `FakeOutput`, `UnixOutput`, and `WindowsOutput` classes to support access to `Output` and added a `IDriver.GetOutput` to acess the `IOutput`. `IOutput` now has a `GetLastOutput` method.

Simplified `DriverAssert` logic and enhanced `DriverTests` with a new test for wide glyph clipping across drivers.

Performed general cleanup, including removal of unused code, improved formatting, and adoption of modern C# practices. Added `using System.Diagnostics` in `OutputBufferImpl` for debugging.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-08 12:28:32 -07:00
Tig
5da7e59aa2 Fixes #4456 - Clear MouseGrabView in App.End (#4460)
* Fixed MouseGrabView bug.

Added extensive test coverage for `Keyboard`, `Mouse`, `Timeout`, and `Popover` functionalities, including edge cases and concurrent access. Introduced parameterized and data-driven tests to reduce redundancy and improve clarity.

Refactored codebase for modularity and maintainability,
introducing new namespaces and reorganizing classes. Enhanced `MouseImpl`, `KeyboardImpl`, and `Runnable` implementations with improved event handling, thread safety, and support for the Terminal.Gui Cancellable Work Pattern (CWP).

Removed deprecated code and legacy tests, such as `LogarithmicTimeout` and `SmoothAcceleratingTimeout`. Fixed bugs related to mouse grabbing during drag operations and unbalanced `ApplicationImpl.Begin/End` calls. Improved documentation and code readability with modern C# features.

* Code cleanup.

* Update Tests/UnitTestsParallelizable/Application/Runnable/RunnableIntegrationTests.cs

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

* Improve null handling and simplify test setup

In `MouseImpl.cs`, added an early `return` after the `UngrabMouse()`
call within the `if (view is null)` block to prevent further execution
when `view` is `null`, improving null reference handling.

In `RunnableIntegrationTests.cs`, removed the initialization of the
`IApplication` object (`app`) from the `MultipleRunnables_IndependentResults`
test method, simplifying the test setup and focusing on runnable behavior.

* Code cleanup

* API doc link cleanup

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-07 13:01:19 -07:00
BDisp
0270183686 Fixes #4453. Regression in wide glyph rendering on all drivers (#4458) 2025-12-07 11:40:43 -07:00
Copilot
dd12df7fb7 Fixes #4176. Removes View.MouseClick (#4450)
* Initial plan

* Add comprehensive MouseClick removal analysis

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

* Fix code review feedback on analysis document

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

* Add actual line numbers to analysis document

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

* Final polish on analysis document - clarify TextView

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

* Phase 3: Port 6 simple Views from MouseClick to Selecting/MouseBindings

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

* Phase 2: Port 10 Scenarios from MouseClick to Selecting/remove

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

* Update analysis document - Phases 2 & 3 complete

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

* Fix failing tests - Button multi-button support and Label focus handling

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

* Phase 4: Port ScrollBar from OnMouseClick to OnSelecting; remove analysis doc

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

* Phase 5: Update/remove tests that explicitly test MouseClick API

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

* Code cleanup

* Remove MouseClick event

Consolidated mouse event handling by removing the `MouseClick`
event and integrating its functionality into the `MouseEvent`
event. Simplified `MouseEventArgs` documentation and added
support for invoking commands bound to mouse events.

Reorganized code by removing `Mouse Pressed Events` and
`Mouse Click Events` regions, introducing a new `WhenGrabbed
Handlers` region. Updated tests to replace `MouseClick` with
`MouseEvent`, adjusted test logic, and improved variable
naming for clarity.

Removed redundant assertions and unused code related to
`MouseClick`. Improved event propagation logic to ensure
proper handling of unhandled events. Performed general code
cleanup to enhance readability and maintainability.

* Updated deep dives.

---------

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>
2025-12-06 14:41:20 -07:00
Copilot
0eafb5947e Move parallel test repeat logic to stress tests (#4455)
* Initial plan

* Move parallel test repeat logic to stress tests

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

* Simplify unit tests workflow and improve comments

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

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-06 11:58:13 -07:00
Copilot
7a8b6e4465 Fixes #4167. Add Accepted event to View (#4452)
* Initial plan

* Add Accepted event to View and remove duplicate implementations

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

* Update RaiseAccepting to call RaiseAccepted and add comprehensive tests

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

* Fix code style violations - use explicit types and target-typed new

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

---------

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>
2025-12-06 09:36:32 -07:00
BDisp
5e3175cd9d Fixes #4449. Regression in IsLegacyConsole mode where dirty cells are not handled correctly (#4451)
* Fixes #4449. Regression in IsLegacyConsole mode where dirty cells are not handled correctly

* Cursor position is always set in the beginning a new row or on non-dirty flags
2025-12-06 09:09:52 -07:00
Tig
d303943809 Fixes #4004 & #4445 - Merge of Application.ForceDriver and Driver.Force16Colors and windows" broken in conhost and cmd (#4448)
* Fixes #4004. Driver "windows" broken in conhost and cmd

* Fix unit tests

* Remove IsVirtualTerminal from IApplication. Add IDriverInternal and IOutputInternal interfaces

* Fix result.IsSupported

* Remove internal interfaces and add them in the implementations classes

* Move Sixel from IApplication to IDriver interface it's a characteristic of the driver

* Only if IOutput is OutputBase then set the internal properties

* Prevents driver windows error on Unix system

* Fix scenario sixel error

* Comment some tests because is keyboard layout dependent and shifted key is needed to produce them (Pt)

* Add 🇵🇹 regional indicators test proving they ca be joined as only one grapheme

* SetConsoleActiveScreenBuffer is already called by the constructor and is only needed once

* Finally fixed non virtual terminal in windows driver

* Add more Sixel unit tests

* Add unit tests for OutputBase class

* Avoid emit escape sequence

* Fix assertion failure in UICatalog

* Let each driver to deal with the Sixel write

* When Shutdown is called by the static Application then the ApplicationImpl.ResetStateStatic should be also called

* Add more OutputBase with Sixel unit tests

* Fix some issues with IsVirtualTerminal and Force16Colors with unit tests improvement

* Add Sixel Detect method unit test

* Make Sixel IsSupported and SupportsTransparency consistent with more unit tests

* Fix namespaces and unit test

* Covering more ApplicationImpl Sixel unit test

* Remove DriverImplProxy because sometimes fails in parallel unit tests

* Fix Init_KeyBindings_Are_Not_Reset unit test failing

* Revert "Fix Init_KeyBindings_Are_Not_Reset unit test failing"

This reverts commit 0ab298bc56.

* Fix Force16Colors but still use Application.Force16Colors because of CM

* Enforce conditional

* Revert change

* Moving to a new file

* Add the same workaround as the All_Scenarios_Benchmark unit test

* Fixes #4440. TextView with ReadOnly as true, MoveRight doesn't select text up to the end of the line

* Fixes #4442. TextField PositionCursor doesn't treat zero width as one column

* Each character must return at least one column, with the exception of Tab.

* Add unit test for the ScrollOffset

* Each character must return at least one column, with the exception of Tab.

* Add unit test for the LeftColumn

* WIP

* Refactor DriverImpl and OutputBase for maintainability

Refactored `DriverImpl` to remove `IDisposable` and streamline event
handling, including replacing `OnSizeMonitorOnSizeChanged` with an
inline lambda. Reintroduced `SizeChanged` and updated `SetScreenSize`
to invoke it. Moved `SupportsTrueColor` from `OutputBase` to
`DriverImpl` and reintroduced `Force16Colors` with updated logic.

Reintroduced and updated several `OutputBuffer`-related properties
and methods in `DriverImpl`, including `Screen`, `Clip`, `Cols`, and
`Contents`. Moved `Clipboard` from `OutputBase` to `DriverImpl` and
initialized it with `FakeClipboard`. Simplified `Refresh` and `ToAnsi`
methods in `DriverImpl`.

Removed `Force16Colors` from `OutputBase` and simplified method
signatures, including `ToAnsi` and `BuildAnsiForRegion`. Fixed a
parameter name typo in `AppendOrWriteAttribute`. Made minor code
formatting adjustments.

These changes improve code maintainability, reduce redundancy, and
align the implementation with updated design requirements.

* Refactor Force16Colors handling and improve UICatalog

Refactored the `Force16Colors` property:
- Moved it from `DriverImpl` to `IOutput` and `OutputBase`.
- Simplified its management by removing redundant logic.
- Added `OnDriverOnForce16ColorsChanged` to handle updates.

Updated `UICatalogRunnable`:
- Replaced `Driver.Force16Colors` with `Application.Driver.Force16Colors`.
- Added an `F7` shortcut to toggle `Force16Colors`.
- Removed redundant event handlers and improved formatting.

Updated `config.json`:
- Replaced `Application.Force16Colors` with `Driver.Force16Colors`.
- Improved theme configuration formatting for readability.

Other changes:
- Removed the `force16Colors` parameter from `IOutput.ToAnsi`.
- Improved diagnostics handling in `UICatalogRunnable`.
- General code cleanup for readability and maintainability.

* Refactor `Force16Colors` access and improve null safety

Refactored `Force16Colors` property access to use `Application.Driver!`
for null safety and consistency. Updated event handlers to align with
this pattern. Replaced nullable `DrawContext?` parameters with
non-nullable `DrawContext` in `OnDrawingContent` overrides across
multiple classes to enforce stricter nullability checks.

Removed unused `_cachedCursorVisibility` field in `OutputBase.cs` and
cleaned up commented-out legacy code in `UICatalogRunnable.cs`. Updated
XML documentation to reflect method signature changes and property
references. Refactored `Shortcut` example in documentation for
consistency.

Replaced `Application.LayoutAndDraw` with `SetNeedsDraw` for marking
views as needing redraw. Performed general code cleanup to remove
redundant code and improve consistency.

* Refactor ForceDriver and Force16Colors properties

Removed `[Obsolete]` from `Application.ForceDriver`, making it a stable API. Added comments to clarify its role as a configuration property and its synchronization with `IApplication.ForceDriver`. Introduced `_forceDriver` as a private backing field.

Removed `Force16Colors` from `ApplicationImpl` and eliminated reset logic for `ForceDriver` and `Force16Colors` during shutdown, shifting state management responsibility to the library user.

Updated comments in `Driver.cs` to document `Force16Colors` as a configuration property and its synchronization with `IDriver.Force16Colors`. Retained `_force16Colors` as a private backing field for configuration overrides.

* Updated docs

* There is no way to detect Sixel transparency and so relying in VTS or Xterm with transparency

* Fix detect Sixel unit tests with the adjusting code

* Refactored Output.

* MErging

* - Added `OnDriverOnForce16ColorsChanged` method to handle `Driver.Force16ColorsChanged` events and update the `Force16Colors` property.

- Implemented `IDisposable` to ensure proper cleanup of resources, including unsubscribing from `SizeMonitor.SizeChanged` and `Driver.Force16ColorsChanged` events, and disposing of `_output`.
- Replaced inline `SizeMonitor.SizeChanged` event handler with a dedicated method, `OnSizeMonitorOnSizeChanged`, for better readability and maintainability.

- Simplified the `Screen` property by removing commented-out code and directly returning a `Rectangle` based on `OutputBuffer` dimensions.
- Updated the `Force16Colors` property to use `_output` for both getting and setting its value.
- Performed general cleanup, including removing unused code and improving code structure.

* merged

* Refactor Sixel handling with ConcurrentQueue

Replaced `List<SixelToRender>` with `ConcurrentQueue<SixelToRender>`
to improve thread safety and performance in sixel management.
Updated the `Images` class to avoid unnecessary removal and
re-creation of sixel objects by updating existing ones in place.

Refactored `Application.Sixel` to return a `ConcurrentQueue` and
introduced `GetSixels` in `IDriver` and `IOutput` for consistent
access. Updated `OutputBase` to use a private `ConcurrentQueue`
and adjusted rendering logic accordingly.

Removed legacy and redundant code, including `Application.Driver?.Sixel.Clear()`
and unused properties in `DriverImpl` and `ApplicationImpl`. Updated
tests in `OutputBaseTests` to align with the new implementation.

Added `using System.Collections.Concurrent` where necessary and
improved documentation to reflect the changes. These updates
enhance thread safety, simplify the codebase, and align with
modern concurrent programming practices.

* Tweak

* Refactor DriverImpl to use Dispose and improve modularity

Replaced `Driver.End()` with `Driver.Dispose()` across the codebase, aligning with the `IDisposable` pattern for proper resource cleanup. Updated `DriverImpl` to implement `Dispose`, ensuring event unsubscriptions and resource disposal.

Enhanced `DriverImpl` structure by organizing code into logical regions, improving modularity and readability. Refactored and reintroduced methods and properties like `Clipboard`, `Screen`, `SetScreenSize`, `Cols`, `Rows`, and others for better encapsulation.

Updated the `IDriver` interface to include `IDisposable` and reorganized it into regions. Added new methods and properties such as `Init`, `Refresh`, `Suspend`, `QueueAnsiRequest`, and `ToAnsi`.

Refactored unit tests to replace `driver.End()` with `driver.Dispose()` and ensured proper resource cleanup. Improved code comments and documentation for better clarity.

Aligned with modern C# practices, adopting features like null-coalescing operators and pattern matching. Removed redundant code, addressed some TODOs, and modularized the codebase for maintainability and extensibility.

* Refactor driver docs and update View.Driver usage

Updated `application.md` to clarify the purpose of the `View.Driver` property, replacing the obsolete `Application.Driver`. Added a reference to the "Drivers Deep Dive" documentation for further details.

Refactored the `OnDrawContent` method to use the `Driver` property, ensuring compatibility with the new driver architecture.

Added a new section, "Testing with the New Architecture," to `application.md`, highlighting the improved testability of the instance-based architecture.

Expanded and reorganized `drivers.md` to provide a detailed breakdown of the `IDriver` interface, including lifecycle, components, screen and display, color support, content buffer, drawing, cursor, input events, and ANSI escape sequences. Introduced new subsections for clarity and emphasized the modular design for maintainability.

Added a note in `drivers.md` discouraging direct access to the `Driver` and recommending higher-level abstractions like `Terminal.Gui.App.Application.Screen` and `Terminal.Gui.ViewBase.View` methods for positioning and drawing.

* Refactor IsVirtualTerminal to IsLegacyConsole

Replaced the `IsVirtualTerminal` property with `IsLegacyConsole` across the codebase to better represent legacy versus modern terminal environments. Updated logic in `SixelSupportDetector`, `DriverImpl`, and `OutputBase` to use the new property.

Refactored tests to align with the updated property, including renaming test methods, adjusting mock setups, and replacing `VirtualTerminalTests` with `LegacyConsoleTests`.

Simplified `WindowsOutput` implementation to handle console modes and sixel rendering based on `IsLegacyConsole`. Removed redundant code related to `IsVirtualTerminal`.

Improved code readability and maintainability by using more descriptive property names and ensuring consistency across the codebase. Updated `.DotSettings` with new entries.

* Update Examples/UICatalog/Scenarios/LineDrawing.cs

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

* Update Examples/UICatalog/Scenarios/Images.cs

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

* Update Examples/UICatalog/Scenarios/Images.cs

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

* Update Terminal.Gui/App/IApplication.cs

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

* Update Terminal.Gui/App/ApplicationImpl.Lifecycle.cs

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

* Update Examples/UICatalog/Scenarios/ColorPicker.cs

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

* Update Examples/UICatalog/Scenarios/ColorPicker.cs

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

* Fix formatting and typo in code and documentation

Improved code readability in `LineDrawing.cs` by fixing spacing
around the ternary operator in `Width` and `Y` property assignments.
Corrected a typo in `drivers.md` by changing "Configuraiton Manager"
to "Configuration Manager" for accurate documentation.

* Test failure casued by assert left in by accident.

* Added a workaround in `OutputBase.cs` to address dirty cell handling in legacy console mode by marking all buffer cells as dirty.

Refactored `_disableMouseCb` event handling in `UICatalogRunnable.cs` to use the `Selecting` event for toggling `Application.IsMouseDisabled`. Simplified `MouseImpl.cs` by converting `App` to an auto-implemented property and removing redundant namespace usage.

Streamlined logging in `WindowsOutput.cs` by replacing verbose `Logging.Logger` calls with shorter alternatives (`Logging.Information`, `Logging.Error`, etc.).

* Update theme and remove unused ListView component

The application's default theme configuration was updated from "Light" to "Amber Phosphor" by modifying the `ConfigurationManager.RuntimeConfig` value.

Additionally, the `ListView` component in the `ExampleWindow` class was removed. This included its initialization, layout properties (`Y`, `Height`, `Width`), and its data source (["One", "Two", "Three", "Four"]).

* Increase safety timeout in NestedRunTimeoutTests to 10s

The timeout duration for the safety mechanism in the
`NestedRunTimeoutTests` class was increased from 5000ms (5s)
to 10000ms (10s). This change allows the app more time to
complete before triggering the safety timeout, reducing the
likelihood of premature termination during long-running tests.

Refactor and enhance test coverage

Refactored `Load_WithInvalidJson_AddsJsonError` test in `SourcesManagerTests.cs` to improve organization and added a note about its impact on parallel execution. Increased the safety timeout in `NestedRunTimeoutTests.cs` from 5 seconds to 10 seconds to address potential premature test timeouts.

* Handle null Driver gracefully in event subscription

Replaced `ArgumentNullException.ThrowIfNull(Driver)` with a null-check conditional in `SubscribeDriverEvents` and `UnsubscribeDriverEvents`. If `Driver` is `null`, the methods now log an error using `Logging.Error` and return early. This prevents potential exceptions and improves error handling.

---------

Co-authored-by: BDisp <bd.bdisp@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-05 17:40:48 -07:00
Tig
f0343e4c3c Merge pull request #4439 from tig/v2_4431-MainLoop 2025-12-04 18:50:19 -07:00
BDisp
241aec0e3d Fixes #4442. TextField PositionCursor doesn't treat zero width as one column (#4443)
* Fixes #4442. TextField PositionCursor doesn't treat zero width as one column

* Each character must return at least one column, with the exception of Tab.

* Add unit test for the ScrollOffset
2025-12-04 17:12:52 -07:00
BDisp
06767193fb Fixes #4440. TextView with ReadOnly as true, MoveRight doesn't select text up to the end of the line (#4441)
* Fixes #4440. TextView with ReadOnly as true, MoveRight doesn't select text up to the end of the line

* Each character must return at least one column, with the exception of Tab.

* Add unit test for the LeftColumn
2025-12-04 17:11:59 -07:00
Tig
32fbcdd7ad Merge branch 'v2_develop' into v2_4431-MainLoop 2025-12-04 17:10:46 -07:00
Tig
25223ce7ec Update Examples/UICatalog/UICatalogRunnable.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-04 17:08:44 -07:00
Tig
b4719e1809 Update Terminal.Gui/ViewBase/View.Drawing.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-04 17:08:18 -07:00
Tig
491229b446 Update Examples/UICatalog/Scenarios/Transparent.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-04 17:07:46 -07:00
Tig
c8fafbcb1a Update Terminal.Gui/ViewBase/View.NeedsDraw.cs
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-04 17:06:31 -07:00
Tig
063a6d7e98 Fixes #945 - Adds simple PowerShell example (#4438)
* pre-alpha -> alpha

* don't build docs for v2_release

* Pulled from v2_release

* Refactor migration guide for Terminal.Gui v2

Restructured and expanded the migration guide to provide a comprehensive resource for transitioning from Terminal.Gui v1 to v2. Key updates include:

- Added a Table of Contents for easier navigation.
- Summarized major architectural changes in v2, including the instance-based application model, IRunnable architecture, and 24-bit TrueColor support.
- Updated examples to reflect new patterns, such as initializers replacing constructors and explicit disposal using `IDisposable`.
- Documented changes to the layout system, including the removal of `Absolute`/`Computed` styles and the introduction of `Viewport`.
- Standardized event patterns to use `object sender, EventArgs args`.
- Detailed updates to the Keyboard, Mouse, and Navigation APIs, including configurable key bindings and viewport-relative mouse coordinates.
- Replaced legacy components like `ScrollView` and `ContextMenu` with built-in scrolling and `PopoverMenu`.
- Clarified disposal rules and introduced best practices for resource management.
- Provided a complete migration example and a summary of breaking changes.

This update aims to simplify the migration process by addressing breaking changes, introducing new features, and aligning with modern .NET conventions.

* Updated runnable

* Add Terminal.Gui integration in PowerShell script

Integrated Terminal.Gui into a PowerShell script by:
- Adding necessary `using namespace` statements.
- Loading DLLs dynamically from a specified `$dllFolder`.
- Creating a Terminal.Gui application with a window and label.
- Providing instructions for building and preparing dependencies.
- Ensuring proper disposal of application resources.
2025-12-04 17:02:58 -07:00
Tig
d85edc94b0 code cleanup 2025-12-04 16:58:20 -07:00
Tig
59714dd111 Code cleanpu 2025-12-04 16:57:14 -07:00
Tig
735be20b26 Merge branch 'v2_4431-MainLoop' of tig:tig/Terminal.Gui into v2_4431-MainLoop 2025-12-04 16:53:40 -07:00
Tig
ec05d9d3f0 Merge branch 'v2_develop' into v2_4431-MainLoop 2025-12-04 16:53:16 -07:00
Tig
ce15aa2d0f Updated OnDrawingContent methods across multiple classes to use non-nullable DrawContext parameters, improving type safety.
Refactored `IDriver` interface:
- Updated `SetScreenSize` to remove `NotSupportedException`.
- Clarified `Refresh` method as internal and updated documentation for `SizeChanged` event.
2025-12-04 16:53:03 -07:00
Tig
b061aacf18 Simplify the Screen property in ApplicationImpl by removing the _screen field and its locking mechanism. The getter now directly retrieves the screen size from the Driver or defaults to 2048x2048. The setter now calls Driver?.SetScreenSize to update the screen size, eliminating the need for the ResetScreen method.
Update `RaiseScreenChangedEvent` to no longer explicitly set the `Screen` property. Remove unnecessary `.ToArray()` conversion in `View.Draw`.

Clarify `Screen` property documentation in `IApplication` to specify constraints on location and size. Update tests to reflect the new behavior where setting the `Screen` property raises the `ScreenChanged` event. Rename and adjust test cases accordingly.
2025-12-04 16:42:51 -07:00
Tig
4738e8535a Optimize screen handling and drawing logic
Added a thread-safe lock mechanism (`_lockScreen`) to ensure safe updates to the `_screen` field, enabling future support for changing the `Driver` based on screen values.

Improved the `ResetScreen` method documentation to clarify its purpose.

Optimized the `LayoutAndDraw` method by:
- Adding a layout step to adjust views based on screen size.
- Reducing unnecessary redraws by selectively updating views that require it.
- Ensuring the terminal driver flushes updates with `Driver?.Refresh()`.

Removed redundant logging to streamline the code.
2025-12-04 16:32:24 -07:00
Tig
ca67dc0472 Updated the Transparent scenario to better demonstrate transparency features, including dynamic resizing, custom drawing, and improved clarity in the TransparentView class. Added new methods to support non-rectangular drawn regions and transparency effects.
Enhanced the `DrawContext` and `View` classes with detailed documentation and examples for implementing transparency. Improved the `OnDrawingContent` method and `DrawingContent` event to support reporting drawn regions for transparency.

Performed general code cleanup, including removing unused code, simplifying `ViewportSettings` usage, and improving property initialization. Minor namespace cleanup was also included.
2025-12-04 16:23:19 -07:00
Tig
e192b5622d Updated the OnDrawingContent method across multiple classes to accept a DrawContext? context parameter, replacing the parameterless version. This change standardizes the drawing API and enables context-aware drawing operations.
The refactor includes:
- Modifying method signatures in classes like `AnimationScenario`, `Images`, `DrawingArea`, `AttributeView`, `Snake`, and others.
- Removing the parameterless `OnDrawingContent` method from the `View` class.
- Updating calls to the base class implementation to pass the `context` parameter.
- Adjusting comments and documentation to reflect the new method signature.

This change ensures consistency and prepares the codebase for more advanced drawing capabilities.
2025-12-04 14:48:02 -07:00
Tig
3a8de25dce Refactored NeedsDraw and SubViewNeedsDraw logic to improve clarity and control over redraw state. Introduced SetSubViewNeedsDrawDownHierarchy for better propagation of redraw flags. Updated Margin and Adornment classes to align with the new redraw management.
Enhanced `View` class drawing logic to ensure proper ordering of margin and subview rendering, and introduced `DoDrawContent` for encapsulated content drawing. Improved comments and documentation for better maintainability.

Updated tests to reflect the new redraw management methods. Made minor formatting changes and removed redundant code for consistency and readability.
2025-12-04 14:41:25 -07:00
Tig
96151201f6 Fix SubViewNeedsDraw handling and improve test coverage
Refactored `View` class to ensure `SuperView.SubViewNeedsDraw`
is managed correctly. Added logic to prevent clearing the flag
prematurely when sibling subviews still require drawing.

Introduced a new `SubViewNeedsDraw` property with a private
setter and added `TODO` comments for potential future
improvements, such as making it a computed property.

Updated and added tests in `NeedsDrawTests` and `StaticDrawTests`
to validate the corrected behavior and prevent regressions.
Re-enabled a previously skipped test after fixing the related bug.
2025-12-04 12:36:54 -07:00
Tig
193a5873d1 Fixes bugs where unnecessary Draw operations were happening in LayoutAndDraw. In some cases causing everything to always be drawn.
Refactored `NeedsDraw` logic into a modular implementation in `View.NeedsDraw.cs`, introducing methods to manage drawing states more effectively. Updated `Menus.cs` event handlers to include null checks for robustness. Improved margin drawing logic in `Margin.cs` with better performance and debugging assertions.

Added comprehensive unit tests in `NeedsDrawTests.cs` and `StaticDrawTests.cs` to validate the new drawing logic, including edge cases and static `View.Draw` behavior. Removed redundant tests from `ViewDrawingFlowTests.cs`.

Refactored diagnostic flags handling in `UICatalogRunnable.cs` for clarity. Performed general code cleanup, leveraging modern C# features and improving maintainability.
2025-12-04 12:20:44 -07:00
Tig
bad2f02697 Merge pull request #4436 from gui-cs/copilot/fix-intermediate-heap-allocations 2025-12-04 06:48:10 -07:00
copilot-swe-agent[bot]
2da9a18466 Remove analysis documentation files
Removed 5 analysis .md files from repository root:
- ALLOCATION_CALL_FLOW.md
- ALLOCATION_DOCS_README.md
- ALLOCATION_INVESTIGATION_SUMMARY.md
- HEAP_ALLOCATION_ANALYSIS.md
- OPTIMIZATION_RECOMMENDATIONS.md

These were temporary analysis documents used during investigation.
The key findings and optimizations are captured in the PR description.

Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-04 02:41:33 +00:00
Tig
6a334bbf2e Optimize drawing logic and refine NeedsDraw handling
Improved the drawing system by adding conditions to check `Border.NeedsDraw` and `Padding.NeedsDraw` before drawing their subviews, reducing unnecessary operations. Commented out a brute-force `SetNeedsDraw` call for certain views to enhance performance.

Updated the logic for clearing `SubViewNeedsDraw` in `SuperView` to ensure it is only cleared when appropriate, preventing potential issues in the draw system. Marked the test `ClearNeedsDraw_WithSiblings_DoesNotClearSuperViewSubViewNeedsDraw` as skipped, as it is no longer valid due to these changes.
2025-12-03 18:02:07 -07:00
Tig
641a0a599c Optimize View drawing logic and update ClearViewport tests
Refactored the `View` class to include a `NeedsDraw` check in
multiple drawing methods, improving rendering efficiency.
Adjusted `OnDrewText` and `DrewText` event handling for
consistency. Removed unused code and redundant tests.

Rewrote and reorganized `ClearViewportTests` for clarity and
compatibility with the new `NeedsDraw` logic. Added new tests
to validate `ClearViewport` behavior under various conditions,
including transparent viewports, event cancellations, and
content-only clearing.

Updated namespaces for better alignment, disabled a noisy
`ComboBoxTests` test, and improved code formatting and
maintainability across files.
2025-12-03 16:30:22 -07:00
Tig
6049857813 Refactor LayoutAndDraw and fix ClearNeedsDraw bugs
Refactored the `LayoutAndDraw` method in `ApplicationImpl.Screen.cs` to improve clarity, naming consistency, and redraw logic. Enhanced handling of the `Driver` object to optimize redraws.

Simplified `IterationImpl` in `ApplicationMainLoop.cs` by commenting out redundant checks. Fixed a bug in `SetCursor` to ensure null safety and improve cursor positioning logic.

Modified `ClearNeedsDraw` in `View.Drawing.cs` to prevent premature clearing of the `SuperView`'s `SubViewNeedsDraw` flag. Added explanatory comments to clarify the behavior.

Introduced new unit tests in `NeedsDrawTests.cs` to verify the correctness of `ClearNeedsDraw`:
- Ensured sibling views do not prematurely clear `SuperView`'s flags.
- Verified proper clearing of flags for views, adornments, and descendants.

Improved test coverage and added detailed comments to document expected behavior.
2025-12-03 15:57:27 -07:00
Tig
d7bcc8c70c Simplify redraw logic and improve output handling
Refactor redraw logic by removing `needsDrawOrLayout` checks and
the `AnySubViewsNeedDrawn` method in `ApplicationMainLoop.cs`.
Always call `App?.LayoutAndDraw(forceRedraw: false)` to simplify
layout and drawing behavior.

Add redraw logging in `ApplicationImpl.Screen.cs` to track redraw
events consistently.

Update `DriverImpl.cs` to always write the `OutputBuffer` during
`Refresh`, ensuring output is consistently handled.
2025-12-03 14:38:57 -07:00
Tig
7e05f204c2 Fix cursor flickering and improve cursor handling
Refactored `OutputBase.Write()` to eliminate cursor flickering by removing the save/restore pattern for cursor visibility. Cursor visibility is now managed solely by `ApplicationMainLoop.SetCursor()`.

Introduced the distinction between the "Draw Cursor" (internal drawing position) and the "Terminal Cursor" (visible input indicator). This resolves issues caused by conflating these concepts in the original design.

Updated `cursor.md` to document the new design, clarify terminology, and emphasize the separation of concerns between drawing operations and cursor positioning.

Resolved issue #3444 (cursor flickering during `TableView` scrolling) and improved the efficiency of `View.PositionCursor()` by proposing caching strategies.

Improved documentation and ensured consistent, intentional cursor visibility and positioning throughout the library.
2025-12-03 14:30:26 -07:00
Tig
77e4d7749c removes force redraw on sizemonitor.poll changes; not needed. 2025-12-03 13:56:46 -07:00
Tig
83a8225dd1 Removes un-needed cursor call from mainloop iteration 2025-12-03 13:52:30 -07:00
copilot-swe-agent[bot]
d425e4edbf Fix TextFormatter.GetDrawRegion per-line allocations using ArrayPool
Applied ArrayPool pattern to GetDrawRegion method:
- Use ArrayPool<string>.Shared.Rent() instead of .ToArray() for grapheme arrays
- Track actual grapheme count separately from rented array length
- Return array to pool in finally block for guaranteed cleanup
- Handle rare case where array needs to grow during enumeration

Impact: Eliminates allocations on layout calculations
- GetDrawRegion called before drawing for text region calculations
- Same allocation pattern as Draw() which was already fixed
- Complements the Draw() optimization for complete text rendering pipeline

All unit tests pass (12,055 parallelizable + 1,173 non-parallel)

Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-03 20:46:45 +00:00
copilot-swe-agent[bot]
12756a29d8 Fix Cell.Grapheme validation allocation by adding GetGraphemeCount
Added allocation-free grapheme counting to GraphemeHelper:
- New GetGraphemeCount() method counts graphemes without materializing array
- Uses TextElementEnumerator directly, avoiding .ToArray() allocation
- Updated Cell.Grapheme setter to use GetGraphemeCount() instead of .ToArray().Length

Impact: Eliminates allocation on every Cell.Grapheme property set
- Validation now happens without intermediate array allocation
- Particularly beneficial for cell-based operations and grid rendering

All unit tests pass (12,055 parallelizable + 1,173 non-parallel)

Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-03 20:24:24 +00:00
copilot-swe-agent[bot]
9feac09e13 Fix TextFormatter.Draw per-line allocations using ArrayPool
Applied ArrayPool pattern to eliminate grapheme array allocations:
- Use ArrayPool<string>.Shared.Rent() instead of .ToArray()
- Track actual grapheme count separately from rented array length
- Return array to pool in finally block for guaranteed cleanup
- Handle rare case where array needs to grow during enumeration

Impact: Eliminates 10-60+ allocations/second for animated content
- Progress bars: ~20-40 allocs/sec → 0
- Text-heavy UIs with frequent redraws significantly improved

All unit tests pass (12,055 parallelizable + 1,173 non-parallel)

Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-03 20:06:12 +00:00
copilot-swe-agent[bot]
a4245bd091 Fix LineCanvas.GetMap per-pixel allocations by reusing buffer
Applied the same allocation-free pattern from GetCellMap() to GetMap():
- Reuse List<IntersectionDefinition> buffer instead of LINQ .ToArray()
- Use CollectionsMarshal.AsSpan() to create ReadOnlySpan
- Eliminates 1,920+ allocations per border redraw (80x24)
- Reduces from O(pixels) allocations to 1 allocation total

All unit tests pass (12,055 parallelizable + 1,173 non-parallel)

Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-03 19:02:44 +00:00
Tig
d21163e394 Merge branch 'v2_develop' into copilot/fix-intermediate-heap-allocations 2025-12-03 11:53:52 -07:00
copilot-swe-agent[bot]
7575a28bd6 Add navigation guide for allocation investigation documents
Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-03 18:24:20 +00:00
copilot-swe-agent[bot]
f858924256 Add executive summary of heap allocation investigation
Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-03 18:22:50 +00:00
copilot-swe-agent[bot]
180e027706 Add detailed allocation flow analysis and optimization recommendations
Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-03 18:21:18 +00:00
copilot-swe-agent[bot]
e6e81781cb Add comprehensive heap allocation analysis document
Co-authored-by: tig <585482+tig@users.noreply.github.com>
2025-12-03 18:18:07 +00:00
Tig
60106dbf71 Merge branch 'v2_develop' of tig:tig/Terminal.Gui into v2_develop 2025-12-03 11:09:19 -07:00