Files
Terminal.Gui/docfx/docs/newinv2.md
Tig a84b2c4896 Fixes #4419, #4148, #4408 - Toplevel is GONE - Replaced by Runnable (#4422)
* WIP: Broken

* Got working. Mostly.

* Parllel tests pass

* More progres

* Fixed app tests.

* Mouse

* more progress.

* working on shortcut

* Shortcut accept on ENTER is broken.

* One left...

* More test progress.

* All unit tests pass. Still some issues though.

* tweak

* Fixed Integration Tests

* Fixed UI Catalog

* Tweaking CP to try to find race condition

* Refactor StandardColors and improve ColorPicker logic

Refactored `StandardColors` to use lazy initialization for static fields, improving performance and avoiding static constructor convoy effects. Introduced `NamesValueFactory` and `MapValueFactory` methods for encapsulated initialization logic.

Simplified `GetColorNames` to directly return `_names.Value`. Improved `TryParseColor` by clarifying default value usage and adopting object initializer syntax. Updated `TryNameColor` to use `_argbNameMap.Value`.

Refactored `GetArgb` for better readability. Replaced `MultiStandardColorNameResolver` with `StandardColorsNameResolver` in `ColorPicker`. Commented out `app.Init("Fake")` in `ColorPickerTests` for testing purposes.

Made minor formatting improvements, including updated comments and XML documentation for consistency.

* revert

* Throttle input loop to prevent CPU spinning

Introduce a 20ms delay in the input loop of `InputImpl<TInputRecord>`
to prevent excessive CPU usage when no input is available. Removed
the `DateTime dt = Now();` line and the `while (Peek())` block, which
previously enqueued input records.

This change improves resource management, especially in scenarios
where multiple `ApplicationImpl` instances are created in parallel
tests without calling `Shutdown()`. It prevents thread pool
exhaustion and ensures better performance in such cases.

* Refactor ApplicationImpl to use IDisposable pattern

Implemented the IDisposable pattern in ApplicationImpl to improve resource management. Added `Dispose` and `DisposeCore` methods, and marked the `Shutdown` method as obsolete, encouraging the use of `Dispose` or `using` statements instead. Updated the `IApplication` interface to inherit from IDisposable and added `GetResult` methods for retrieving run session results.

Refactored unit tests to adopt the new lifecycle management approach, replacing legacy `Shutdown` calls with `Dispose` or `using`. Removed fragile and obsolete tests, and re-enabled previously skipped tests after addressing underlying issues.

Updated `FakeApplicationLifecycle` and `SetupFakeApplicationAttribute` to align with the new disposal pattern. Improved documentation and examples to guide users toward modern usage patterns. Maintained backward compatibility for legacy singleton usage.

* Add IDisposable pattern with input loop throttling

- Add IDisposable to IApplication for proper resource cleanup
- Add 20ms throttle to input loop (prevents CPU spinning)
- Add Lazy<T> to StandardColors (eliminates convoy effect)
- Add MainLoopCoordinatorTests suite (5 new tests)
- Add Dispose() calls to all 16 ColorPickerTests
- Mark Application.Shutdown() as [Obsolete]

IApplication now requires Dispose() for cleanup

Performance: 100x CPU reduction, 15x faster disposal, tests complete in <5s

Fixes: Thread leaks, CPU saturation, test hangs in parallel execution
Docs: Updated application.md and newinv2.md with disposal patterns

* Refactor test for input loop throttling clarity

Updated `InputLoop_Throttle_Limits_Poll_Rate` test to improve clarity, reliability, and efficiency:
- Rewrote summary comment to clarify purpose and emphasize the 20ms throttle's role in preventing CPU spinning.
- Replaced `var` with explicit types for better readability.
- Reduced test duration from 1s to 500ms to improve test speed.
- Revised assertions:
  - Replaced range-based assertion with upper-bound check to ensure poll count is below 500, avoiding timing sensitivity issues.
  - Added assertion to verify the thread ran and was not immediately canceled.
- Added a 2-second timeout to `inputTask.Wait` and verified task completion.
- Improved comments to explain test behavior and reasoning behind changes.

* tweaks

* Fix nullabiltiy stuff.

* runnable fixes

* more nullabe

* More nullability

* warnings gone

* Fixed fluent test failure.

* Refactor ApplicationImpl and update Runnable layout logic

Refactored `ApplicationImpl.Run.cs` for improved readability and
atomicity:
- Combined `if (wasModal)` with `SessionStack?.TryPop` to streamline
  logic.
