mirror of
https://github.com/gui-cs/Terminal.Gui.git
synced 2025-12-26 07:47:54 +01:00
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>
This commit is contained in:
@@ -8,7 +8,7 @@ Terminal.Gui v2 uses an instance-based application architecture that decouples v
|
||||
graph TB
|
||||
subgraph ViewTree["View Hierarchy (SuperView/SubView)"]
|
||||
direction TB
|
||||
Top[Application.Current<br/>Window]
|
||||
Top[app.Current<br/>Window]
|
||||
Menu[MenuBar]
|
||||
Status[StatusBar]
|
||||
Content[Content View]
|
||||
@@ -22,7 +22,7 @@ graph TB
|
||||
Content --> Button2
|
||||
end
|
||||
|
||||
subgraph Stack["Application.SessionStack"]
|
||||
subgraph Stack["app.SessionStack"]
|
||||
direction TB
|
||||
S1[Window<br/>Currently Active]
|
||||
S2[Previous Toplevel<br/>Waiting]
|
||||
@@ -41,7 +41,7 @@ graph TB
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as Application
|
||||
participant App as IApplication
|
||||
participant Main as Main Window
|
||||
participant Dialog as Dialog
|
||||
|
||||
@@ -68,24 +68,29 @@ sequenceDiagram
|
||||
|
||||
### Instance-Based vs Static
|
||||
|
||||
**Terminal.Gui v2** has transitioned from a static singleton pattern to an instance-based architecture:
|
||||
**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:
|
||||
|
||||
```csharp
|
||||
// OLD (v1 / early v2 - now obsolete):
|
||||
// OLD (v1 / early v2 - still works but obsolete):
|
||||
Application.Init();
|
||||
Application.Top.Add(myView);
|
||||
Application.Run();
|
||||
var top = new Toplevel();
|
||||
top.Add(myView);
|
||||
Application.Run(top);
|
||||
top.Dispose();
|
||||
Application.Shutdown();
|
||||
|
||||
// NEW (v2 instance-based):
|
||||
var app = Application.Create ();
|
||||
// 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:
|
||||
@@ -226,19 +231,23 @@ int sessionCount = App?.SessionStack.Count ?? 0;
|
||||
|
||||
## Migration from Static Application
|
||||
|
||||
The static `Application` class now delegates to `ApplicationImpl.Instance` and is marked obsolete:
|
||||
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:
|
||||
|
||||
```csharp
|
||||
public static class Application
|
||||
public static partial class Application
|
||||
{
|
||||
[Obsolete("Use ApplicationImpl.Instance.Current or view.App?.Current")]
|
||||
public static Toplevel? Current => Instance?.Current;
|
||||
[Obsolete("The legacy static Application object is going away.")]
|
||||
public static Toplevel? Current => ApplicationImpl.Instance.Current;
|
||||
|
||||
[Obsolete("Use ApplicationImpl.Instance.SessionStack or view.App?.SessionStack")]
|
||||
public static ConcurrentStack<Toplevel> SessionStack => Instance?.SessionStack ?? new();
|
||||
[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**
|
||||
@@ -472,16 +481,19 @@ public class Service
|
||||
}
|
||||
```
|
||||
|
||||
### DON'T: Assume Application.Instance Exists
|
||||
### DON'T: Use Static Application in New Code
|
||||
|
||||
```csharp
|
||||
❌ AVOID:
|
||||
public class Service
|
||||
❌ AVOID (obsolete pattern):
|
||||
public void Refresh()
|
||||
{
|
||||
public void DoWork()
|
||||
{
|
||||
var app = Application.Instance; // Might be null!
|
||||
}
|
||||
Application.Current?.SetNeedsDraw(); // Obsolete static access
|
||||
}
|
||||
|
||||
✅ PREFERRED:
|
||||
public void Refresh()
|
||||
{
|
||||
App?.Current?.SetNeedsDraw(); // Use View.App property
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -459,7 +459,8 @@ ThemeManager.ThemeChanged += (sender, e) =>
|
||||
{
|
||||
// Theme has changed
|
||||
// Refresh all views to use new theme
|
||||
Application.Current?.SetNeedsDraw();
|
||||
// From within a View, use: App?.Current?.SetNeedsDraw();
|
||||
// Or access via IApplication instance: app.Current?.SetNeedsDraw();
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
@@ -13,10 +13,13 @@ Welcome to the Terminal.Gui documentation! This comprehensive guide covers every
|
||||
- [Getting Started](~/docs/getting-started.md) - Quick start guide to create your first Terminal.Gui application
|
||||
- [Migrating from v1 to v2](~/docs/migratingfromv1.md) - Complete guide for upgrading existing applications
|
||||
- [What's New in v2](~/docs/newinv2.md) - Overview of new features and improvements
|
||||
- [Showcase](~/docs/showcase.md) - Showcase of TUI apps built with Terminal.Gui
|
||||
|
||||
## Deep Dives
|
||||
|
||||
- [ANSI Response Parser](~/docs/ansiparser.md) - Terminal sequence parsing and state management
|
||||
- [Application](~/docs/application.md) - Application lifecycle, initialization, and main loop
|
||||
- [Arrangement](~/docs/arrangement.md) - View arrangement and positioning strategies
|
||||
- [Cancellable Work Pattern](~/docs/cancellable-work-pattern.md) - Core design pattern for extensible workflows
|
||||
- [Character Map Scenario](~/docs/CharacterMap.md) - Complex drawing, scrolling, and Unicode rendering example
|
||||
- [Command System](~/docs/command.md) - Command execution, key bindings, and the Selecting/Accepting concepts
|
||||
@@ -24,6 +27,7 @@ Welcome to the Terminal.Gui documentation! This comprehensive guide covers every
|
||||
- [Cross-Platform Driver Model](~/docs/drivers.md) - Platform abstraction and console driver architecture
|
||||
- [Cursor System](~/docs/cursor.md) - Modern cursor management and positioning (proposed design)
|
||||
- [Dim.Auto](~/docs/dimauto.md) - Automatic view sizing based on content
|
||||
- [Drawing](~/docs/drawing.md) - Drawing primitives, rendering, and graphics operations
|
||||
- [Events](~/docs/events.md) - Event patterns and handling throughout the framework
|
||||
- [Keyboard Input](~/docs/keyboard.md) - Key handling, bindings, commands, and shortcuts
|
||||
- [Layout System](~/docs/layout.md) - View positioning, sizing, and arrangement
|
||||
@@ -33,7 +37,11 @@ Welcome to the Terminal.Gui documentation! This comprehensive guide covers every
|
||||
- [Mouse Input](~/docs/mouse.md) - Mouse event handling and interaction patterns
|
||||
- [Navigation](~/docs/navigation.md) - Focus management, keyboard navigation, and accessibility
|
||||
- [Popovers](~/docs/Popovers.md) - Drawing outside viewport boundaries for menus and popups
|
||||
- [Scheme](~/docs/scheme.md) - Color schemes, styling, and visual theming
|
||||
- [Scrolling](~/docs/scrolling.md) - Built-in scrolling, virtual content areas, and scroll bars
|
||||
- [TableView](~/docs/tableview.md) - Table view component, data binding, and column management
|
||||
- [TreeView](~/docs/treeview.md) - Tree view component, hierarchical data, and node management
|
||||
- [View](~/docs/View.md) - Base view class, view hierarchy, and core view functionality
|
||||
|
||||
## API Reference
|
||||
|
||||
|
||||
@@ -93,6 +93,74 @@ In v1, @Terminal.Gui./Terminal.Gui.Application.Init) automatically created a top
|
||||
* Update any code that assumes `Application.Init` automatically created a toplevel view and set `Application.Current`.
|
||||
* Update any code that assumes `Application.Init` automatically disposed of the toplevel view when the application exited.
|
||||
|
||||
## Instance-Based Application Architecture
|
||||
|
||||
See the [Application Deep Dive](application.md) for complete details on the new application architecture.
|
||||
|
||||
Terminal.Gui v2 introduces an instance-based application architecture. While the static `Application` class still works (marked obsolete), the recommended pattern is to use `Application.Create()` to get an `IApplication` instance.
|
||||
|
||||
### Key Changes
|
||||
|
||||
- **Static Application is Obsolete**: The static `Application` class delegates to `ApplicationImpl.Instance` (a singleton) and is marked `[Obsolete]` but remains functional for backward compatibility.
|
||||
- **Recommended Pattern**: Use `Application.Create()` to get a new `IApplication` instance for better testability and multiple application contexts.
|
||||
- **View.App Property**: Every view has an `App` property that references its `IApplication` context, enabling views to access application services without static dependencies.
|
||||
|
||||
### Migration Strategies
|
||||
|
||||
**Option 1: Continue Using Static Application (Backward Compatible)**
|
||||
|
||||
The static `Application` class still works, so existing v1 code can continue to work with minimal changes:
|
||||
|
||||
```csharp
|
||||
// v1 code (still works in v2, but obsolete)
|
||||
Application.Init();
|
||||
var top = new Toplevel();
|
||||
top.Add(myView);
|
||||
Application.Run(top);
|
||||
top.Dispose();
|
||||
Application.Shutdown();
|
||||
```
|
||||
|
||||
**Option 2: Migrate to Instance-Based Pattern (Recommended)**
|
||||
|
||||
For new code or when refactoring, use the instance-based pattern:
|
||||
|
||||
```csharp
|
||||
// v2 recommended pattern
|
||||
var app = Application.Create();
|
||||
app.Init();
|
||||
var top = new Toplevel();
|
||||
top.Add(myView);
|
||||
app.Run(top);
|
||||
top.Dispose();
|
||||
app.Shutdown();
|
||||
```
|
||||
|
||||
**Option 3: Use View.App Property**
|
||||
|
||||
When accessing application services from within views, use the `App` property instead of static `Application`:
|
||||
|
||||
```csharp
|
||||
// OLD (v1 / obsolete static):
|
||||
public void Refresh()
|
||||
{
|
||||
Application.Current?.SetNeedsDraw();
|
||||
}
|
||||
|
||||
// NEW (v2 - use View.App):
|
||||
public void Refresh()
|
||||
{
|
||||
App?.Current?.SetNeedsDraw();
|
||||
}
|
||||
```
|
||||
|
||||
### Benefits of Instance-Based Architecture
|
||||
|
||||
- **Testability**: Views can be tested without `Application.Init()` by setting `view.App = mockApp`
|
||||
- **Multiple Contexts**: Multiple `IApplication` instances can coexist
|
||||
- **Clear Ownership**: Views explicitly know their application context
|
||||
- **Reduced Global State**: Less reliance on static singletons
|
||||
|
||||
## @Terminal.Gui.Pos and @Terminal.Gui.Dim types now adhere to standard C# idioms
|
||||
|
||||
* In v1, the @Terminal.Gui.Pos and @Terminal.Gui.Dim types (e.g. @Terminal.Gui.Pos.PosView) were nested classes and marked @Terminal.Gui.internal. In v2, they are no longer nested, and have appropriate public APIs.
|
||||
|
||||
@@ -9,7 +9,7 @@ Terminal.Gui applications run on a single main thread with an event loop that pr
|
||||
Terminal.Gui follows the standard UI toolkit pattern where **all UI operations must happen on the main thread**. Attempting to modify views or their properties from background threads will result in undefined behavior and potential crashes.
|
||||
|
||||
### The Golden Rule
|
||||
> Always use `Application.Invoke()` to update the UI from background threads.
|
||||
> Always use `Application.Invoke()` (static, obsolete) or `app.Invoke()` (instance-based, recommended) to update the UI from background threads. From within a View, use `App?.Invoke()`.
|
||||
|
||||
## Background Operations
|
||||
|
||||
@@ -47,6 +47,7 @@ private async void LoadDataButton_Clicked()
|
||||
|
||||
When working with traditional threading APIs or when async/await isn't suitable:
|
||||
|
||||
**From within a View (recommended):**
|
||||
```csharp
|
||||
private void StartBackgroundWork()
|
||||
{
|
||||
@@ -58,14 +59,14 @@ private void StartBackgroundWork()
|
||||
Thread.Sleep(50); // Simulate work
|
||||
|
||||
// Marshal back to main thread for UI updates
|
||||
Application.Invoke(() =>
|
||||
App?.Invoke(() =>
|
||||
{
|
||||
progressBar.Fraction = i / 100f;
|
||||
statusLabel.Text = $"Progress: {i}%";
|
||||
});
|
||||
}
|
||||
|
||||
Application.Invoke(() =>
|
||||
App?.Invoke(() =>
|
||||
{
|
||||
statusLabel.Text = "Complete!";
|
||||
});
|
||||
@@ -73,6 +74,41 @@ private void StartBackgroundWork()
|
||||
}
|
||||
```
|
||||
|
||||
**Using IApplication instance (recommended):**
|
||||
```csharp
|
||||
var app = Application.Create();
|
||||
app.Init();
|
||||
|
||||
private void StartBackgroundWork(IApplication app)
|
||||
{
|
||||
Task.Run(() =>
|
||||
{
|
||||
// This code runs on a background thread
|
||||
for (int i = 0; i <= 100; i++)
|
||||
{
|
||||
Thread.Sleep(50); // Simulate work
|
||||
|
||||
// Marshal back to main thread for UI updates
|
||||
app.Invoke(() =>
|
||||
{
|
||||
progressBar.Fraction = i / 100f;
|
||||
statusLabel.Text = $"Progress: {i}%";
|
||||
});
|
||||
}
|
||||
|
||||
app.Invoke(() =>
|
||||
{
|
||||
statusLabel.Text = "Complete!";
|
||||
});
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
**Using static Application (obsolete but still works):**
|
||||
```csharp
|
||||
Application.Invoke(() => { /* ... */ });
|
||||
```
|
||||
|
||||
## Timers
|
||||
|
||||
Use timers for periodic updates like clocks, status refreshes, or animations:
|
||||
@@ -89,10 +125,11 @@ public class ClockView : View
|
||||
Add(timeLabel);
|
||||
|
||||
// Update every second
|
||||
timerToken = Application.AddTimeout(
|
||||
// Use App?.AddTimeout() when available, or Application.AddTimeout() (obsolete)
|
||||
timerToken = App?.AddTimeout(
|
||||
TimeSpan.FromSeconds(1),
|
||||
UpdateTime
|
||||
);
|
||||
) ?? Application.AddTimeout(TimeSpan.FromSeconds(1), UpdateTime);
|
||||
}
|
||||
|
||||
private bool UpdateTime()
|
||||
@@ -105,7 +142,7 @@ public class ClockView : View
|
||||
{
|
||||
if (disposing && timerToken != null)
|
||||
{
|
||||
Application.RemoveTimeout(timerToken);
|
||||
App?.RemoveTimeout(timerToken) ?? Application.RemoveTimeout(timerToken);
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
@@ -220,6 +257,13 @@ Task.Run(() =>
|
||||
### ❌ Don't: Forget to clean up timers
|
||||
```csharp
|
||||
// Memory leak - timer keeps running after view is disposed
|
||||
// From within a View:
|
||||
App?.AddTimeout(TimeSpan.FromSeconds(1), UpdateStatus);
|
||||
|
||||
// Or with IApplication instance:
|
||||
app.AddTimeout(TimeSpan.FromSeconds(1), UpdateStatus);
|
||||
|
||||
// Or static (obsolete but works):
|
||||
Application.AddTimeout(TimeSpan.FromSeconds(1), UpdateStatus);
|
||||
```
|
||||
|
||||
|
||||
@@ -176,25 +176,30 @@ The @Terminal.Gui.App.ApplicationNavigation.AdvanceFocus method causes the focus
|
||||
The implementation is simple:
|
||||
|
||||
```cs
|
||||
return Application.Current?.AdvanceFocus (direction, behavior);
|
||||
return app.Current?.AdvanceFocus (direction, behavior);
|
||||
```
|
||||
|
||||
This method is called from the `Command` handlers bound to the application-scoped keybindings created during `Application.Init`. It is `public` as a convenience.
|
||||
This method is called from the `Command` handlers bound to the application-scoped keybindings created during `app.Init()`. It is `public` as a convenience.
|
||||
|
||||
**Note:** When accessing from within a View, use `App?.Current` instead of `Application.Current` (which is obsolete).
|
||||
|
||||
This method replaces about a dozen functions in v1 (scattered across `Application` and `Toplevel`).
|
||||
|
||||
### Application Navigation Examples
|
||||
|
||||
```csharp
|
||||
var app = Application.Create();
|
||||
app.Init();
|
||||
|
||||
// Listen for global focus changes
|
||||
Application.Navigation.FocusedChanged += (sender, e) =>
|
||||
app.Navigation.FocusedChanged += (sender, e) =>
|
||||
{
|
||||
var focused = Application.Navigation.GetFocused();
|
||||
var focused = app.Navigation.GetFocused();
|
||||
StatusBar.Text = $"Focused: {focused?.GetType().Name ?? "None"}";
|
||||
};
|
||||
|
||||
// Prevent certain views from getting focus
|
||||
Application.Navigation.FocusedChanging += (sender, e) =>
|
||||
app.Navigation.FocusedChanging += (sender, e) =>
|
||||
{
|
||||
if (e.NewView is SomeRestrictedView)
|
||||
{
|
||||
|
||||
@@ -15,6 +15,47 @@ Terminal.Gui v2 represents a fundamental rethinking of the library's architectur
|
||||
|
||||
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](application.md) 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
|
||||
|
||||
```csharp
|
||||
// Recommended v2 pattern (instance-based)
|
||||
var app = Application.Create();
|
||||
app.Init();
|
||||
var top = new Toplevel { Title = "My App" };
|
||||
top.Add(myView);
|
||||
app.Run(top);
|
||||
top.Dispose();
|
||||
app.Shutdown();
|
||||
|
||||
// Static pattern (obsolete but still works)
|
||||
Application.Init();
|
||||
var top = new Toplevel { 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
|
||||
|
||||
## Modern Look & Feel - Technical Details
|
||||
|
||||
### TrueColor Support
|
||||
|
||||
@@ -2,10 +2,16 @@
|
||||
href: index.md
|
||||
- name: Getting Started
|
||||
href: getting-started.md
|
||||
- name: Showcase
|
||||
href: showcase.md
|
||||
- name: What's new in v2
|
||||
href: newinv2.md
|
||||
- name: v1 To v2 Migration
|
||||
href: migratingfromv1.md
|
||||
- name: Lexicon & Taxonomy
|
||||
href: lexicon.md
|
||||
- name: Application Deep Dive
|
||||
href: application.md
|
||||
- name: Arrangement
|
||||
href: arrangement.md
|
||||
- name: Cancellable Work Pattern
|
||||
@@ -24,10 +30,6 @@
|
||||
href: drivers.md
|
||||
- name: Events Deep Dive
|
||||
href: events.md
|
||||
- name: Lexicon & Taxonomy
|
||||
href: lexicon.md
|
||||
- name: Terminology Proposal
|
||||
href: terminology-index.md
|
||||
- name: Keyboard
|
||||
href: keyboard.md
|
||||
- name: Layout Engine
|
||||
@@ -40,14 +42,16 @@
|
||||
href: navigation.md
|
||||
- name: Popovers
|
||||
href: Popovers.md
|
||||
- name: View Deep Dive
|
||||
href: View.md
|
||||
- name: View List
|
||||
href: views.md
|
||||
- name: Scheme Deep Dive
|
||||
href: scheme.md
|
||||
- name: Scrolling
|
||||
href: scrolling.md
|
||||
- name: TableView Deep Dive
|
||||
href: tableview.md
|
||||
- name: TreeView Deep Dive
|
||||
href: treeview.md
|
||||
- name: View Deep Dive
|
||||
href: View.md
|
||||
- name: View List
|
||||
href: views.md
|
||||
|
||||
|
||||
Reference in New Issue
Block a user