Files
Terminal.Gui/docfx/docs/application.md
Tig a6258ed398 Updates IListDataSource.Render to rename the start parameter to viewportXOffset (#4392)
* Add comprehensive unit tests for WindowsKeyConverter

- Implement 118 parallelizable unit tests for WindowsKeyConverter

- Cover ToKey and ToKeyInfo methods with full bidirectional testing

- Test basic characters, modifiers, special keys, function keys

- Test VK_PACKET Unicode/IME input

- Test OEM keys, NumPad keys, and lock states

- Include round-trip conversion tests

- All tests passing successfully

Fixes #4389

* Rename `start` parameter to `viewportXOffset` for clarity

The `start` parameter in several methods and interfaces has been
renamed to `viewportXOffset` to better reflect its purpose as the
horizontal offset of the viewport during string rendering.

- Updated method signatures in `ListViewWithSelection` to use
  `viewportXOffset` instead of `start`, including default values.
- Modified the `RenderUstr` method in `ListViewWithSelection` to
  use `viewportXOffset` for calculating the starting index.
- Renamed the `start` parameter to `viewportXOffset` in the
  `IListDataSource` interface and updated its documentation.
- Replaced all occurrences of `start` with `viewportXOffset` in
  the `ListWrapper<T>` class, including method calls and logic.
- Updated the `RenderUstr` method in `ListWrapper<T>` to use
  `viewportXOffset` for substring calculations.
- Adjusted the test method in `ListViewTests.cs` to reflect the
  parameter name change.

These changes improve code readability and make the parameter's
role in rendering logic more explicit.

* Remove WindowsKeyConverterTests class that was added by mistake

* Modernized ListView and IListDataSource - Tons of new unit tests

Refactored `ListView` and `IListDataSource` to improve readability, maintainability, and functionality. Introduced `ListWrapper<T>` as a default implementation of `IListDataSource` for easier integration with standard collections.

Enhanced `ListView` with better handling of marking, selection, and scrolling. Replaced `viewportXOffset` with `viewportX` for horizontal scrolling. Added `EnsureSelectedItemVisible` to maintain visibility of the selected item.

Updated `IListDataSource` with detailed XML documentation and added `SuspendCollectionChangedEvent` for bulk updates. Improved null safety with nullable reference types.

Added comprehensive unit tests for `ListWrapper<T>` and `IListDataSource` to ensure robustness. Modernized the codebase with C# features like expression-bodied members and pattern matching. Fixed bugs related to `SelectedItem` validation and rendering artifacts.

* Improve index validation in ComboBox and ListView

Enhance robustness by adding stricter checks for valid indices
in ComboBox and ListView. Updated conditions in the
`_listview.SelectedItemChanged` event handler to ensure `e.Item`
is non-negative before accessing `_searchSet`. Modified the
`SetValue` method to use `e.Item` instead of `_listview.SelectedItem`.

In ListView, updated the `OnSelectedChanged` method to validate
that `SelectedItem` is non-negative (`>= 0`) before accessing
the `Source` list. These changes prevent potential out-of-range
errors and improve code safety.

* Refactor and enhance test coverage across modules

Refactored and added new tests to improve coverage, readability, and consistency across multiple test files. Key changes include:

- **ShortcutTests.cs**: Added tests for `BindKeyToApplication` and removed redundant tests.
- **SourcesManagerTests.cs**: Renamed `Update_*` tests to `Load_*` for clarity.
- **ArrangementTests.cs**: Reintroduced `MouseGrabHandler` tests, added `ViewArrangement` flag tests, and improved structure.
- **NeedsDrawTests.cs**: Replaced `Application.Screen.Size` with fixed dimensions for better isolation.
- **DimAutoTests.cs**: Updated layout tests to use fixed dimensions.
- **FrameTests.cs**: Standardized object initialization and validated frame behavior.
- **SubViewTests.cs**: Improved formatting and modernized event handling.
- **NumericUpDownTests.cs**: Decoupled layout tests from screen size.

General improvements:
- Enhanced formatting and removed redundant tests.
- Added comments for clarity.
- Introduced `ITestOutputHelper` for better debugging in `ArrangementTests`.

* Refactor to use nullable types for better null safety

Enabled nullable reference types across the codebase to improve null safety and prevent potential null reference issues. Refactored `SelectedItem` and related properties from `int` to `int?` to represent no selection with `null` instead of `-1`. Updated logic, event arguments, and method signatures to handle nullable values consistently.

Simplified object initialization using modern C# syntax and improved code readability with interpolated strings. Added null checks and early returns to prevent runtime errors. Enhanced error handling by throwing `ArgumentOutOfRangeException` for invalid values.

Updated tests to reflect the changes, replacing assertions for `-1` with `null` and ensuring proper handling of nullable values. Cleaned up redundant code and improved formatting for better maintainability.

* on` functionality has been deprecated, refactored, or removed from the `Shortcut` class.

* Refactor: Transition to instance-based architecture

Updated `Run-LocalCoverage.ps1` to increase `--blame-hang-timeout` from 10s to 60s. Improved null safety in `GuiTestContext` by adding null-conditional operators. Commented out problematic code in `SetupFakeApplicationAttribute.cs` to prevent test hangs.

Excluded `ViewBase` files from `UnitTests.Parallelizable.csproj` and removed redundant folder declarations. Simplified event handling in `IListDataSourceTests.cs` and updated `ListViewTests.cs` to use nullable reference types.

Enhanced documentation to emphasize the transition to an instance-based application architecture. Updated examples in `application.md`, `multitasking.md`, and `navigation.md` to reflect the use of `Application.Create()` and `View.App`. Clarified the obsolescence of the static `Application` class.

Revised table of contents in `toc.yml` to include new sections like "Application Deep Dive" and "Scheme Deep Dive." Added `dotnet-tools.json` for tool configuration.

These changes improve maintainability, testability, and alignment with modern C# practices.

* Refactor ListViewTests to use Terminal.Gui framework

The `ListViewTests` class has been refactored to replace the `AutoInitShutdown` attribute with explicit application lifecycle management using `IApplication` and `app.Init()` from the `Terminal.Gui` framework.

Key changes include:
- Rewriting tests to use `Terminal.Gui`'s application lifecycle.
- Adding a private `_output` field for logging test output via `ITestOutputHelper`.
- Updating `DriverAssert.AssertDriverContentsWithFrameAre` to include `app.Driver` for UI verification.
- Rewriting tests like `Clicking_On_Border_Is_Ignored`, `EnsureSelectedItemVisible_SelectedItem`, and others to align with the new framework.
- Adding explicit calls to `app.Shutdown()` for proper cleanup.
- Enabling nullable reference types with `#nullable enable`.
- Updating `using` directives and `namespace` to reflect the new structure.

These changes improve test maintainability, compatibility, and diagnostics.

* Update Terminal.Gui/Views/CollectionNavigation/CollectionNavigatorBase.cs

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

* Update Terminal.Gui/Views/CollectionNavigation/CollectionNavigatorBase.cs

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

* Update Examples/UICatalog/UICatalogTop.cs

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

* Update Terminal.Gui/Views/ListWrapper.cs

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

* Update Terminal.Gui/Views/ListWrapper.cs

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

* Updated the `SetMark` method to return `Source.IsMarked(SelectedItem.Value)` for consistency and removed an outdated comment questioning its correctness.

Enhanced the exception message in the `SelectedItem` property setter to provide clearer guidance when the value is out of range.

* Add comprehensive ListView behavior test coverage

Added multiple test methods to validate `ListView` behavior:
- `Vertical_ScrollBar_Hides_And_Shows_As_Needed`: Ensures the vertical scrollbar auto-hides/shows based on content height.
- `Mouse_Wheel_Scrolls`: Verifies vertical scrolling with the mouse wheel updates `TopItem`.
- `SelectedItem_With_Source_Null_Does_Nothing`: Confirms no exceptions occur when setting `SelectedItem` with a `null` source.
- `Horizontal_Scroll`: Tests horizontal scrolling, including programmatic and mouse wheel interactions, ensuring `LeftItem` updates correctly.
- `SetSourceAsync_SetsSource`: Validates the asynchronous `SetSourceAsync` method updates the source and item count.
- `AllowsMultipleSelection_Set_To_False_Unmarks_All_But_Selected`: Ensures disabling multiple selection unmarks all but the selected item.
- `Source_CollectionChanged_Remove`: Confirms `SelectedItem` and source count update correctly when items are removed from the source collection.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-19 20:39:34 -05:00

12 KiB

Application Architecture

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

View Hierarchy and Run Stack

graph TB
    subgraph ViewTree["View Hierarchy (SuperView/SubView)"]
        direction TB
        Top[app.Current<br/>Window]
        Menu[MenuBar]
        Status[StatusBar]
        Content[Content View]
        Button1[Button]
        Button2[Button]
        
        Top --> Menu
        Top --> Status
        Top --> Content
        Content --> Button1
        Content --> Button2
    end
    
    subgraph Stack["app.SessionStack"]
        direction TB
        S1[Window<br/>Currently Active]
        S2[Previous Toplevel<br/>Waiting]
        S3[Base Toplevel<br/>Waiting]
        
        S1 -.-> S2 -.-> S3
    end
    
    Top -.->|"same instance"| S1
    
    style Top fill:#ccffcc,stroke:#339933,stroke-width:3px
    style S1 fill:#ccffcc,stroke:#339933,stroke-width:3px

Usage Example Flow

sequenceDiagram
    participant App as IApplication
    participant Main as Main Window
    participant Dialog as Dialog
    
    Note over App: Initially empty SessionStack
    
    App->>Main: Run(mainWindow)
    activate Main
    Note over App: SessionStack: [Main]<br/>Current: Main
    
    Main->>Dialog: Run(dialog)
    activate Dialog
    Note over App: SessionStack: [Dialog, Main]<br/>Current: Dialog
    
    Dialog->>App: RequestStop()
    deactivate Dialog
    Note over App: SessionStack: [Main]<br/>Current: Main
    
    Main->>App: RequestStop()
    deactivate Main
    Note over App: SessionStack: []<br/>Current: null

Key Concepts

Instance-Based vs Static

Terminal.Gui v2 supports both static and instance-based patterns. The static Application class is marked obsolete but still functional for backward compatibility. The recommended pattern is to use Application.Create() to get an IApplication instance:

// OLD (v1 / early v2 - still works but obsolete):
Application.Init();
var top = new Toplevel();
top.Add(myView);
Application.Run(top);
top.Dispose();
Application.Shutdown();

// NEW (v2 recommended - instance-based):
var app = Application.Create();
app.Init();
var top = new Toplevel();
top.Add(myView);
app.Run(top);
top.Dispose();
app.Shutdown();

Note: The static Application class delegates to ApplicationImpl.Instance (a singleton). Application.Create() creates a new ApplicationImpl instance, enabling multiple application contexts and better testability.

View.App Property

Every view now has an App property that references its application context:

public class View
{
    /// <summary>
    /// Gets the application context for this view.
    /// </summary>
    public IApplication? App { get; internal set; }
    
    /// <summary>
    /// Gets the application context, checking parent hierarchy if needed.
    /// Override to customize application resolution.
    /// </summary>
    public virtual IApplication? GetApp() => App ?? SuperView?.GetApp();
}

Benefits:

  • Views can be tested without Application.Init()
  • Multiple applications can coexist
  • Clear ownership: views know their context
  • Reduced global state dependencies

Accessing Application from Views

Recommended pattern:

public class MyView : View
{
    public override void OnEnter(View view)
    {
        // Use View.App instead of static Application
        App?.Current?.SetNeedsDraw();
        
        // Access SessionStack
        if (App?.SessionStack.Count > 0)
        {
            // Work with sessions
        }
    }
}

Alternative - dependency injection:

public class MyView : View
{
    private readonly IApplication _app;
    
    public MyView(IApplication app)
    {
        _app = app;
        // Now completely decoupled from static Application
    }
    
    public void DoWork()
    {
        _app.Current?.SetNeedsDraw();
    }
}

IApplication Interface

The IApplication interface defines the application contract:

public interface IApplication
{
    /// <summary>
    /// Gets the currently running Toplevel (the "current session").
    /// Renamed from "Top" for clarity.
    /// </summary>
    Toplevel? Current { get; }
    
    /// <summary>
    /// Gets the stack of running sessions.
    /// Renamed from "TopLevels" to align with SessionToken terminology.
    /// </summary>
    ConcurrentStack<Toplevel> SessionStack { get; }
    
    IDriver? Driver { get; }
    IMainLoopCoordinator? MainLoop { get; }
    
    void Init(string? driverName = null);
    void Shutdown();
    SessionToken? Begin(Toplevel toplevel);
    void End(SessionToken sessionToken);
    // ... other members
}

Terminology Changes

Terminal.Gui v2 modernized its terminology for clarity:

Application.Current (formerly "Top")

The Current property represents the currently running Toplevel (the active session):

// Access the current session
Toplevel? current = app.Current;

// From within a view
Toplevel? current = App?.Current;

Why "Current" instead of "Top"?

  • Follows .NET patterns (Thread.CurrentThread, HttpContext.Current)
  • Self-documenting: immediately clear it's the "current" active view
  • Less confusing than "Top" which could mean "topmost in Z-order"

Application.SessionStack (formerly "TopLevels")

The SessionStack property is the stack of running sessions:

// Access all running sessions
foreach (var toplevel in app.SessionStack)
{
    // Process each session
}

// From within a view
int sessionCount = App?.SessionStack.Count ?? 0;

Why "SessionStack" instead of "TopLevels"?

  • Describes both content (sessions) and structure (stack)
  • Aligns with SessionToken terminology
  • Follows .NET naming patterns (descriptive + collection type)

Migration from Static Application

The static Application class delegates to ApplicationImpl.Instance (a singleton) and is marked obsolete. All static methods and properties are marked with [Obsolete] but remain functional for backward compatibility:

public static partial class Application
{
    [Obsolete("The legacy static Application object is going away.")]
    public static Toplevel? Current => ApplicationImpl.Instance.Current;
    
    [Obsolete("The legacy static Application object is going away.")]
    public static ConcurrentStack<Toplevel> SessionStack => ApplicationImpl.Instance.SessionStack;
    
    // ... other obsolete static members
}

Important: The static Application class uses a singleton (ApplicationImpl.Instance), while Application.Create() creates new instances. For new code, prefer the instance-based pattern using Application.Create().

Migration Strategies

Strategy 1: Use View.App

// OLD:
void MyMethod()
{
    Application.Current?.SetNeedsDraw();
}

// NEW:
void MyMethod(View view)
{
    view.App?.Current?.SetNeedsDraw();
}

Strategy 2: Pass IApplication

// OLD:
void ProcessSessions()
{
    foreach (var toplevel in Application.SessionStack)
    {
        // Process
    }
}

// NEW:
void ProcessSessions(IApplication app)
{
    foreach (var toplevel in app.SessionStack)
    {
        // Process
    }
}

Strategy 3: Store IApplication Reference

public class MyService
{
    private readonly IApplication _app;
    
    public MyService(IApplication app)
    {
        _app = app;
    }
    
    public void DoWork()
    {
        _app.Current?.Title = "Processing...";
    }
}

Session Management

Begin and End

Applications manage sessions through Begin() and End():

var app = Application.Create ();
app.Init();

var toplevel = new Toplevel();

// Begin a new session - pushes to SessionStack
SessionToken? token = app.Begin(toplevel);

// Current now points to this toplevel
Debug.Assert(app.Current == toplevel);

// End the session - pops from SessionStack
if (token != null)
{
    app.End(token);
}

// Current restored to previous toplevel (if any)

Nested Sessions

Multiple sessions can run nested:

var app = Application.Create ();
app.Init();

// Session 1
var main = new Toplevel { Title = "Main" };
var token1 = app.Begin(main);
// app.Current == main, SessionStack.Count == 1

// Session 2 (nested)
var dialog = new Dialog { Title = "Dialog" };
var token2 = app.Begin(dialog);
// app.Current == dialog, SessionStack.Count == 2

// End dialog
app.End(token2);
// app.Current == main, SessionStack.Count == 1

// End main
app.End(token1);
// app.Current == null, SessionStack.Count == 0

View.Driver Property

Similar to View.App, views now have a Driver property:

public class View
{
    /// <summary>
    /// Gets the driver for this view.
    /// </summary>
    public IDriver? Driver => GetDriver();
    
    /// <summary>
    /// Gets the driver, checking application context if needed.
    /// Override to customize driver resolution.
    /// </summary>
    public virtual IDriver? GetDriver() => App?.Driver;
}

Usage:

public override void OnDrawContent(Rectangle viewport)
{
    // Use view's driver instead of Application.Driver
    Driver?.Move(0, 0);
    Driver?.AddStr("Hello");
}

Testing with the New Architecture

The instance-based architecture dramatically improves testability:

Testing Views in Isolation

[Fact]
public void MyView_DisplaysCorrectly()
{
    // Create mock application
    var mockApp = new Mock<IApplication>();
    mockApp.Setup(a => a.Current).Returns(new Toplevel());
    
    // Create view with mock app
    var view = new MyView { App = mockApp.Object };
    
    // Test without Application.Init()!
    view.SetNeedsDraw();
    Assert.True(view.NeedsDraw);
    
    // No Application.Shutdown() needed!
}

Testing with Real ApplicationImpl

[Fact]
public void MyView_WorksWithRealApplication()
{
    var app = Application.Create ();
    try
    {
        app.Init(new FakeDriver());
        
        var view = new MyView();
        var top = new Toplevel();
        top.Add(view);
        
        app.Begin(top);
        
        // View.App automatically set
        Assert.NotNull(view.App);
        Assert.Same(app, view.App);
        
        // Test view behavior
        view.DoSomething();
        
    }
    finally
    {
        app.Shutdown();
    }
}

Best Practices

DO: Use View.App

 GOOD:
public void Refresh()
{
    App?.Current?.SetNeedsDraw();
}

DON'T: Use Static Application

 AVOID:
public void Refresh()
{
    Application.Current?.SetNeedsDraw(); // Obsolete!
}

DO: Pass IApplication as Dependency

 GOOD:
public class Service
{
    public Service(IApplication app) { }
}

DON'T: Use Static Application in New Code

 AVOID (obsolete pattern):
public void Refresh()
{
    Application.Current?.SetNeedsDraw(); // Obsolete static access
}

 PREFERRED:
public void Refresh()
{
    App?.Current?.SetNeedsDraw(); // Use View.App property
}

DO: Override GetApp() for Custom Resolution

 GOOD:
public class SpecialView : View
{
    private IApplication? _customApp;
    
    public override IApplication? GetApp()
    {
        return _customApp ?? base.GetApp();
    }
}

Advanced Scenarios

Multiple Applications

The instance-based architecture enables multiple applications:

// Application 1
var app1 = Application.Create ();
app1.Init(new WindowsDriver());
var top1 = new Toplevel { Title = "App 1" };
// ... configure top1

// Application 2 (different driver!)
var app2 = Application.Create ();
app2.Init(new CursesDriver());
var top2 = new Toplevel { Title = "App 2" };
// ... configure top2

// Views in top1 use app1
// Views in top2 use app2

Application-Agnostic Views

Create views that work with any application:

public class UniversalView : View
{
    public void ShowMessage(string message)
    {
        // Works regardless of which application context
        var app = GetApp();
        if (app != null)
        {
            var msg = new MessageBox(message);
            app.Begin(msg);
        }
    }
}

See Also

  • Navigation - Navigation with the instance-based architecture
  • Keyboard - Keyboard handling through View.App
  • Mouse - Mouse handling through View.App
  • Drivers - Driver access through View.Driver
  • Multitasking - Session management with SessionStack