- Simplified restoration of `previousRunnable` by reducing nesting.
- Updated comments for clarity and retained `SetIsModal` call.

Simplified focus-setting logic in `ApplicationImpl.Run.cs` using
pattern matching for `TopRunnableView`.

In `Runnable<TResult>`, added `SetNeedsLayout` after `IsModalChanged`
to ensure layout updates. Removed an unused empty line for cleanup.

Corrected namespace in `GetViewsUnderLocationForRootTests.cs` to
align with test structure.

* Update layout on modal state change

A call to `SetNeedsLayout()` was added to the `OnIsModalChanged`
method in the `Runnable` class. This ensures that the layout
is updated whenever the modal state changes.

* Increase test timeout for inputTask.Wait to 10 seconds

Extended the timeout duration for the `inputTask.Wait` method
from 4 seconds to 10 seconds in `MainLoopCoordinatorTests`.
This change ensures the test has a longer window to complete
under conditions of increased load or slower execution
environments, reducing the likelihood of false test failures.

* Refactor project files and simplify test logic

Removed `<LangVersion>` and `<ImplicitUsings>` properties from
`UnitTests.csproj` and `UnitTests.Parallelizable.csproj` to rely
on default SDK settings and disable implicit global usings.

Simplified the `SizeChanged_Event_Still_Fires_For_Compatibility`
test in `FakeDriverTests` by removing the `screenChangedFired`
variable, its associated event handler, and related assertions.
Also removed obsolete warning suppression directives as they
are no longer needed.

* Reduce UnitTestsParallelizable iterations from 10 to 3

Reduced the number of iterations for the UnitTestsParallelizable
test suite from 10 to 3 to save time and resources while still
exposing concurrency issues. Updated the loop and log messages
to reflect the new iteration count.

* disabled InputLoop_Throttle_Limits_Poll_Rate

* Refactor app lifecycle and improve Runnable API

Refactored `Program.cs` to simplify application lifecycle:
- Modularized app creation, initialization, and disposal.
- Improved result handling and ensured proper resource cleanup.

Re-implemented `Runnable<TResult>` with a cleaner design:
- Retained functionality while improving readability and structure.
- Added XML documentation and followed the Cancellable Work Pattern.

Re-implemented `RunnableWrapper<TView, TResult>`:
- Enabled wrapping any `View` to make it runnable with typed results.
- Added examples and remarks for better developer guidance.

Re-implemented `ViewRunnableExtensions`:
- Provided fluent API for making views runnable with or without results.
- Enhanced documentation with examples for common use cases.

General improvements:
- Enhanced code readability, maintainability, and error handling.
- Replaced redundant code with cleaner, more maintainable versions.

* Modernize codebase for Terminal.Gui and MVVM updates

Refactored `LoginView` to remove redundant `Application.LayoutAndDraw()`
call. Enhanced `LoginViewModel` with new observable properties for
automatic property change notifications. Updated `Message` class to use
nullable generics for improved type safety.

Replaced legacy `Application.Init()` and `Application.Run()` calls with
the modern `IApplication` API across `Program.cs`, `Example.cs`, and
`ReactiveExample`. Ensured proper disposal of `IApplication` instances
to prevent resource leaks.

Updated `TerminalScheduler` to integrate with `IApplication` for
invoking actions and managing timeouts. Added null checks and improved
timeout disposal logic for robustness.

Refactored `ExampleWindow` for better readability and alignment with
modern `Terminal.Gui` conventions. Cleaned up unused imports and
improved code clarity across the codebase.

Updated README.md to reflect the latest `Terminal.Gui` practices,
including examples of the `IApplication` API and automatic UI refresh
handling. Renamed `LoginAction` to `LoginActions` for consistency.

* Refactor: Transition to IRunnable-based architecture

Replaced `Toplevel` with `Window` as the primary top-level UI element. Introduced the `IRunnable` interface to modernize the architecture, enabling greater flexibility and testability. Deprecated the static `Application` class in favor of the instance-based `IApplication` model, which supports multiple application contexts.

Updated methods like `Application.Run()` and `Application.RequestStop()` to use `IRunnable`. Removed or replaced legacy `Modal` properties with `IsModal`. Enhanced the `IApplication` interface with a fluent API, including methods like `Run<TRunnable>()` and `GetResult<T>()`.

Refactored tests and examples to align with the new architecture. Updated documentation to reflect the instance-based model. Deprecated obsolete members and methods, including `Application.Current` and `Application.TopRunnable`.

