mirror of
https://github.com/gui-cs/Terminal.Gui.git
synced 2025-12-26 15:57:56 +01:00
* 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. * Refactor to use Application.Instance for lifecycle management Replaced all occurrences of `ApplicationImpl.Instance` with the new `Application.Instance` property across the codebase to align with the updated application lifecycle model. Encapsulated the `ApplicationImpl` class by making it `internal`, ensuring it is no longer directly accessible outside its assembly. Introduced the `[Obsolete]` `Application.Instance` property as a backward-compatible singleton for the legacy static `Application` model, while encouraging the use of `Application.Create()` for new code. Updated `MessageBox` methods to use `Application.Instance` for consistent modal dialog management. Improved documentation to reflect these changes and emphasize the transition to the instance-based application model. Performed code cleanup in multiple classes to ensure consistency and maintainability. These changes maintain backward compatibility while preparing the codebase for the eventual removal of the legacy `ApplicationImpl` class. * Fix doc bug * - Removed obsolete `.cd` class diagram files. - Introduced `IRunnable` interface for decoupling component execution. - Added fluent API for running dialogs and retrieving results. - Enhanced `View` with `App` and `Driver` properties for better decoupling. - Improved testability with support for mock and real applications. - Implemented `IDisposable` for proper resource cleanup. - Replaced `RunnableSessionStack` with `SessionStack` for session management. - Updated driver architecture to align with the new model. - Scoped `IKeyboard` to application contexts for modularity. - Updated documentation with migration strategies and best practices. These changes modernize the library, improve maintainability, and align with current development practices.
This commit is contained in:
@@ -18,7 +18,7 @@ Terminal.Gui v2 uses an instance-based application architecture with the **IRunn
|
||||
graph TB
|
||||
subgraph ViewTree["View Hierarchy (SuperView/SubView)"]
|
||||
direction TB
|
||||
Top[app.Current<br/>Window]
|
||||
Top[app.TopRunnable<br/>Window]
|
||||
Menu[MenuBar]
|
||||
Status[StatusBar]
|
||||
Content[Content View]
|
||||
@@ -59,19 +59,19 @@ sequenceDiagram
|
||||
|
||||
App->>Main: Run(mainWindow)
|
||||
activate Main
|
||||
Note over App: SessionStack: [Main]<br/>Current: Main
|
||||
Note over App: SessionStack: [Main]<br/>TopRunnable: Main
|
||||
|
||||
Main->>Dialog: Run(dialog)
|
||||
activate Dialog
|
||||
Note over App: SessionStack: [Dialog, Main]<br/>Current: Dialog
|
||||
Note over App: SessionStack: [Dialog, Main]<br/>TopRunnable: Dialog
|
||||
|
||||
Dialog->>App: RequestStop()
|
||||
deactivate Dialog
|
||||
Note over App: SessionStack: [Main]<br/>Current: Main
|
||||
Note over App: SessionStack: [Main]<br/>TopRunnable: Main
|
||||
|
||||
Main->>App: RequestStop()
|
||||
deactivate Main
|
||||
Note over App: SessionStack: []<br/>Current: null
|
||||
Note over App: SessionStack: []<br/>TopRunnable: null
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
@@ -82,37 +82,37 @@ sequenceDiagram
|
||||
|
||||
```csharp
|
||||
// OLD (v1 / early v2 - still works but obsolete):
|
||||
Application.Init();
|
||||
var top = new Window();
|
||||
top.Add(myView);
|
||||
Application.Run(top);
|
||||
top.Dispose();
|
||||
Application.Shutdown(); // Obsolete - use Dispose() instead
|
||||
Application.Init ();
|
||||
Window top = new ();
|
||||
top.Add (myView);
|
||||
Application.Run (top);
|
||||
top.Dispose ();
|
||||
Application.Shutdown (); // Obsolete - use Dispose() instead
|
||||
|
||||
// RECOMMENDED (v2 - instance-based with using statement):
|
||||
using (var app = Application.Create().Init())
|
||||
using (IApplication app = Application.Create ().Init ())
|
||||
{
|
||||
var top = new Window();
|
||||
top.Add(myView);
|
||||
app.Run(top);
|
||||
top.Dispose();
|
||||
Window top = new ();
|
||||
top.Add (myView);
|
||||
app.Run (top);
|
||||
top.Dispose ();
|
||||
} // app.Dispose() called automatically
|
||||
|
||||
// WITH IRunnable (fluent API with automatic disposal):
|
||||
using (var app = Application.Create().Init())
|
||||
using (IApplication app = Application.Create ().Init ())
|
||||
{
|
||||
app.Run<ColorPickerDialog>();
|
||||
Color? result = app.GetResult<Color>();
|
||||
app.Run<ColorPickerDialog> ();
|
||||
Color? result = app.GetResult<Color> ();
|
||||
}
|
||||
|
||||
// SIMPLEST (manual disposal):
|
||||
var app = Application.Create().Init();
|
||||
app.Run<ColorPickerDialog>();
|
||||
Color? result = app.GetResult<Color>();
|
||||
app.Dispose();
|
||||
IApplication app = Application.Create ().Init ();
|
||||
app.Run<ColorPickerDialog> ();
|
||||
Color? result = app.GetResult<Color> ();
|
||||
app.Dispose ();
|
||||
```
|
||||
|
||||
**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.
|
||||
**Note:** The static `Application` class delegates to a singleton instance accessible via `Application.Instance`. `Application.Create()` creates a **new** application instance, enabling multiple application contexts and better testability.
|
||||
|
||||
### View.App Property
|
||||
|
||||
@@ -130,7 +130,7 @@ public class View
|
||||
/// Gets the application context, checking parent hierarchy if needed.
|
||||
/// Override to customize application resolution.
|
||||
/// </summary>
|
||||
public virtual IApplication? GetApp() => App ?? SuperView?.GetApp();
|
||||
public virtual IApplication? GetApp () => App ?? SuperView?.GetApp ();
|
||||
}
|
||||
```
|
||||
|
||||
@@ -147,10 +147,10 @@ public class View
|
||||
```csharp
|
||||
public class MyView : View
|
||||
{
|
||||
public override void OnEnter(View view)
|
||||
public override void OnEnter (View view)
|
||||
{
|
||||
// Use View.App instead of static Application
|
||||
App?.Current?.SetNeedsDraw();
|
||||
App?.TopRunnable?.SetNeedsDraw ();
|
||||
|
||||
// Access SessionStack
|
||||
if (App?.SessionStack.Count > 0)
|
||||
@@ -168,15 +168,15 @@ public class MyView : View
|
||||
{
|
||||
private readonly IApplication _app;
|
||||
|
||||
public MyView(IApplication app)
|
||||
public MyView (IApplication app)
|
||||
{
|
||||
_app = app;
|
||||
// Now completely decoupled from static Application
|
||||
}
|
||||
|
||||
public void DoWork()
|
||||
public void DoWork ()
|
||||
{
|
||||
_app.Current?.SetNeedsDraw();
|
||||
_app.TopRunnable?.SetNeedsDraw ();
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -199,26 +199,26 @@ The fluent API enables elegant method chaining with automatic resource managemen
|
||||
|
||||
```csharp
|
||||
// Recommended: using statement with GetResult
|
||||
using (var app = Application.Create().Init())
|
||||
using (IApplication app = Application.Create ().Init ())
|
||||
{
|
||||
app.Run<ColorPickerDialog>();
|
||||
Color? result = app.GetResult<Color>();
|
||||
app.Run<ColorPickerDialog> ();
|
||||
Color? result = app.GetResult<Color> ();
|
||||
|
||||
if (result is { })
|
||||
{
|
||||
ApplyColor(result);
|
||||
ApplyColor (result);
|
||||
}
|
||||
}
|
||||
|
||||
// Alternative: Manual disposal
|
||||
var app = Application.Create().Init();
|
||||
app.Run<ColorPickerDialog>();
|
||||
Color? result = app.GetResult<Color>();
|
||||
app.Dispose();
|
||||
IApplication app = Application.Create ().Init ();
|
||||
app.Run<ColorPickerDialog> ();
|
||||
Color? result = app.GetResult<Color> ();
|
||||
app.Dispose ();
|
||||
|
||||
if (result is { })
|
||||
{
|
||||
ApplyColor(result);
|
||||
ApplyColor (result);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -240,19 +240,19 @@ if (result is { })
|
||||
|
||||
```csharp
|
||||
// Framework ownership - automatic disposal
|
||||
using (var app = Application.Create().Init())
|
||||
using (IApplication app = Application.Create ().Init ())
|
||||
{
|
||||
app.Run<MyDialog>(); // Dialog disposed automatically when Run returns
|
||||
var result = app.GetResult<MyResultType>();
|
||||
app.Run<MyDialog> (); // Dialog disposed automatically when Run returns
|
||||
MyResultType? result = app.GetResult<MyResultType> ();
|
||||
}
|
||||
|
||||
// Caller ownership - manual disposal
|
||||
using (var app = Application.Create().Init())
|
||||
using (IApplication app = Application.Create ().Init ())
|
||||
{
|
||||
var dialog = new MyDialog();
|
||||
app.Run(dialog);
|
||||
var result = dialog.Result;
|
||||
dialog.Dispose(); // Caller must dispose
|
||||
MyDialog dialog = new ();
|
||||
app.Run (dialog);
|
||||
MyResultType? result = dialog.Result;
|
||||
dialog.Dispose (); // Caller must dispose
|
||||
}
|
||||
```
|
||||
|
||||
@@ -265,35 +265,36 @@ public class FileDialog : Runnable<string?>
|
||||
{
|
||||
private TextField _pathField;
|
||||
|
||||
public FileDialog()
|
||||
public FileDialog ()
|
||||
{
|
||||
Title = "Select File";
|
||||
|
||||
_pathField = new TextField { X = 1, Y = 1, Width = Dim.Fill(1) };
|
||||
_pathField = new () { X = 1, Y = 1, Width = Dim.Fill (1) };
|
||||
|
||||
var okButton = new Button { Text = "OK", IsDefault = true };
|
||||
okButton.Accepting += (s, e) => {
|
||||
Button okButton = new () { Text = "OK", IsDefault = true };
|
||||
okButton.Accepting += (s, e) =>
|
||||
{
|
||||
Result = _pathField.Text;
|
||||
Application.RequestStop();
|
||||
Application.RequestStop ();
|
||||
};
|
||||
|
||||
Add(_pathField, okButton);
|
||||
Add (_pathField, okButton);
|
||||
}
|
||||
|
||||
protected override bool OnIsRunningChanging(bool oldValue, bool newValue)
|
||||
protected override bool OnIsRunningChanging (bool oldValue, bool newValue)
|
||||
{
|
||||
if (!newValue) // Stopping - extract result before disposal
|
||||
{
|
||||
Result = _pathField?.Text;
|
||||
}
|
||||
return base.OnIsRunningChanging(oldValue, newValue);
|
||||
return base.OnIsRunningChanging (oldValue, newValue);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Lifecycle Properties
|
||||
|
||||
- **`IsRunning`** - True when runnable is on `RunnableSessionStack`
|
||||
- **`IsRunning`** - True when runnable is on `SessionStack`
|
||||
- **`IsModal`** - True when runnable is at top of stack (capturing all input)
|
||||
- **`Result`** - Typed result value set before stopping
|
||||
|
||||
@@ -310,7 +311,7 @@ All events follow Terminal.Gui's Cancellable Work Pattern:
|
||||
**Example - Result Extraction:**
|
||||
|
||||
```csharp
|
||||
protected override bool OnIsRunningChanging(bool oldValue, bool newValue)
|
||||
protected override bool OnIsRunningChanging (bool oldValue, bool newValue)
|
||||
{
|
||||
if (!newValue) // Stopping
|
||||
{
|
||||
@@ -318,33 +319,39 @@ protected override bool OnIsRunningChanging(bool oldValue, bool newValue)
|
||||
Result = _colorPicker.SelectedColor;
|
||||
|
||||
// Optionally cancel stop (e.g., unsaved changes)
|
||||
if (HasUnsavedChanges())
|
||||
if (HasUnsavedChanges ())
|
||||
{
|
||||
int response = MessageBox.Query("Save?", "Save changes?", "Yes", "No", "Cancel");
|
||||
if (response == 2) return true; // Cancel stop
|
||||
if (response == 0) Save();
|
||||
var response = MessageBox.Query ("Save?", "Save changes?", "Yes", "No", "Cancel");
|
||||
if (response == 2)
|
||||
{
|
||||
return true; // Cancel stop
|
||||
}
|
||||
if (response == 0)
|
||||
{
|
||||
Save ();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return base.OnIsRunningChanging(oldValue, newValue);
|
||||
return base.OnIsRunningChanging (oldValue, newValue);
|
||||
}
|
||||
```
|
||||
|
||||
### RunnableSessionStack
|
||||
### SessionStack
|
||||
|
||||
The `RunnableSessionStack` manages all running `IRunnable` sessions:
|
||||
The `SessionStack` manages all running `IRunnable` sessions:
|
||||
|
||||
```csharp
|
||||
public interface IApplication
|
||||
{
|
||||
/// <summary>
|
||||
/// Stack of running IRunnable sessions.
|
||||
/// Each entry is a RunnableSessionToken wrapping an IRunnable.
|
||||
/// Each entry is a SessionToken wrapping an IRunnable.
|
||||
/// </summary>
|
||||
ConcurrentStack<RunnableSessionToken>? RunnableSessionStack { get; }
|
||||
ConcurrentStack<SessionToken>? SessionStack { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The IRunnable at the top of RunnableSessionStack (currently modal).
|
||||
/// The IRunnable at the top of SessionStack (currently modal).
|
||||
/// </summary>
|
||||
IRunnable? TopRunnable { get; }
|
||||
}
|
||||
@@ -353,9 +360,9 @@ public interface IApplication
|
||||
**Stack Behavior:**
|
||||
|
||||
- Push: `Begin(IRunnable)` adds to top of stack
|
||||
- Pop: `End(RunnableSessionToken)` removes from stack
|
||||
- Pop: `End(SessionToken)` removes from stack
|
||||
- Peek: `TopRunnable` returns current modal runnable
|
||||
- All: `RunnableSessionStack` enumerates all running sessions
|
||||
- All: `SessionStack` enumerates all running sessions
|
||||
|
||||
## IApplication Interface
|
||||
|
||||
@@ -374,19 +381,19 @@ public interface IApplication
|
||||
IMainLoopCoordinator? Coordinator { get; }
|
||||
|
||||
// Fluent API methods
|
||||
IApplication Init(string? driverName = null);
|
||||
void Dispose(); // IDisposable
|
||||
IApplication Init (string? driverName = null);
|
||||
void Dispose (); // IDisposable
|
||||
|
||||
// Runnable methods
|
||||
SessionToken? Begin(IRunnable runnable);
|
||||
object? Run(IRunnable runnable, Func<Exception, bool>? errorHandler = null);
|
||||
IApplication Run<TRunnable>(Func<Exception, bool>? errorHandler = null) where TRunnable : IRunnable, new();
|
||||
void RequestStop(IRunnable? runnable);
|
||||
void End(SessionToken sessionToken);
|
||||
SessionToken? Begin (IRunnable runnable);
|
||||
object? Run (IRunnable runnable, Func<Exception, bool>? errorHandler = null);
|
||||
IApplication Run<TRunnable> (Func<Exception, bool>? errorHandler = null) where TRunnable : IRunnable, new();
|
||||
void RequestStop (IRunnable? runnable);
|
||||
void End (SessionToken sessionToken);
|
||||
|
||||
// Result extraction
|
||||
object? GetResult();
|
||||
T? GetResult<T>() where T : class;
|
||||
object? GetResult ();
|
||||
T? GetResult<T> () where T : class;
|
||||
|
||||
// ... other members
|
||||
}
|
||||
@@ -423,13 +430,13 @@ The `SessionStack` property is the stack of running sessions:
|
||||
|
||||
```csharp
|
||||
// Access all running sessions
|
||||
foreach (var runnable in app.SessionStack)
|
||||
foreach (SessionToken runnable in app.SessionStack)
|
||||
{
|
||||
// Process each session
|
||||
}
|
||||
|
||||
// From within a view
|
||||
int sessionCount = App?.SessionStack.Count ?? 0;
|
||||
var sessionCount = App?.SessionStack.Count ?? 0;
|
||||
```
|
||||
|
||||
**Why "SessionStack" instead of "Runnables"?**
|
||||
@@ -439,25 +446,25 @@ int sessionCount = App?.SessionStack.Count ?? 0;
|
||||
|
||||
## 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:
|
||||
The static `Application` class delegates to a singleton instance and is marked obsolete. All static methods and properties are marked with `[Obsolete]` but remain functional for backward compatibility:
|
||||
|
||||
```csharp
|
||||
public static partial class Application
|
||||
{
|
||||
[Obsolete("The legacy static Application object is going away.")]
|
||||
public static View? TopRunnableView => ApplicationImpl.Instance.TopRunnableView;
|
||||
[Obsolete ("The legacy static Application object is going away.")]
|
||||
public static View? TopRunnableView => Instance.TopRunnableView;
|
||||
|
||||
[Obsolete("The legacy static Application object is going away.")]
|
||||
public static IRunnable? TopRunnable => ApplicationImpl.Instance.TopRunnable;
|
||||
[Obsolete ("The legacy static Application object is going away.")]
|
||||
public static IRunnable? TopRunnable => Instance.TopRunnable;
|
||||
|
||||
[Obsolete("The legacy static Application object is going away.")]
|
||||
public static ConcurrentStack<SessionToken>? SessionStack => ApplicationImpl.Instance.SessionStack;
|
||||
[Obsolete ("The legacy static Application object is going away.")]
|
||||
public static ConcurrentStack<SessionToken>? SessionStack => 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()`.
|
||||
**Important:** The static `Application` class uses a singleton (`Application.Instance`), while `Application.Create()` creates new instances. For new code, prefer the instance-based pattern using `Application.Create()`.
|
||||
|
||||
### Migration Strategies
|
||||
|
||||
@@ -465,15 +472,15 @@ public static partial class Application
|
||||
|
||||
```csharp
|
||||
// OLD:
|
||||
void MyMethod()
|
||||
void MyMethod ()
|
||||
{
|
||||
Application.TopRunnable?.SetNeedsDraw();
|
||||
Application.TopRunnable?.SetNeedsDraw ();
|
||||
}
|
||||
|
||||
// NEW:
|
||||
void MyMethod(View view)
|
||||
void MyMethod (View view)
|
||||
{
|
||||
view.App?.TopRunnableView?.SetNeedsDraw();
|
||||
view.App?.TopRunnableView?.SetNeedsDraw ();
|
||||
}
|
||||
```
|
||||
|
||||
@@ -481,18 +488,18 @@ void MyMethod(View view)
|
||||
|
||||
```csharp
|
||||
// OLD:
|
||||
void ProcessSessions()
|
||||
void ProcessSessions ()
|
||||
{
|
||||
foreach (var runnable in Application.SessionStack)
|
||||
foreach (SessionToken runnable in Application.SessionStack)
|
||||
{
|
||||
// Process
|
||||
}
|
||||
}
|
||||
|
||||
// NEW:
|
||||
void ProcessSessions(IApplication app)
|
||||
void ProcessSessions (IApplication app)
|
||||
{
|
||||
foreach (var runnable in app.SessionStack)
|
||||
foreach (SessionToken runnable in app.SessionStack)
|
||||
{
|
||||
// Process
|
||||
}
|
||||
@@ -506,14 +513,14 @@ public class MyService
|
||||
{
|
||||
private readonly IApplication _app;
|
||||
|
||||
public MyService(IApplication app)
|
||||
public MyService (IApplication app)
|
||||
{
|
||||
_app = app;
|
||||
}
|
||||
|
||||
public void DoWork()
|
||||
public void DoWork ()
|
||||
{
|
||||
_app.Current?.Title = "Processing...";
|
||||
_app.TopRunnable?.Title = "Processing...";
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -530,9 +537,9 @@ Terminal.Gui v2 implements the `IDisposable` pattern for proper resource cleanup
|
||||
|
||||
```csharp
|
||||
// Automatic disposal with using statement
|
||||
using (var app = Application.Create().Init())
|
||||
using (IApplication app = Application.Create ().Init ())
|
||||
{
|
||||
app.Run<MyDialog>();
|
||||
app.Run<MyDialog> ();
|
||||
// app.Dispose() automatically called when scope exits
|
||||
}
|
||||
```
|
||||
@@ -541,15 +548,15 @@ using (var app = Application.Create().Init())
|
||||
|
||||
```csharp
|
||||
// Manual disposal
|
||||
var app = Application.Create();
|
||||
IApplication app = Application.Create ();
|
||||
try
|
||||
{
|
||||
app.Init();
|
||||
app.Run<MyDialog>();
|
||||
app.Init ();
|
||||
app.Run<MyDialog> ();
|
||||
}
|
||||
finally
|
||||
{
|
||||
app.Dispose(); // Ensure cleanup even if exception occurs
|
||||
app.Dispose (); // Ensure cleanup even if exception occurs
|
||||
}
|
||||
```
|
||||
|
||||
@@ -561,44 +568,44 @@ finally
|
||||
|
||||
```csharp
|
||||
// RECOMMENDED (using statement):
|
||||
using (var app = Application.Create().Init())
|
||||
using (IApplication app = Application.Create ().Init ())
|
||||
{
|
||||
app.Run<MyDialog>();
|
||||
var result = app.GetResult<MyResult>();
|
||||
app.Run<MyDialog> ();
|
||||
MyResult? result = app.GetResult<MyResult> ();
|
||||
// app.Dispose() called automatically here
|
||||
}
|
||||
|
||||
// ALTERNATIVE (manual disposal):
|
||||
var app = Application.Create().Init();
|
||||
app.Run<MyDialog>();
|
||||
var result = app.GetResult<MyResult>();
|
||||
app.Dispose(); // Must call explicitly
|
||||
IApplication app = Application.Create ().Init ();
|
||||
app.Run<MyDialog> ();
|
||||
MyResult? result = app.GetResult<MyResult> ();
|
||||
app.Dispose (); // Must call explicitly
|
||||
|
||||
// OLD (obsolete - do not use):
|
||||
var result = app.Run<MyDialog>().Shutdown() as MyResult;
|
||||
object? result = app.Run<MyDialog> ().Shutdown ();
|
||||
```
|
||||
|
||||
### Input Thread Lifecycle
|
||||
|
||||
When you call `Init()`, Terminal.Gui starts a dedicated input thread that continuously polls for console input. This thread must be stopped properly:
|
||||
When calling `Init()`, Terminal.Gui starts a dedicated input thread that continuously polls for console input. This thread must be stopped properly:
|
||||
|
||||
```csharp
|
||||
var app = Application.Create();
|
||||
app.Init("fake"); // Input thread starts here
|
||||
IApplication app = Application.Create ();
|
||||
app.Init ("fake"); // Input thread starts here
|
||||
|
||||
// Input thread runs in background at ~50 polls/second (20ms throttle)
|
||||
|
||||
app.Dispose(); // Cancels input thread and waits for it to exit
|
||||
app.Dispose (); // Cancels input thread and waits for it to exit
|
||||
```
|
||||
|
||||
**Important for Tests**: Always dispose applications in tests to prevent thread leaks:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void My_Test()
|
||||
public void My_Test ()
|
||||
{
|
||||
using var app = Application.Create();
|
||||
app.Init("fake");
|
||||
using IApplication app = Application.Create ();
|
||||
app.Init ("fake");
|
||||
|
||||
// Test code here
|
||||
|
||||
@@ -612,22 +619,22 @@ The legacy static `Application` singleton can be re-initialized after disposal (
|
||||
|
||||
```csharp
|
||||
// Test 1
|
||||
Application.Init();
|
||||
Application.Shutdown(); // Obsolete but still works for legacy singleton
|
||||
Application.Init ();
|
||||
Application.Shutdown (); // Obsolete but still works for legacy singleton
|
||||
|
||||
// Test 2 - singleton resets and can be re-initialized
|
||||
Application.Init(); // ✅ Works!
|
||||
Application.Shutdown(); // Obsolete but still works for legacy singleton
|
||||
Application.Init (); // ✅ Works!
|
||||
Application.Shutdown (); // Obsolete but still works for legacy singleton
|
||||
```
|
||||
|
||||
However, instance-based applications follow standard `IDisposable` semantics and cannot be reused after disposal:
|
||||
|
||||
```csharp
|
||||
var app = Application.Create();
|
||||
app.Init();
|
||||
app.Dispose();
|
||||
IApplication app = Application.Create ();
|
||||
app.Init ();
|
||||
app.Dispose ();
|
||||
|
||||
app.Init(); // ❌ Throws ObjectDisposedException
|
||||
app.Init (); // ❌ Throws ObjectDisposedException
|
||||
```
|
||||
|
||||
## Session Management
|
||||
@@ -637,21 +644,21 @@ app.Init(); // ❌ Throws ObjectDisposedException
|
||||
Applications manage sessions through `Begin()` and `End()`:
|
||||
|
||||
```csharp
|
||||
using var app = Application.Create ();
|
||||
app.Init();
|
||||
using IApplication app = Application.Create ();
|
||||
app.Init ();
|
||||
|
||||
var window = new Window();
|
||||
Window window = new ();
|
||||
|
||||
// Begin a new session - pushes to SessionStack
|
||||
SessionToken? token = app.Begin(window);
|
||||
SessionToken? token = app.Begin (window);
|
||||
|
||||
// TopRunnable now points to this window
|
||||
Debug.Assert(app.TopRunnable == window);
|
||||
Debug.Assert (app.TopRunnable == window);
|
||||
|
||||
// End the session - pops from SessionStack
|
||||
if (token != null)
|
||||
{
|
||||
app.End(token);
|
||||
app.End (token);
|
||||
}
|
||||
|
||||
// TopRunnable restored to previous runnable (if any)
|
||||
@@ -662,25 +669,25 @@ if (token != null)
|
||||
Multiple sessions can run nested:
|
||||
|
||||
```csharp
|
||||
using var app = Application.Create ();
|
||||
app.Init();
|
||||
using IApplication app = Application.Create ();
|
||||
app.Init ();
|
||||
|
||||
// Session 1
|
||||
var main = new Window { Title = "Main" };
|
||||
var token1 = app.Begin(main);
|
||||
Window main = new () { Title = "Main" };
|
||||
SessionToken? token1 = app.Begin (main);
|
||||
// app.TopRunnable == main, SessionStack.Count == 1
|
||||
|
||||
// Session 2 (nested)
|
||||
var dialog = new Dialog { Title = "Dialog" };
|
||||
var token2 = app.Begin(dialog);
|
||||
Dialog dialog = new () { Title = "Dialog" };
|
||||
SessionToken? token2 = app.Begin (dialog);
|
||||
// app.TopRunnable == dialog, SessionStack.Count == 2
|
||||
|
||||
// End dialog
|
||||
app.End(token2);
|
||||
app.End (token2);
|
||||
// app.TopRunnable == main, SessionStack.Count == 1
|
||||
|
||||
// End main
|
||||
app.End(token1);
|
||||
app.End (token1);
|
||||
// app.TopRunnable == null, SessionStack.Count == 0
|
||||
```
|
||||
|
||||
@@ -694,24 +701,24 @@ public class View
|
||||
/// <summary>
|
||||
/// Gets the driver for this view.
|
||||
/// </summary>
|
||||
public IDriver? Driver => GetDriver();
|
||||
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;
|
||||
public virtual IDriver? GetDriver () => App?.Driver;
|
||||
}
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
|
||||
```csharp
|
||||
public override void OnDrawContent(Rectangle viewport)
|
||||
public override void OnDrawContent (Rectangle viewport)
|
||||
{
|
||||
// Use view's driver instead of Application.Driver
|
||||
Driver?.Move(0, 0);
|
||||
Driver?.AddStr("Hello");
|
||||
Driver?.Move (0, 0);
|
||||
Driver?.AddStr ("Hello");
|
||||
}
|
||||
```
|
||||
|
||||
@@ -723,44 +730,44 @@ The instance-based architecture dramatically improves testability:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void MyView_DisplaysCorrectly()
|
||||
public void MyView_DisplaysCorrectly ()
|
||||
{
|
||||
// Create mock application
|
||||
var mockApp = new Mock<IApplication>();
|
||||
mockApp.Setup(a => a.Current).Returns(new Runnable());
|
||||
Mock<IApplication> mockApp = new ();
|
||||
mockApp.Setup (a => a.TopRunnable).Returns (new Runnable ());
|
||||
|
||||
// Create view with mock app
|
||||
var view = new MyView { App = mockApp.Object };
|
||||
MyView view = new () { App = mockApp.Object };
|
||||
|
||||
// Test without Application.Init()!
|
||||
view.SetNeedsDraw();
|
||||
Assert.True(view.NeedsDraw);
|
||||
view.SetNeedsDraw ();
|
||||
Assert.True (view.NeedsDraw);
|
||||
|
||||
// No Application.Shutdown() needed!
|
||||
}
|
||||
```
|
||||
|
||||
### Testing with Real ApplicationImpl
|
||||
### Testing with Real Application
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void MyView_WorksWithRealApplication()
|
||||
public void MyView_WorksWithRealApplication ()
|
||||
{
|
||||
using var app = Application.Create ();
|
||||
app.Init("fake");
|
||||
using IApplication app = Application.Create ();
|
||||
app.Init ("fake");
|
||||
|
||||
var view = new MyView();
|
||||
var top = new Window();
|
||||
top.Add(view);
|
||||
MyView view = new ();
|
||||
Window top = new ();
|
||||
top.Add (view);
|
||||
|
||||
app.Begin(top);
|
||||
app.Begin (top);
|
||||
|
||||
// View.App automatically set
|
||||
Assert.NotNull(view.App);
|
||||
Assert.Same(app, view.App);
|
||||
Assert.NotNull (view.App);
|
||||
Assert.Same (app, view.App);
|
||||
|
||||
// Test view behavior
|
||||
view.DoSomething();
|
||||
view.DoSomething ();
|
||||
}
|
||||
```
|
||||
|
||||
@@ -770,9 +777,9 @@ public void MyView_WorksWithRealApplication()
|
||||
|
||||
```csharp
|
||||
✅ GOOD:
|
||||
public void Refresh()
|
||||
public void Refresh ()
|
||||
{
|
||||
App?.TopRunnableView?.SetNeedsDraw();
|
||||
App?.TopRunnableView?.SetNeedsDraw ();
|
||||
}
|
||||
```
|
||||
|
||||
@@ -780,9 +787,9 @@ public void Refresh()
|
||||
|
||||
```csharp
|
||||
❌ AVOID:
|
||||
public void Refresh()
|
||||
public void Refresh ()
|
||||
{
|
||||
Application.TopRunnableView?.SetNeedsDraw(); // Obsolete!
|
||||
Application.TopRunnableView?.SetNeedsDraw (); // Obsolete!
|
||||
}
|
||||
```
|
||||
|
||||
@@ -792,7 +799,7 @@ public void Refresh()
|
||||
✅ GOOD:
|
||||
public class Service
|
||||
{
|
||||
public Service(IApplication app) { }
|
||||
public Service (IApplication app) { }
|
||||
}
|
||||
```
|
||||
|
||||
@@ -800,15 +807,15 @@ public class Service
|
||||
|
||||
```csharp
|
||||
❌ AVOID (obsolete pattern):
|
||||
public void Refresh()
|
||||
public void Refresh ()
|
||||
{
|
||||
Application.TopRunnableView?.SetNeedsDraw(); // Obsolete static access
|
||||
Application.TopRunnableView?.SetNeedsDraw (); // Obsolete static access
|
||||
}
|
||||
|
||||
✅ PREFERRED:
|
||||
public void Refresh()
|
||||
public void Refresh ()
|
||||
{
|
||||
App?.TopRunnableView?.SetNeedsDraw(); // Use View.App property
|
||||
App?.TopRunnableView?.SetNeedsDraw (); // Use View.App property
|
||||
}
|
||||
```
|
||||
|
||||
@@ -820,9 +827,9 @@ public class SpecialView : View
|
||||
{
|
||||
private IApplication? _customApp;
|
||||
|
||||
public override IApplication? GetApp()
|
||||
public override IApplication? GetApp ()
|
||||
{
|
||||
return _customApp ?? base.GetApp();
|
||||
return _customApp ?? base.GetApp ();
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -835,15 +842,15 @@ The instance-based architecture enables multiple applications:
|
||||
|
||||
```csharp
|
||||
// Application 1
|
||||
using var app1 = Application.Create ();
|
||||
app1.Init("windows");
|
||||
var top1 = new Window { Title = "App 1" };
|
||||
using IApplication app1 = Application.Create ();
|
||||
app1.Init ("windows");
|
||||
Window top1 = new () { Title = "App 1" };
|
||||
// ... configure top1
|
||||
|
||||
// Application 2 (different driver!)
|
||||
using var app2 = Application.Create ();
|
||||
app2.Init("unix");
|
||||
var top2 = new Window { Title = "App 2" };
|
||||
using IApplication app2 = Application.Create ();
|
||||
app2.Init ("unix");
|
||||
Window top2 = new () { Title = "App 2" };
|
||||
// ... configure top2
|
||||
|
||||
// Views in top1 use app1
|
||||
@@ -857,14 +864,14 @@ Create views that work with any application:
|
||||
```csharp
|
||||
public class UniversalView : View
|
||||
{
|
||||
public void ShowMessage(string message)
|
||||
public void ShowMessage (string message)
|
||||
{
|
||||
// Works regardless of which application context
|
||||
var app = GetApp();
|
||||
IApplication? app = GetApp ();
|
||||
if (app != null)
|
||||
{
|
||||
var msg = new MessageBox(message);
|
||||
app.Begin(msg);
|
||||
MessageBox msg = new (message);
|
||||
app.Begin (msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ The driver architecture employs a **multi-threaded design** for optimal responsi
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ ApplicationImpl.Init() │
|
||||
│ IApplication.Init() │
|
||||
│ Creates MainLoopCoordinator<T> with │
|
||||
│ ComponentFactory<T> │
|
||||
└────────────────┬────────────────────────────┘
|
||||
@@ -128,7 +128,7 @@ This separation ensures that input is never lost and the UI remains responsive d
|
||||
|
||||
When you call `Application.Init()`:
|
||||
|
||||
1. **ApplicationImpl.Init()** is invoked
|
||||
1. **IApplication.Init()** is invoked
|
||||
2. Creates a `MainLoopCoordinator<T>` with the appropriate `ComponentFactory<T>`
|
||||
3. **MainLoopCoordinator.StartAsync()** begins:
|
||||
- Starts the input thread which creates `IInput<T>`
|
||||
@@ -220,6 +220,5 @@ This ensures Terminal.Gui applications can be debugged directly in Visual Studio
|
||||
## See Also
|
||||
|
||||
- @Terminal.Gui.Drivers - API Reference
|
||||
- @Terminal.Gui.App.Application - Application class
|
||||
- @Terminal.Gui.App.ApplicationImpl - Application implementation
|
||||
- @Terminal.Gui.App.IApplication - Application interface
|
||||
- @Terminal.Gui.App.MainLoopCoordinator`1 - Main loop coordination
|
||||
|
||||
@@ -230,7 +230,7 @@ The @Terminal.Gui.App.Keyboard class implements @Terminal.Gui.App.IKeyboard and
|
||||
- **Events**: KeyDown, KeyUp events for application-level keyboard monitoring
|
||||
- **Command Implementations**: Handlers for Application-scoped commands (Quit, Suspend, Navigation, Refresh, Arrange)
|
||||
|
||||
The @Terminal.Gui.App.ApplicationImpl class creates and manages the @Terminal.Gui.App.IKeyboard instance, setting its `IApplication` property to `this` to provide the necessary @Terminal.Gui.App.IApplication reference.
|
||||
The @Terminal.Gui.App.IApplication implementations create and manage the @Terminal.Gui.App.IKeyboard instance, setting its `IApplication` property to `this` to provide the necessary @Terminal.Gui.App.IApplication reference.
|
||||
|
||||
## Driver
|
||||
|
||||
|
||||
Reference in New Issue
Block a user