Improved event handling by replacing the `Accept` event with `Accepting` and using `e.Handled` for event processing. Updated threading examples to use `App?.Invoke()` or `app.Invoke()` for UI updates. Cleaned up redundant code and redefined modal behavior for better consistency.

These changes modernize the `Terminal.Gui` library, improving clarity, usability, and maintainability while ensuring backward compatibility where possible.

* Refactor: Replace Toplevel with Runnable class

This commit introduces a major architectural update to the `Terminal.Gui` library, replacing the legacy `Toplevel` class with the new `Runnable` class. The changes span the entire codebase, including core functionality, tests, documentation, and configuration files.

- **Core Class Replacement**:
  - Replaced `Toplevel` with `Runnable` as the base class for modal views and session management.
  - Updated all references to `Toplevel` in the codebase, including constructors, methods, and properties.

- **Configuration Updates**:
  - Updated `tui-config-schema.json` to reflect the new `Runnable` scheme.

- **New Classes**:
  - Added `UICatalogRunnable` for managing the UI Catalog application.
  - Introduced `Runnable<TResult>` as a generic base class for blocking sessions with result handling.

- **Documentation and Tests**:
  - Updated documentation to emphasize `Runnable` and mark `Toplevel` as obsolete.
  - Refactored test cases to use `Runnable` and ensure compatibility.

- **Behavioral Improvements**:
  - Enhanced lifecycle management and alignment with the `IRunnable` interface.
  - Improved clarity and consistency in naming conventions.

These changes modernize the library, improve flexibility, and provide a clearer architecture for developers.

* Refactor: Consolidate Runnable classes and decouple View from ApplicationImpl

- Made Runnable<TResult> inherit from Runnable (eliminating ~180 LOC duplication)
- Moved View init/layout/cursor logic from ApplicationImpl to Runnable lifecycle events
- ApplicationImpl.Begin now operates purely on IRunnable interface

Related to #4419

* Simplified the disposal logic in `ApplicationImpl.Run.cs` by replacing
the type-specific check for `View` with a more general check for
`IDisposable`. This ensures proper disposal of any `IDisposable`
object, improving robustness.

Removed the `FrameworkOwnedRunnable` property from the `ApplicationImpl`
class in `ApplicationImpl.cs` and the `IApplication` interface in
`IApplication.cs`. This eliminates the need to manage this property,
reducing complexity and improving maintainability.

Updated `application.md` to reflect the removal of the
`FrameworkOwnedRunnable` property, ensuring the documentation aligns
with the updated codebase.

* Replaces the legacy `Shutdown()` method with `Dispose()` to align
with the `IDisposable` pattern, ensuring proper resource cleanup
and simplifying the API. The `Dispose()` method is now the
recommended way to release resources, with `using` statements
encouraged for automatic disposal.

Key changes:
- Marked `Shutdown()` as obsolete; it now internally calls `Dispose()`.
- Updated the fluent API to remove `Shutdown()` from chaining.
- Enhanced session lifecycle management for thread safety.
- Updated tests to validate proper disposal and state reset.
- Improved `IRunnable` integration with automatic disposal for
  framework-created runnables.
- Maintained backward compatibility for the legacy static
  `Application` singleton.
- Refactored documentation and examples to reflect modern practices
  and emphasize `Dispose()` usage.

These changes modernize the `Terminal.Gui` lifecycle, improve
testability, and encourage alignment with .NET conventions.

* Refactor runnable app context handling in ApplicationImpl

Refactor how the application context is set for `runnable` objects
by introducing a new `SetApp` method in the `IRunnable` interface.
This replaces the previous logic of directly setting the `App`
property for `View` objects, making the process more generic and
encapsulated within `IRunnable` implementations.

Simplify `Mouse.UngrabMouse()` by removing the conditional check
and calling it unconditionally.

Make a minor formatting adjustment in the generic constraint of
`Run<TRunnable>` in `ApplicationImpl`.

Add `SetApp(IApplication app)` to the `IRunnable` interface and
implement it in the `Runnable` class to set the `App` property
to the provided application instance.

* Improve docs, tests, and modularity across the codebase

Reorganized and updated `CONTRIBUTING.md`:
- Added **Key Architecture Concepts** section and reordered the table of contents.
- Updated testing requirements to discourage legacy patterns.
- Added instructions for replicating CI workflows locally.
- Clarified PR guidelines and coding style expectations.

Enhanced `README.md` with detailed CI/CD workflow documentation.

Refactored `ColorPicker.Prompt` to use `IApplication` for improved modularity and testability.

Introduced `IApplicationScreenChangedTests` for comprehensive testing of `ScreenChanged` events and `Screen` property.

Refactored `ApplicationScreenTests` and `TextView.PromptForColors` to align with modern patterns.

Updated `Terminal.sln` to include `.github/workflows/README.md`.

Performed general cleanup:
- Removed outdated documentation links.
- Improved XML documentation and coding consistency.

* readme tweaks

* Improve thread safety, layout, and test coverage

Refactored `OutputBufferImpl.cs` to enhance thread safety by locking shared resources and adding bounds checks for columns and rows. Improved handling of wide characters and removed outdated TODO comments.

Updated `Runnable.cs` to call `SetNeedsDraw()` on modal state changes, ensuring proper layout and drawing updates. Simplified layout handling in `ApplicationImpl.Run.cs` by replacing redundant comments with a `LayoutAndDraw()` call.

Added a check in `AllViewsTester.cs` to skip creating instances of `RunnableWrapper` types with unsatisfiable generic constraints, logging a warning when encountered.

Enhanced `ListViewTests.cs` by adding explicit `app.LayoutAndDraw()` calls to validate visual output and ensure tests reflect the updated application state.

These changes improve robustness, prevent race conditions, and ensure consistent behavior across the application.

* Refactor: Rename Toplevel to Runnable and update logic

Updated the `Border` class to use `Command.Quit` instead of
`Command.QuitToplevel` in the `CloseButton.Accept` handler.

Renamed test methods in `GetViewsAtLocationTests.cs` to replace
"Toplevel" with "Runnable" for consistency. Updated `Runnable<bool>`
instances to use "topRunnable" as the `Id` property.

These changes align the codebase with updated naming conventions
and improve clarity.

* Removed `ToplevelTests` and migrated relevant test cases to
`MouseDragTests` with improved structure and coverage. Updated
tests to use `Application.Create`, `app.Begin`, and `app.End`
for better resource management and lifecycle handling.

Replaced direct event handling with `app.Mouse.RaiseMouseEvent`
to align with the application's event-handling mechanism. Added
`Runnable` objects to ensure views are properly initialized and
disposed of within the application context.

Enhanced tests to include assertions for minimum width and
height constraints during resize operations. Removed redundant
tests and streamlined logic to reduce duplication and improve
maintainability.

* Reorged Unit Test namespaces.

* more

* Refactor tests and update namespaces for consistency

Updated namespaces in `ArrangementTests.cs` and `MouseDragTests.cs` for better organization. Enhanced `ArrangementTests.cs` with additional checks for arrangement flags. Reformatted and re-added `MouseDragTests.cs` and `SchemeTests.cs` with modern C# features like nullable annotations and object initializers. Ensured no functional changes while improving code clarity and consistency.

* Fix nullability warnings in MouseDragTests.cs

Updated `app.End` calls to use the null-forgiving operator (`!`)
on `app.SessionStack` to ensure it is treated as non-null.
This change addresses potential nullability warnings and
improves code safety and clarity. Applied consistently across
all relevant test cases in the `MouseDragTests` class.
2025-12-01 12:54:21 -07:00

28 KiB

Terminal.Gui v2

This document provides an in-depth overview of the new features, improvements, and architectural changes in Terminal.Gui v2 compared to v1.

For information on how to port code from v1 to v2, see the v1 To v2 Migration Guide.

Architectural Overhaul and Design Philosophy

Terminal.Gui v2 represents a fundamental rethinking of the library's architecture, driven by the need for better maintainability, performance, and developer experience. The primary design goals in v2 include:

  • Decoupling of Concepts: In v1, many concepts like focus management, layout, and input handling were tightly coupled, leading to fragile and hard-to-predict behavior. v2 explicitly separates these concerns, resulting in a more modular and testable codebase.
  • Performance Optimization: v2 reduces overhead in rendering, event handling, and view management by streamlining internal data structures and algorithms.
  • Modern .NET Practices: The API has been updated to align with contemporary .NET conventions, such as using events with EventHandler<T> and leveraging modern C# features like target-typed new and file-scoped namespaces.
  • Accessibility and Usability: v2 places a stronger emphasis on ensuring that terminal applications are accessible, with improved keyboard navigation and visual feedback.

This architectural shift has resulted in the removal of thousands of lines of redundant or overly complex code from v1, replaced with cleaner, more focused implementations.

Instance-Based Application Architecture

See the Application Deep Dive for complete details on the new application architecture.

Terminal.Gui v2 introduces an instance-based application architecture that decouples views from global application state, dramatically improving testability and enabling multiple application contexts.

Key Changes

  • Instance-Based Pattern: The recommended pattern is to use Application.Create() to get an IApplication instance, rather than using the static Application class (which is marked obsolete but still functional for backward compatibility).
  • View.App Property: Every view now has an App property that references its IApplication context, enabling views to access application services without static dependencies.
  • Session Management: Applications manage sessions through Begin() and End() methods, with a SessionStack tracking nested sessions and Current representing the active session.
  • Improved Testability: Views can be tested in isolation by setting their App property to a mock IApplication, eliminating the need for Application.Init() in unit tests.

Example Usage

// Recommended v2 pattern (instance-based)
var app = Application.Create();
app.Init();
var top = new Runnable { Title = "My App" };
top.Add(myView);
app.Run(top);
top.Dispose();
app.Shutdown();

// Static pattern (obsolete but still works)
Application.Init();
var top = new Runnable { Title = "My App" };
top.Add(myView);
Application.Run(top);
top.Dispose();
Application.Shutdown();

Benefits

  • Testability: Views can be tested without initializing the entire application
  • Multiple Contexts: Multiple IApplication instances can coexist (useful for testing or complex scenarios)
  • Clear Ownership: Views explicitly know their application context via the App property
  • Reduced Global State: Less reliance on static singletons improves code maintainability
  • Proper Resource Management: IDisposable pattern ensures clean shutdown of input threads and driver resources

Resource Management

Terminal.Gui v2 implements the IDisposable pattern for proper resource cleanup:

// Recommended pattern with using statement
using (var app = Application.Create().Init())
{
    app.Run<MyDialog>();
    var result = app.GetResult<MyResult>();
}

// Or with try/finally
var app = Application.Create();
try
{
    app.Init();
    app.Run<MyDialog>();
}
finally
{
    app.Dispose(); // Stops input thread, releases resources
}

Key Changes from v1:

  • Input Thread Management: v2 starts a dedicated input thread that polls console input at ~50 polls/second (20ms throttle) to prevent CPU spinning
  • Clean Shutdown: Dispose() cancels the input thread and waits for it to exit, preventing thread leaks
  • Test-Friendly: Always dispose applications in tests to prevent thread pool exhaustion from leaked input threads

Obsolete Shutdown() Method: The Shutdown() method is marked obsolete. Use Dispose() and GetResult() instead:

// OLD (v1/early v2):
var result = app.Run<MyDialog>().Shutdown() as MyResult;

// NEW (v2 recommended):
using (var app = Application.Create().Init())
{
    app.Run<MyDialog>();
    var result = app.GetResult<MyResult>();
}

Modern Look & Feel - Technical Details

TrueColor Support

See the Drawing Deep Dive for complete details on the color system.

  • Implementation: v2 introduces 24-bit color support by extending the Attribute class to handle RGB values, with fallback to 16-color mode for older terminals. This is evident in the IConsoleDriver implementations, which now map colors to the appropriate terminal escape sequences.
  • Impact: Developers can now use a full spectrum of colors without manual palette management, as seen in v1. The Color struct in v2 supports direct RGB input, and drivers handle the translation to terminal capabilities via IConsoleDriver.SupportsTrueColor.
  • Usage: See the ColorPicker view for an example of how TrueColor is leveraged to provide a rich color selection UI.

Enhanced Borders and Padding (Adornments)

See the Layout Deep Dive for complete details on the adornments system.

  • Implementation: v2 introduces a new Adornment class hierarchy, with Margin, Border, and Padding as distinct view-like entities that wrap content. This is a significant departure from v1, where borders were often hardcoded or required custom drawing.
  • Code Change: In v1, View had rudimentary border support via properties like BorderStyle. In v2, View has a View.Border property of type Border, which is itself a configurable entity with properties like Thickness, Border.LineStyle, and Border.Settings.
  • Impact: This allows for consistent border rendering across all views and simplifies custom view development by providing a reusable adornment framework.

User Configurable Color Themes and Text Styles

See the Configuration Deep Dive and Scheme Deep Dive for complete details.

  • Implementation: v2 adds a ConfigurationManager that supports loading and saving color schemes from configuration files. Themes are applied via Scheme objects, which can be customized per view or globally. Each Attribute in a Scheme now includes a TextStyle property supporting Bold, Italic, Underline, Strikethrough, Blink, Reverse, and Faint text styles.
  • Impact: Unlike v1, where color schemes were static or required manual override, v2 enables end-users to personalize not just colors but also text styling (bold, italic, underline, etc.) without code changes, significantly enhancing accessibility and user preference support.

Enhanced Unicode/Wide Character Support

  • Implementation: v2 improves Unicode handling by correctly managing wide characters in text rendering and input processing. The TextFormatter class now accounts for Unicode width in layout calculations.
  • Impact: This fixes v1 issues where wide characters (e.g., CJK scripts) could break layout or input handling, making Terminal.Gui v2 suitable for international applications.

LineCanvas

See the Drawing Deep Dive for complete details on LineCanvas and the drawing system.

  • Implementation: A new LineCanvas class provides a drawing API for creating lines and shapes using box-drawing characters. It includes logic for auto-joining lines at intersections, selecting appropriate glyphs dynamically.
  • Code Example: In v2, LineCanvas is used internally by views like Border and Line to draw clean, connected lines, a feature absent in v1.
  • Impact: Developers can create complex diagrams or UI elements with minimal effort, improving the visual fidelity of terminal applications.

Simplified API - Under the Hood

API Consistency and Reduction

  • Change: v2 revisits every public API, consolidating redundant methods and properties. For example, v1 had multiple focus-related methods scattered across View and Application; v2 centralizes these in ApplicationNavigation.
  • Impact: This reduces the learning curve for new developers and minimizes the risk of using deprecated or inconsistent APIs.
  • Example: The v1 View.MostFocused property is replaced by Application.Navigation.GetFocused(), reducing traversal overhead and clarifying intent.

Modern .NET Standards

  • Change: Events in v2 use EventHandler<T> instead of v1's custom delegate types. Methods follow consistent naming (e.g., OnHasFocusChanged vs. v1's varied naming).
  • Impact: Developers familiar with .NET conventions will find v2 more intuitive, and tools like IntelliSense provide better support due to standardized signatures.

Performance Gains

  • Change: v2 optimizes rendering by minimizing unnecessary redraws through a smarter NeedsDisplay system and reducing object allocations in hot paths like event handling.
  • Impact: Applications built with v2 will feel snappier, especially in complex UIs with many views or frequent updates, addressing v1 performance bottlenecks.

View Improvements - Deep Dive

Deterministic View Lifetime Management

  • v1 Issue: Lifetime rules for View objects were unclear, leading to memory leaks or premature disposal, especially with Application.Run.
  • v2 Solution: v2 defines explicit rules for view disposal and ownership, enforced by unit tests. Application.Run now clearly manages the lifecycle of Runnable views, ensuring deterministic cleanup.
  • Impact: Developers can predict when resources are released, reducing bugs related to dangling references or uninitialized states.

Adornments Framework

See the Layout Deep Dive and View Deep Dive for complete details.

  • Technical Detail: Adornments are implemented as nested views that surround the content area, each with its own drawing and layout logic. Border supports multiple LineStyle options (Single, Double, Heavy, Rounded, Dashed, Dotted) with automatic line intersection handling via LineCanvas.
  • Code Change: In v2, View has properties View.Margin, View.Border, and View.Padding, each configurable independently, unlike v1's limited border support.
  • Impact: This modular approach allows for reusable UI elements and simplifies creating visually consistent applications.

Built-in Scrolling/Virtual Content Area

See the Scrolling Deep Dive and Layout Deep Dive for complete details.

  • v1 Issue: Scrolling required using ScrollView or manual offset management, which was error-prone.
  • v2 Solution: Every View in v2 has a View.Viewport rectangle representing the visible portion of a potentially larger content area defined by View.GetContentSize. Changing Viewport.Location scrolls the content.
  • Code Example: In v2, TextView uses this to handle large text buffers without additional wrapper views.
  • Impact: Simplifies implementing scrollable content and reduces the need for specialized container views.

Improved ScrollBar

  • Change: v2 replaces ScrollBarView with ScrollBar, a cleaner implementation integrated with the built-in scrolling system. View.VerticalScrollBar and View.HorizontalScrollBar properties enable scroll bars with minimal code.
  • Impact: Developers can add scroll bars to any view without managing separate view hierarchies, a significant usability improvement over v1.

DimAuto, PosAnchorEnd, and PosAlign

See the Layout Deep Dive and DimAuto Deep Dive for complete details.

  • Dim.Auto: Automatically sizes views based on content or subviews, reducing manual layout calculations.
  • Pos.AnchorEnd: Allows anchoring to the right or bottom of a superview, enabling flexible layouts not easily achievable in v1.
  • Pos.Align: Provides alignment options (left, center, right) for multiple views, streamlining UI design.
  • Impact: These features reduce boilerplate layout code and support responsive designs in terminal constraints.

View Arrangement

See the Arrangement Deep Dive for complete details.

Keyboard Navigation Overhaul

See the Navigation Deep Dive for complete details on the navigation system.

  • v1 Issue: Navigation was inconsistent, with coupled concepts like View.CanFocus and TabStop leading to unpredictable focus behavior.
  • v2 Solution: v2 decouples these concepts, introduces TabBehavior enum for clearer intent (TabStop, TabGroup, NoStop), and centralizes navigation logic in ApplicationNavigation.
  • Impact: Ensures accessibility by guaranteeing keyboard access to all focusable elements, with unit tests enforcing navigation keys on built-in views.

Sizable/Movable Views

  • Implementation: Any view can be made resizable or movable by setting View.Arrangement flags, with built-in mouse and keyboard handlers for interaction.
  • Impact: Enhances user experience by allowing runtime UI customization, a feature limited to specific views like Window in v1.

New and Improved Built-in Views - Detailed Analysis

See the Views Overview for a complete catalog of all built-in views.

New Views

v2 introduces many new View subclasses that were not present in v1:

  • Bar: A foundational view for horizontal or vertical layouts of Shortcut or other items, used in StatusBar, MenuBar, and PopoverMenu.
  • CharMap: A scrollable, searchable Unicode character map with support for the Unicode Character Database (UCD) API, enabling users to browse and select from all Unicode codepoints with detailed character information. See Character Map Deep Dive.
  • ColorPicker: Leverages TrueColor for a comprehensive color selection experience, supporting multiple color models (HSV, RGB, HSL, Grayscale) with interactive color bars.
  • DatePicker: Provides a calendar-based date selection UI with month/year navigation, leveraging v2's improved drawing and navigation systems.
  • FlagSelector: Enables selection of non-mutually-exclusive flags with checkbox-based UI, supporting both dictionary-based and enum-based flag definitions.
  • GraphView: Displays graphs (bar charts, scatter plots, line graphs) with flexible axes, labels, scaling, scrolling, and annotations - bringing data visualization to the terminal.
  • Line: Draws single horizontal or vertical lines using the LineCanvas system with automatic intersection handling and multiple line styles (Single, Double, Heavy, Rounded, Dashed, Dotted).
  • Menu System (MenuBar, PopoverMenu): A completely redesigned menu system built on the Bar infrastructure, providing a more flexible and visually appealing menu experience.
  • NumericUpDown: Type-safe numeric input with increment/decrement buttons, supporting int, long, float, double, and decimal types.
  • OptionSelector: Displays a list of mutually-exclusive options with checkbox-style UI (radio button equivalent), supporting both horizontal and vertical orientations.
  • Shortcut: An opinionated view for displaying commands with key bindings, simplifying status bar and toolbar creation with consistent visual presentation.
  • Slider: A sophisticated control for range selection with multiple styles (horizontal/vertical bars, indicators), multiple options per slider, configurable legends, and event-driven value changes.
  • SpinnerView: Displays animated spinner glyphs to indicate progress or activity, with multiple built-in styles (Line, Dots, Bounce, etc.) and support for auto-spin or manual animation control.

Improved Views

Many existing views from v1 have been significantly enhanced in v2:

  • FileDialog (OpenDialog, SaveDialog): Completely modernized with TreeView for hierarchical file navigation, Unicode glyphs for icons, search functionality, and history tracking - far surpassing v1's basic file dialogs.
  • ScrollBar: Replaces v1's ScrollBarView with a cleaner implementation featuring automatic show/hide, proportional sizing with ScrollSlider, and seamless integration with View's built-in scrolling system.
  • StatusBar: Rebuilt on the Bar infrastructure, providing more flexible item management, automatic sizing, and better visual presentation.
  • TableView: Massively enhanced with support for generic collections (via IEnumerableTableSource), checkboxes with CheckBoxTableSourceWrapper, tree structures via TreeTableSource, custom cell rendering, and significantly improved performance. See TableView Deep Dive.
  • ScrollView: Deprecated in favor of View's built-in scrolling capabilities, eliminating the need for wrapper views and simplifying scrollable content implementation.

Beauty - Visual Enhancements

Borders

See the Drawing Deep Dive for complete details on borders and LineCanvas.

  • Implementation: Uses the Border adornment with LineStyle options and LineCanvas for automatic line intersection handling.
  • Impact: Adds visual polish to UI elements, making applications feel more refined compared to v1's basic borders.

Gradient

See the Drawing Deep Dive for complete details on gradients and fills.

  • Implementation: Gradient and GradientFill APIs allow rendering color transitions across view elements, using TrueColor for smooth effects.
  • Impact: Enables modern-looking UI elements like gradient borders or backgrounds, not possible in v1 without custom drawing.

Configuration Manager - Persistence and Customization

See the Configuration Deep Dive for complete details on the configuration system.

  • Technical Detail: ConfigurationManager in v2 uses JSON to persist settings like themes, key bindings, and view properties to disk via SettingsScope and ConfigLocations.
  • Code Change: Unlike v1, where settings were ephemeral or hardcoded, v2 provides a centralized system for loading/saving configurations using the ConfigurationManagerAttribute.
  • Impact: Allows for user-specific customizations and library-wide settings without recompilation, enhancing flexibility.

Logging & Metrics - Debugging and Performance

See the Logging Deep Dive for complete details on the logging and metrics system.

  • Implementation: v2 introduces a multi-level logging system via Logging for internal operations (e.g., rendering, input handling) using Microsoft.Extensions.Logging.ILogger, and metrics for performance tracking via Logging.Meter (e.g., frame rate, redraw times, iteration timing).
  • Impact: Developers can diagnose issues like slow redraws or terminal compatibility problems using standard .NET logging frameworks (Serilog, NLog, etc.) and metrics tools (dotnet-counters), a capability absent in v1, reducing guesswork in debugging.

Sixel Image Support - Graphics in Terminal

  • Technical Detail: v2 supports the Sixel protocol for rendering images and animations directly in compatible terminals (e.g., Windows Terminal, xterm) via SixelEncoder.
  • Code Change: New rendering logic in console drivers detects terminal support via SixelSupportDetector and handles Sixel data transmission through SixelToRender.
  • Impact: Brings graphical capabilities to terminal applications, far beyond v1's text-only rendering, opening up new use cases like image previews.

Updated Keyboard API - Comprehensive Input Handling

See the Keyboard Deep Dive and Command Deep Dive for complete details.

Key Class

  • Change: Replaces v1's KeyEvent struct with a Key class, providing a high-level abstraction over raw key codes with properties for modifiers and key type.
  • Impact: Simplifies keyboard handling by abstracting platform differences, making code more portable and readable.

Key Bindings

  • Implementation: v2 introduces a binding system mapping keys to Command enums via View.KeyBindings, with scopes (Application, Focused, HotKey) for priority.
  • Impact: Replaces v1's ad-hoc key handling with a structured approach, allowing views to declare supported commands via View.AddCommand and customize responses easily.
  • Example: TextField in v2 binds Key.Tab to text insertion rather than focus change, customizable by developers.

Default Close Key

  • Change: Changed from Ctrl+Q in v1 to Esc in v2 for closing apps or Runnable views, accessible via Application.QuitKey.
  • Impact: Aligns with common user expectations, improving UX consistency across terminal applications.

Updated Mouse API - Enhanced Interaction

See the Mouse Deep Dive for complete details on mouse handling.

MouseEventArgs Class

  • Change: Replaces v1's MouseEventEventArgs with MouseEventArgs, providing a cleaner structure for mouse data (position, flags via MouseFlags).
  • Impact: Simplifies event handling with a more intuitive API, reducing errors in mouse interaction logic.

Granular Mouse Handling

  • Implementation: v2 offers specific events for clicks (View.MouseClick), double-clicks, and movement, with MouseFlags for button states.
  • Impact: Developers can handle complex mouse interactions (e.g., drag-and-drop) more easily than in v1.

Highlight Event and Continuous Button Presses

AOT Support - Deployment and Performance

  • Implementation: v2 ensures compatibility with Ahead-of-Time compilation and single-file applications by avoiding reflection patterns problematic for AOT, using source generators and SourceGenerationContext for JSON serialization.
  • Impact: Simplifies deployment for environments requiring Native AOT (see Examples/NativeAot), a feature not explicitly supported in v1, reducing runtime overhead and enabling faster startup times.

Conclusion

Terminal.Gui v2 is a transformative update, addressing core limitations of v1 through architectural redesign, performance optimizations, and feature enhancements. From TrueColor and adornments for visual richness to decoupled navigation and modern input APIs for usability, v2 provides a robust foundation for building sophisticated terminal applications. The detailed changes in view management, configuration, and debugging tools empower developers to create more maintainable and user-friendly applications.