Browse Source

Merge branch 'v2_develop' into copilot/fix-e6dde989-9ea1-4d83-8522-54ed8f70815a

Tig 1 month ago
parent
commit
2fbfb31a73
79 changed files with 3603 additions and 2874 deletions
  1. 2 45
      .cursorrules
  2. 123 24
      .github/ISSUE_TEMPLATE/bug_report.md
  3. 4 324
      .github/copilot-instructions.md
  4. 10 175
      AGENTS.md
  5. 344 159
      CONTRIBUTING.md
  6. 4 1
      Examples/UICatalog/Scenarios/AnimationScenario/AnimationScenario.cs
  7. 0 1
      Examples/UICatalog/Scenarios/Arrangement.cs
  8. 0 1
      Examples/UICatalog/Scenarios/Clipping.cs
  9. 0 2
      Examples/UICatalog/Scenarios/ProgressBarStyles.cs
  10. 0 1
      Examples/UICatalog/Scenarios/Shortcuts.cs
  11. 1 1
      README.md
  12. 1 1
      Terminal.Gui/App/Application.Lifecycle.cs
  13. 4 76
      Terminal.Gui/App/Application.Run.cs
  14. 0 3
      Terminal.Gui/App/Application.cs
  15. 1 1
      Terminal.Gui/App/ApplicationImpl.cs
  16. 0 24
      Terminal.Gui/App/MainLoop/IMainLoopDriver.cs
  17. 0 122
      Terminal.Gui/App/MainLoop/LegacyMainLoopDriver.cs
  18. 2 17
      Terminal.Gui/App/MainLoop/MainLoopSyncContext.cs
  19. 56 2
      Terminal.Gui/Drivers/AnsiHandling/EscSeqUtils/EscSeqUtils.cs
  20. 345 0
      Terminal.Gui/Drivers/AnsiHandling/Osc8UrlLinker.cs
  21. 1 2
      Terminal.Gui/Drivers/ConsoleDriver.cs
  22. 1 1
      Terminal.Gui/Drivers/ConsoleDriverFacade.cs
  23. 5 0
      Terminal.Gui/Drivers/DotNetDriver/NetInput.cs
  24. 1 27
      Terminal.Gui/Drivers/FakeDriver/FakeDriver.cs
  25. 0 38
      Terminal.Gui/Drivers/FakeDriver/FakeMainLoop.cs
  26. 1 2
      Terminal.Gui/Drivers/IConsoleDriver.cs
  27. 48 53
      Terminal.Gui/Drivers/OutputBase.cs
  28. 34 68
      Terminal.Gui/README.md
  29. 10 10
      Terminal.Gui/ViewBase/Adornment/ShadowView.cs
  30. 1 1
      Terminal.Gui/ViewBase/View.Drawing.cs
  31. 3 0
      Terminal.Gui/ViewBase/View.cs
  32. 1 1
      Terminal.Gui/Views/Color/ColorBar.cs
  33. 4 4
      Terminal.Gui/Views/FileDialogs/FileDialog.cs
  34. 1 1
      Terminal.Gui/Views/GraphView/GraphView.cs
  35. 1 1
      Terminal.Gui/Views/GraphView/IAnnotation.cs
  36. 2 2
      Terminal.Gui/Views/GraphView/TextAnnotation.cs
  37. 3 3
      Terminal.Gui/Views/ListView.cs
  38. 18 20
      Terminal.Gui/Views/Menuv1/Menu.cs
  39. 1 1
      Terminal.Gui/Views/Menuv1/MenuBar.cs
  40. 4 4
      Terminal.Gui/Views/ProgressBar.cs
  41. 1 1
      Terminal.Gui/Views/RadioGroup.cs
  42. 2 2
      Terminal.Gui/Views/Slider/Slider.cs
  43. 1 1
      Terminal.Gui/Views/SpinnerView/SpinnerView.cs
  44. 19 20
      Terminal.Gui/Views/TableView/TableView.cs
  45. 1 1
      Terminal.Gui/Views/TableView/TreeTableSource.cs
  46. 3 3
      Terminal.Gui/Views/TextInput/TextField.cs
  47. 4 4
      Terminal.Gui/Views/TextInput/TextValidateField.cs
  48. 1 1
      Terminal.Gui/Views/TreeView/Branch.cs
  49. 3 3
      Terminal.Gui/Views/TreeView/TreeView.cs
  50. 3 2
      Terminal.sln
  51. 2 1
      Terminal.sln.ToDo.DotSettings
  52. 8 3
      Tests/StressTests/ApplicationStressTests.cs
  53. 2 20
      Tests/UnitTests/Application/ApplicationTests.cs
  54. 0 842
      Tests/UnitTests/Application/MainLoopTests.cs
  55. 0 1
      Tests/UnitTests/Application/RunStateTests.cs
  56. 2 2
      Tests/UnitTests/ConsoleDrivers/ConsoleDriverTests.cs
  57. 9 13
      Tests/UnitTests/Dialogs/WizardTests.cs
  58. 2 2
      Tests/UnitTests/View/Adornment/BorderTests.cs
  59. 0 1
      Tests/UnitTests/View/Draw/AllViewsDrawTests.cs
  60. 3 3
      Tests/UnitTests/View/Draw/ClearViewportTests.cs
  61. 0 1
      Tests/UnitTests/View/Layout/LayoutTests.cs
  62. 0 1
      Tests/UnitTests/Views/AllViewsTests.cs
  63. 6 6
      Tests/UnitTests/Views/LabelTests.cs
  64. 8 11
      Tests/UnitTests/Views/Menuv1/MenuBarv1Tests.cs
  65. 2 2
      Tests/UnitTests/Views/TextViewTests.cs
  66. 0 300
      Tests/UnitTestsParallelizable/ConsoleDrivers/MainLoopDriverTests.cs
  67. 170 0
      Tests/UnitTestsParallelizable/ConsoleDrivers/UrlHyperlinkerTests.cs
  68. 1 1
      Tests/UnitTestsParallelizable/MockConsoleDriver.cs
  69. 0 1
      Tests/UnitTestsParallelizable/TestSetup.cs
  70. 633 56
      docfx/docs/View.md
  71. 684 51
      docfx/docs/arrangement.md
  72. 807 217
      docfx/docs/config.md
  73. 25 7
      docfx/docs/drivers.md
  74. 38 9
      docfx/docs/migratingfromv1.md
  75. 4 4
      docfx/docs/multitasking.md
  76. 116 56
      docfx/docs/newinv2.md
  77. 6 6
      docfx/includes/arrangement-lexicon.md
  78. BIN
      local_packages/Terminal.Gui.2.0.0.nupkg
  79. BIN
      local_packages/Terminal.Gui.2.0.0.snupkg

+ 2 - 45
.cursorrules

@@ -1,48 +1,5 @@
 # Terminal.Gui - Cursor AI Rules
 
-This project uses comprehensive AI agent instructions. See:
-- `.github/copilot-instructions.md` - Complete onboarding guide (primary reference)
-- `AGENTS.md` - General AI agent guidelines
+> **📘 Source of Truth: [CONTRIBUTING.md](CONTRIBUTING.md)**
 
-## Quick Reference
-
-### Project Type
-- .NET 8.0 cross-platform console UI toolkit
-- 496 source files in core library
-- GitFlow branching (v2_develop = default)
-
-### Essential Commands
-
-```bash
-# Always run from repo root in this order:
-dotnet restore                                              # First! (~15-20s)
-dotnet build --configuration Debug --no-restore            # ~50s, expect ~326 warnings
-dotnet test Tests/UnitTestsParallelizable --no-build       # Preferred test suite
-dotnet run --project Examples/UICatalog/UICatalog.csproj   # Demo app
-```
-
-### Code Style (Enforced)
-- **DO**: Use explicit types (avoid `var`), target-typed `new()`, 4-space indent
-- **DO**: Format only files you modify (ReSharper/Rider `Ctrl-E-C` or `Ctrl-K-D`)
-- **DO**: Follow `.editorconfig` and `Terminal.sln.DotSettings`
-- **DON'T**: Add new linters, modify unrelated code, decrease test coverage
-
-### Testing Rules
-- Add new tests to `Tests/UnitTestsParallelizable/` (preferred)
-- Avoid `Application.Init` and static dependencies in tests
-- Don't use `[AutoInitShutdown]` attribute (legacy)
-- Maintain 70%+ code coverage on new code
-
-### API Documentation (Required)
-- All public APIs need XML docs (`<summary>`, `<remarks>`, `<example>`)
-- Use `<see cref=""/>` for cross-references
-- Complex topics → `docfx/docs/*.md`
-
-### Common Issues
-- ~326 build warnings are normal (nullable refs, etc.)
-- Tests can take 5-10 minutes
-- Run `dotnet restore` before any build
-- Read `.github/copilot-instructions.md` for full troubleshooting
-
----
-**See `.github/copilot-instructions.md` for complete instructions**
+This project uses [CONTRIBUTING.md](CONTRIBUTING.md) as the single source of truth for contribution guidelines. AI agents, including CoPilot and Cursor **MUST** follow the guidelines in [CONTRIBUTING.md](CONTRIBUTING.md)/

+ 123 - 24
.github/ISSUE_TEMPLATE/bug_report.md

@@ -1,41 +1,140 @@
 ---
 name: Bug report
-about: Create a report to help us improve
+about: Create a report to help us improve Terminal.Gui
 title: ''
 labels: bug
 assignees: ''
 
 ---
 
-**Describe the bug**
+## Describe the bug
+
 A clear and concise description of what the bug is.
 
-**To Reproduce**
+## To Reproduce
+
 Steps to reproduce the behavior:
-1. Go to '...'
-2. Click on '....'
-3. Scroll down to '....'
-4. See error
 
-**Expected behavior**
-A clear and concise description of what you expected to happen.
+1. Run the following code:
+   ```csharp
+   // Paste your minimal reproduction code here
+   ```
+
+2. Expected behavior: (describe what should happen)
+
+3. Actual behavior: (describe what actually happens)
+
+## Environment
+
+Please run the following commands in your terminal and paste the output:
+
+### OS Information
+
+**Windows (PowerShell):**
+```powershell
+"OS: $(Get-CimInstance Win32_OperatingSystem | Select-Object -ExpandProperty Caption) $(Get-CimInstance Win32_OperatingSystem | Select-Object -ExpandProperty Version)"
+```
+
+**macOS/Linux:**
+```bash
+echo "OS: $(uname -s) $(uname -r)"
+```
+
+**Output:**
+```
+(paste output here)
+```
+
+### Terminal Information
+
+**Windows Terminal:**
+```powershell
+"Terminal: Windows Terminal $(Get-AppxPackage -Name Microsoft.WindowsTerminal | Select-Object -ExpandProperty Version)"
+```
+
+**Other terminals:**
+```bash
+echo $TERM
+```
+
+**Output:**
+```
+(paste output here)
+```
+
+### PowerShell Version
+
+```powershell
+$PSVersionTable.PSVersion
+```
+
+**Output:**
+```
+(paste output here)
+```
+
+### .NET Information
+
+```bash
+dotnet --version
+dotnet --info
+```
+
+**Output:**
+```
+(paste output here)
+```
+
+### Terminal.Gui Version
+
+**Option 1 - Run UICatalog (easiest):**
+
+UICatalog displays the Terminal.Gui version in its About box and status bar.
+
+```bash
+dotnet run --project Examples/UICatalog/UICatalog.csproj
+```
+
+**Option 2 - NuGet Package Version:**
+```
+(e.g., 2.0.0-alpha.1, 2.0.0-develop.123, etc.)
+```
+
+**Option 3 - Building from source:**
+```bash
+git rev-parse HEAD
+git describe --tags --always --dirty
+```
+
+**Version:**
+```
+(paste version here)
+```
+
+## Screenshots, GIFs, or Terminal Output
+
+If applicable, add screenshots, animated GIFs, or copy/paste terminal output to help explain your problem.
+
+**Animated GIFs are especially helpful for showing behavior!**
+
+- **Windows**: [ShareX](https://getsharex.com/) (free, captures screen to GIF)
+- **macOS**: [Kap](https://getkap.co/) (free, open source)
+- **Linux**: [Peek](https://github.com/phw/peek) (free)
+
+**For terminal output, use code blocks:**
 
-**Screenshots**
-If applicable, add screenshots to help explain your problem.
+```
+(paste terminal output here)
+```
 
-**Desktop (please complete the following information):**
- - OS: [e.g. iOS]
- - Browser [e.g. chrome, safari]
- - Version [e.g. 22]
+## Additional context
 
-**Smartphone (please complete the following information):**
- - Device: [e.g. iPhone6]
- - OS: [e.g. iOS8.1]
- - Browser [e.g. stock browser, safari]
- - Version [e.g. 22]
+Add any other context about the problem here, such as:
+- Does this happen consistently or intermittently?
+- Did this work in a previous version?
+- Are there any error messages in the console?
+- Terminal configuration or settings that might be relevant?
 
-**Additional context**
-Add any other context about the problem here.
+## For Maintainers
 
-**Set Project & Milestone**
-If you have access, please don't forget to set the right Project and Milestone.
+**Set Project & Milestone:** If you have access, please don't forget to set the right Project and Milestone.

+ 4 - 324
.github/copilot-instructions.md

@@ -1,327 +1,7 @@
-# Terminal.Gui - Copilot Coding Agent Instructions
+# Terminal.Gui - CoPilot AI Rules
 
-This file provides onboarding instructions for GitHub Copilot and other AI coding agents working with Terminal.Gui.
+> **📘 Source of Truth: [../CONTRIBUTING.md](../CONTRIBUTING.md)**
 
-## Project Overview
+This project uses [../CONTRIBUTING.md](../CONTRIBUTING.md) as the single source of truth for contribution guidelines. AI agents, including CoPilot and Cursor **MUST** follow the guidelines in [../CONTRIBUTING.md](CONTRIBUTING.md)/
 
-**Terminal.Gui** is a cross-platform UI toolkit for creating console-based graphical user interfaces in .NET. It's a large codebase (~1,050 C# files, 333MB) providing a comprehensive framework for building interactive console applications with support for keyboard and mouse input, customizable views, and a robust event system.
-
-**Key characteristics:**
-- **Language**: C# (net8.0)
-- **Size**: ~496 source files in core library, ~1,050 total C# files
-- **Platform**: Cross-platform (Windows, macOS, Linux)
-- **Architecture**: Console UI toolkit with driver-based architecture
-- **Version**: v2 (Alpha), v1 (maintenance mode)
-- **Branching**: GitFlow model (v2_develop is default/active development)
-
-## Building and Testing
-
-### Required Tools
-- **.NET SDK**: 8.0.0 (see `global.json`)
-- **Runtime**: .NET 8.x (latest GA)
-- **Optional**: ReSharper/Rider for code formatting
-
-### Build Commands (In Order)
-
-**ALWAYS run these commands from the repository root:**
-
-1. **Restore packages** (required first, ~15-20 seconds):
-   ```bash
-   dotnet restore
-   ```
-
-2. **Build solution** (Debug, ~50 seconds):
-   ```bash
-   dotnet build --configuration Debug --no-restore
-   ```
-   - Expect ~326 warnings (nullable reference warnings, unused variables, etc.) - these are normal
-   - 0 errors expected
-
-3. **Build Release** (for packaging):
-   ```bash
-   dotnet build --configuration Release --no-restore
-   ```
-
-### Test Commands
-
-**Two test projects exist:**
-
-1. **Non-parallel tests** (depend on static state, ~10 min timeout):
-   ```bash
-   dotnet test Tests/UnitTests --no-build --verbosity normal
-   ```
-   - Uses `Application.Init` and static state
-   - Cannot run in parallel
-   - Includes `--blame` flags for crash diagnostics
-
-2. **Parallel tests** (can run concurrently, ~10 min timeout):
-   ```bash
-   dotnet test Tests/UnitTestsParallelizable --no-build --verbosity normal
-   ```
-   - No dependencies on static state
-   - Preferred for new tests
-
-3. **Integration tests**:
-   ```bash
-   dotnet test Tests/IntegrationTests --no-build --verbosity normal
-   ```
-
-**Important**: Tests may take significant time. CI uses blame flags for crash detection:
-```bash
---diag:logs/UnitTests/logs.txt --blame --blame-crash --blame-hang --blame-hang-timeout 60s --blame-crash-collect-always
-```
-
-### Running Examples
-
-**UICatalog** (comprehensive demo app):
-```bash
-dotnet run --project Examples/UICatalog/UICatalog.csproj
-```
-
-## Repository Structure
-
-### Root Directory Files
-- `Terminal.sln` - Main solution file
-- `Terminal.sln.DotSettings` - ReSharper code style settings
-- `.editorconfig` - Code formatting rules (111KB, extensive)
-- `global.json` - .NET SDK version pinning
-- `Directory.Build.props` - Common MSBuild properties
-- `Directory.Packages.props` - Central package version management
-- `GitVersion.yml` - Version numbering configuration
-- `AGENTS.md` - General AI agent instructions (also useful reference)
-- `CONTRIBUTING.md` - Contribution guidelines
-- `README.md` - Project documentation
-
-### Main Directories
-
-**`/Terminal.Gui/`** - Core library (496 C# files):
-- `App/` - Application lifecycle (`Application.cs` static class, `RunState`, `MainLoop`)
-- `Configuration/` - `ConfigurationManager` for settings
-- `Drivers/` - Console driver implementations (`IConsoleDriver`, `NetDriver`, `UnixDriver`, `WindowsDriver`)
-- `Drawing/` - Rendering system (attributes, colors, glyphs)
-- `Input/` - Keyboard and mouse input handling
-- `ViewBase/` - Core `View` class hierarchy and layout
-- `Views/` - Specific View subclasses (Window, Dialog, Button, ListView, etc.)
-- `Text/` - Text manipulation and formatting
-
-**`/Tests/`**:
-- `UnitTests/` - Non-parallel tests (use `Application.Init`, static state)
-- `UnitTestsParallelizable/` - Parallel tests (no static dependencies)
-- `IntegrationTests/` - Integration tests
-- `StressTests/` - Long-running stress tests (scheduled daily)
-- `coverlet.runsettings` - Code coverage configuration
-
-**`/Examples/`**:
-- `UICatalog/` - Comprehensive demo app for manual testing
-- `Example/` - Basic example
-- `NativeAot/`, `SelfContained/` - Deployment examples
-- `ReactiveExample/`, `CommunityToolkitExample/` - Integration examples
-
-**`/docfx/`** - Documentation source:
-- `docs/` - Conceptual documentation (deep dives)
-- `api/` - Generated API docs (gitignored)
-- `docfx.json` - DocFX configuration
-
-**`/Scripts/`** - PowerShell build utilities (requires PowerShell 7.4+)
-
-**`/.github/workflows/`** - CI/CD pipelines:
-- `unit-tests.yml` - Main test workflow (Ubuntu, Windows, macOS)
-- `build-release.yml` - Release build verification
-- `integration-tests.yml` - Integration test workflow
-- `publish.yml` - NuGet package publishing
-- `api-docs.yml` - Documentation building and deployment
-- `codeql-analysis.yml` - Security scanning
-
-## Code Style and Quality
-
-### Formatting
-- **Do NOT add formatting tools** - Use existing `.editorconfig` and `Terminal.sln.DotSettings`
-- Format code with:
-  1. ReSharper/Rider (`Ctrl-E-C`)
-  2. JetBrains CleanupCode CLI tool (free)
-  3. Visual Studio (`Ctrl-K-D`) as fallback
-- **Only format files you modify**
-
-### Code Style Tenets
-1. **Six-Year-Old Reading Level** - Readability over terseness
-2. **Consistency, Consistency, Consistency** - Follow existing patterns ruthlessly
-3. **Don't be Weird** - Follow Microsoft/.NET conventions
-4. **Set and Forget** - Rely on automated tooling
-5. **Documentation is the Spec** - API docs are source of truth
-
-### Coding Conventions
-
-**⚠️ CRITICAL - These rules MUST be followed in ALL new code:**
-
-#### Type Declarations and Object Creation
-- **ALWAYS use explicit types** - Never use `var` except for basic types (`int`, `string`, `bool`, `double`, `float`, `decimal`, `char`, `byte`)
-  ```csharp
-  // ✅ CORRECT - Explicit types
-  View view = new () { Width = 10 };
-  MouseEventArgs args = new () { Position = new Point(5, 5) };
-  List<View?> views = new ();
-  var count = 0;  // OK - int is a basic type
-  var name = "test";  // OK - string is a basic type
-  
-  // ❌ WRONG - Using var for non-basic types
-  var view = new View { Width = 10 };
-  var args = new MouseEventArgs { Position = new Point(5, 5) };
-  var views = new List<View?>();
-  ```
-
-- **ALWAYS use target-typed `new()`** - Use `new ()` instead of `new TypeName()` when the type is already declared
-  ```csharp
-  // ✅ CORRECT - Target-typed new
-  View view = new () { Width = 10 };
-  MouseEventArgs args = new ();
-  
-  // ❌ WRONG - Redundant type name
-  View view = new View() { Width = 10 };
-  MouseEventArgs args = new MouseEventArgs();
-  ```
-
-#### Other Conventions
-- Follow `.editorconfig` settings (e.g., braces on new lines, spaces after keywords)
-- 4-space indentation
-- No trailing whitespace
-- See `CONTRIBUTING.md` for full guidelines
-
-**These conventions apply to ALL code - production code, test code, examples, and samples.**
-
-## Testing Requirements
-
-### Code Coverage
-- **Never decrease code coverage** - PRs must maintain or increase coverage
-- Target: 70%+ coverage for new code
-- CI monitors coverage on each PR
-
-### Test Patterns
-- **Parallelizable tests preferred** - Add new tests to `UnitTestsParallelizable` when possible
-- **Avoid static dependencies** - Don't use `Application.Init`, `ConfigurationManager` in tests
-- **Don't use `[AutoInitShutdown]`** - Legacy pattern, being phased out
-- **Make tests granular** - Each test should cover smallest area possible
-- Follow existing test patterns in respective test projects
-
-### Test Configuration
-- `xunit.runner.json` - xUnit configuration
-- `coverlet.runsettings` - Coverage settings (OpenCover format)
-
-## API Documentation Requirements
-
-**All public APIs MUST have XML documentation:**
-- Clear, concise `<summary>` tags
-- Use `<see cref=""/>` for cross-references
-- Add `<remarks>` for context
-- Include `<example>` for non-obvious usage
-- Complex topics → `docfx/docs/*.md` files
-- Proper English and grammar
-
-## Common Build Issues
-
-### Issue: Build Warnings
-- **Expected**: ~326 warnings (nullable refs, unused vars, xUnit suggestions)
-- **Action**: Don't add new warnings; fix warnings in code you modify
-
-### Issue: Test Timeouts
-- **Expected**: Tests can take 5-10 minutes
-- **Action**: Use appropriate timeout values (60-120 seconds for test commands)
-
-### Issue: Restore Failures
-- **Solution**: Ensure `dotnet restore` completes before building
-- **Note**: Takes 15-20 seconds on first run
-
-### Issue: NativeAot/SelfContained Build
-- **Solution**: Restore these projects explicitly:
-  ```bash
-  dotnet restore ./Examples/NativeAot/NativeAot.csproj -f
-  dotnet restore ./Examples/SelfContained/SelfContained.csproj -f
-  ```
-
-## CI/CD Validation
-
-The following checks run on PRs:
-
-1. **Unit Tests** (`unit-tests.yml`):
-   - Runs on Ubuntu, Windows, macOS
-   - Both parallel and non-parallel test suites
-   - Code coverage collection
-   - 10-minute timeout per job
-
-2. **Build Release** (`build-release.yml`):
-   - Verifies Release configuration builds
-   - Tests NativeAot and SelfContained builds
-   - Packs NuGet package
-
-3. **Integration Tests** (`integration-tests.yml`):
-   - Cross-platform integration testing
-   - 10-minute timeout
-
-4. **CodeQL Analysis** (`codeql-analysis.yml`):
-   - Security vulnerability scanning
-
-To replicate CI locally:
-```bash
-# Full CI sequence:
-dotnet restore
-dotnet build --configuration Debug --no-restore
-dotnet test Tests/UnitTests --no-build --verbosity normal
-dotnet test Tests/UnitTestsParallelizable --no-build --verbosity normal
-dotnet build --configuration Release --no-restore
-```
-
-## Branching and PRs
-
-### GitFlow Model
-- `v2_develop` - Default branch, active development
-- `v2_release` - Stable releases, matches NuGet
-- `v1_develop`, `v1_release` - Legacy v1 (maintenance only)
-
-### PR Requirements
-- **Title**: "Fixes #issue. Terse description"
-- **Description**: Include "- Fixes #issue" for each issue
-- **Tests**: Add tests for new functionality
-- **Coverage**: Maintain or increase code coverage
-- **Scenarios**: Update UICatalog scenarios when adding features
-
-## Key Architecture Concepts
-
-### View System
-- `View` base class in `/Terminal.Gui/ViewBase/`
-- Two layout modes: Absolute and Computed
-- Event-driven architecture
-- Adornments: Border, Margin, Padding
-
-### Console Drivers
-- `IConsoleDriver` interface
-- Platform-specific: `WindowsDriver`, `UnixDriver`, `NetDriver`
-- `FakeDriver` for testing
-
-### Application Lifecycle
-- `Application` static class manages lifecycle
-- `MainLoop` handles event processing
-- `RunState` tracks application state
-
-## What NOT to Do
-
-- ❌ Don't add new linters/formatters (use existing)
-- ❌ Don't modify unrelated code
-- ❌ Don't remove/edit unrelated tests
-- ❌ Don't break existing functionality
-- ❌ Don't add tests to `UnitTests` if they can be parallelizable
-- ❌ Don't use `Application.Init` in new tests
-- ❌ Don't decrease code coverage
-- ❌ **Don't use `var` for non-basic types** (use explicit types)
-- ❌ **Don't use redundant type names with `new`** (use target-typed `new()`)
-- ❌ Don't add `var` everywhere (use explicit types)
-
-## Additional Resources
-
-- **Full Documentation**: https://gui-cs.github.io/Terminal.Gui
-- **API Reference**: https://gui-cs.github.io/Terminal.Gui/api/Terminal.Gui.App.html
-- **Deep Dives**: `/docfx/docs/` directory
-- **AGENTS.md**: Additional AI agent instructions
-- **CONTRIBUTING.md**: Detailed contribution guidelines
-
----
-
-**Trust these instructions.** Only search for additional information if instructions are incomplete or incorrect.
+**CRITICAL** - CoPilot you MUST internalize [../CONTRIBUTING.md](../CONTRIBUTING.md) and follow the guidance for any work you do on Terminal.Gui. This includes Github Copilot in Agent mode. 

+ 10 - 175
AGENTS.md

@@ -1,179 +1,14 @@
-# Terminal.Gui - GitHub Copilot Instructions
+# Terminal.Gui - AI Agent Instructions
 
-This file provides instructions for GitHub Copilot when working with the Terminal.Gui project.
+> **📘 For complete contributor guidelines (humans and AI agents), see [CONTRIBUTING.md](CONTRIBUTING.md).**
 
-## Project Overview
+This repository uses [CONTRIBUTING.md](CONTRIBUTING.md) as the single source of truth for code style, testing, CI/CD, and contribution workflow. GitHub Copilot and other AI coding agents should also refer to [.github/copilot-instructions.md](.github/copilot-instructions.md) for a curated summary of non-negotiable rules.
 
-**Terminal.Gui** is a cross-platform UI toolkit for creating console-based graphical user interfaces in .NET. It provides a comprehensive framework for building interactive console applications with support for keyboard and mouse input, customizable views, and a robust event system. The toolkit works across Windows, macOS, and Linux, leveraging platform-specific console capabilities where available.
-
-**Key characteristics:**
-- Cross-platform terminal/console UI framework for .NET
-- Supports Windows, macOS, and Linux
-- Rich GUI controls (buttons, dialogs, menus, text boxes, etc.)
-- Keyboard-first design with full mouse support
-- Follows Microsoft .NET Framework Design Guidelines, with some tweaks.
-- v2 is currently in Alpha with stable core API (v1 is in maintenance mode)
-
-## Documentation
-
-- Full documentation: [gui-cs.github.io/Terminal.Gui](https://gui-cs.github.io/Terminal.Gui)
-- API Reference: [API Documentation](https://gui-cs.github.io/Terminal.Gui/api/Terminal.Gui.App.html)
-- Getting Started: [Getting Started Guide](https://gui-cs.github.io/Terminal.Gui/docs/getting-started)
-
-## Repository Structure
-
-- `/Terminal.Gui/` - Core library source code
-  - `App/` - Core application logic, `Application.cs` (static class managing `RunState` and `MainLoop`)
-  - `Configuration/` - `ConfigurationManager` for application settings
-  - `Drivers/` - Console driver implementations (`IConsoleDriver.cs`, `NetDriver`, `UnixDriver`, `WindowsDriver`)
-  - `Drawing/` - Rendering graphical elements in the console
-  - `Input/` - Keyboard and mouse input handling
-  - `View/` - Core `View` class hierarchy
-  - `Views/` - Specific sub-classes of `View` (Toplevel, Window, Dialog, etc.)
-- `/Examples/` - Sample applications and demos
-- `/Examples/UICatalog/` - Comprehensive demo app for manual testing
-- `/Tests/` - Unit and integration tests
-- `/docfx/` - Documentation source files (Deep Dive Articles and API docs)
-- `/Scripts/` - Build and utility scripts
-
-## Branching Model
-
-**Terminal.Gui uses GitFlow:**
-- `v2_develop` - Default branch for v2 development (active development)
-- `v2_release` - Stable release branches matching NuGet packages
-
-## Code Style and Standards
-
-### Code Style Tenets
-
-1. **Six-Year-Old Reading Level** - Prioritize readability over terseness. Use clear variable names and comments.
-2. **Consistency, Consistency, Consistency** - Follow established patterns ruthlessly.
-3. **Don't be Weird** - Follow Microsoft and .NET community conventions.
-4. **Set and Forget** - Use ReSharper/Rider for automated formatting.
-5. **Documentation is the Spec** - API documentation is the source of truth.
-
-### Coding Conventions
-
-- Based on [Microsoft C# Coding Conventions](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions)
-- Project settings defined and enforced via `./Terminal.sln.DotSettings` and `./.editorconfig`
-- Use `var` only for the most basic dotnet types - prefer explicit types for clarity
-- Use target-typed new
-
-## API Design Guidelines
-
-### Public API Tenets
-
-1. **Stand on the shoulders of giants** - Follow [Microsoft .NET Framework Design Guidelines](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/)
-2. **Don't Break Existing Stuff** - Avoid breaking changes; find compatible ways to add features
-3. **Fail-fast** - Prefer early failure to expose bugs sooner
-4. **Standards Reduce Complexity** - Use standard .NET idioms, tweaked to match Terminal.Gui. 
-
-### API Documentation Requirements
-
-**All public APIs must have XML documentation:**
-- Clear, concise, and complete `<summary>` tags
-- Use `<see cref=""/>` liberally for cross-references
-- Add `<remarks>` for context and detailed explanations
-- Document complex topics in `docfx/articles/*.md` files
-- Use proper English and correct grammar
-- Provide sample code via `<example>` in cases where a sample is needed (not for very obvious things)
-
-### Events
-
-- Follow the [Events Deep Dive](https://gui-cs.github.io/Terminal.Gui/docs/events.html) documentation
-- Use the Cancellable Work Pattern for user-initiated actions
-- Use the CWPHelpers if possible
-- Name event handlers consistently (e.g., `On[EventName]`), following dotnet guidelines.
-
-## User Experience Tenets
-
-1. **Honor What's Come Before** - Follow established Mac/Windows GUI idioms (e.g., `Ctrl-C` for copy)
-2. **Consistency Matters** - Common UI patterns should be consistent (e.g., `Ctrl-Q` quits modals)
-3. **Honor the OS, but Work Everywhere** - Take advantage of platform capabilities while maintaining cross-platform support
-4. **Keyboard first, Mouse also** - Optimize for keyboard, but ensure everything also works with mouse
-
-## Testing
-
-### Unit Test Requirements
-
-- **Never decrease code coverage** - Aim for 70%+ coverage on new code
-- Write unit tests for all new functionality
-- Follow existing test patterns in `/Tests/`
-- Many existing unit tests are obtuse and not really unit tests. Anytime new tests are added or updated, strive to refactor the tests into more granular tests where each test covers the smallest area possible. 
-- Many existing unit tests in the `./Tests/UnitTests` project incorrectly require `Application.Init` and use `[AutoInitShutdown]`. Anytime new tests are added or updated, strive to remove these dependencies and make the tests parallelizable. This means not taking any dependency on static objects like `Application` and `ConfigurationManager`. 
-
-## Pull Request Guidelines
-
-- Titles should be of the form "Fixes #issue. Terse description." 
-- If the PR addresses multiple issues, use "Fixes #issue1, #issue2. Terse description."
-- First comment should include "- Fixes #issue" for each issue addressed. If an issue is only partially addressed, use "Partially addresses #issue".
-- First comment should include a thorough description of the change and any impact. 
-- Put temporary .md files in `/docfx/docs/drafts/` and remove before merging.
-
-## Building and Running
-
-### Build the Solution
-```powershell
-dotnet build
-```
-
-### Run Tests
-```powershell
-dotnet test
-```
-
-## Key Concepts
-
-`./docfx/docs` contains a set of architectural and key-concept deep-dives. 
-
-## Additional Guidelines
-1. Maintain existing code structure and organization unless explicitly told
-2. View sub-classes must not use private APIs
-3. Suggest changes to the `./docfx/docs/` folder when appropriate
-
-## Working with Pull Request Branches
-
-When creating PRs, include instructions at the end of each PR description for how to pull the branch down locally. Use the following template, adapted for the typical remote setup where `origin` points to the user's fork and `upstream` points to `gui-cs/Terminal.Gui`:
-
-```markdown
-## How to Pull This PR Branch Locally
-
-If you want to test or modify this PR locally, use one of these approaches based on your remote setup:
-
-### Method 1: Fetch from upstream (if branch exists there)
-```bash
-# Fetch the branch from upstream
-git fetch upstream <branch-name>
-
-# Switch to the branch
-git checkout <branch-name>
-
-# Make your changes, then commit them
-git add .
-git commit -m "Your commit message"
-
-# Push to your fork (origin)
-git push origin <branch-name>
-```
-
-### Method 2: Fetch by PR number
-```bash
-# Fetch the PR branch from upstream by PR number
-git fetch upstream pull/<PR_NUMBER>/head:<branch-name>
-
-# Switch to the branch
-git checkout <branch-name>
-
-# Make your changes, then commit them
-git add .
-git commit -m "Your commit message"
-
-# Push to your fork (origin)
-git push origin <branch-name>
-```
-
-The PR will automatically update when you push to the branch in your fork.
-```
-
-**Note:** Adjust the remote names if your setup differs (e.g., if `origin` points to `gui-cs/Terminal.Gui` and you have a separate remote for your fork).
+**Key highlights for AI agents:**
+- Always use explicit types (no `var` except for built-in simple types)
+- Always use target-typed `new()` syntax
+- Add new tests to `Tests/UnitTestsParallelizable/` when possible
+- Never decrease code coverage
+- Follow `.editorconfig` and `Terminal.sln.DotSettings` for formatting
 
+See [CONTRIBUTING.md](CONTRIBUTING.md) for complete details.

+ 344 - 159
CONTRIBUTING.md

@@ -1,234 +1,419 @@
 # Contributing to Terminal.Gui
 
-We welcome contributions from the community. See [Issues](https://github.com/gui-cs/Terminal.Gui/issues) for a list of open [bugs](https://github.com/gui-cs/Terminal.Gui/issues?q=is%3Aopen+is%3Aissue+label%3Abug) and [enhancements](https://github.com/gui-cs/Terminal.Gui/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement). Contributors looking for something fun to work on should look at issues tagged as:
+> **📘 This document is the single source of truth for all contributors (humans and AI agents) to Terminal.Gui.**
 
-- [good first issue](https://github.com/gui-cs/Terminal.Gui/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
-- [up for grabs](https://github.com/gui-cs/Terminal.Gui/issues?q=is%3Aopen+is%3Aissue+label%3Aup-for-grabs)
-- [help wanted](https://github.com/gui-cs/Terminal.Gui/issues?q=is%3Aopen+is%3Aissue+label%3Aup-for-grabs)
+Welcome! This guide provides everything you need to know to contribute effectively to Terminal.Gui, including project structure, build instructions, coding conventions, testing requirements, and CI/CD workflows.
 
-## Forking and Submitting Changes
+## Table of Contents
 
-Terminal.Gui uses the [GitFlow](https://nvie.com/posts/a-successful-git-branching-model/) branching model. 
+- [Project Overview](#project-overview)
+- [Building and Testing](#building-and-testing)
+- [Coding Conventions](#coding-conventions)
+- [Testing Requirements](#testing-requirements)
+- [API Documentation Requirements](#api-documentation-requirements)
+- [Pull Request Guidelines](#pull-request-guidelines)
+- [CI/CD Workflows](#cicd-workflows)
+- [Repository Structure](#repository-structure)
+- [Branching Model](#branching-model)
+- [Key Architecture Concepts](#key-architecture-concepts)
+- [What NOT to Do](#what-not-to-do)
+- [Additional Resources](#additional-resources)
 
-* The `v1_release` and `v2_release` branches are always stable, and always match the most recently released Nuget package.
-* The `v1_develop` and `v2_develop` branches are where new development and bug-fixes happen. `v2_develop` is the default Github branch.
+---
 
-### Forking Terminal.Gui
+## Project Overview
 
-1. Use GitHub to fork the `Terminal.Gui` repo to your account (https://github.com/gui-cs/Terminal.Gui/fork).
+**Terminal.Gui** is a cross-platform UI toolkit for creating console-based graphical user interfaces in .NET. It's a large codebase (~1,050 C# files, 333MB) providing a comprehensive framework for building interactive console applications with support for keyboard and mouse input, customizable views, and a robust event system.
 
-2. Clone your fork to your local machine
+**Key characteristics:**
+- **Language**: C# (net8.0)
+- **Size**: ~496 source files in core library, ~1,050 total C# files
+- **Platform**: Cross-platform (Windows, macOS, Linux)
+- **Architecture**: Console UI toolkit with driver-based architecture
+- **Version**: v2 (Alpha), v1 (maintenance mode)
+- **Branching**: GitFlow model (v2_develop is default/active development)
 
-```
-git clone https://github.com/<yourID>/Terminal.Gui
-```
+---
 
-Now, your local repo will have an `origin` remote pointing to `https://github.com/<yourID>/Terminal.Gui`.
+## Building and Testing
 
-3. Add a remote for `upstream`: 
-```
-git remote add upstream https://github.com/gui-cs/Terminal.Gui
-```
-You now have your own fork and a local repo that references it as `origin`. Your local repo also now references the orignal Terminal.Gui repo as `upstream`. 
+### Required Tools
 
-### Starting to Make a Change
+- **.NET SDK**: 8.0.0 (see `global.json`)
+- **Runtime**: .NET 8.x (latest GA)
+- **Optional**: ReSharper/Rider for code formatting (honor `.editorconfig` and `Terminal.sln.DotSettings`)
 
-Ensure your local `v1_develop` (for v1) or `v2_develop` (for v2) branch is up-to-date with `upstream` (`github.com/gui-cs/Terminal.Gui`):
-```powershell
-cd ./Terminal.Gui
-git checkout v2_develop
-git pull upstream v2_develop
-```
+### Build Commands (In Order)
 
-Create a new local branch:
-```powershell
-git checkout -b my_new_branch
-```
+**ALWAYS run these commands from the repository root:**
+
+1. **Restore packages** (required first, ~15-20 seconds):
+   ```bash
+   dotnet restore
+   ```
 
-### Making Changes
-Follow all the guidelines below.
+2. **Build solution** (Debug, ~50 seconds):
+   ```bash
+   dotnet build --configuration Debug --no-restore
+   ```
+   - Expect ~326 warnings (nullable reference warnings, unused variables, etc.) - these are normal
+   - 0 errors expected
 
-* [Coding Style](#TerminalGui-Coding-Style)
-* [Unit Tests](#Unit-Tests)
-* [Sample Code](#Sample-Code)
-* API Documentation
-* etc...
+3. **Build Release** (for packaging):
+   ```bash
+   dotnet build --configuration Release --no-restore
+   ```
 
-When you're ready, commit your changes:
+### Test Commands
 
-```powershell
-git add .
-git commit -m "Fixes #1234. Some bug"
-```
+**Two test projects exist:**
 
-### Submitting a Pull Request
+1. **Non-parallel tests** (depend on static state, ~10 min timeout):
+   ```bash
+   dotnet test Tests/UnitTests --no-build --verbosity normal
+   ```
+   - Uses `Application.Init` and static state
+   - Cannot run in parallel
+   - Includes `--blame` flags for crash diagnostics
+
+2. **Parallel tests** (can run concurrently, ~10 min timeout):
+   ```bash
+   dotnet test Tests/UnitTestsParallelizable --no-build --verbosity normal
+   ```
+   - No dependencies on static state
+   - **Preferred for new tests**
 
-1. Push your local branch to your fork (`origin`):
+3. **Integration tests**:
+   ```bash
+   dotnet test Tests/IntegrationTests --no-build --verbosity normal
+   ```
 
-```powershell
-git push --set-upstream origin my_new_branch
+**Important**: Tests may take significant time. CI uses blame flags for crash detection:
+```bash
+--diag:logs/UnitTests/logs.txt --blame --blame-crash --blame-hang --blame-hang-timeout 60s --blame-crash-collect-always
 ```
 
-2. Create the Pull Request:
+### Common Build Issues
+
+#### Issue: Build Warnings
+- **Expected**: ~326 warnings (nullable refs, unused vars, xUnit suggestions)
+- **Action**: Don't add new warnings; fix warnings in code you modify
+
+#### Issue: Test Timeouts
+- **Expected**: Tests can take 5-10 minutes
+- **Action**: Use appropriate timeout values (60-120 seconds for test commands)
+
+#### Issue: Restore Failures
+- **Solution**: Ensure `dotnet restore` completes before building
+- **Note**: Takes 15-20 seconds on first run
 
-In the output of the `git push` command you'll see instructions with a link to the Pull Request:
+#### Issue: NativeAot/SelfContained Build
+- **Solution**: Restore these projects explicitly:
+  ```bash
+  dotnet restore ./Examples/NativeAot/NativeAot.csproj -f
+  dotnet restore ./Examples/SelfContained/SelfContained.csproj -f
+  ```
 
-```powershell
- $ git push --set-upstream origin my_new_branch
-Enumerating objects: 8, done.
-...
-remote:
-remote: Create a pull request for 'my_new_branch' on GitHub by visiting:
-remote:      https://github.com/<yourID>/Terminal.Gui/pull/new/more_doc_fixes
-remote:
-...
+### Running Examples
+
+**UICatalog** (comprehensive demo app):
+```bash
+dotnet run --project Examples/UICatalog/UICatalog.csproj
 ```
 
-3. Go to that URL and create the Pull Request:
+---
 
-(in Windows Terminal, just CTRL-Click on the URL)
+## Coding Conventions
 
-Follow the template instructions found on Github.
+### Code Style Tenets
 
-## Tenets for [gui-cs](www.github.com/gui-cs) Code Style (Unless you have better ones)
+1. **Six-Year-Old Reading Level** - Readability over terseness
+2. **Consistency, Consistency, Consistency** - Follow existing patterns ruthlessly
+3. **Don't be Weird** - Follow Microsoft/.NET conventions
+4. **Set and Forget** - Rely on automated tooling
+5. **Documentation is the Spec** - API docs are source of truth
 
-* **Six-Year-Old Reading Level** - Our code style is biased towards code readability and away from terseness. This is *Systems Software* and needs to stand the test of time. Code should be structured and use variable names that make it readable by a 6-year-old, and comments in code are encouraged. 
-* **Consistency, Consistency, Consistency** - We adopt and document our standards for code style and then enforce them ruthlessly. For example, we require code reviews to pay attention to code style, not just functionality. 
-* **Don't be Weird** - Like all developers we have opinions, but our opinions on code style are tempered by existing standards. We are biased towards code style that used by Microsoft and other leading dotnet developers. For example, we choose 4 spaces for indentation instead of 8.
-* **Set and Forget** - We embrace and encourage the use of technology that makes it easy for contributors to apply best-practice code-style, such as ReSharper. As we do so we are mindful that tools can cause hidden issues and merge hell.
-* **Documentation is the Spec** - We care deeply about providing delightful developer documentation and are sticklers for grammar and clarity. If the code and the docs conflict, we are biased to believe what we wrote in the API documentation. This drives a virtuous cycle of clear thinking.
+### Code Formatting
 
-**Terminal.Gui** uses a derivative of the [Microsoft C# Coding Conventions](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions), with any deviations from those (somewhat older) conventions codified in the .editorconfig for the solution, as well as even more specific definitions in team-shared dotsettings files, used by ReSharper and Rider.\
+- **Do NOT add formatting tools** - Use existing `.editorconfig` and `Terminal.sln.DotSettings`
+- Format code with:
+  1. ReSharper/Rider (`Ctrl-E-C`)
+  2. JetBrains CleanupCode CLI tool (free)
+  3. Visual Studio (`Ctrl-K-D`) as fallback
+- **Only format files you modify**
 
-### Critical Coding Standards
+### Critical Coding Rules
 
-**⚠️ These rules MUST be followed in ALL new code (production, tests, examples, samples):**
+**⚠️ CRITICAL - These rules MUST be followed in ALL new or modified code:**
 
 #### Type Declarations and Object Creation
 
-1. **ALWAYS use explicit types** - Never use `var` except for basic types (`int`, `string`, `bool`, `double`, `float`, `decimal`, `char`, `byte`)
-
-   ```csharp
-   // ✅ CORRECT - Explicit types
-   View view = new () { Width = 10 };
-   MouseEventArgs args = new () { Position = new Point(5, 5) };
-   List<View?> views = new ();
-   var count = 0;  // OK - int is a basic type
-   var name = "test";  // OK - string is a basic type
-   
-   // ❌ WRONG - Using var for non-basic types
-   var view = new View { Width = 10 };
-   var args = new MouseEventArgs { Position = new Point(5, 5) };
-   var views = new List<View?>();
-   ```
-
-2. **ALWAYS use target-typed `new()`** - Use `new ()` instead of `new TypeName()` when the type is already declared
+- **ALWAYS use explicit types** - Never use `var` except for built-in simple types (`int`, `string`, `bool`, `double`, `float`, `decimal`, `char`, `byte`)
+  ```csharp
+  // ✅ CORRECT - Explicit types
+  View view = new () { Width = 10 };
+  MouseEventArgs args = new () { Position = new Point(5, 5) };
+  List<View?> views = new ();
+  var count = 0;  // OK - int is a built-in type
+  var name = "test";  // OK - string is a built-in type
+  
+  // ❌ WRONG - Using var for non-built-in types
+  var view = new View { Width = 10 };
+  var args = new MouseEventArgs { Position = new Point(5, 5) };
+  var views = new List<View?>();
+  ```
+
+- **ALWAYS use target-typed `new()`** - Use `new ()` instead of `new TypeName()` when the type is already declared
+  ```csharp
+  // ✅ CORRECT - Target-typed new
+  View view = new () { Width = 10 };
+  MouseEventArgs args = new ();
+  
+  // ❌ WRONG - Redundant type name
+  View view = new View() { Width = 10 };
+  MouseEventArgs args = new MouseEventArgs();
+  ```
+
+#### Other Conventions
+
+- Follow `.editorconfig` settings (e.g., braces on new lines, spaces after keywords)
+- 4-space indentation
+- No trailing whitespace
+- File-scoped namespaces
+
+**⚠️ CRITICAL - These conventions apply to ALL code - production code, test code, examples, and samples.**
+
+---
+
+## Testing Requirements
+
+### Code Coverage
+
+- **Never decrease code coverage** - PRs must maintain or increase coverage
+- Target: 70%+ coverage for new code
+- CI monitors coverage on each PR
+
+### Test Patterns
+
+- **Parallelizable tests preferred** - Add new tests to `UnitTestsParallelizable` when possible
+- **Avoid static dependencies** - Don't use `Application.Init`, `ConfigurationManager` in tests
+- **Don't use `[AutoInitShutdown]`** - Legacy pattern, being phased out
+- **Make tests granular** - Each test should cover smallest area possible
+- Follow existing test patterns in respective test projects
+
+### Test Configuration
+
+- `xunit.runner.json` - xUnit configuration
+- `coverlet.runsettings` - Coverage settings (OpenCover format)
+
+---
+
+## API Documentation Requirements
+
+**All public APIs MUST have XML documentation:**
+
+- Clear, concise `<summary>` tags
+- Use `<see cref=""/>` for cross-references
+- Add `<remarks>` for context
+- Include `<example>` for non-obvious usage
+- Complex topics → `docfx/docs/*.md` files
+- Proper English and grammar - Clear, concise, complete. Use imperative mood.
+
+---
+
+## Pull Request Guidelines
+
+### PR Requirements
+
+- **Title**: "Fixes #issue. Terse description". If multiple issues, list all, separated by commas (e.g. "Fixes #123, #456. Terse description")
+- **Description**: 
+  - Include "- Fixes #issue" for each issue near the top
+  - **ALWAYS** include instructions for pulling down locally at end of Description
+  - Suggest user setup a remote named `copilot` pointing to your fork
+  - Example:
+    ```markdown
+    # To pull down this PR locally:
+    git remote add copilot <your-fork-url>
+    git fetch copilot <branch-name>
+    git checkout copilot/<branch-name>
+    ```
+- **Coding Style**: Follow all coding conventions in this document for new and modified code
+- **Tests**: Add tests for new functionality (see [Testing Requirements](#testing-requirements))
+- **Coverage**: Maintain or increase code coverage
+- **Scenarios**: Update UICatalog scenarios when adding features
+- **Warnings**: **CRITICAL - PRs must not introduce any new warnings**
+  - Any file modified in a PR that currently generates warnings **MUST** be fixed to remove those warnings
+  - Exception: Warnings caused by `[Obsolete]` attributes can remain
+  - Expected baseline: ~326 warnings (mostly nullable reference warnings, unused variables, xUnit suggestions)
+  - Action: Before submitting a PR, verify your changes don't add new warnings and fix any warnings in files you modify
+
+---
+
+## CI/CD Workflows
+
+The repository uses multiple GitHub Actions workflows. What runs and when:
+
+### 1) Build Solution (`.github/workflows/build.yml`)
+
+- **Triggers**: push and pull_request to `v2_release`, `v2_develop` (ignores `**.md`); supports `workflow_call`
+- **Runner/timeout**: `ubuntu-latest`, 10 minutes
+- **Steps**:
+  - Checkout and setup .NET 8.x GA
+  - `dotnet restore`
+  - Build Debug: `dotnet build --configuration Debug --no-restore -property:NoWarn=0618%3B0612`
+  - Build Release (library): `dotnet build Terminal.Gui/Terminal.Gui.csproj --configuration Release --no-incremental --force -property:NoWarn=0618%3B0612`
+  - Pack Release: `dotnet pack Terminal.Gui/Terminal.Gui.csproj --configuration Release --output ./local_packages -property:NoWarn=0618%3B0612`
+  - Restore NativeAot/SelfContained examples, then restore solution again
+  - Build Release for `Examples/NativeAot` and `Examples/SelfContained`
+  - Build Release solution
+  - Upload artifacts named `build-artifacts`, retention 1 day
 
-   ```csharp
-   // ✅ CORRECT - Target-typed new
-   View view = new () { Width = 10 };
-   MouseEventArgs args = new ();
-   
-   // ❌ WRONG - Redundant type name
-   View view = new View() { Width = 10 };
-   MouseEventArgs args = new MouseEventArgs();
-   ```
+### 2) Build & Run Unit Tests (`.github/workflows/unit-tests.yml`)
 
-**Why these rules matter:**
-- Explicit types improve code readability and make the type system more apparent
-- Target-typed `new()` reduces redundancy while maintaining clarity
-- Consistency across the codebase makes it easier for all contributors to read and maintain code
-- These conventions align with modern C# best practices (C# 9.0+)
+- **Triggers**: push and pull_request to `v2_release`, `v2_develop` (ignores `**.md`)
+- **Process**: Calls build workflow, then runs:
+  - Non-parallel UnitTests on Ubuntu/Windows/macOS matrix with coverage and blame/diag flags; `xunit.stopOnFail=false`
+  - Parallel UnitTestsParallelizable similarly with coverage; `xunit.stopOnFail=false`
+  - Uploads logs per-OS
 
-### Code Formatting
+### 3) Build & Run Integration Tests (`.github/workflows/integration-tests.yml`)
 
-Before you commit code, please run the formatting rules on **only the code file(s) you have modified**, in one of the following ways, in order of most preferred to least preferred:
+- **Triggers**: push and pull_request to `v2_release`, `v2_develop` (ignores `**.md`)
+- **Process**: Calls build workflow, then runs IntegrationTests on matrix with blame/diag; `xunit.stopOnFail=true`
+- Uploads logs per-OS
 
- 1. `Ctrl-E-C` if using ReSharper or Rider
- 2. Running the free [CleanupCode](https://www.jetbrains.com/help/resharper/CleanupCode.html) tool from JetBrains (this applies the same formatting rules as if you had used ReSharper or Rider, but is free for all users, if you don't have a license for those products)
-     - Run at the command line, from the solution root directory, as: `cleanupcode.exe relative/path/to/your/file.cs`
- 3. If you are unable to use either of those options, the last resort is to use `Ctrl-K-D` in Visual Studio (with default C# developer key bindings), to apply the subset of the formatting rules that Visual Studio can apply.
+### 4) Publish to NuGet (`.github/workflows/publish.yml`)
 
-## User Experience Tenets
+- **Triggers**: push to `v2_release`, `v2_develop`, and tags `v*` (ignores `**.md`)
+- Uses GitVersion to compute SemVer, builds Release, packs with symbols, and pushes to NuGet.org using `NUGET_API_KEY`
 
-**Terminal.Gui**, as a UI framework, heavily influences how console graphical user interfaces (GUIs) work. We use the following [tenets](https://ceklog.kindel.com/2020/02/10/tenets/) to guide us:
+### 5) Build and publish API docs (`.github/workflows/api-docs.yml`)
 
-*NOTE: Like all tenets, these are up for debate. If you disagree, have questions, or suggestions about these tenets and guidelines submit an Issue using the [design](https://github.com/gui-cs/Terminal.Gui/issues?q=is%3Aopen+is%3Aissue+label%3Adesign) tag.*
+- **Triggers**: push to `v1_release` and `v2_develop`
+- Builds DocFX site on Windows and deploys to GitHub Pages when `ref_name` is `v2_release` or `v2_develop`
 
-1. **Honor What's Come Before**. The Mac and Windows OS's have well-established GUI idioms that are mostly consistent. We adhere to these versus inventing new ways for users to do things. For example, **Terminal.Gui** adopts the `ctrl/command-c`, `ctrl/command-v`, and `ctrl/command-x` keyboard shortcuts for cut, copy, and paste versus defining new shortcuts.
-2. **Consistency Matters**. Common UI idioms should be consistent across the GUI framework. For example, `ctrl/command-q` quits/exits all modal views. See [Issue #456](https://github.com/gui-cs/Terminal.Gui/issues/456) as a counter-example that should be fixed.
-3. **Honor the OS, but Work Everywhere**. **Terminal.Gui** is cross-platform, but we support taking advantage of a platform's unique advantages. For example, the Windows Console API is richer than the Unix API in terms of keyboard handling. Thus, in Windows pressing the `alt` key in a **Terminal.Gui** app will activate the `MenuBar`, but in Unix, the user has to press the full hotkey (e.g. `alt-f`) or `F9`. 
-4. **Keyboard first, Mouse also**. Users use consoles primarily with the keyboard; **Terminal.Gui** is optimized for getting stuff done without using the Mouse. However, as a GUI framework, the Mouse is essential thus we strive to ensure that everything also works via the Mouse.
+### Replicating CI Locally
+
+```bash
+# Full CI sequence:
+dotnet restore
+dotnet build --configuration Debug --no-restore
+dotnet test Tests/UnitTests --no-build --verbosity normal
+dotnet test Tests/UnitTestsParallelizable --no-build --verbosity normal
+dotnet build --configuration Release --no-restore
+```
 
-## Public API Tenets & Guidelines
+---
 
-**Terminal.Gui** provides an API that is used by many. As the project evolves, contributors should follow these [tenets](https://ceklog.kindel.com/2020/02/10/tenets/) to ensure Consistency and backward compatibility.
+## Repository Structure
 
-*NOTE: Like all tenets, these are up for debate. If you disagree, have questions, or suggestions about these tenets and guidelines submit an Issue using the [design](https://github.com/gui-cs/Terminal.Gui/issues?q=is%3Aopen+is%3Aissue+label%3Adesign) tag.*
+### Root Directory Files
 
-1. **Stand on the shoulders of giants.** Follow the [Microsoft .NET Framework Design Guidelines](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/) where appropriate. 
-2. **Don't Break Existing Stuff.** Avoid breaking changes to user behavior or the public API; instead, figure out how to implement new functionality in a similar way. If a breaking change can't be avoided, follow the guidelines below.
-3. **Fail-fast.** Fail-fast makes bugs and failures appear sooner, leading to a higher-quality framework and API.
-4. **Standards Reduce Complexity**. We strive to adopt standard API idoms because doing so reduces complexity for users of the API. For example, see Tenet #1 above. A counterexample is [Issue #447](https://github.com/gui-cs/Terminal.Gui/issues/447).
+- `Terminal.sln` - Main solution file
+- `Terminal.sln.DotSettings` - ReSharper code style settings
+- `.editorconfig` - Code formatting rules (111KB, extensive)
+- `global.json` - .NET SDK version pinning
+- `Directory.Build.props` - Common MSBuild properties
+- `Directory.Packages.props` - Central package version management
+- `GitVersion.yml` - Version numbering configuration
+- `CONTRIBUTING.md` - This file - contribution guidelines (source of truth)
+- `AGENTS.md` - Pointer to this file for AI agents
+- `README.md` - Project documentation
 
-### Include API Documentation
+### Main Directories
 
-Great care has been provided thus far in ensuring **Terminal.Gui** has great [API Documentation](https://gui-cs.github.io/Terminal.Gui). Contributors have the responsibility of continuously improving the API Documentation.
+**`/Terminal.Gui/`** - Core library (496 C# files):
+- `App/` - Application lifecycle (`Application.cs` static class, `RunState`, `MainLoop`)
+- `Configuration/` - `ConfigurationManager` for settings
+- `Drivers/` - Console driver implementations (`IConsoleDriver`, `NetDriver`, `UnixDriver`, `WindowsDriver`)
+- `Drawing/` - Rendering system (attributes, colors, glyphs)
+- `Input/` - Keyboard and mouse input handling
+- `ViewBase/` - Core `View` class hierarchy and layout
+- `Views/` - Specific View subclasses (Window, Dialog, Button, ListView, etc.)
+- `Text/` - Text manipulation and formatting
+- `FileServices/` - File operations and services
 
-- All public APIs must have clear, concise, and complete documentation in the form of [XML Documentation](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/).
-- Keep the `<summary></summary>` terse.
-- Use `<see cref=""/>` liberally to cross-link topics.
-- Use `<remarks></remarks>` to add more context and explanation.
-- For complex topics, provide conceptual documentation in the `docfx/articles` folder as a `.md` file. It will automatically get picked up and be added to [Conceptual Documentation](https://gui-cs.github.io/Terminal.Gui/docs/index.html).
-- Use proper English and good grammar.
+**`/Tests/`**:
+- `UnitTests/` - Non-parallel tests (use `Application.Init`, static state)
+- `UnitTestsParallelizable/` - Parallel tests (no static dependencies) - **Preferred**
+- `IntegrationTests/` - Integration tests
+- `StressTests/` - Long-running stress tests (scheduled daily)
+- `coverlet.runsettings` - Code coverage configuration
 
-### Defining Events
+**`/Examples/`**:
+- `UICatalog/` - Comprehensive demo app for manual testing
+- `Example/` - Basic example
+- `NativeAot/`, `SelfContained/` - Deployment examples
+- `ReactiveExample/`, `CommunityToolkitExample/` - Integration examples
 
-See https://gui-cs.github.io/Terminal.Gui/docs/events.html
+**`/docfx/`** - Documentation source:
+- `docs/` - Conceptual documentation (deep dives)
+- `api/` - Generated API docs (gitignored)
+- `docfx.json` - DocFX configuration
 
+**`/Scripts/`** - PowerShell build utilities (requires PowerShell 7.4+)
 
-### Defining new `View` classes
+**`/.github/workflows/`** - CI/CD pipelines (see [CI/CD Workflows](#cicd-workflows))
 
-- Support parameterless constructors (see [Issue 102](Parameterless constructors #102)). Do not require callers to use a parameterized constructor except when forcing `Absolute Layout`).
-- Avoid doing initialization via constructors. Instead use a property so consumers can use object initialization (e.g. `var foo = new Foo() { a = b };`).
-- Ensure the `UICatalog` demo for the new class illustrates both `Absolutle Layout` and `Computed Layout`.
+---
 
-## Breaking Changes to User Behavior or the Public API
+## Branching Model
 
-- Tag all pull requests that cause breaking changes to user behavior or the public API with the [breaking-change](https://github.com/gui-cs/Terminal.Gui/issues?q=is%3Aopen+is%3Aissue+label%3Abreaking-change) tag. This will help project maintainers track and document these.
-- Add a `<remark></remark>` to the XML Documentation to the code describing the breaking change. These will get picked up in the [API Documentation](https://gui-cs.github.io/Terminal.Gui/api/Terminal.Gui.html).
+### GitFlow Model
 
-## Unit Tests
+- `v2_develop` - Default branch, active development
+- `v2_release` - Stable releases, matches NuGet
+- `v1_develop`, `v1_release` - Legacy v1 (maintenance only)
 
-PRs should never cause code coverage to go down. Ideally, every PR will get the project closer to 100%. PRs that include new functionality (e.g. a new control) should have at least 70% code coverage for the new functionality. 
+---
 
-**Terminal.Gui** has an automated unit or regression test suite. See the [Testing wiki](https://github.com/gui-cs/Terminal.Gui/wiki/Testing).
+## Key Architecture Concepts
 
-We analyze unit tests and code coverage on each PR push. 
+**⚠️ CRITICAL - Contributors should understand these concepts before starting work.**
 
-The code coverage of the latest released build (on NuGet) is shown as a badge at the top of `README.md`. Here as well:
+See `/docfx/docs/` for deep dives on:
 
-![Code Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/migueldeicaza/90ef67a684cb71db1817921a970f8d27/raw/code-coverage.json)
+- **Application Lifecycle** - How `Application.Init`, `Application.Run`, and `Application.Shutdown` work
+- **View Hierarchy** - Understanding `View`, `Toplevel`, `Window`, and view containment
+- **Layout System** - Pos, Dim, and automatic layout
+- **Event System** - How keyboard, mouse, and application events flow
+- **Driver Architecture** - How console drivers abstract platform differences
+- **Drawing Model** - How rendering works with Attributes, Colors, and Glyphs
 
-The project uses Fine Code Coverage to allow easy access to code coverage info on a per-component basis.
+Key documentation:
+- [View Documentation](https://gui-cs.github.io/Terminal.Gui/docs/View.html)
+- [Events Deep Dive](https://gui-cs.github.io/Terminal.Gui/docs/events.html)
+- [Layout System](https://gui-cs.github.io/Terminal.Gui/docs/layout.html)
+- [Keyboard Handling](https://gui-cs.github.io/Terminal.Gui/docs/keyboard.html)
+- [Mouse Support](https://gui-cs.github.io/Terminal.Gui/docs/mouse.html)
+- [Drivers](https://gui-cs.github.io/Terminal.Gui/docs/drivers.html)
 
-Use the following command to generate the same CC info that the Publish Github Action uses to publish the results to the badge:
+---
 
-```
-dotnet test --no-restore --verbosity normal --collect:"XPlat Code Coverage"  --settings UnitTests/coverlet.runsettings
-```
+## What NOT to Do
 
-Then open up the resulting `coverage.opencover.xml` file and you'll see the `sequenceCoverage` value:
+- ❌ Don't add new linters/formatters (use existing)
+- ❌ Don't modify unrelated code
+- ❌ Don't remove/edit unrelated tests
+- ❌ Don't break existing functionality
+- ❌ Don't add tests to `UnitTests` if they can be parallelizable
+- ❌ Don't use `Application.Init` in new tests
+- ❌ Don't decrease code coverage
+- ❌ **Don't use `var` for anything but built-in simple types** (use explicit types)
+- ❌ **Don't use redundant type names with `new`** (**ALWAYS PREFER** target-typed `new ()`)
+- ❌ **Don't introduce new warnings** (fix warnings in files you modify; exception: `[Obsolete]` warnings)
 
-```xml
-<?xml version="1.0" encoding="utf-8"?>
-<CoverageSession>
-  <Summary numSequencePoints="15817" visitedSequencePoints="7249" numBranchPoints="9379" visitedBranchPoints="3640" sequenceCoverage="45.83" branchCoverage="38.81" maxCyclomaticComplexity="10276" minCyclomaticComplexity="10276" visitedClasses="105" numClasses="141" visitedMethods="965" numMethods="1751" />
- 
-```
+---
 
-## Sample Code
+## Additional Resources
 
-[UI Catalog](https://github.com/gui-cs/Terminal.Gui/tree/master/UICatalog) is a great sample app for manual testing.
+- **Full Documentation**: https://gui-cs.github.io/Terminal.Gui
+- **API Reference**: https://gui-cs.github.io/Terminal.Gui/api/Terminal.Gui.App.html
+- **Deep Dives**: `/docfx/docs/` directory
+- **Getting Started**: https://gui-cs.github.io/Terminal.Gui/docs/getting-started.html
+- **Migrating from v1 to v2**: https://gui-cs.github.io/Terminal.Gui/docs/migratingfromv1.html
+- **Showcase**: https://gui-cs.github.io/Terminal.Gui/docs/showcase.html
+
+---
 
-When adding new functionality, fixing bugs, or changing things, please either add a new `Scenario` to **UICatalog** or update an existing `Scenario` to fully illustrate your work and provide a test-case.
+**Thank you for contributing to Terminal.Gui!** 🎉

+ 4 - 1
Examples/UICatalog/Scenarios/AnimationScenario/AnimationScenario.cs

@@ -40,7 +40,10 @@ public class AnimationScenario : Scenario
 
         var lbl2 = new Label
         {
-            X = Pos.AnchorEnd (), Y = Pos.AnchorEnd (), Text = "https://commons.wikimedia.org/wiki/File:Spinning_globe.gif"
+            // This ensures the URL that has an underscore is drawn correctly
+            HotKeySpecifier = new Rune ('\xFFFF'),
+            X = Pos.AnchorEnd (), Y = Pos.AnchorEnd (), 
+            Text = "https://commons.wikimedia.org/wiki/File:Spinning_globe.gif"
         };
         win.Add (lbl2);
 

+ 0 - 1
Examples/UICatalog/Scenarios/Arrangement.cs

@@ -99,7 +99,6 @@ public class Arrangement : Scenario
 
                              progressBar.Fraction += 0.01f;
 
-                             Application.Wakeup ();
 
                              progressBar.SetNeedsDraw ();
                          };

+ 0 - 1
Examples/UICatalog/Scenarios/Clipping.cs

@@ -100,7 +100,6 @@ public class Clipping : Scenario
                                  {
                                      tiledProgressBar1.Pulse ();
                                      tiledProgressBar2.Pulse ();
-                                     Application.Wakeup ();
                                  };
 
         progressTimer.Start ();

+ 0 - 2
Examples/UICatalog/Scenarios/ProgressBarStyles.cs

@@ -198,7 +198,6 @@ public class ProgressBarStyles : Scenario
                                                                       button.Enabled = true;
                                                                   }
 
-                                                                  Application.Wakeup ();
                                                               },
                                                               null,
                                                               0,
@@ -282,7 +281,6 @@ public class ProgressBarStyles : Scenario
                                      marqueesBlocksPB.Text = marqueesContinuousPB.Text = DateTime.Now.TimeOfDay.ToString ();
                                      marqueesBlocksPB.Pulse ();
                                      marqueesContinuousPB.Pulse ();
-                                     Application.Wakeup ();
                                  },
                                  null,
                                  0,

+ 0 - 1
Examples/UICatalog/Scenarios/Shortcuts.cs

@@ -384,7 +384,6 @@ public class Shortcuts : Scenario
 
                                  pb.Fraction += 0.01f;
 
-                                 Application.Wakeup ();
 
                                  pb.SetNeedsDraw ();
                              }

+ 1 - 1
README.md

@@ -86,7 +86,7 @@ Or, you can use the [Terminal.Gui.Templates](https://github.com/gui-cs/Terminal.
 
 # Contributing
 
-See [CONTRIBUTING.md](./CONTRIBUTING.md).
+See [CONTRIBUTING.md](CONTRIBUTING.md) for complete contribution guidelines.
 
 Debates on architecture and design can be found in Issues tagged with [design](https://github.com/gui-cs/Terminal.Gui/issues?q=is%3Aopen+is%3Aissue+label%3Av2+label%3Adesign).
 

+ 1 - 1
Terminal.Gui/App/Application.Lifecycle.cs

@@ -131,7 +131,7 @@ public static partial class Application // Lifecycle (Init/Shutdown)
 
         try
         {
-            MainLoop = Driver!.Init ();
+            Driver!.Init ();
             SubscribeDriverEvents ();
         }
         catch (InvalidOperationException ex)

+ 4 - 76
Terminal.Gui/App/Application.Run.cs

@@ -61,15 +61,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
     {
         ArgumentNullException.ThrowIfNull (toplevel);
 
-        //#if DEBUG_IDISPOSABLE
-        //        Debug.Assert (!toplevel.WasDisposed);
-
-        //        if (_cachedRunStateToplevel is { } && _cachedRunStateToplevel != toplevel)
-        //        {
-        //            Debug.Assert (_cachedRunStateToplevel.WasDisposed);
-        //        }
-        //#endif
-
         // Ensure the mouse is ungrabbed.
         if (Mouse.MouseGrabView is { })
         {
@@ -130,11 +121,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
                     TopLevels.Push (toplevel);
                 }
             }
-
-            //if (TopLevels.FindDuplicates (new ToplevelEqualityComparer ()).Count > 0)
-            //{
-            //    throw new ArgumentException ("There are duplicates Toplevel IDs");
-            //}
         }
 
         if (Top is null)
@@ -174,11 +160,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
             toplevel.EndInit (); // Calls Layout
         }
 
-        // Call ConfigurationManager Apply here to ensure all subscribers to ConfigurationManager.Applied
-        // can update their state appropriately.
-        // BUGBUG: DO NOT DO THIS. Leave this commented out until we can figure out how to do this right
-        //Apply ();
-
         // Try to set initial focus to any TabStop
         if (!toplevel.HasFocus)
         {
@@ -391,18 +372,12 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
     /// <param name="action">the action to be invoked on the main processing thread.</param>
     public static void Invoke (Action action) { ApplicationImpl.Instance.Invoke (action); }
 
-    // TODO: Determine if this is really needed. The only code that calls WakeUp I can find
-    // is ProgressBarStyles, and it's not clear it needs to.
-
-    /// <summary>Wakes up the running application that might be waiting on input.</summary>
-    public static void Wakeup () { MainLoop?.Wakeup (); }
-
     /// <summary>
     ///     Causes any Toplevels that need layout to be laid out. Then draws any Toplevels that need display. Only Views that
     ///     need to be laid out (see <see cref="View.NeedsLayout"/>) will be laid out.
     ///     Only Views that need to be drawn (see <see cref="View.NeedsDraw"/>) will be drawn.
     /// </summary>
-    /// <param name="forceDraw">
+    /// <param name="forceRedraw">
     ///     If <see langword="true"/> the entire View hierarchy will be redrawn. The default is <see langword="false"/> and
     ///     should only be overriden for testing.
     /// </param>
@@ -415,10 +390,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
     /// <remarks>See also <see cref="Timeout"/></remarks>
     public static event EventHandler<IterationEventArgs>? Iteration;
 
-    /// <summary>The <see cref="MainLoop"/> driver for the application</summary>
-    /// <value>The main loop.</value>
-    internal static MainLoop? MainLoop { get; set; }
-
     /// <summary>
     ///     Set to true to cause <see cref="End"/> to be called after the first iteration. Set to false (the default) to
     ///     cause the application to continue running until Application.RequestStop () is called.
@@ -436,11 +407,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
 
         for (state.Toplevel.Running = true; state.Toplevel?.Running == true;)
         {
-            if (MainLoop is { })
-            {
-                MainLoop.Running = true;
-            }
-
             if (EndAfterFirstIteration && !firstIteration)
             {
                 return;
@@ -449,11 +415,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
             firstIteration = RunIteration (ref state, firstIteration);
         }
 
-        if (MainLoop is { })
-        {
-            MainLoop.Running = false;
-        }
-
         // Run one last iteration to consume any outstanding input events from Driver
         // This is important for remaining OnKeyUp events.
         RunIteration (ref state, firstIteration);
@@ -467,35 +428,10 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
     /// <returns><see langword="false"/> if at least one iteration happened.</returns>
     public static bool RunIteration (ref RunState state, bool firstIteration = false)
     {
-        // If the driver has events pending do an iteration of the driver MainLoop
-        if (MainLoop is { Running: true } && MainLoop.EventsPending ())
-        {
-            // Notify Toplevel it's ready
-            if (firstIteration)
-            {
-                state.Toplevel.OnReady ();
-            }
-
-            MainLoop.RunIteration ();
-
-            Iteration?.Invoke (null, new ());
-        }
-
-        firstIteration = false;
-
-        if (Top is null)
-        {
-            return firstIteration;
-        }
-
-        LayoutAndDraw (TopLevels.Any (v => v.NeedsLayout || v.NeedsDraw));
-
-        if (PositionCursor ())
-        {
-            Driver?.UpdateCursor ();
-        }
+        ApplicationImpl appImpl = (ApplicationImpl)ApplicationImpl.Instance;
+        appImpl.Coordinator?.RunIteration ();
 
-        return firstIteration;
+        return false;
     }
 
     /// <summary>Stops the provided <see cref="Toplevel"/>, causing or the <paramref name="top"/> if provided.</summary>
@@ -510,14 +446,6 @@ public static partial class Application // Run (Begin -> Run -> Layout/Draw -> E
     /// </remarks>
     public static void RequestStop (Toplevel? top = null) { ApplicationImpl.Instance.RequestStop (top); }
 
-    internal static void OnNotifyStopRunState (Toplevel top)
-    {
-        if (EndAfterFirstIteration)
-        {
-            NotifyStopRunState?.Invoke (top, new (top));
-        }
-    }
-
     /// <summary>
     ///     Building block API: completes the execution of a <see cref="Toplevel"/> that was started with
     ///     <see cref="Begin(Toplevel)"/> .

+ 0 - 3
Terminal.Gui/App/Application.cs

@@ -216,9 +216,6 @@ public static partial class Application
         Top = null;
         _cachedRunStateToplevel = null;
 
-        // MainLoop stuff
-        MainLoop?.Dispose ();
-        MainLoop = null;
         MainThreadId = -1;
         Iteration = null;
         EndAfterFirstIteration = false;

+ 1 - 1
Terminal.Gui/App/ApplicationImpl.cs

@@ -499,7 +499,7 @@ public class ApplicationImpl : IApplication
     public void Invoke (Action action)
     {
         // If we are already on the main UI thread
-        if (_mainThreadId == Thread.CurrentThread.ManagedThreadId)
+        if (Application.Top is { Running: true } && _mainThreadId == Thread.CurrentThread.ManagedThreadId)
         {
             action ();
             return;

+ 0 - 24
Terminal.Gui/App/MainLoop/IMainLoopDriver.cs

@@ -1,24 +0,0 @@
-#nullable enable
-namespace Terminal.Gui.App;
-
-/// <summary>Interface to create a platform specific <see cref="MainLoop"/> driver.</summary>
-internal interface IMainLoopDriver
-{
-    /// <summary>Must report whether there are any events pending, or even block waiting for events.</summary>
-    /// <returns><see langword="true"/>, if there were pending events, <see langword="false"/> otherwise.</returns>
-    bool EventsPending ();
-
-    /// <summary>The iteration function.</summary>
-    void Iteration ();
-
-    /// <summary>Initializes the <see cref="MainLoop"/>, gets the calling main loop for the initialization.</summary>
-    /// <remarks>Call <see cref="TearDown"/> to release resources.</remarks>
-    /// <param name="mainLoop">Main loop.</param>
-    void Setup (MainLoop mainLoop);
-
-    /// <summary>Tears down the <see cref="MainLoop"/> driver. Releases resources created in <see cref="Setup"/>.</summary>
-    void TearDown ();
-
-    /// <summary>Wakes up the <see cref="MainLoop"/> that might be waiting on input, must be thread safe.</summary>
-    void Wakeup ();
-}

+ 0 - 122
Terminal.Gui/App/MainLoop/LegacyMainLoopDriver.cs

@@ -1,122 +0,0 @@
-#nullable enable
-//
-// LegacyMainLoopDriver.cs: IMainLoopDriver and MainLoop for legacy v1 driver based applications
-//
-// Authors:
-//   Miguel de Icaza ([email protected])
-//
-
-using System.Collections.ObjectModel;
-
-namespace Terminal.Gui.App;
-
-/// <summary>
-///     The main event loop of legacy v1 driver based applications.
-/// </summary>
-/// <remarks>
-///     <para>
-///         This class is provided for backward compatibility with the legacy FakeDriver implementation.
-///         New code should use the modern <see cref="ApplicationMainLoop{T}"/> architecture instead.
-///     </para>
-///     <para>
-///         Monitoring of file descriptors is only available on Unix, there does not seem to be a way of supporting this
-///         on Windows.
-///     </para>
-/// </remarks>
-[Obsolete ("This class is for legacy FakeDriver compatibility only. Use ApplicationMainLoop<T> for new code.")]
-public class MainLoop : IDisposable
-{
-    /// <summary>
-    /// Gets the class responsible for handling timeouts
-    /// </summary>
-    public ITimedEvents TimedEvents { get; } = new TimedEvents();
-
-    /// <summary>Creates a new MainLoop.</summary>
-    /// <remarks>Use <see cref="Dispose"/> to release resources.</remarks>
-    /// <param name="driver">
-    ///     The <see cref="IConsoleDriver"/> instance (one of the implementations FakeMainLoop, UnixMainLoop,
-    ///     NetMainLoop or WindowsMainLoop).
-    /// </param>
-    internal MainLoop (IMainLoopDriver driver)
-    {
-        MainLoopDriver = driver;
-        driver.Setup (this);
-    }
-
-
-    /// <summary>The current <see cref="IMainLoopDriver"/> in use.</summary>
-    /// <value>The main loop driver.</value>
-    internal IMainLoopDriver? MainLoopDriver { get; private set; }
-
-    /// <summary>Used for unit tests.</summary>
-    internal bool Running { get; set; }
-
-
-    /// <inheritdoc/>
-    public void Dispose ()
-    {
-        GC.SuppressFinalize (this);
-        Stop ();
-        Running = false;
-        MainLoopDriver?.TearDown ();
-        MainLoopDriver = null;
-    }
-
-
-    /// <summary>Determines whether there are pending events to be processed.</summary>
-    /// <remarks>
-    ///     You can use this method if you want to probe if events are pending. Typically used if you need to flush the
-    ///     input queue while still running some of your own code in your main thread.
-    /// </remarks>
-    internal bool EventsPending () { return MainLoopDriver!.EventsPending (); }
-
-
-    /// <summary>Runs the <see cref="MainLoop"/>. Used only for unit tests.</summary>
-    internal void Run ()
-    {
-        bool prev = Running;
-        Running = true;
-
-        while (Running)
-        {
-            EventsPending ();
-            RunIteration ();
-        }
-
-        Running = prev;
-    }
-
-    /// <summary>Runs one iteration of timers and file watches</summary>
-    /// <remarks>
-    ///     Use this to process all pending events (timers handlers and file watches).
-    ///     <code>
-    ///     while (main.EventsPending ()) RunIteration ();
-    ///   </code>
-    /// </remarks>
-    internal void RunIteration ()
-    {
-        RunAnsiScheduler ();
-
-        MainLoopDriver?.Iteration ();
-
-        TimedEvents.RunTimers ();
-    }
-
-    private void RunAnsiScheduler ()
-    {
-        Application.Driver?.GetRequestScheduler ().RunSchedule ();
-    }
-
-    /// <summary>Stops the main loop driver and calls <see cref="IMainLoopDriver.Wakeup"/>. Used only for unit tests.</summary>
-    internal void Stop ()
-    {
-        Running = false;
-        Wakeup ();
-    }
-
-
-    /// <summary>Wakes up the <see cref="MainLoop"/> that might be waiting on input.</summary>
-    internal void Wakeup () { MainLoopDriver?.Wakeup (); }
-
-
-}

+ 2 - 17
Terminal.Gui/App/MainLoop/MainLoopSyncContext.cs

@@ -10,23 +10,8 @@ internal sealed class MainLoopSyncContext : SynchronizationContext
 
     public override void Post (SendOrPostCallback d, object state)
     {
-        // Queue the task
-        if (ApplicationImpl.Instance.IsLegacy)
-        {
-            Application.MainLoop?.TimedEvents.Add (TimeSpan.Zero,
-                                                   () =>
-                                                   {
-                                                       d (state);
-
-                                                       return false;
-                                                   }
-                                                  );
-            Application.MainLoop?.Wakeup ();
-        }
-        else
-        {
-            ApplicationImpl.Instance.Invoke (() => { d (state); });
-        }
+        // Queue the task using the modern architecture
+        ApplicationImpl.Instance.Invoke (() => { d (state); });
     }
 
     //_mainLoop.Driver.Wakeup ();

+ 56 - 2
Terminal.Gui/Drivers/AnsiHandling/EscSeqUtils/EscSeqUtils.cs

@@ -931,7 +931,7 @@ public static class EscSeqUtils
             _isButtonClicked = false;
             _isButtonDoubleClicked = true;
 
-            Application.MainLoop?.TimedEvents.Add (TimeSpan.Zero,
+            ApplicationImpl.Instance.TimedEvents?.Add (TimeSpan.Zero,
                                           () =>
                                           {
                                               Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
@@ -970,7 +970,7 @@ public static class EscSeqUtils
                 mouseFlags.Add (GetButtonClicked (buttonState));
                 _isButtonClicked = true;
 
-                Application.MainLoop?.TimedEvents.Add (TimeSpan.Zero,
+                ApplicationImpl.Instance.TimedEvents?.Add (TimeSpan.Zero,
                                               () =>
                                               {
                                                   Task.Run (async () => await ProcessButtonClickedAsync ());
@@ -2076,4 +2076,58 @@ public static class EscSeqUtils
     public const string CSI_ReportTerminalSizeInChars_ResponseValue = "8";
 
     #endregion
+
+    #region OSC 8 Hyperlinks
+
+    /// <summary>
+    ///     OSC (Operating System Command) escape sequence prefix.
+    /// </summary>
+    /// <remarks>
+    ///     OSC sequences are used for operating system-specific commands like setting window title,
+    ///     hyperlinks (OSC 8), and other terminal emulator features.
+    /// </remarks>
+    public const string OSC = "\u001B]";
+
+    /// <summary>
+    ///     String Terminator (ST) - terminates OSC sequences.
+    /// </summary>
+    /// <remarks>
+    ///     Can also be represented as BEL (0x07) in some terminals, but ST is more modern.
+    /// </remarks>
+    public const string ST = "\u001B\\";
+
+    /// <summary>
+    ///     Starts a hyperlink using OSC 8 escape sequence.
+    /// </summary>
+    /// <param name="url">The URL to link to (e.g., "https://github.com").</param>
+    /// <param name="id">Optional hyperlink ID for matching start/end pairs. Use null for automatic matching.</param>
+    /// <returns>The OSC 8 start sequence.</returns>
+    /// <remarks>
+    ///     OSC 8 format: ESC ] 8 ; params ; URL ST
+    ///     Supported in Windows Terminal, iTerm2, and other modern terminals.
+    ///     Must be followed by visible text, then terminated with <see cref="OSC_EndHyperlink"/>.
+    /// </remarks>
+    public static string OSC_StartHyperlink (string url, string? id = null)
+    {
+        // Format: ESC ] 8 ; params ; URL ST
+        // params can include "id=value" for matching start/end
+        string parameters = string.IsNullOrEmpty (id) ? "" : $"id={id}";
+        return $"{OSC}8;{parameters};{url}{ST}";
+    }
+
+    /// <summary>
+    ///     Ends a hyperlink using OSC 8 escape sequence.
+    /// </summary>
+    /// <returns>The OSC 8 end sequence.</returns>
+    /// <remarks>
+    ///     This terminates the hyperlink started by <see cref="OSC_StartHyperlink"/>.
+    ///     Format: ESC ] 8 ; ; ST (empty URL ends the hyperlink).
+    /// </remarks>
+    public static string OSC_EndHyperlink ()
+    {
+        // Format: ESC ] 8 ; ; ST (empty URL ends hyperlink)
+        return $"{OSC}8;;{ST}";
+    }
+
+    #endregion
 }

+ 345 - 0
Terminal.Gui/Drivers/AnsiHandling/Osc8UrlLinker.cs

@@ -0,0 +1,345 @@
+#nullable enable
+
+namespace Terminal.Gui.Drivers;
+
+internal static class Osc8UrlLinker
+{
+    internal readonly struct Options
+    {
+        internal readonly string [] _allowedSchemes;
+        internal readonly bool _validateWithUri;
+
+        private Options (string [] allowedSchemes, bool validateWithUri)
+        {
+            _allowedSchemes = allowedSchemes;
+            _validateWithUri = validateWithUri;
+        }
+
+        public static Options CreateDefault ()
+        {
+            return new Options (
+                allowedSchemes: ["http", "https", "ftp", "ftps"],
+                validateWithUri: true
+            );
+        }
+    }
+
+    private static readonly Options _defaultOptions = Options.CreateDefault ();
+
+    internal static StringBuilder WrapOsc8 (StringBuilder input)
+    {
+        return WrapOsc8 (input, _defaultOptions);
+    }
+
+    internal static StringBuilder WrapOsc8 (StringBuilder input, Options options)
+    {
+        if (input is null || input.Length == 0)
+        {
+            return input;
+        }
+
+        string text = input.ToString ();
+        int len = text.Length;
+
+        StringBuilder? result = null;
+        int copyFrom = 0;
+
+        int i = 0;
+        while (i < len)
+        {
+            if (text [i] == '\x1B')
+            {
+                int escEnd = ParseEscapeSequence (text, i, len);
+                if (result != null)
+                {
+                    if (i > copyFrom)
+                    {
+                        result.Append (text, copyFrom, i - copyFrom);
+                    }
+
+                    result.Append (text, i, escEnd - i);
+                    copyFrom = escEnd;
+                }
+
+                i = escEnd;
+                continue;
+            }
+
+            int segStart = i;
+            int nextEsc = text.IndexOf ('\x1B', segStart);
+            if (nextEsc < 0)
+            {
+                nextEsc = len;
+            }
+
+            bool changed;
+            string processed = WrapPlainText (text, segStart, nextEsc, options, out changed);
+
+            if (changed)
+            {
+                result ??= new StringBuilder (text.Length + 100);
+
+                if (segStart > copyFrom)
+                {
+                    result.Append (text, copyFrom, segStart - copyFrom);
+                }
+
+                result.Append (processed);
+                copyFrom = nextEsc;
+            }
+
+            i = nextEsc;
+        }
+
+        if (result is null)
+        {
+            return input;
+        }
+
+        if (copyFrom < len)
+        {
+            result.Append (text, copyFrom, len - copyFrom);
+        }
+
+        return result;
+    }
+
+    private static int ParseEscapeSequence (string text, int start, int len)
+    {
+        int i = start;
+        if (i + 1 >= len)
+        {
+            return len;
+        }
+
+        char c1 = text [i + 1];
+
+        if (c1 == '[')
+        {
+            int j = i + 2;
+            while (j < len)
+            {
+                char ch = text [j++];
+                if (ch >= '@' && ch <= '~')
+                {
+                    break;
+                }
+            }
+
+            return j;
+        }
+
+        if (c1 == ']')
+        {
+            int j = i + 2;
+            while (j < len)
+            {
+                char ch = text [j++];
+                if (ch == '\x07')
+                {
+                    break;
+                }
+
+                if (ch == '\x1B')
+                {
+                    if (j < len && text [j] == '\\')
+                    {
+                        j++;
+                        break;
+                    }
+                }
+            }
+
+            return j;
+        }
+
+        return Math.Min (i + 2, len);
+    }
+
+    private static string WrapPlainText (string full, int start, int endExclusive, Options options, out bool changed)
+    {
+        ReadOnlySpan<char> span = full.AsSpan (start, endExclusive - start);
+        ReadOnlySpan<char> delimiter = "://".AsSpan ();
+        int i = 0;
+        int copyFrom = 0;
+        StringBuilder? sb = null;
+
+        while (i < span.Length)
+        {
+            int rel = span.Slice (i).IndexOf (delimiter, StringComparison.Ordinal);
+            if (rel < 0)
+            {
+                break;
+            }
+
+            int delimAt = i + rel;
+            int schemeEnd = delimAt;
+            int schemeStart = schemeEnd - 1;
+
+            while (schemeStart >= 0 && char.IsLetter (span [schemeStart]))
+            {
+                schemeStart--;
+            }
+
+            schemeStart++;
+
+            if (schemeStart < 0 || schemeStart >= schemeEnd)
+            {
+                i = delimAt + delimiter.Length;
+                continue;
+            }
+
+            ReadOnlySpan<char> scheme = span.Slice (schemeStart, schemeEnd - schemeStart);
+            if (!IsAllowedScheme (scheme, options))
+            {
+                i = delimAt + delimiter.Length;
+                continue;
+            }
+
+            int urlStart = schemeStart;
+            int j = delimAt + delimiter.Length;
+
+            while (j < span.Length && !IsUrlTerminator (span [j]))
+            {
+                j++;
+            }
+
+            // Trim punctuation from the end of the URL, but remember it so we can re-append it after the hyperlink
+            int urlEnd = TrimTrailingPunctuation (span, urlStart, j);
+            ReadOnlySpan<char> trailing = span.Slice (urlEnd, j - urlEnd);
+
+            if (urlEnd <= (delimAt + delimiter.Length))
+            {
+                i = j;
+                continue;
+            }
+
+            string candidate = span.Slice (urlStart, urlEnd - urlStart).ToString ();
+
+            Uri? _;
+            if (options._validateWithUri && !IsValidUrl (candidate, options, out _))
+            {
+                i = j;
+                continue;
+            }
+
+            sb ??= new StringBuilder (span.Length + 64);
+
+            if (urlStart > copyFrom)
+            {
+                sb.Append (span.Slice (copyFrom, urlStart - copyFrom));
+            }
+
+            // Preserve original candidate for link target and display
+            string linkTarget = candidate;
+
+            sb.Append (EscSeqUtils.OSC_StartHyperlink (linkTarget));
+            sb.Append (candidate);
+            sb.Append (EscSeqUtils.OSC_EndHyperlink ());
+
+            // Re-append the trimmed punctuation/suffix (e.g., "!", ",", ")")
+            if (!trailing.IsEmpty)
+            {
+                sb.Append (trailing);
+            }
+
+            copyFrom = j;
+            i = j;
+        }
+
+        if (sb is null)
+        {
+            changed = false;
+            return span.ToString ();
+        }
+
+        if (copyFrom < span.Length)
+        {
+            sb.Append (span.Slice (copyFrom));
+        }
+
+        changed = true;
+        return sb.ToString ();
+    }
+
+    private static bool IsAllowedScheme (ReadOnlySpan<char> scheme, Options options)
+    {
+        for (int i = 0; i < options._allowedSchemes.Length; i++)
+        {
+            string s = options._allowedSchemes [i];
+            if (scheme.Equals (s, StringComparison.OrdinalIgnoreCase))
+            {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    private static bool IsUrlTerminator (char c)
+    {
+        return char.IsWhiteSpace (c) || c == '<' || c == '>' || c == '"' || c == '\'' || c == '\x1B';
+    }
+
+    private static int TrimTrailingPunctuation (ReadOnlySpan<char> span, int start, int end)
+    {
+        int e = end;
+
+        while (e > start)
+        {
+            char c = span [e - 1];
+            if (c is '.' or ',' or '!' or '?' or ';' or ':' or ']' or '}' or '"')
+            {
+                e--;
+            }
+            else
+            {
+                break;
+            }
+        }
+
+        if (e > start && span [e - 1] == ')')
+        {
+            int opens = 0;
+            int closes = 0;
+
+            for (int k = start; k < e; k++)
+            {
+                if (span [k] == '(')
+                {
+                    opens++;
+                }
+                else if (span [k] == ')')
+                {
+                    closes++;
+                }
+            }
+
+            while (e > start && closes > opens && span [e - 1] == ')')
+            {
+                e--;
+                closes--;
+            }
+        }
+
+        return e;
+    }
+
+    private static bool IsValidUrl (string candidate, Options options, out Uri? uri)
+    {
+        if (Uri.TryCreate (candidate, UriKind.Absolute, out uri))
+        {
+            for (int i = 0; i < options._allowedSchemes.Length; i++)
+            {
+                string s = options._allowedSchemes [i];
+                if (uri.Scheme.Equals (s, StringComparison.OrdinalIgnoreCase))
+                {
+                    return true;
+                }
+            }
+        }
+
+        uri = null;
+        return false;
+    }
+}

+ 1 - 2
Terminal.Gui/Drivers/ConsoleDriver.cs

@@ -550,8 +550,7 @@ public abstract class ConsoleDriver : IConsoleDriver
     #region Setup & Teardown
 
     /// <summary>Initializes the driver</summary>
-    /// <returns>Returns an instance of <see cref="MainLoop"/> using the <see cref="IMainLoopDriver"/> for the driver.</returns>
-    public abstract MainLoop Init ();
+    public abstract void Init ();
 
     /// <summary>Ends the execution of the console driver.</summary>
     public abstract void End ();

+ 1 - 1
Terminal.Gui/Drivers/ConsoleDriverFacade.cs

@@ -365,7 +365,7 @@ internal class ConsoleDriverFacade<T> : IConsoleDriver, IConsoleDriverFacade
 
     /// <summary>Initializes the driver</summary>
     /// <returns>Returns an instance of <see cref="MainLoop"/> using the <see cref="IMainLoopDriver"/> for the driver.</returns>
-    public MainLoop Init () { throw new NotSupportedException (); }
+    public void Init () { throw new NotSupportedException (); }
 
     /// <summary>Ends the execution of the console driver.</summary>
     public void End ()

+ 5 - 0
Terminal.Gui/Drivers/DotNetDriver/NetInput.cs

@@ -86,6 +86,11 @@ public class NetInput : ConsoleInput<ConsoleKeyInfo>, INetInput
     {
         base.Dispose ();
 
+        if (ConsoleDriver.RunningUnitTests)
+        {
+            return;
+        }
+
         // Disable mouse events first
         Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
 

+ 1 - 27
Terminal.Gui/Drivers/FakeDriver/FakeDriver.cs

@@ -91,9 +91,7 @@ public class FakeDriver : ConsoleDriver
         FakeConsole.Clear ();
     }
 
-    private FakeMainLoop? _mainLoopDriver;
-
-    public override MainLoop Init ()
+    public override void Init ()
     {
         FakeConsole.MockKeyPresses.Clear ();
 
@@ -102,12 +100,6 @@ public class FakeDriver : ConsoleDriver
         FakeConsole.Clear ();
         ResizeScreen ();
         CurrentAttribute = new Attribute (Color.White, Color.Black);
-        //ClearContents ();
-
-        _mainLoopDriver = new FakeMainLoop (this);
-        _mainLoopDriver.MockKeyPressed = MockKeyPressedHandler;
-
-        return new MainLoop (_mainLoopDriver);
     }
 
     public override bool UpdateScreen ()
@@ -346,24 +338,6 @@ public class FakeDriver : ConsoleDriver
 
     private CursorVisibility _savedCursorVisibility;
 
-    private void MockKeyPressedHandler (ConsoleKeyInfo consoleKeyInfo)
-    {
-        if (consoleKeyInfo.Key == ConsoleKey.Packet)
-        {
-            consoleKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
-        }
-
-        KeyCode map = MapKey (consoleKeyInfo);
-
-        if (IsValidInput (map, out map))
-        {
-            OnKeyDown (new (map));
-            OnKeyUp (new (map));
-        }
-
-        //OnKeyPressed (new KeyEventArgs (map));
-    }
-
     /// <inheritdoc/>
     public override bool GetCursorVisibility (out CursorVisibility visibility)
     {

+ 0 - 38
Terminal.Gui/Drivers/FakeDriver/FakeMainLoop.cs

@@ -1,38 +0,0 @@
-
-namespace Terminal.Gui.Drivers;
-
-internal class FakeMainLoop : IMainLoopDriver
-{
-    public Action<ConsoleKeyInfo> MockKeyPressed;
-
-    public FakeMainLoop (IConsoleDriver consoleDriver = null)
-    {
-        // No implementation needed for FakeMainLoop
-    }
-
-    public void Setup (MainLoop mainLoop)
-    {
-        // No implementation needed for FakeMainLoop
-    }
-
-    public void Wakeup ()
-    {
-        // No implementation needed for FakeMainLoop
-    }
-
-    public bool EventsPending ()
-    {
-        // Always return true for FakeMainLoop
-        return true;
-    }
-
-    public void Iteration ()
-    {
-        if (FakeConsole.MockKeyPresses.Count > 0)
-        {
-            MockKeyPressed?.Invoke (FakeConsole.MockKeyPresses.Pop ());
-        }
-    }
-
-    public void TearDown () { }
-}

+ 1 - 2
Terminal.Gui/Drivers/IConsoleDriver.cs

@@ -214,8 +214,7 @@ public interface IConsoleDriver
     void UpdateCursor ();
 
     /// <summary>Initializes the driver</summary>
-    /// <returns>Returns an instance of <see cref="MainLoop"/> using the <see cref="IMainLoopDriver"/> for the driver.</returns>
-    MainLoop Init ();
+    void Init ();
 
     /// <summary>Ends the execution of the console driver.</summary>
     void End ();

+ 48 - 53
Terminal.Gui/Drivers/OutputBase.cs

@@ -1,13 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
+#nullable enable
 namespace Terminal.Gui.Drivers;
 
 /// <summary>
-/// Abstract base class to assist with implementing <see cref="IConsoleOutput"/>.
+///     Abstract base class to assist with implementing <see cref="IConsoleOutput"/>.
 /// </summary>
 public abstract class OutputBase
 {
@@ -16,6 +11,13 @@ public abstract class OutputBase
     // Last text style used, for updating style with EscSeqUtils.CSI_AppendTextStyleChange().
     private TextStyle _redrawTextStyle = TextStyle.None;
 
+    /// <summary>
+    ///     Changes the visibility of the cursor in the terminal to the specified <paramref name="visibility"/> e.g.
+    ///     the flashing indicator, invisible, box indicator etc.
+    /// </summary>
+    /// <param name="visibility"></param>
+    public abstract void SetCursorVisibility (CursorVisibility visibility);
+
     /// <inheritdoc cref="IConsoleOutput.Write(IOutputBuffer)"/>
     public virtual void Write (IOutputBuffer buffer)
     {
@@ -24,13 +26,6 @@ public abstract class OutputBase
             return;
         }
 
-        //if (Console.WindowHeight < 1
-        //    || buffer.Contents.Length != buffer.Rows * buffer.Cols
-        //    || buffer.Rows != Console.WindowHeight)
-        //{
-        //    //     return;
-        //}
-
         var top = 0;
         var left = 0;
         int rows = buffer.Rows;
@@ -42,16 +37,11 @@ public abstract class OutputBase
         CursorVisibility? savedVisibility = _cachedCursorVisibility;
         SetCursorVisibility (CursorVisibility.Invisible);
 
-        const int maxCharsPerRune = 2;
-        Span<char> runeBuffer = stackalloc char [maxCharsPerRune];
+        const int MAX_CHARS_PER_RUNE = 2;
+        Span<char> runeBuffer = stackalloc char [MAX_CHARS_PER_RUNE];
 
         for (int row = top; row < rows; row++)
         {
-            //if (Console.WindowHeight < 1)
-            //{
-            //    return;
-            //}
-
             if (!SetCursorPositionImpl (0, row))
             {
                 return;
@@ -90,16 +80,21 @@ public abstract class OutputBase
                         lastCol = col;
                     }
 
-                    Attribute attr = buffer.Contents [row, col].Attribute.Value;
+                    Attribute? attribute = buffer.Contents [row, col].Attribute;
 
-                    // Performance: Only send the escape sequence if the attribute has changed.
-                    if (attr != redrawAttr)
+                    if (attribute is { })
                     {
-                        redrawAttr = attr;
+                        Attribute attr = attribute.Value;
+
+                        // Performance: Only send the escape sequence if the attribute has changed.
+                        if (attr != redrawAttr)
+                        {
+                            redrawAttr = attr;
 
-                        AppendOrWriteAttribute (output, attr, _redrawTextStyle);
+                            AppendOrWriteAttribute (output, attr, _redrawTextStyle);
 
-                        _redrawTextStyle = attr.Style;
+                            _redrawTextStyle = attr.Style;
+                        }
                     }
 
                     outputWidth++;
@@ -120,8 +115,6 @@ public abstract class OutputBase
                         // For now, we just ignore the list of CMs.
                         //foreach (var combMark in Contents [row, col].CombiningMarks) {
                         //	output.Append (combMark);
-                        //}
-                        // WriteToConsole (output, ref lastCol, row, ref outputWidth);
                     }
                     else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
                     {
@@ -136,7 +129,10 @@ public abstract class OutputBase
             if (output.Length > 0)
             {
                 SetCursorPositionImpl (lastCol, row);
-                Write (output);
+
+                // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
+                StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
+                Write (processed);
             }
         }
 
@@ -154,32 +150,19 @@ public abstract class OutputBase
     }
 
     /// <summary>
-    /// Changes the color and text style of the console to the given <paramref name="attr"/> and <paramref name="redrawTextStyle"/>.
-    /// If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to <paramref name="output"/>
-    /// otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
+    ///     Changes the color and text style of the console to the given <paramref name="attr"/> and
+    ///     <paramref name="redrawTextStyle"/>.
+    ///     If command can be buffered in line with other output (e.g. CSI sequence) then it should be appended to
+    ///     <paramref name="output"/>
+    ///     otherwise the relevant output state should be flushed directly (e.g. by calling relevant win 32 API method)
     /// </summary>
     /// <param name="output"></param>
     /// <param name="attr"></param>
     /// <param name="redrawTextStyle"></param>
     protected abstract void AppendOrWriteAttribute (StringBuilder output, Attribute attr, TextStyle redrawTextStyle);
 
-    private void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
-    {
-        SetCursorPositionImpl (lastCol, row);
-        Write (output);
-        output.Clear ();
-        lastCol += outputWidth;
-        outputWidth = 0;
-    }
-
     /// <summary>
-    /// Output the contents of the <paramref name="output"/> to the console.
-    /// </summary>
-    /// <param name="output"></param>
-    protected abstract void Write (StringBuilder output);
-
-    /// <summary>
-    /// When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
+    ///     When overriden in derived class, positions the terminal output cursor to the specified point on the screen.
     /// </summary>
     /// <param name="screenPositionX">Column to move cursor to</param>
     /// <param name="screenPositionY">Row to move cursor to</param>
@@ -187,9 +170,21 @@ public abstract class OutputBase
     protected abstract bool SetCursorPositionImpl (int screenPositionX, int screenPositionY);
 
     /// <summary>
-    /// Changes the visibility of the cursor in the terminal to the specified <paramref name="visibility"/> e.g.
-    /// the flashing indicator, invisible, box indicator etc.
+    ///     Output the contents of the <paramref name="output"/> to the console.
     /// </summary>
-    /// <param name="visibility"></param>
-    public abstract void SetCursorVisibility (CursorVisibility visibility);
+    /// <param name="output"></param>
+    protected abstract void Write (StringBuilder output);
+
+    private void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
+    {
+        SetCursorPositionImpl (lastCol, row);
+
+        // Wrap URLs with OSC 8 hyperlink sequences using the new Osc8UrlLinker
+        StringBuilder processed = Osc8UrlLinker.WrapOsc8 (output);
+        Write (processed);
+
+        output.Clear ();
+        lastCol += outputWidth;
+        outputWidth = 0;
+    }
 }

+ 34 - 68
Terminal.Gui/README.md

@@ -8,43 +8,7 @@
 
 ## Project Folder Structure
 
-- `\` - The root folder contains the core solution and project files for the library.
-	- `Terminal.Gui.sln` - The Visual Studio solution file for the project.
-	- `Terminal.Gui.csproj` - The project file defining build configurations and dependencies.
-	- `App\` - Contains the core `Application` logic, including `Application.cs`, a `static` class that serves as the base 'application engine', managing `RunState` and `MainLoop`.
-
-- `Configuration\` - Classes related to the `ConfigurationManager` for handling application settings.
-
-- `Drivers\` - Contains the console driver implementations:
-	- `IConsoleDriver.cs` - Defines the Console Driver API.
-	- Driver implementations for .NET (`DotNetDriver`), Unix & macOS (`UnixDriver`), and Windows (`WindowsDriver`).
-
-- `Drawing\` - Classes related to rendering graphical elements in the console.
-
-- `FileServices\` - Utility classes for file operations and services.
-
-- `Input\` - Classes handling keyboard and mouse input:
-	- `Events.cs` - Defines structs and classes for keyboard and mouse events.
-
-- `Resources\` - Assets and resources used by the library.
-
-- `Text\` - Classes for text processing and formatting.
-
-- `View\` - Core `View` class hierarchy (excluding specific sub-classes):
-	- `View.cs` - The base class for non-modal visual elements such as controls.
-	- Related subdirectories for layout and positioning logic.
-
-- `ViewBase\` - Base classes and utilities for views.
-
-- `Views\` - Specific sub-classes of `View`:
-	- `Toplevel` - Base class for modal visual elements like top-level windows and dialogs, supporting `MenuBar` and `StatusBar`.
-	- `Window` - Implements framed top-level views with titles.
-	- `Dialog` - Specialized windows for user interaction.
-	- Other specialized view classes.
-
-## Showcase
-
-See the [Showcase](docs/showcase.md) to find independent applications and examples built with Terminal.Gui.
+This directory contains the core **Terminal.Gui** library source code. For a detailed repository structure, see [CONTRIBUTING.md - Repository Structure](../CONTRIBUTING.md#repository-structure).
 
 ## Getting Started
 
@@ -52,14 +16,9 @@ For instructions on how to start using **Terminal.Gui**, refer to the [Getting S
 
 ## Documentation
 
-Comprehensive documentation for **Terminal.Gui** is available at [gui-cs.github.io/Terminal.Gui](https://gui-cs.github.io/Terminal.Gui). Key resources include:
-- [Events Deep Dive](https://gui-cs.github.io/Terminal.Gui/docs/events.html) - Detailed guide on event handling and the Cancellable Work Pattern.
-- [View Documentation](https://gui-cs.github.io/Terminal.Gui/docs/View.html) - Information on creating and customizing views.
-- [Keyboard Handling](https://gui-cs.github.io/Terminal.Gui/docs/keyboard.html) - Guide to managing keyboard input.
-- [Mouse Support](https://gui-cs.github.io/Terminal.Gui/docs/mouse.html) - Details on implementing mouse interactions.
-- [Showcase](https://gui-cs.github.io/Terminal.Gui/docs/showcase.html) - A collection of applications and examples built with Terminal.Gui.
+Comprehensive documentation is available at [gui-cs.github.io/Terminal.Gui](https://gui-cs.github.io/Terminal.Gui).
 
-For information on generating and updating the API documentation locally, refer to the [DocFX README](../docfx/README.md) in the `docfx` folder.
+For information on generating and updating the API documentation locally, refer to the [DocFX README](../docfx/README.md).
 
 ## Versioning
 
@@ -75,7 +34,7 @@ The project version (used in the NuGet package and `Terminal.Gui.dll`) is determ
 To define a new version, tag a commit using `git tag`:
 
 ```powershell
-git tag v1.3.4-beta.5 -a -m "Release v1.3.4 Beta 5"
+git tag v2.1.0-beta.1 -a -m "Release v2.1.0 Beta 1"
 dotnet-gitversion /updateprojectfiles
 dotnet build -c Release
 ```
@@ -92,15 +51,15 @@ To release a new version, follow these steps based on [Semantic Versioning](http
 
 ### Steps for Release:
 
-1. **Verify the `develop` branch is ready for release**:
-	- Ensure all changes are committed and pushed to the `develop` branch.
-	- Ensure your local `develop` branch is up-to-date with `upstream/develop`.
+1. **Verify the `v2_develop` branch is ready for release**:
+	- Ensure all changes are committed and pushed to the `v2_develop` branch.
+	- Ensure your local `v2_develop` branch is up-to-date with `upstream/v2_develop`.
 
-2. **Create a pull request for the release in the `develop` branch**:
+2. **Create a pull request for the release in the `v2_develop` branch**:
 	- Title the PR as "Release vX.Y.Z".
 	```powershell
-	git checkout develop
-	git pull upstream develop
+	git checkout v2_develop
+	git pull upstream v2_develop
 	git checkout -b vX_Y_Z
 	git add .
 	git commit -m "Release vX.Y.Z"
@@ -110,28 +69,28 @@ To release a new version, follow these steps based on [Semantic Versioning](http
 
 3. **On github.com, verify the build action worked on your fork, then merge the PR**.
 
-4. **Pull the merged `develop` from `upstream`**:
+4. **Pull the merged `v2_develop` from `upstream`**:
 	```powershell
-	git checkout develop
-	git pull upstream develop
+	git checkout v2_develop
+	git pull upstream v2_develop
 	```
 
-5. **Merge `develop` into `main`**:
+5. **Merge `v2_develop` into `v2_release`**:
 	```powershell
-	git checkout main
-	git pull upstream main
-	git merge develop
+	git checkout v2_release
+	git pull upstream v2_release
+	git merge v2_develop
 	```
 	- Fix any merge errors.
 
-6. **Create a new annotated tag for the release on `main`**:
+6. **Create a new annotated tag for the release on `v2_release`**:
 	```powershell
 	git tag vX.Y.Z -a -m "Release vX.Y.Z"
 	```
 
-7. **Push the new tag to `main` on `upstream`**:
+7. **Push the new tag to `v2_release` on `upstream`**:
 	```powershell
-	git push --atomic upstream main vX.Y.Z
+	git push --atomic upstream v2_release vX.Y.Z
 	```
 
 8. **Monitor Github Actions to ensure the NuGet publishing worked**:
@@ -143,18 +102,25 @@ To release a new version, follow these steps based on [Semantic Versioning](http
 10. **Add a new Release in Github**:
 	- Go to [GitHub Releases](https://github.com/gui-cs/Terminal.Gui/releases) and generate release notes with the list of PRs since the last release.
 
-11. **Update the `develop` branch with the new version**:
+11. **Update the `v2_develop` branch with the new version**:
 	```powershell
-	git checkout develop
-	git pull upstream develop
-	git merge main
-	git push upstream develop
+	git checkout v2_develop
+	git pull upstream v2_develop
+	git merge v2_release
+	git push upstream v2_develop
 	```
 
 ## NuGet
 
-The official NuGet package for Terminal.Gui is available at [https://www.nuget.org/packages/Terminal.Gui](https://www.nuget.org/packages/Terminal.Gui). When a new version tag is defined and merged into `main`, a NuGet package is automatically generated by a GitHub Action. Pre-release versions (e.g., `1.3.4-beta.5`) are tagged as pre-release on NuGet.
+The official NuGet package for Terminal.Gui is available at [https://www.nuget.org/packages/Terminal.Gui](https://www.nuget.org/packages/Terminal.Gui). When a new version tag is defined and merged into `v2_release`, a NuGet package is automatically generated by a GitHub Action. Pre-release versions (e.g., `2.0.0-beta.5`) are tagged as pre-release on NuGet.
 
 ## Contributing
 
-We welcome contributions from the community. For detailed guidelines on how to contribute, including coding style, unit tests, and pull request processes, please refer to [CONTRIBUTING.md](https://github.com/gui-cs/Terminal.Gui/blob/master/CONTRIBUTING.md).
+We welcome contributions from the community. For complete contribution guidelines, including:
+- Build and test instructions
+- Coding conventions and style rules
+- Testing requirements and patterns
+- Pull request guidelines
+- CI/CD workflows
+
+Please refer to [CONTRIBUTING.md](../CONTRIBUTING.md) in the repository root.

+ 10 - 10
Terminal.Gui/ViewBase/Adornment/ShadowView.cs

@@ -95,12 +95,12 @@ internal class ShadowView : View
         {
             for (int c = Math.Max (0, screen.X + 1); c < screen.X + screen.Width; c++)
             {
-                Driver?.Move (c, r);
+                Driver.Move (c, r);
                 SetAttribute (GetAttributeUnderLocation (new (c, r)));
 
-                if (c < Driver?.Contents!.GetLength (1) && r < Driver?.Contents?.GetLength (0))
+                if (c < ScreenContents?.GetLength (1) && r < ScreenContents?.GetLength (0))
                 {
-                    Driver.AddRune (Driver.Contents [r, c].Rune);
+                    AddRune (ScreenContents [r, c].Rune);
                 }
             }
         }
@@ -129,12 +129,12 @@ internal class ShadowView : View
         {
             for (int r = Math.Max (0, screen.Y); r < screen.Y + viewport.Height; r++)
             {
-                Driver?.Move (c, r);
+                Driver.Move (c, r);
                 SetAttribute (GetAttributeUnderLocation (new (c, r)));
 
-                if (Driver?.Contents is { } && screen.X < Driver.Contents.GetLength (1) && r < Driver.Contents.GetLength (0))
+                if (ScreenContents is { } && screen.X < ScreenContents.GetLength (1) && r < ScreenContents.GetLength (0))
                 {
-                    Driver.AddRune (Driver.Contents [r, c].Rune);
+                    AddRune (ScreenContents [r, c].Rune);
                 }
             }
         }
@@ -151,14 +151,14 @@ internal class ShadowView : View
             return Attribute.Default;
         }
 
-        if (Driver?.Contents == null ||
-            location.Y < 0 || location.Y >= Driver.Contents.GetLength (0) ||
-            location.X < 0 || location.X >= Driver.Contents.GetLength (1))
+        if (ScreenContents == null ||
+            location.Y < 0 || location.Y >= ScreenContents.GetLength (0) ||
+            location.X < 0 || location.X >= ScreenContents.GetLength (1))
         {
             return Attribute.Default;
         }
 
-        Attribute attr = Driver!.Contents! [location.Y, location.X].Attribute!.Value;
+        Attribute attr = ScreenContents [location.Y, location.X].Attribute!.Value;
 
         var newAttribute =
             new Attribute (

+ 1 - 1
Terminal.Gui/ViewBase/View.Drawing.cs

@@ -658,7 +658,7 @@ public partial class View // Drawing APIs
                     Driver.Move (p.Key.X, p.Key.Y);
 
                     // TODO: #2616 - Support combining sequences that don't normalize
-                    Driver.AddRune (p.Value.Value.Rune);
+                    AddRune (p.Value.Value.Rune);
                 }
             }
 

+ 3 - 0
Terminal.Gui/ViewBase/View.cs

@@ -130,6 +130,9 @@ public partial class View : IDisposable, ISupportInitializeNotification
         set => _driver = value;
     }
 
+    /// <summary>Gets the screen buffer contents. This is a convenience property for Views that need direct access to the screen buffer.</summary>
+    protected Cell [,]? ScreenContents => Driver?.Contents;
+
     /// <summary>Initializes a new instance of <see cref="View"/>.</summary>
     /// <remarks>
     ///     <para>

+ 1 - 1
Terminal.Gui/Views/Color/ColorBar.cs

@@ -92,7 +92,7 @@ internal abstract class ColorBar : View, IColorBar
         {
             Move (0, 0);
             SetAttribute (HasFocus ? GetAttributeForRole (VisualRole.Focus) : GetAttributeForRole (VisualRole.Normal));
-            Driver?.AddStr (Text);
+            AddStr (Text);
 
             // TODO: is there a better method than this? this is what it is in TableView
             xOffset = Text.EnumerateRunes ().Sum (c => c.GetColumns ());

+ 4 - 4
Terminal.Gui/Views/FileDialogs/FileDialog.cs

@@ -427,9 +427,9 @@ public class FileDialog : Dialog, IDesignable
             Move (0, Viewport.Height / 2);
 
             SetAttribute (new (Color.Red, GetAttributeForRole (VisualRole.Normal).Background));
-            Driver!.AddStr (new (' ', feedbackPadLeft));
-            Driver.AddStr (_feedback);
-            Driver.AddStr (new (' ', feedbackPadRight));
+            AddStr (new (' ', feedbackPadLeft));
+            AddStr (_feedback);
+            AddStr (new (' ', feedbackPadRight));
         }
 
         return true;
@@ -507,7 +507,7 @@ public class FileDialog : Dialog, IDesignable
             _allowedTypeMenuBar.DrawingContent += (s, e) =>
                                                   {
                                                       _allowedTypeMenuBar.Move (e.NewViewport.Width - 1, 0);
-                                                      Driver!.AddRune (Glyphs.DownArrow);
+                                                      AddRune (Glyphs.DownArrow);
                                                   };
 
             Add (_allowedTypeMenuBar);

+ 1 - 1
Terminal.Gui/Views/GraphView/GraphView.cs

@@ -213,7 +213,7 @@ public class GraphView : View, IDesignable
         for (var i = 0; i < Viewport.Height; i++)
         {
             Move (0, i);
-            Driver?.AddStr (new (' ', Viewport.Width));
+            AddStr (new (' ', Viewport.Width));
         }
 
         // If there is no data do not display a graph

+ 1 - 1
Terminal.Gui/Views/GraphView/IAnnotation.cs

@@ -18,7 +18,7 @@ public interface IAnnotation
 
     /// <summary>
     ///     Called once after series have been rendered (or before if <see cref="BeforeSeries"/> is true). Use
-    ///     <see cref="View.Driver"/> to draw and <see cref="View.Viewport"/> to avoid drawing outside of graph
+    ///     methods like <see cref="View.AddStr(string)"/> and <see cref="View.AddRune(Rune)"/> to draw. Use <see cref="View.Viewport"/> to avoid drawing outside of graph.
     /// </summary>
     /// <param name="graph"></param>
     void Render (GraphView graph);

+ 2 - 2
Terminal.Gui/Views/GraphView/TextAnnotation.cs

@@ -68,11 +68,11 @@ public class TextAnnotation : IAnnotation
 
         if (Text.Length < availableWidth)
         {
-            graph.Driver?.AddStr (Text);
+            graph.AddStr (Text);
         }
         else
         {
-            graph.Driver?.AddStr (Text.Substring (0, availableWidth));
+            graph.AddStr (Text.Substring (0, availableWidth));
         }
     }
 }

+ 3 - 3
Terminal.Gui/Views/ListView.cs

@@ -750,7 +750,7 @@ public class ListView : View, IDesignable
             {
                 for (var c = 0; c < f.Width; c++)
                 {
-                    Driver?.AddRune ((Rune)' ');
+                    AddRune ((Rune)' ');
                 }
             }
             else
@@ -766,11 +766,11 @@ public class ListView : View, IDesignable
 
                 if (_allowsMarking)
                 {
-                    Driver?.AddRune (
+                    AddRune (
                                     _source.IsMarked (item) ? AllowsMultipleSelection ? Glyphs.CheckStateChecked : Glyphs.Selected :
                                     AllowsMultipleSelection ? Glyphs.CheckStateUnChecked : Glyphs.UnSelected
                                    );
-                    Driver?.AddRune ((Rune)' ');
+                    AddRune ((Rune)' ');
                 }
 
                 Source.Render (this, isSelected, item, col, row, f.Width - col, start);

+ 18 - 20
Terminal.Gui/Views/Menuv1/Menu.cs

@@ -847,7 +847,7 @@ internal sealed class Menu : View
                 continue;
             }
 
-            if (ViewportToScreen (Viewport).Y + i >= Driver.Rows)
+            if (ViewportToScreen (Viewport).Y + i >= Application.Screen.Height)
             {
                 break;
             }
@@ -863,11 +863,10 @@ internal sealed class Menu : View
 
             if (item is null && BorderStyle != LineStyle.None)
             {
-                Point s = ViewportToScreen (new Point (-1, i));
-                Driver.Move (s.X, s.Y);
-                Driver.AddRune (Glyphs.LeftTee);
+                Move (-1, i);
+                AddRune (Glyphs.LeftTee);
             }
-            else if (Frame.X < Driver.Cols)
+            else if (Frame.X < Application.Screen.Width)
             {
                 Move (0, i);
             }
@@ -882,28 +881,28 @@ internal sealed class Menu : View
                     continue;
                 }
 
-                if (ViewportToScreen (Viewport).X + p >= Driver.Cols)
+                if (ViewportToScreen (Viewport).X + p >= Application.Screen.Width)
                 {
                     break;
                 }
 
                 if (item is null)
                 {
-                    Driver.AddRune (Glyphs.HLine);
+                    AddRune (Glyphs.HLine);
                 }
                 else if (i == 0 && p == 0 && _host.UseSubMenusSingleFrame && item.Parent!.Parent is { })
                 {
-                    Driver.AddRune (Glyphs.LeftArrow);
+                    AddRune (Glyphs.LeftArrow);
                 }
 
                 // This `- 3` is left border + right border + one row in from right
                 else if (p == Frame.Width - 3 && _barItems?.SubMenu (_barItems.Children [i]!) is { })
                 {
-                    Driver.AddRune (Glyphs.RightArrow);
+                    AddRune (Glyphs.RightArrow);
                 }
                 else
                 {
-                    Driver.AddRune ((Rune)' ');
+                    AddRune ((Rune)' ');
                 }
             }
 
@@ -911,9 +910,8 @@ internal sealed class Menu : View
             {
                 if (BorderStyle != LineStyle.None && SuperView?.Frame.Right - Frame.X > Frame.Width)
                 {
-                    Point s = ViewportToScreen (new Point (Frame.Width - 2, i));
-                    Driver.Move (s.X, s.Y);
-                    Driver.AddRune (Glyphs.RightTee);
+                    Move (Frame.Width - 2, i);
+                    AddRune (Glyphs.RightTee);
                 }
 
                 continue;
@@ -950,9 +948,9 @@ internal sealed class Menu : View
 
             Point screen = ViewportToScreen (new Point (0, i));
 
-            if (screen.X < Driver.Cols)
+            if (screen.X < Application.Screen.Width)
             {
-                Driver.Move (screen.X + 1, screen.Y);
+                Move (1, i);
 
                 if (!item.IsEnabled ())
                 {
@@ -991,16 +989,16 @@ internal sealed class Menu : View
                 int col = Frame.Width - l - 3;
                 screen = ViewportToScreen (new Point (col, i));
 
-                if (screen.X < Driver.Cols)
+                if (screen.X < Application.Screen.Width)
                 {
-                    Driver.Move (screen.X, screen.Y);
-                    Driver.AddStr (item.Help);
+                    Move (col, i);
+                    AddStr (item.Help);
 
                     // The shortcut tag string
                     if (!string.IsNullOrEmpty (item.ShortcutTag))
                     {
-                        Driver.Move (screen.X + l - item.ShortcutTag.GetColumns (), screen.Y);
-                        Driver.AddStr (item.ShortcutTag);
+                        Move (col + l - item.ShortcutTag.GetColumns (), i);
+                        AddStr (item.ShortcutTag);
                     }
                 }
             }

+ 1 - 1
Terminal.Gui/Views/Menuv1/MenuBar.cs

@@ -697,7 +697,7 @@ public class MenuBar : View, IDesignable
     internal Point GetScreenOffset ()
     {
         // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
-        if (Driver is null)
+        if (Application.Screen.Height == 0)
         {
             return Point.Empty;
         }

+ 4 - 4
Terminal.Gui/Views/ProgressBar.cs

@@ -144,11 +144,11 @@ public class ProgressBar : View, IDesignable
             {
                 if (Array.IndexOf (_activityPos!, i) != -1)
                 {
-                    Driver?.AddRune (SegmentCharacter);
+                    AddRune (SegmentCharacter);
                 }
                 else
                 {
-                    Driver?.AddRune ((Rune)' ');
+                    AddRune ((Rune)' ');
                 }
             }
         }
@@ -159,12 +159,12 @@ public class ProgressBar : View, IDesignable
 
             for (i = 0; (i < mid) & (i < Viewport.Width); i++)
             {
-                Driver?.AddRune (SegmentCharacter);
+                AddRune (SegmentCharacter);
             }
 
             for (; i < Viewport.Width; i++)
             {
-                Driver?.AddRune ((Rune)' ');
+                AddRune ((Rune)' ');
             }
         }
 

+ 1 - 1
Terminal.Gui/Views/RadioGroup.cs

@@ -375,7 +375,7 @@ public class RadioGroup : View, IDesignable, IOrientation
 
             string rl = _radioLabels [i];
             SetAttribute (GetAttributeForRole (VisualRole.Normal));
-            Driver?.AddStr ($"{(i == _selected ? Glyphs.Selected : Glyphs.UnSelected)} ");
+            AddStr ($"{(i == _selected ? Glyphs.Selected : Glyphs.UnSelected)} ");
             TextFormatter.FindHotKey (rl, HotKeySpecifier, out int hotPos, out Key hotKey);
 
             if (hotPos != -1 && hotKey != Key.Empty)

+ 2 - 2
Terminal.Gui/Views/Slider/Slider.cs

@@ -441,13 +441,13 @@ public class Slider<T> : View, IOrientation
     private void MoveAndAdd (int x, int y, Rune rune)
     {
         Move (x, y);
-        Driver?.AddRune (rune);
+        AddRune (rune);
     }
 
     private void MoveAndAdd (int x, int y, string str)
     {
         Move (x, y);
-        Driver?.AddStr (str);
+        AddStr (str);
     }
 
     /// <summary>Sets the dimensions of the Slider to the ideal values.</summary>

+ 1 - 1
Terminal.Gui/Views/SpinnerView/SpinnerView.cs

@@ -187,7 +187,7 @@ public class SpinnerView : View, IDesignable
         if (Sequence is { Length: > 0 } && _currentIdx < Sequence.Length)
         {
             Move (Viewport.X, Viewport.Y);
-            Driver?.AddStr (Sequence [_currentIdx]);
+            AddStr (Sequence [_currentIdx]);
         }
     }
 

+ 19 - 20
Terminal.Gui/Views/TableView/TableView.cs

@@ -943,7 +943,7 @@ public class TableView : View, IDesignable
         SetAttribute (GetAttributeForRole (VisualRole.Normal));
 
         //invalidate current row (prevents scrolling around leaving old characters in the frame
-        Driver?.AddStr (new (' ', Viewport.Width));
+        AddStr (new (' ', Viewport.Width));
 
         var line = 0;
 
@@ -1289,12 +1289,11 @@ public class TableView : View, IDesignable
     protected virtual void OnSelectedCellChanged (SelectedCellChangedEventArgs args) { SelectedCellChanged?.Invoke (this, args); }
 
     /// <summary>
-    ///     Override to provide custom multi colouring to cells.  Use <see cref="View.Driver"/> to with
-    ///     <see cref="IConsoleDriver.AddStr(string)"/>.  The driver will already be in the correct place when rendering and
-    ///     you
-    ///     must render the full <paramref name="render"/> or the view will not look right.  For simpler provision of color use
-    ///     <see cref="ColumnStyle.ColorGetter"/> For changing the content that is rendered use
-    ///     <see cref="ColumnStyle.RepresentationGetter"/>
+    ///     Override to provide custom multi-coloring to cells. Use methods like <see cref="View.AddStr(string)"/>.
+    ///     The cursor will already be in the correct position when rendering. You must render the full
+    ///     <paramref name="render"/> or the view will not look right. For simpler color provision use
+    ///     <see cref="ColumnStyle.ColorGetter"/>. For changing the content that is rendered use
+    ///     <see cref="ColumnStyle.RepresentationGetter"/>.
     /// </summary>
     /// <param name="cellAttribute"></param>
     /// <param name="render"></param>
@@ -1310,19 +1309,19 @@ public class TableView : View, IDesignable
             {
                 // invert the color of the current cell for the first character
                 SetAttribute (new (cellAttribute.Foreground, cellAttribute.Background, TextStyle.Reverse));
-                Driver?.AddRune ((Rune)render [0]);
+                AddRune ((Rune)render [0]);
 
                 if (render.Length > 1)
                 {
                     SetAttribute (cellAttribute);
-                    Driver?.AddStr (render.Substring (1));
+                    AddStr (render.Substring (1));
                 }
             }
         }
         else
         {
             SetAttribute (cellAttribute);
-            Driver?.AddStr (render);
+            AddStr (render);
         }
     }
 
@@ -1349,10 +1348,10 @@ public class TableView : View, IDesignable
     /// <returns></returns>
     internal int GetHeaderHeightIfAny () { return ShouldRenderHeaders () ? GetHeaderHeight () : 0; }
 
-    private void AddRuneAt (IConsoleDriver d, int col, int row, Rune ch)
+    private void AddRuneAt (int col, int row, Rune ch)
     {
         Move (col, row);
-        d?.AddRune (ch);
+        AddRune (ch);
     }
 
     /// <summary>
@@ -1534,14 +1533,14 @@ public class TableView : View, IDesignable
     /// <param name="width"></param>
     private void ClearLine (int row, int width)
     {
-        if (Driver is null)
+        if (Application.Screen.Height == 0)
         {
             return;
         }
 
         Move (0, row);
         SetAttribute (GetAttributeForRole (VisualRole.Normal));
-        Driver.AddStr (new (' ', width));
+        AddStr (new (' ', width));
     }
 
     private void ClearMultiSelectedRegions (bool keepToggledSelections)
@@ -1734,7 +1733,7 @@ public class TableView : View, IDesignable
                 }
             }
 
-            AddRuneAt (Driver, c, row, rune);
+            AddRuneAt (c, row, rune);
         }
     }
 
@@ -1762,7 +1761,7 @@ public class TableView : View, IDesignable
 
             Move (current.X, row);
 
-            Driver?.AddStr (TruncateOrPad (colName, colName, current.Width, colStyle));
+            AddStr (TruncateOrPad (colName, colName, current.Width, colStyle));
 
             if (Style.ExpandLastColumn == false && current.IsVeryLast)
             {
@@ -1810,9 +1809,9 @@ public class TableView : View, IDesignable
                 }
             }
 
-            if (Driver is { })
+            if (Application.Screen.Height > 0)
             {
-                AddRuneAt (Driver, c, row, rune);
+                AddRuneAt (c, row, rune);
             }
         }
     }
@@ -1906,7 +1905,7 @@ public class TableView : View, IDesignable
                 }
             }
 
-            AddRuneAt (Driver, c, row, rune);
+            AddRuneAt (c, row, rune);
         }
     }
 
@@ -1934,7 +1933,7 @@ public class TableView : View, IDesignable
         }
 
         SetAttribute (attribute.Value);
-        Driver?.AddStr (new (' ', Viewport.Width));
+        AddStr (new (' ', Viewport.Width));
 
         // Render cells for each visible header for the current row
         for (var i = 0; i < columnsToRender.Length; i++)

+ 1 - 1
Terminal.Gui/Views/TableView/TreeTableSource.cs

@@ -178,7 +178,7 @@ public class TreeTableSource<T> : IEnumerableTableSource<T>, IDisposable where T
 
         Branch<T> branch = RowToBranch (hit.Value.Y);
 
-        if (branch.IsHitOnExpandableSymbol (Application.Driver, offsetX.Value))
+        if (branch.IsHitOnExpandableSymbol (offsetX.Value))
         {
             T m = branch.Model;
 

+ 3 - 3
Terminal.Gui/Views/TextInput/TextField.cs

@@ -973,7 +973,7 @@ public class TextField : View, IDesignable
 
             if (col + cols <= width)
             {
-                Driver?.AddRune (Secret ? Glyphs.Dot : rune);
+                AddRune (Secret ? Glyphs.Dot : rune);
             }
 
             if (!TextModel.SetCol (ref col, width, cols))
@@ -992,7 +992,7 @@ public class TextField : View, IDesignable
         // Fill rest of line with spaces
         for (int i = col; i < width; i++)
         {
-            Driver?.AddRune ((Rune)' ');
+            AddRune ((Rune)' ');
         }
 
         PositionCursor ();
@@ -1717,7 +1717,7 @@ public class TextField : View, IDesignable
             render = render [..Viewport.Width];
         }
 
-        Driver?.AddStr (render);
+        AddStr (render);
     }
 
     private void SetClipboard (IEnumerable<Rune> text)

+ 4 - 4
Terminal.Gui/Views/TextInput/TextValidateField.cs

@@ -177,7 +177,7 @@ public class TextValidateField : View, IDesignable
         if (_provider is null)
         {
             Move (0, 0);
-            Driver?.AddStr ("Error: ITextValidateProvider not set!");
+            AddStr ("Error: ITextValidateProvider not set!");
 
             return true;
         }
@@ -194,7 +194,7 @@ public class TextValidateField : View, IDesignable
 
         for (var i = 0; i < marginLeft; i++)
         {
-            Driver?.AddRune ((Rune)' ');
+            AddRune ((Rune)' ');
         }
 
         // Content
@@ -203,7 +203,7 @@ public class TextValidateField : View, IDesignable
         // Content
         for (var i = 0; i < _provider.DisplayText.Length; i++)
         {
-            Driver?.AddRune ((Rune)_provider.DisplayText [i]);
+            AddRune ((Rune)_provider.DisplayText [i]);
         }
 
         // Right Margin
@@ -211,7 +211,7 @@ public class TextValidateField : View, IDesignable
 
         for (var i = 0; i < marginRight; i++)
         {
-            Driver?.AddRune ((Rune)' ');
+            AddRune ((Rune)' ');
         }
 
         return true;

+ 1 - 1
Terminal.Gui/Views/TreeView/Branch.cs

@@ -454,7 +454,7 @@ internal class Branch<T> where T : class
     /// <param name="driver"></param>
     /// <param name="x"></param>
     /// <returns></returns>
-    internal bool IsHitOnExpandableSymbol (IConsoleDriver driver, int x)
+    internal bool IsHitOnExpandableSymbol (int x)
     {
         // if leaf node then we cannot expand
         if (!CanExpand ())

+ 3 - 3
Terminal.Gui/Views/TreeView/TreeView.cs

@@ -1065,7 +1065,7 @@ public class TreeView<T> : View, ITreeView where T : class
                 return false;
             }
 
-            bool isExpandToggleAttempt = clickedBranch.IsHitOnExpandableSymbol (Driver, me.Position.X);
+            bool isExpandToggleAttempt = clickedBranch.IsHitOnExpandableSymbol (me.Position.X);
 
             // If we are already selected (double click)
             if (Equals (SelectedObject, clickedBranch.Model))
@@ -1157,7 +1157,7 @@ public class TreeView<T> : View, ITreeView where T : class
         if (TreeBuilder is null)
         {
             Move (0, 0);
-            Driver?.AddStr (NoBuilderError);
+            AddStr (NoBuilderError);
 
             return true;
         }
@@ -1179,7 +1179,7 @@ public class TreeView<T> : View, ITreeView where T : class
                 // Else clear the line to prevent stale symbols due to scrolling etc
                 Move (0, line);
                 SetAttribute (GetAttributeForRole (VisualRole.Normal));
-                Driver?.AddStr (new (' ', Viewport.Width));
+                AddStr (new (' ', Viewport.Width));
             }
         }
 

+ 3 - 2
Terminal.sln

@@ -1,7 +1,7 @@
 
 Microsoft Visual Studio Solution File, Format Version 12.00
 # Visual Studio Version 18
-VisualStudioVersion = 18.0.11018.127 d18.0
+VisualStudioVersion = 18.0.11018.127
 MinimumVisualStudioVersion = 10.0.40219.1
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Terminal.Gui", "Terminal.Gui\Terminal.Gui.csproj", "{00F366F8-DEE4-482C-B9FD-6DB0200B79E5}"
 EndProject
@@ -32,7 +32,7 @@ EndProject
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GitHub", "GitHub", "{13BB2C46-B324-4B9C-92EB-CE6184D4736E}"
 	ProjectSection(SolutionItems) = preProject
 		.github\workflows\api-docs.yml = .github\workflows\api-docs.yml
-		.github\workflows\build-release.yml = .github\workflows\build-release.yml
+		.github\workflows\build.yml = .github\workflows\build.yml
 		.github\workflows\check-duplicates.yml = .github\workflows\check-duplicates.yml
 		copilot-instructions.md = copilot-instructions.md
 		GitVersion.yml = GitVersion.yml
@@ -47,6 +47,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{C7A51224-5
 		.github\CODEOWNERS = .github\CODEOWNERS
 		CODE_OF_CONDUCT.md = CODE_OF_CONDUCT.md
 		CONTRIBUTING.md = CONTRIBUTING.md
+		.github\copilot-instructions.md = .github\copilot-instructions.md
 		README.md = README.md
 	EndProjectSection
 EndProject

+ 2 - 1
Terminal.sln.ToDo.DotSettings

@@ -1,4 +1,5 @@
-<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
+	<s:Boolean x:Key="/Default/CodeEditing/StackTraceExplorer/AutoOpen/@EntryValue">False</s:Boolean>
 	<s:String x:Key="/Default/PatternsAndTemplates/Todo/TodoPatterns/=4386F01B791C56499C7EA059B55FFB54/Name/@EntryValue">Bug</s:String>
 	<s:String x:Key="/Default/PatternsAndTemplates/Todo/TodoPatterns/=4386F01B791C56499C7EA059B55FFB54/Pattern/@EntryValue">(?&lt;=\W|^)(?&lt;TAG&gt;BUGBUG|BUG|PROBLEM): *(?&lt;Message&gt;[\S].*)$</s:String>
 	<s:String x:Key="/Default/PatternsAndTemplates/Todo/TodoPatterns/=4386F01B791C56499C7EA059B55FFB54/TodoIconStyle/@EntryValue">Warning</s:String>

+ 8 - 3
Tests/StressTests/ApplicationStressTests.cs

@@ -17,9 +17,7 @@ public class ApplicationStressTests : TestsAllViews
 
     private const int NUM_PASSES = 50;
     private const int NUM_INCREMENTS = 500;
-    
-    // Use longer timeout when running under debugger to account for slower iterations
-    private static readonly int POLL_MS = System.Diagnostics.Debugger.IsAttached ? 500 : 100;
+    private const int POLL_MS = 100;
 
     /// <summary>
     /// Stress test for Application.Invoke to verify that invocations from background threads
@@ -79,6 +77,13 @@ public class ApplicationStressTests : TestsAllViews
                 while (_tbCounter != (j + 1) * numIncrements) // Wait for tbCounter to reach expected value
                 {
                     int tbNow = _tbCounter;
+
+                    // Wait for Application.Top to be running to ensure timed events can be processed
+                    while (Application.Top is null || Application.Top is { Running: false })
+                    {
+                        Thread.Sleep (1);
+                    }
+
                     _wakeUp.Wait (pollMs);
 
                     if (_tbCounter != tbNow)

+ 2 - 20
Tests/UnitTests/Application/ApplicationTests.cs

@@ -159,7 +159,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -316,7 +315,6 @@ public class ApplicationTests
             // Don't check Application.Force16Colors
             //Assert.False (Application.Force16Colors);
             Assert.Null (Application.Driver);
-            Assert.Null (Application.MainLoop);
             Assert.False (Application.EndAfterFirstIteration);
 
             // Commented out because if CM changed the defaults, those changes should
@@ -472,7 +470,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -486,7 +483,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -522,14 +518,12 @@ public class ApplicationTests
         Application.End (runstate);
 
         Assert.NotNull (Application.Top);
-        Assert.NotNull (Application.MainLoop);
         Assert.NotNull (Application.Driver);
 
         topLevel.Dispose ();
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -584,13 +578,12 @@ public class ApplicationTests
     [AutoInitShutdown]
     public void Invoke_Adds_Idle ()
     {
-        var top = new Toplevel ();
+        Toplevel top = new ();
         RunState rs = Application.Begin (top);
-        var firstIteration = false;
 
         var actionCalled = 0;
         Application.Invoke (() => { actionCalled++; });
-        Application.RunIteration (ref rs, firstIteration);
+        ApplicationImpl.Instance.TimedEvents!.RunTimers ();
         Assert.Equal (1, actionCalled);
         top.Dispose ();
         Application.Shutdown ();
@@ -677,7 +670,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -701,7 +693,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -735,7 +726,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -753,7 +743,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -775,7 +764,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
 
         a.After (null);
@@ -794,7 +782,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -813,7 +800,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -830,7 +816,6 @@ public class ApplicationTests
         Application.Shutdown ();
 
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -850,7 +835,6 @@ public class ApplicationTests
         top.Dispose ();
         Application.Shutdown ();
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -873,7 +857,6 @@ public class ApplicationTests
         top.Dispose ();
         Application.Shutdown ();
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 
@@ -893,7 +876,6 @@ public class ApplicationTests
         top.Dispose ();
         Application.Shutdown ();
         Assert.Null (Application.Top);
-        Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 

+ 0 - 842
Tests/UnitTests/Application/MainLoopTests.cs

@@ -1,842 +0,0 @@
-using System.Diagnostics;
-
-// Alias Console to MockConsole so we don't accidentally use Console
-
-namespace UnitTests.ApplicationTests;
-
-/// <summary>Tests MainLoop using the FakeMainLoop.</summary>
-public class MainLoopTests
-{
-    private static Button btn;
-    private static string cancel;
-    private static string clickMe;
-    private static int four;
-    private static int one;
-    private static string pewPew;
-    private static bool taskCompleted;
-
-    // TODO: EventsPending tests
-    // - wait = true
-    // - wait = false
-
-    // TODO: Add IMainLoop tests
-    private static int three;
-    private static int total;
-    private static int two;
-    private static int zero;
-
-    // See Also ConsoleDRivers/MainLoopDriverTests.cs for tests of the MainLoopDriver
-
-    // Idle Handler tests
-    [Fact]
-    public void AddTimeout_Adds_And_Removes ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        Func<bool> fnTrue = () => true;
-        Func<bool> fnFalse = () => false;
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fnTrue);
-        var b = ml.TimedEvents.Add (TimeSpan.Zero, fnFalse);
-
-        Assert.Equal (2, ml.TimedEvents.Timeouts.Count);
-        Assert.Equal (fnTrue, ml.TimedEvents.Timeouts.ElementAt (0).Value.Callback);
-        Assert.NotEqual (fnFalse, ml.TimedEvents.Timeouts.ElementAt (0).Value.Callback);
-
-        Assert.True (ml.TimedEvents.Remove (a));
-        Assert.Single (ml.TimedEvents.Timeouts);
-
-        // BUGBUG: This doesn't throw or indicate an error. Ideally RemoveIdle would either 
-        // throw an exception in this case, or return an error.
-        // No. Only need to return a boolean.
-        Assert.False (ml.TimedEvents.Remove (a));
-
-        Assert.True (ml.TimedEvents.Remove (b));
-
-        // BUGBUG: This doesn't throw an exception or indicate an error. Ideally RemoveIdle would either 
-        // throw an exception in this case, or return an error.
-        // No. Only need to return a boolean.
-        Assert.False (ml.TimedEvents.Remove(b));
-    }
-
-    [Fact]
-    public void AddTimeout_Function_GetsCalled_OnIteration ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            return true;
-                        };
-
-        ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        ml.RunIteration ();
-        Assert.Equal (1, functionCalled);
-    }
-
-    [Fact]
-    public void AddTimeout_Twice_Returns_False_Called_Twice ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn1 = () =>
-                         {
-                             functionCalled++;
-
-                             return false;
-                         };
-
-        // Force stop if 10 iterations
-        var stopCount = 0;
-
-        Func<bool> fnStop = () =>
-                            {
-                                stopCount++;
-
-                                if (stopCount == 10)
-                                {
-                                    ml.Stop ();
-                                }
-
-                                return true;
-                            };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
-        var b = ml.TimedEvents.Add (TimeSpan.Zero, fn1);
-        ml.Run ();
-
-        Assert.True (ml.TimedEvents.Remove(a));
-        Assert.False (ml.TimedEvents.Remove (a));
-
-        // Cannot remove b because it returned false i.e. auto removes itself
-        Assert.False (ml.TimedEvents.Remove (b));
-
-        Assert.Equal (1, functionCalled);
-    }
-
-    [Fact]
-    public void AddTimeoutTwice_Function_CalledTwice ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            return true;
-                        };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        var b = ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        ml.RunIteration ();
-        Assert.Equal (2, functionCalled);
-        Assert.Equal (2, ml.TimedEvents.Timeouts.Count);
-
-        functionCalled = 0;
-        Assert.True (ml.TimedEvents.Remove (a));
-        Assert.Single (ml.TimedEvents.Timeouts);
-        ml.RunIteration ();
-        Assert.Equal (1, functionCalled);
-
-        functionCalled = 0;
-        Assert.True (ml.TimedEvents.Remove (b));
-        Assert.Empty (ml.TimedEvents.Timeouts);
-        ml.RunIteration ();
-        Assert.Equal (0, functionCalled);
-        Assert.False (ml.TimedEvents.Remove (b));
-    }
-
-    [Fact]
-    public void AddThenRemoveIdle_Function_NotCalled ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            return true;
-                        };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        Assert.True (ml.TimedEvents.Remove (a));
-        ml.RunIteration ();
-        Assert.Equal (0, functionCalled);
-    }
-
-    // Timeout Handler Tests
-    [Fact]
-    public void AddTimer_Adds_Removes_NoFaults ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        var ms = 100;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback);
-
-        Assert.True (ml.TimedEvents.Remove (token));
-
-        // BUGBUG: This should probably fault?
-        // Must return a boolean.
-        Assert.False (ml.TimedEvents.Remove (token));
-    }
-
-    [Fact]
-    public async Task AddTimer_Duplicate_Keys_Not_Allowed ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        const int ms = 100;
-        object token1 = null, token2 = null;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  if (callbackCount == 2)
-                                  {
-                                      ml.Stop ();
-                                  }
-
-                                  return true;
-                              };
-
-        var task1 = new Task (() => token1 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback));
-        var task2 = new Task (() => token2 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback));
-        Assert.Null (token1);
-        Assert.Null (token2);
-        task1.Start ();
-        task2.Start ();
-        ml.Run ();
-        Assert.NotNull (token1);
-        Assert.NotNull (token2);
-        await Task.WhenAll (task1, task2);
-        Assert.True (ml.TimedEvents.Remove (token1));
-        Assert.True (ml.TimedEvents.Remove (token2));
-
-        Assert.Equal (2, callbackCount);
-    }
-
-    // Timeout Handler Tests
-    [Fact]
-    public void AddTimer_EventFired ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        var ms = 100;
-
-        // Use Stopwatch ticks since TimedEvents now uses Stopwatch.GetTimestamp internally
-        long originTicks = Stopwatch.GetTimestamp () * TimeSpan.TicksPerSecond / Stopwatch.Frequency;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  return true;
-                              };
-
-        object sender = null;
-        TimeoutEventArgs args = null;
-
-        ml.TimedEvents.Added += (s, e) =>
-                                       {
-                                           sender = s;
-                                           args = e;
-                                       };
-
-        object token = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback);
-
-        Assert.Same (ml.TimedEvents, sender);
-        Assert.NotNull (args.Timeout);
-        Assert.True (args.Ticks - originTicks >= 100 * TimeSpan.TicksPerMillisecond);
-    }
-
-    [Fact]
-    public void AddTimer_In_Parallel_Wont_Throw ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        const int ms = 100;
-        object token1 = null, token2 = null;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  if (callbackCount == 2)
-                                  {
-                                      ml.Stop ();
-                                  }
-
-                                  return true;
-                              };
-
-        Parallel.Invoke (
-                         () => token1 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback),
-                         () => token2 = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback)
-                        );
-        ml.Run ();
-        Assert.NotNull (token1);
-        Assert.NotNull (token2);
-        Assert.True (ml.TimedEvents.Remove (token1));
-        Assert.True (ml.TimedEvents.Remove (token2));
-
-        Assert.Equal (2, callbackCount);
-    }
-
-    [Fact]
-    public void AddTimer_Remove_NotCalled ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-
-        // Force stop if 10 iterations
-        var stopCount = 0;
-
-        Func<bool> fnStop = () =>
-                            {
-                                stopCount++;
-
-                                if (stopCount == 10)
-                                {
-                                    ml.Stop ();
-                                }
-
-                                return true;
-                            };
-        ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (ms, callback);
-        Assert.True (ml.TimedEvents.Remove (token));
-        ml.Run ();
-        Assert.Equal (0, callbackCount);
-    }
-
-    [Fact]
-    public void AddTimer_ReturnFalse_StopsBeingCalled ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-
-        // Force stop if 10 iterations
-        var stopCount = 0;
-
-        Func<bool> fnStop = () =>
-                            {
-                                Thread.Sleep (10); // Sleep to enable timer to fire
-                                stopCount++;
-
-                                if (stopCount == 10)
-                                {
-                                    ml.Stop ();
-                                }
-
-                                return true;
-                            };
-        ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  return false;
-                              };
-
-        object token = ml.TimedEvents.Add (ms, callback);
-        ml.Run ();
-        Assert.Equal (1, callbackCount);
-        Assert.Equal (10, stopCount);
-        Assert.False (ml.TimedEvents.Remove (token));
-    }
-
-    [Fact]
-    public void AddTimer_Run_Called ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        var ms = 100;
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-                                  ml.Stop ();
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (TimeSpan.FromMilliseconds (ms), callback);
-        ml.Run ();
-        Assert.True (ml.TimedEvents.Remove (token));
-
-        Assert.Equal (1, callbackCount);
-    }
-
-    [Fact]
-    public void AddTimer_Run_CalledAtApproximatelyRightTime ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-        var watch = new Stopwatch ();
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  watch.Stop ();
-                                  callbackCount++;
-                                  ml.Stop ();
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (ms, callback);
-        watch.Start ();
-        ml.Run ();
-
-        // +/- 100ms should be good enuf
-        // https://github.com/xunit/assert.xunit/pull/25
-        Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
-
-        Assert.True (ml.TimedEvents.Remove (token));
-        Assert.Equal (1, callbackCount);
-    }
-
-    [Fact]
-    public void AddTimer_Run_CalledTwiceApproximatelyRightTime ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-        var watch = new Stopwatch ();
-
-        var callbackCount = 0;
-
-        Func<bool> callback = () =>
-                              {
-                                  callbackCount++;
-
-                                  if (callbackCount == 2)
-                                  {
-                                      watch.Stop ();
-                                      ml.Stop ();
-                                  }
-
-                                  return true;
-                              };
-
-        object token = ml.TimedEvents.Add (ms, callback);
-        watch.Start ();
-        ml.Run ();
-
-        // +/- 100ms should be good enuf
-        // https://github.com/xunit/assert.xunit/pull/25
-        Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
-
-        Assert.True (ml.TimedEvents.Remove (token));
-        Assert.Equal (2, callbackCount);
-    }
-
-    [Fact]
-    public void CheckTimersAndIdleHandlers_NoTimers_Returns_False ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        bool retVal = ml.TimedEvents.CheckTimers(out int waitTimeOut);
-        Assert.False (retVal);
-        Assert.Equal (-1, waitTimeOut);
-    }
-
-    [Fact]
-    public void CheckTimersAndIdleHandlers_NoTimers_WithIdle_Returns_True ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        Func<bool> fnTrue = () => true;
-
-        ml.TimedEvents.Add (TimeSpan.Zero, fnTrue);
-        bool retVal = ml.TimedEvents.CheckTimers(out int waitTimeOut);
-        Assert.True (retVal);
-        Assert.Equal (0, waitTimeOut);
-    }
-
-    [Fact]
-    public void CheckTimersAndIdleHandlers_With1Timer_Returns_Timer ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-
-        static bool Callback () { return false; }
-
-        _ = ml.TimedEvents.Add (ms, Callback);
-        bool retVal = ml.TimedEvents.CheckTimers (out int waitTimeOut);
-
-        Assert.True (retVal);
-
-        // It should take < 10ms to execute to here
-        Assert.True (ms.TotalMilliseconds <= waitTimeOut + 10);
-    }
-
-    [Fact]
-    public void CheckTimersAndIdleHandlers_With2Timers_Returns_Timer ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-        TimeSpan ms = TimeSpan.FromMilliseconds (50);
-
-        static bool Callback () { return false; }
-
-        _ = ml.TimedEvents.Add (ms, Callback);
-        _ = ml.TimedEvents.Add (ms, Callback);
-        bool retVal = ml.TimedEvents.CheckTimers (out int waitTimeOut);
-
-        Assert.True (retVal);
-
-        // It should take < 10ms to execute to here
-        Assert.True (ms.TotalMilliseconds <= waitTimeOut + 10);
-    }
-
-    [Fact]
-    public void False_Idle_Stops_It_Being_Called_Again ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn1 = () =>
-                         {
-                             functionCalled++;
-
-                             if (functionCalled == 10)
-                             {
-                                 return false;
-                             }
-
-                             return true;
-                         };
-
-        // Force stop if 20 iterations
-        var stopCount = 0;
-
-        Func<bool> fnStop = () =>
-                            {
-                                stopCount++;
-
-                                if (stopCount == 20)
-                                {
-                                    ml.Stop ();
-                                }
-
-                                return true;
-                            };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fnStop);
-        var b = ml.TimedEvents.Add (TimeSpan.Zero, fn1);
-        ml.Run ();
-        Assert.True (ml.TimedEvents.Remove (a));
-        Assert.False (ml.TimedEvents.Remove (a));
-
-        Assert.Equal (10, functionCalled);
-        Assert.Equal (20, stopCount);
-    }
-
-    [Fact]
-    public void Internal_Tests ()
-    {
-        var testMainloop = new TestMainloop ();
-        var mainloop = new MainLoop (testMainloop);
-        Assert.Empty (mainloop.TimedEvents.Timeouts);
-
-        Assert.NotNull (
-                        new Terminal.Gui.App.Timeout { Span = new (), Callback = () => true }
-                       );
-    }
-
-    [Theory]
-    [MemberData (nameof (TestAddTimeout))]
-    public void Mainloop_Invoke_Or_AddTimeout_Can_Be_Used_For_Events_Or_Actions (
-        Action action,
-        string pclickMe,
-        string pcancel,
-        string ppewPew,
-        int pzero,
-        int pone,
-        int ptwo,
-        int pthree,
-        int pfour
-    )
-    {
-        // TODO: Expand this test to test all drivers
-        Application.Init (null, "fakedriver");
-
-        total = 0;
-        btn = null;
-        clickMe = pclickMe;
-        cancel = pcancel;
-        pewPew = ppewPew;
-        zero = pzero;
-        one = pone;
-        two = ptwo;
-        three = pthree;
-        four = pfour;
-        taskCompleted = false;
-
-        var btnLaunch = new Button { Text = "Open Window" };
-
-        btnLaunch.Accepting += (s, e) => action ();
-
-        var top = new Toplevel ();
-        top.Add (btnLaunch);
-
-        int iterations = -1;
-
-        Application.Iteration += (s, a) =>
-                                 {
-                                     iterations++;
-
-                                     if (iterations == 0)
-                                     {
-                                         Assert.Null (btn);
-                                         Assert.Equal (zero, total);
-                                         Assert.False (btnLaunch.NewKeyDownEvent (Key.Space));
-
-                                         if (btn == null)
-                                         {
-                                             Assert.Null (btn);
-                                             Assert.Equal (zero, total);
-                                         }
-                                         else
-                                         {
-                                             Assert.Equal (clickMe, btn.Text);
-                                             Assert.Equal (four, total);
-                                         }
-                                     }
-                                     else if (iterations == 1)
-                                     {
-                                         Assert.Equal (clickMe, btn.Text);
-                                         Assert.Equal (zero, total);
-                                         Assert.False (btn.NewKeyDownEvent (Key.Space));
-                                         Assert.Equal (cancel, btn.Text);
-                                         Assert.Equal (one, total);
-                                     }
-                                     else if (taskCompleted)
-                                     {
-                                         Application.RequestStop ();
-                                     }
-                                 };
-
-        Application.Run (top);
-        top.Dispose ();
-
-        Assert.True (taskCompleted);
-        Assert.Equal (clickMe, btn.Text);
-        Assert.Equal (four, total);
-
-        Application.Shutdown ();
-    }
-    
-    [Fact]
-    public void RemoveIdle_Function_NotCalled ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            return true;
-                        };
-
-        Assert.False (ml.TimedEvents.Remove ("flibble"));
-        ml.RunIteration ();
-        Assert.Equal (0, functionCalled);
-    }
-
-    [Fact]
-    public void Run_Runs_Idle_Stop_Stops_Idle ()
-    {
-        var ml = new MainLoop (new FakeMainLoop ());
-
-        var functionCalled = 0;
-
-        Func<bool> fn = () =>
-                        {
-                            functionCalled++;
-
-                            if (functionCalled == 10)
-                            {
-                                ml.Stop ();
-                            }
-
-                            return true;
-                        };
-
-        var a = ml.TimedEvents.Add (TimeSpan.Zero, fn);
-        ml.Run ();
-        Assert.True (ml.TimedEvents.Remove (a));
-
-        Assert.Equal (10, functionCalled);
-    }
-
-    public static IEnumerable<object []> TestAddTimeout
-    {
-        get
-        {
-            // Goes fine
-            Action a1 = StartWindow;
-
-            yield return new object [] { a1, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
-
-            // Also goes fine
-            Action a2 = () => Application.Invoke (StartWindow);
-
-            yield return new object [] { a2, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
-        }
-    }
-
-    private static async void RunAsyncTest (object sender, EventArgs e)
-    {
-        Assert.Equal (clickMe, btn.Text);
-        Assert.Equal (zero, total);
-
-        btn.Text = "Cancel";
-        Interlocked.Increment (ref total);
-        btn.SetNeedsDraw ();
-
-        await Task.Run (
-                        () =>
-                        {
-                            try
-                            {
-                                Assert.Equal (cancel, btn.Text);
-                                Assert.Equal (one, total);
-
-                                RunSql ();
-                            }
-                            finally
-                            {
-                                SetReadyToRun ();
-                            }
-                        }
-                       )
-                  .ContinueWith (
-                                 async (s, e) =>
-                                 {
-                                     await Task.Delay (1000);
-                                     Assert.Equal (clickMe, btn.Text);
-                                     Assert.Equal (three, total);
-
-                                     Interlocked.Increment (ref total);
-
-                                     Assert.Equal (clickMe, btn.Text);
-                                     Assert.Equal (four, total);
-
-                                     taskCompleted = true;
-                                 },
-                                 TaskScheduler.FromCurrentSynchronizationContext ()
-                                );
-    }
-
-    private static void RunSql ()
-    {
-        Thread.Sleep (100);
-        Assert.Equal (cancel, btn.Text);
-        Assert.Equal (one, total);
-
-        Application.Invoke (
-                            () =>
-                            {
-                                btn.Text = "Pew Pew";
-                                Interlocked.Increment (ref total);
-                                btn.SetNeedsDraw ();
-                            }
-                           );
-    }
-
-    private static void SetReadyToRun ()
-    {
-        Thread.Sleep (100);
-        Assert.Equal (pewPew, btn.Text);
-        Assert.Equal (two, total);
-
-        Application.Invoke (
-                            () =>
-                            {
-                                btn.Text = "Click Me";
-                                Interlocked.Increment (ref total);
-                                btn.SetNeedsDraw ();
-                            }
-                           );
-    }
-
-    private static void StartWindow ()
-    {
-        var startWindow = new Window { Modal = true };
-
-        btn = new() { Text = "Click Me" };
-
-        btn.Accepting += RunAsyncTest;
-
-        var totalbtn = new Button { X = Pos.Right (btn), Text = "total" };
-
-        totalbtn.Accepting += (s, e) => { MessageBox.Query ("Count", $"Count is {total}", "Ok"); };
-
-        startWindow.Add (btn);
-        startWindow.Add (totalbtn);
-
-        Application.Run (startWindow);
-
-        Assert.Equal (clickMe, btn.Text);
-        Assert.Equal (four, total);
-
-        Application.RequestStop ();
-    }
-
-    private class MillisecondTolerance : IEqualityComparer<TimeSpan>
-    {
-        public MillisecondTolerance (int tolerance) { _tolerance = tolerance; }
-        private readonly int _tolerance;
-        public bool Equals (TimeSpan x, TimeSpan y) { return Math.Abs (x.Milliseconds - y.Milliseconds) <= _tolerance; }
-        public int GetHashCode (TimeSpan obj) { return obj.GetHashCode (); }
-    }
-
-    private class TestMainloop : IMainLoopDriver
-    {
-        private MainLoop mainLoop;
-        public bool EventsPending () { throw new NotImplementedException (); }
-        public void Iteration () { throw new NotImplementedException (); }
-        public void TearDown () { throw new NotImplementedException (); }
-        public void Setup (MainLoop mainLoop) { this.mainLoop = mainLoop; }
-        public void Wakeup () { throw new NotImplementedException (); }
-    }
-}

+ 0 - 1
Tests/UnitTests/Application/RunStateTests.cs

@@ -45,7 +45,6 @@ public class RunStateTests
 #endif
 
         Assert.Null (Application.Top);
-    //    Assert.Null (Application.MainLoop);
         Assert.Null (Application.Driver);
     }
 

+ 2 - 2
Tests/UnitTests/ConsoleDrivers/ConsoleDriverTests.cs

@@ -50,8 +50,8 @@ public class ConsoleDriverTests
     public void Init_Inits (Type driverType)
     {
         var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        MainLoop ml = driver.Init ();
-        Assert.NotNull (ml);
+        driver.Init ();
+        // Note: MainLoop is no longer returned from Init() as part of legacy MainLoop removal
         Assert.NotNull (driver.Clipboard);
         Console.ForegroundColor = ConsoleColor.Red;
         Assert.Equal (ConsoleColor.Red, Console.ForegroundColor);

+ 9 - 13
Tests/UnitTests/Dialogs/WizardTests.cs

@@ -20,8 +20,8 @@ public class WizardTests ()
     public void Finish_Button_Closes ()
     {
         // https://github.com/gui-cs/Terminal.Gui/issues/1833
-        var wizard = new Wizard ();
-        var step1 = new WizardStep { Title = "step1" };
+        Wizard wizard = new ();
+        WizardStep step1 = new () { Title = "step1" };
         wizard.AddStep (step1);
 
         var finishedFired = false;
@@ -31,11 +31,10 @@ public class WizardTests ()
         wizard.Closed += (s, e) => { closedFired = true; };
 
         RunState runstate = Application.Begin (wizard);
-        var firstIteration = true;
-        Application.RunIteration (ref runstate, firstIteration);
+        AutoInitShutdownAttribute.RunIteration ();
 
         wizard.NextFinishButton.InvokeCommand (Command.Accept);
-        Application.RunIteration (ref runstate, firstIteration);
+        AutoInitShutdownAttribute.RunIteration ();
         Application.End (runstate);
         Assert.True (finishedFired);
         Assert.True (closedFired);
@@ -44,10 +43,9 @@ public class WizardTests ()
 
         // Same test, but with two steps
         wizard = new ();
-        firstIteration = false;
         step1 = new() { Title = "step1" };
         wizard.AddStep (step1);
-        var step2 = new WizardStep { Title = "step2" };
+        WizardStep step2 = new () { Title = "step2" };
         wizard.AddStep (step2);
 
         finishedFired = false;
@@ -57,7 +55,7 @@ public class WizardTests ()
         wizard.Closed += (s, e) => { closedFired = true; };
 
         runstate = Application.Begin (wizard);
-        Application.RunIteration (ref runstate, firstIteration);
+        AutoInitShutdownAttribute.RunIteration ();
 
         Assert.Equal (step1.Title, wizard.CurrentStep.Title);
         wizard.NextFinishButton.InvokeCommand (Command.Accept);
@@ -77,7 +75,6 @@ public class WizardTests ()
 
         // Same test, but with two steps but the 1st one disabled
         wizard = new ();
-        firstIteration = false;
         step1 = new() { Title = "step1" };
         wizard.AddStep (step1);
         step2 = new() { Title = "step2" };
@@ -91,7 +88,7 @@ public class WizardTests ()
         wizard.Closed += (s, e) => { closedFired = true; };
 
         runstate = Application.Begin (wizard);
-        Application.RunIteration (ref runstate, firstIteration);
+        AutoInitShutdownAttribute.RunIteration ();
 
         Assert.Equal (step2.Title, wizard.CurrentStep.Title);
         Assert.Equal (wizard.GetLastStep ().Title, wizard.CurrentStep.Title);
@@ -458,13 +455,12 @@ public class WizardTests ()
                 Glyphs.LRCornerDbl
             }";
 
-        var wizard = new Wizard { Title = title, Width = width, Height = height };
+        Wizard wizard = new () { Title = title, Width = width, Height = height };
         wizard.AddStep (new() { Title = stepTitle });
 
         //wizard.LayoutSubViews ();
-        var firstIteration = false;
         RunState runstate = Application.Begin (wizard);
-        Application.RunIteration (ref runstate, firstIteration);
+        AutoInitShutdownAttribute.RunIteration ();
 
         // TODO: Disabled until Dim.Auto is used in Dialog
         //DriverAsserts.AssertDriverContentsWithFrameAre (

+ 2 - 2
Tests/UnitTests/View/Adornment/BorderTests.cs

@@ -222,7 +222,7 @@ public class BorderTests (ITestOutputHelper output)
     [InlineData (10)]
     public void Border_With_Title_Border_Double_Thickness_Top_Three_Size_Width (int width)
     {
-        var win = new Window
+        Window win = new ()
         {
             Title = "1234", Width = Dim.Fill (), Height = Dim.Fill (), BorderStyle = LineStyle.Double
         };
@@ -231,7 +231,7 @@ public class BorderTests (ITestOutputHelper output)
         RunState rs = Application.Begin (win);
 
         AutoInitShutdownAttribute.FakeResize(new Size(width, 4));
-        Application.RunIteration (ref rs, false);
+        AutoInitShutdownAttribute.RunIteration ();
         var expected = string.Empty;
 
         switch (width)

+ 0 - 1
Tests/UnitTests/View/Draw/AllViewsDrawTests.cs

@@ -12,7 +12,6 @@ public class AllViewsDrawTests (ITestOutputHelper output) : TestsAllViews
     {
         Application.ResetState (true);
         // Required for spinner view that wants to register timeouts
-        Application.MainLoop = new MainLoop (new FakeMainLoop (Application.Driver));
 
         var view = (View)CreateInstanceIfNotGeneric (viewType);
 

+ 3 - 3
Tests/UnitTests/View/Draw/ClearViewportTests.cs

@@ -321,7 +321,7 @@ public class ClearViewportTests (ITestOutputHelper output)
     {
         ConfigurationManager.Enable (ConfigLocations.LibraryResources);
 
-        var root = new View { Width = 20, Height = 10 };
+        View root = new () { Width = 20, Height = 10 };
 
         string text = new ('c', 100);
 
@@ -335,10 +335,10 @@ public class ClearViewportTests (ITestOutputHelper output)
 
         root.Add (v);
 
-        var top = new Toplevel ();
+        Toplevel top = new ();
         top.Add (root);
         RunState runState = Application.Begin (top);
-        Application.RunIteration (ref runState);
+        AutoInitShutdownAttribute.RunIteration ();
 
         if (label)
         {

+ 0 - 1
Tests/UnitTests/View/Layout/LayoutTests.cs

@@ -12,7 +12,6 @@ public class LayoutTests (ITestOutputHelper output) : TestsAllViews
     {
 
         // Required for spinner view that wants to register timeouts
-        Application.MainLoop = new MainLoop (new FakeMainLoop (Application.Driver));
 
         var view = (View)CreateInstanceIfNotGeneric (viewType);
 

+ 0 - 1
Tests/UnitTests/Views/AllViewsTests.cs

@@ -14,7 +14,6 @@ public class AllViewsTests (ITestOutputHelper output) : TestsAllViews
     public void AllViews_Center_Properly (Type viewType)
     {
         // Required for spinner view that wants to register timeouts
-        Application.MainLoop = new (new FakeMainLoop (Application.Driver));
 
         var view = CreateInstanceIfNotGeneric (viewType);
 

+ 6 - 6
Tests/UnitTests/Views/LabelTests.cs

@@ -91,20 +91,20 @@ public class LabelTests (ITestOutputHelper output)
     [AutoInitShutdown]
     public void Label_Draw_Fill_Remaining ()
     {
-        var tfSize = new Size (80, 1);
+        Size tfSize = new (80, 1);
 
-        var label = new Label { Text = "This label needs to be cleared before rewritten.", Width = tfSize.Width, Height = tfSize.Height };
+        Label label = new () { Text = "This label needs to be cleared before rewritten.", Width = tfSize.Width, Height = tfSize.Height };
 
-        var tf1 = new TextFormatter { Direction = TextDirection.LeftRight_TopBottom, ConstrainToSize = tfSize };
+        TextFormatter tf1 = new () { Direction = TextDirection.LeftRight_TopBottom, ConstrainToSize = tfSize };
         tf1.Text = "This TextFormatter (tf1) without fill will not be cleared on rewritten.";
 
-        var tf2 = new TextFormatter { Direction = TextDirection.LeftRight_TopBottom, ConstrainToSize = tfSize, FillRemaining = true };
+        TextFormatter tf2 = new () { Direction = TextDirection.LeftRight_TopBottom, ConstrainToSize = tfSize, FillRemaining = true };
         tf2.Text = "This TextFormatter (tf2) with fill will be cleared on rewritten.";
 
-        var top = new Toplevel ();
+        Toplevel top = new ();
         top.Add (label);
         RunState runState = Application.Begin (top);
-        Application.RunIteration (ref runState);
+        AutoInitShutdownAttribute.RunIteration ();
 
         Assert.False (label.TextFormatter.FillRemaining);
         Assert.False (tf1.FillRemaining);

+ 8 - 11
Tests/UnitTests/Views/Menuv1/MenuBarv1Tests.cs

@@ -467,7 +467,7 @@ public class MenuBarv1Tests (ITestOutputHelper output)
         Button.DefaultShadow = ShadowStyle.None;
 
         Toplevel top = new ();
-        var win = new Window ();
+        Window win = new ();
         top.Add (win);
         RunState rsTop = Application.Begin (top);
         AutoInitShutdownAttribute.FakeResize(new Size(40, 15))    ;
@@ -503,8 +503,8 @@ public class MenuBarv1Tests (ITestOutputHelper output)
             "Save As",
             "Delete"
         };
-        var dialog = new Dialog { X = 2, Y = 2, Width = 15, Height = 4 };
-        var menu = new MenuBar { X = Pos.Center (), Width = 10 };
+        Dialog dialog = new () { X = 2, Y = 2, Width = 15, Height = 4 };
+        MenuBar menu = new () { X = Pos.Center (), Width = 10 };
 
         menu.Menus = new MenuBarItem []
         {
@@ -572,7 +572,7 @@ public class MenuBarv1Tests (ITestOutputHelper output)
         }
 
         RunState rsDialog = Application.Begin (dialog);
-        Application.RunIteration (ref rsDialog);
+        AutoInitShutdownAttribute.RunIteration ();
 
         Assert.Equal (new (2, 2, 15, 4), dialog.Frame);
 
@@ -598,7 +598,7 @@ public class MenuBarv1Tests (ITestOutputHelper output)
 
         Assert.Equal ("File", menu.Menus [0].Title);
         menu.OpenMenu ();
-        Application.RunIteration (ref rsDialog);
+        AutoInitShutdownAttribute.RunIteration ();
 
         DriverAssert.AssertDriverContentsWithFrameAre (
                                                       @"
@@ -623,9 +623,7 @@ public class MenuBarv1Tests (ITestOutputHelper output)
         Application.RaiseMouseEvent (new () { ScreenPosition = new (20, 5), Flags = MouseFlags.Button1Clicked });
 
         // Need to fool MainLoop into thinking it's running
-        Application.MainLoop.Running = true;
-        bool firstIteration = true;
-        Application.RunIteration (ref rsDialog, firstIteration);
+        AutoInitShutdownAttribute.RunIteration ();
         Assert.Equal (items [0], menu.Menus [0].Title);
 
         DriverAssert.AssertDriverContentsWithFrameAre (
@@ -654,13 +652,13 @@ public class MenuBarv1Tests (ITestOutputHelper output)
 
             Application.RaiseMouseEvent (new () { ScreenPosition = new (20, 5 + i), Flags = MouseFlags.Button1Clicked });
 
-            Application.RunIteration (ref rsDialog);
+            AutoInitShutdownAttribute.RunIteration ();
             Assert.Equal (items [i], menu.Menus [0].Title);
         }
 
         AutoInitShutdownAttribute.FakeResize(new Size(20, 15));
         menu.OpenMenu ();
-        Application.RunIteration (ref rsDialog);
+        AutoInitShutdownAttribute.RunIteration ();
 
         DriverAssert.AssertDriverContentsWithFrameAre (
                                                       @"
@@ -816,7 +814,6 @@ public class MenuBarv1Tests (ITestOutputHelper output)
         Application.RaiseMouseEvent (new () { ScreenPosition = new (20, 5), Flags = MouseFlags.Button1Clicked });
 
         // Need to fool MainLoop into thinking it's running
-        Application.MainLoop.Running = true;
         AutoInitShutdownAttribute.RunIteration ();
         Assert.Equal (items [0], menu.Menus [0].Title);
 

+ 2 - 2
Tests/UnitTests/Views/TextViewTests.cs

@@ -4813,7 +4813,7 @@ This is the second line.
     public void Selected_Text_Shows ()
     {
         // Proves #3022 is fixed (TextField selected text does not show in v2)
-        var top = new Toplevel ();
+        Toplevel top = new ();
         top.Add (_textView);
         RunState rs = Application.Begin (top);
 
@@ -4833,7 +4833,7 @@ This is the second line.
 
         _textView.NewKeyDownEvent (Key.CursorRight.WithCtrl.WithShift);
 
-        Application.RunIteration (ref rs, true);
+        AutoInitShutdownAttribute.RunIteration ();
         Assert.Equal (new (4, 0), _textView.CursorPosition);
 
         //                                             TAB to jump between text fields.

+ 0 - 300
Tests/UnitTestsParallelizable/ConsoleDrivers/MainLoopDriverTests.cs

@@ -1,300 +0,0 @@
-using Xunit.Abstractions;
-
-// Alias Console to MockConsole so we don't accidentally use Console
-
-namespace UnitTests_Parallelizable.DriverTests;
-
-public class MainLoopDriverTests : UnitTests.Parallelizable.ParallelizableBase
-{
-    public MainLoopDriverTests (ITestOutputHelper output) { ConsoleDriver.RunningUnitTests = true; }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_AddTimeout_ValidIdleHandler_ReturnsToken (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-        var idleHandlerInvoked = false;
-
-        bool IdleHandler ()
-        {
-            idleHandlerInvoked = true;
-
-            return false;
-        }
-
-        var token = mainLoop.TimedEvents.Add(TimeSpan.Zero, IdleHandler);
-
-        Assert.NotNull (token);
-        Assert.False (idleHandlerInvoked); // Idle handler should not be invoked immediately
-        mainLoop.RunIteration (); // Run an iteration to process the idle handler
-        Assert.True (idleHandlerInvoked); // Idle handler should be invoked after processing
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_AddTimeout_ValidParameters_ReturnsToken (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-        var callbackInvoked = false;
-
-        object token = mainLoop.TimedEvents.Add (
-                                            TimeSpan.FromMilliseconds (100),
-                                            () =>
-                                            {
-                                                callbackInvoked = true;
-
-                                                return false;
-                                            }
-                                           );
-
-        Assert.NotNull (token);
-        mainLoop.RunIteration (); // Run an iteration to process the timeout
-        Assert.False (callbackInvoked); // Callback should not be invoked immediately
-        Thread.Sleep (200); // Wait for the timeout
-        mainLoop.RunIteration (); // Run an iteration to process the timeout
-        Assert.True (callbackInvoked); // Callback should be invoked after the timeout
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_CheckTimersAndIdleHandlers_IdleHandlersActive_ReturnsTrue (
-        Type driverType,
-        Type mainLoopDriverType
-    )
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        mainLoop.TimedEvents.Add (TimeSpan.Zero, () => false);
-        bool result = mainLoop.TimedEvents.CheckTimers (out int waitTimeout);
-
-        Assert.True (result);
-        Assert.Equal (0, waitTimeout);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_CheckTimers_NoTimersOrIdleHandlers_ReturnsFalse (
-        Type driverType,
-        Type mainLoopDriverType
-    )
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        bool result = mainLoop.TimedEvents.CheckTimers (out int waitTimeout);
-
-        Assert.False (result);
-        Assert.Equal (-1, waitTimeout);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_CheckTimersAndIdleHandlers_TimersActive_ReturnsTrue (
-        Type driverType,
-        Type mainLoopDriverType
-    )
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        mainLoop.TimedEvents.Add (TimeSpan.FromMilliseconds (100), () => false);
-        bool result = mainLoop.TimedEvents.CheckTimers(out int waitTimeout);
-
-        Assert.True (result);
-        Assert.True (waitTimeout >= 0);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_Constructs_Disposes (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        // Check default values
-        Assert.NotNull (mainLoop);
-        Assert.Equal (mainLoopDriver, mainLoop.MainLoopDriver);
-        Assert.Empty (mainLoop.TimedEvents.Timeouts);
-        Assert.False (mainLoop.Running);
-
-        // Clean up
-        mainLoop.Dispose ();
-
-        // TODO: It'd be nice if we could really verify IMainLoopDriver.TearDown was called
-        // and that it was actually cleaned up.
-        Assert.Null (mainLoop.MainLoopDriver);
-        Assert.Empty (mainLoop.TimedEvents.Timeouts);
-        Assert.False (mainLoop.Running);
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RemoveIdle_InvalidToken_ReturnsFalse (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        bool result = mainLoop.TimedEvents.Remove("flibble");
-
-        Assert.False (result);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RemoveIdle_ValidToken_ReturnsTrue (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        bool IdleHandler () { return false; }
-
-
-        var token = mainLoop.TimedEvents.Add (TimeSpan.Zero, IdleHandler);
-        bool result = mainLoop.TimedEvents.Remove (token);
-
-        Assert.True (result);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RemoveTimeout_InvalidToken_ReturnsFalse (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        bool result = mainLoop.TimedEvents.Remove (new object ());
-
-        Assert.False (result);
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RemoveTimeout_ValidToken_ReturnsTrue (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-
-        object token = mainLoop.TimedEvents.Add (TimeSpan.FromMilliseconds (100), () => false);
-        bool result = mainLoop.TimedEvents.Remove (token);
-
-        Assert.True (result);
-        mainLoop.Dispose ();
-    }
-
-    [Theory]
-    [InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    //[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    //[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    //[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-
-    //[InlineData (typeof (ANSIDriver), typeof (AnsiMainLoopDriver))]
-    public void MainLoop_RunIteration_ValidIdleHandler_CallsIdleHandler (Type driverType, Type mainLoopDriverType)
-    {
-        var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-        var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, driver);
-        var mainLoop = new MainLoop (mainLoopDriver);
-        var idleHandlerInvoked = false;
-
-        Func<bool> idleHandler = () =>
-                                 {
-                                     idleHandlerInvoked = true;
-
-                                     return false;
-                                 };
-
-        mainLoop.TimedEvents.Add (TimeSpan.Zero, idleHandler);
-        mainLoop.RunIteration (); // Run an iteration to process the idle handler
-
-        Assert.True (idleHandlerInvoked);
-        mainLoop.Dispose ();
-    }
-
-    //[Theory]
-    //[InlineData (typeof (FakeDriver), typeof (FakeMainLoop))]
-    ////[InlineData (typeof (DotNetDriver), typeof (NetMainLoop))]
-    ////[InlineData (typeof (UnixDriver), typeof (UnixMainLoop))]
-    ////[InlineData (typeof (WindowsDriver), typeof (WindowsMainLoop))]
-    //public void MainLoop_Invoke_ValidAction_RunsAction (Type driverType, Type mainLoopDriverType)
-    //{
-    //	var driver = (IConsoleDriver)Activator.CreateInstance (driverType);
-    //	var mainLoopDriver = (IMainLoopDriver)Activator.CreateInstance (mainLoopDriverType, new object [] { driver });
-    //	var mainLoop = new MainLoop (mainLoopDriver);
-    //	var actionInvoked = false;
-
-    //	mainLoop.Invoke (() => { actionInvoked = true; });
-    //	mainLoop.RunIteration (); // Run an iteration to process the action.
-
-    //	Assert.True (actionInvoked);
-    //	mainLoop.Dispose ();
-    //}
-}

+ 170 - 0
Tests/UnitTestsParallelizable/ConsoleDrivers/UrlHyperlinkerTests.cs

@@ -0,0 +1,170 @@
+#nullable enable
+using System.Text;
+using Xunit.Abstractions;
+
+namespace Terminal.Gui.DriverTests;
+
+public class Osc8UrlLinkerTests (ITestOutputHelper output)
+{
+    private readonly ITestOutputHelper _output = output;
+
+    [Theory]
+    [InlineData ("<https://example.com>", "<", "https://example.com", ">")]
+    [InlineData ("\"https://example.com\"", "\"", "https://example.com", "\"")]
+    public void WrapOsc8_Does_Not_Cross_Delimiters (string input, string prefix, string url, string suffix)
+    {
+        string actual = Wrap (input);
+        string expected = prefix + LinkWrappedWithOSCs (url) + suffix;
+        Assert.Equal (expected, actual);
+    }
+
+    [Theory]
+    [InlineData ("No url here")]
+    [InlineData ("http://")]
+    [InlineData ("://missing-scheme.com")]
+    public void WrapOsc8_Leaves_Text_Unchanged_Without_Urls (string input)
+    {
+        StringBuilder sb = new (input);
+        StringBuilder result = Osc8UrlLinker.WrapOsc8 (sb);
+
+        Assert.Same (sb, result);
+        Assert.Equal (input, result.ToString ());
+    }
+
+    [Fact]
+    public void WrapOsc8_Stops_At_Ansi_Escape_Sequence ()
+    {
+        var esc = "\x1B[38;2;173m";
+        string input = "https://example.com" + esc + "/more";
+
+        string wrapped = Wrap (input);
+        string expected = LinkWrappedWithOSCs ("https://example.com") + esc + "/more";
+        Assert.Equal (expected, wrapped);
+
+        // Verify that the hyperlinked visible content contains no ESC
+        string start = EscSeqUtils.OSC_StartHyperlink ("https://example.com");
+        string end = EscSeqUtils.OSC_EndHyperlink ();
+        int s = wrapped.IndexOf (start, StringComparison.Ordinal);
+        Assert.True (s >= 0);
+
+        int e = wrapped.IndexOf (end, s + start.Length, StringComparison.Ordinal);
+        Assert.True (e > s);
+
+        int contentStart = s + start.Length;
+        int contentLength = e - contentStart;
+        string visible = wrapped.Substring (contentStart, contentLength);
+
+        Assert.DoesNotContain ('\x1B', visible);
+        Assert.Equal ("https://example.com", visible);
+    }
+
+    [Theory]
+    [InlineData ("See https://example.com/path.", "See ", "https://example.com/path", ".")]
+    [InlineData ("See https://example.com/file.tar.gz,", "See ", "https://example.com/file.tar.gz", ",")]
+    [InlineData ("See https://example.com/path_(with)_parens)", "See ", "https://example.com/path_(with)_parens", ")")]
+    public void WrapOsc8_Trims_Trailing_Punctuation (string input, string prefix, string url, string suffix)
+    {
+        string actual = Wrap (input);
+        string expected = prefix + LinkWrappedWithOSCs (url) + suffix;
+        Assert.Equal (expected, actual);
+    }
+
+    [Theory]
+    [InlineData (
+                    "Multiple: https://a.com, https://b.com!",
+                    "Multiple: ",
+                    "https://a.com",
+                    ", ",
+                    "https://b.com",
+                    "!")]
+    [InlineData (
+                    "List https://one.com https://two.com https://three.com",
+                    "List ",
+                    "https://one.com",
+                    " ",
+                    "https://two.com",
+                    " ",
+                    "https://three.com",
+                    "")]
+    public void WrapOsc8_Wraps_Multiple_Urls (string input, params string [] segments)
+    {
+        // segments: text0, url1, text1, [url2, text2]...
+        string expected = BuildExpected (segments);
+
+        string actual = Wrap (input);
+        Assert.Equal (expected, actual);
+    }
+
+    [Theory]
+    [InlineData ("https://github.com", "https://github.com")]
+    [InlineData ("http://example.com", "http://example.com")]
+    [InlineData ("ftp://ftp.example.com/file.zip", "ftp://ftp.example.com/file.zip")]
+    [InlineData ("https://example.com:8080/path", "https://example.com:8080/path")]
+    [InlineData ("https://example.com/path#anchor", "https://example.com/path#anchor")]
+    [InlineData ("https://example.com/path?query=value&other=123", "https://example.com/path?query=value&other=123")]
+    [InlineData ("https://commons.wikimedia.org/wiki/File:Spinning_globe.gif", "https://commons.wikimedia.org/wiki/File:Spinning_globe.gif")]
+    public void WrapOsc8_Wraps_Standalone_Url (string input, string expectedUrl)
+    {
+        string actual = Wrap (input);
+        string expected = LinkWrappedWithOSCs (expectedUrl);
+        Assert.Equal (expected, actual);
+    }
+
+    [Theory]
+    [InlineData (
+                    "Visit https://github.com for more info",
+                    "Visit ",
+                    "https://github.com",
+                    " for more info")]
+    [InlineData (
+                    "Check out https://commons.wikimedia.org/wiki/File:Spinning_globe.gif!",
+                    "Check out ",
+                    "https://commons.wikimedia.org/wiki/File:Spinning_globe.gif",
+                    "!")]
+    [InlineData (
+                    "URLs: https://example.com and http://other.com",
+                    "URLs: ",
+                    "https://example.com",
+                    " and ",
+                    "http://other.com",
+                    "")]
+    public void WrapOsc8_Wraps_Urls_In_Text (string input, params string [] segments)
+    {
+        // segments: text0, url1, text1, [url2, text2]...
+        string expected = BuildExpected (segments);
+
+        string actual = Wrap (input);
+        Assert.Equal (expected, actual);
+    }
+
+    private static string BuildExpected (string [] segments)
+    {
+        // segments must be: text0, url1, text1, url2, text2, ...
+        string expected = segments.Length > 0 ? segments [0] : string.Empty;
+
+        for (var i = 1; i + 1 < segments.Length; i += 2)
+        {
+            string url = segments [i];
+            string textAfter = segments [i + 1];
+
+            expected += LinkWrappedWithOSCs (url);
+            expected += textAfter;
+        }
+
+        return expected;
+    }
+
+    private static string LinkWrappedWithOSCs (string url, string? display = null)
+    {
+        display ??= url;
+
+        return EscSeqUtils.OSC_StartHyperlink (url) + display + EscSeqUtils.OSC_EndHyperlink ();
+    }
+
+    private static string Wrap (string input)
+    {
+        StringBuilder sb = new (input);
+
+        return Osc8UrlLinker.WrapOsc8 (sb).ToString ();
+    }
+}

+ 1 - 1
Tests/UnitTestsParallelizable/MockConsoleDriver.cs

@@ -155,7 +155,7 @@ internal class MockConsoleDriver : IConsoleDriver
     public void UpdateCursor () {}
 
     /// <inheritdoc />
-    public MainLoop Init () { return null!; }
+    public void Init () { }
 
     /// <inheritdoc />
     public void End () {  }

+ 0 - 1
Tests/UnitTestsParallelizable/TestSetup.cs

@@ -47,7 +47,6 @@ public class GlobalTestSetup : IDisposable
         // Don't check Application.Force16Colors
         //Assert.False (Application.Force16Colors);
         Assert.Null (Application.Driver);
-        Assert.Null (Application.MainLoop);
         Assert.False (Application.EndAfterFirstIteration);
         Assert.Equal (Key.Tab.WithShift, Application.PrevTabKey);
         Assert.Equal (Key.Tab, Application.NextTabKey);

+ 633 - 56
docfx/docs/View.md

@@ -1,114 +1,691 @@
 # View Deep Dive
 
-## Hierarchy
+[View](~/api/Terminal.Gui.ViewBase.View.yml) is the base class for all visible UI elements in Terminal.Gui. View provides core functionality for layout, drawing, input handling, navigation, and scrolling. All interactive controls, windows, and dialogs derive from View.
 
-  * @Terminal.Gui.View - The base class for implementing higher-level visual/interactive Terminal.Gui elements. Implemented in the @Terminal.Gui.ViewBase.View base class.
-  
-  * *SubView* - A View that is contained in another view and will be rendered as part of the containing view's **ContentArea**. SubViews are added to another view via the @"Terminal.Gui.ViewBase.View.Add(Terminal.Gui.View)" method. A View may only be a SubView of a single View. Each View has a @Terminal.Gui.ViewBase.View.SubViews property that is a list of all SubViews that have been added.
-  
-  * @Terminal.Gui.View.SuperView - The View that is a container for SubViews. Each View has a @Terminal.Gui.ViewBase.View.SuperView property that references it's SuperView after it has been added.
-  
-  * *Child View* - A view that holds a reference to another view in a parent/child relationship. Terminal.Gui uses the terms "Child" and "Parent" sparingly. Generally SubView/SuperView is preferred.
-  
-  * *Parent View* - A view that holds a reference to another view in a parent/child relationship, but is NOT a SuperView of the child. Terminal.Gui uses the terms "Child" and "Parent" sparingly. Generally SubView/SuperView is preferred.
+See the [Views Overview](views.md) for a catalog of all built-in View subclasses.
+
+## Table of Contents
+
+- [View Hierarchy](#view-hierarchy)
+- [View Composition](#view-composition)
+- [Core Concepts](#core-concepts)
+- [View Lifecycle](#view-lifecycle)
+- [Subsystems](#subsystems)
+- [Common View Patterns](#common-view-patterns)
+- [Modal Views](#modal-views)
+
+---
+
+## View Hierarchy
+
+### Terminology
+
+- **[View](~/api/Terminal.Gui.ViewBase.View.yml)** - The base class for all visible UI elements
+- **SubView** - A View that is contained in another View and rendered as part of the containing View's content area. SubViews are added via [View.Add](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Add_Terminal_Gui_ViewBase_View_)
+- **SuperView** - The View that contains SubViews. Each View has a [View.SuperView](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperView) property that references its container
+- **Child View** - A view that holds a reference to another view in a parent/child relationship (used sparingly; generally SubView/SuperView is preferred)
+- **Parent View** - A view that holds a reference to another view but is NOT a SuperView (used sparingly)
+
+### Key Properties
+
+- [View.SubViews](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SubViews) - Read-only list of all SubViews added to this View
+- [View.SuperView](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperView) - The View's container (null if the View has no container)
+- [View.Id](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Id) - Unique identifier for the View (should be unique among siblings)
+- [View.Data](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Data) - Arbitrary data attached to the View
 
-## Composition
+---
+
+## View Composition
+
+Views are composed of several nested layers that define how they are positioned, drawn, and scrolled:
 
 [!INCLUDE [View Composition](~/includes/view-composition.md)]
 
-### List of Built-In Views
+### The Layers
+
+1. **[Frame](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Frame)** - The outermost rectangle defining the View's location and size relative to the SuperView's content area
+2. **[Margin](~/api/Terminal.Gui.ViewBase.Margin.yml)** - Adornment that provides spacing between the View and other SubViews
+3. **[Border](~/api/Terminal.Gui.ViewBase.Border.yml)** - Adornment that draws the visual border and title
+4. **[Padding](~/api/Terminal.Gui.ViewBase.Padding.yml)** - Adornment that provides spacing between the border and the viewport
+5. **[Viewport](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Viewport)** - Rectangle describing the visible portion of the content area
+6. **Content Area** - The total area where content can be drawn (defined by [View.GetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_GetContentSize))
+
+See the [Layout Deep Dive](layout.md) for complete details on View composition and layout.
+
+---
+
+## Core Concepts
+
+### Frame vs. Viewport
+
+- **Frame** - The View's location and size in SuperView-relative coordinates. Frame includes all adornments (Margin, Border, Padding)
+- **Viewport** - The visible "window" into the View's content, located inside the adornments. Viewport coordinates are always relative to (0,0) of the content area
+
+```csharp
+// Frame is SuperView-relative
+view.Frame = new Rectangle(10, 5, 50, 20);
+
+// Viewport is content-relative (the visible portal)
+view.Viewport = new Rectangle(0, 0, 45, 15); // Adjusted for adornments
+```
+
+### Content Area and Scrolling
+
+The **Content Area** is where the View's content is drawn. By default, the content area size matches the Viewport size. To enable scrolling:
+
+1. Call [View.SetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SetContentSize_System_Nullable_System_Drawing_Size__) with a size larger than the Viewport
+2. Change `Viewport.Location` to scroll the content
+
+See the [Scrolling Deep Dive](scrolling.md) for complete details.
+
+### Adornments
+
+[Adornments](~/api/Terminal.Gui.ViewBase.Adornment.yml) are special Views that surround the content:
+
+- **[Margin](~/api/Terminal.Gui.ViewBase.Margin.yml)** - Transparent spacing outside the Border
+- **[Border](~/api/Terminal.Gui.ViewBase.Border.yml)** - Visual frame with [LineStyle](~/api/Terminal.Gui.Drawing.LineStyle.yml), title, and arrangement UI
+- **[Padding](~/api/Terminal.Gui.ViewBase.Padding.yml)** - Spacing inside the Border, outside the Viewport
+
+Each adornment has a [Thickness](~/api/Terminal.Gui.Drawing.Thickness.yml) that defines the width of each side (Top, Right, Bottom, Left).
+
+See the [Layout Deep Dive](layout.md) for complete details on adornments.
+
+---
+
+## View Lifecycle
 
-See [List of Built-In Views](views.md)
+### Initialization
+
+Views implement [ISupportInitializeNotification](https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.isupportinitializenotification):
+
+1. **Constructor** - Creates the View and sets up default state
+2. **[BeginInit](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_BeginInit)** - Signals initialization is starting
+3. **[EndInit](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_EndInit)** - Signals initialization is complete; raises [View.Initialized](~/api/Terminal.Gui.ViewBase.View.yml) event
+4. **[IsInitialized](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_IsInitialized)** - Property indicating if initialization is complete
+
+### Disposal
+
+Views are [IDisposable](https://docs.microsoft.com/en-us/dotnet/api/system.idisposable):
+
+- Call [View.Dispose](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Dispose) to clean up resources
+- The [View.Disposing](~/api/Terminal.Gui.ViewBase.View.yml) event is raised when disposal begins
+- Automatically disposes SubViews, adornments, and scroll bars
+
+---
+
+## Subsystems
+
+View is organized as a partial class across multiple files, each handling a specific subsystem:
   
 ### Commands
 
 See the [Command Deep Dive](command.md).
 
-### Input
+- [View.AddCommand](~/api/Terminal.Gui.ViewBase.View.yml) - Declares commands the View supports
+- [View.InvokeCommand](~/api/Terminal.Gui.ViewBase.View.yml) - Invokes a command
+- [Command](~/api/Terminal.Gui.Input.Command.yml) enum - Standard set of commands (Accept, Select, HotKey, etc.)
+
+### Input Handling
+
+#### Keyboard
 
-See the [Keyboard Deep Dive](keyboard.md) and [Mouse Deep Dive](mouse.md).
+See the [Keyboard Deep Dive](keyboard.md).
+
+- [View.KeyBindings](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_KeyBindings) - Maps keys to Commands
+- [View.HotKey](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HotKey) - The hot key for the View
+- [View.HotKeySpecifier](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HotKeySpecifier) - Character used to denote hot keys in text (default: '_')
+- Events: `KeyDown`, `KeyUp`, `InvokingKeyBindings`
+
+#### Mouse
+
+See the [Mouse Deep Dive](mouse.md).
+
+- [View.MouseBindings](~/api/Terminal.Gui.ViewBase.View.yml) - Maps mouse events to Commands
+- [View.WantContinuousButtonPresses](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_WantContinuousButtonPresses) - Enables continuous button press events
+- [View.Highlight](~/api/Terminal.Gui.ViewBase.View.yml) - Event for visual feedback on mouse hover/click
+- [View.HighlightStyle](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HighlightStyle) - Visual style when highlighted
+- Events: `MouseEnter`, `MouseLeave`, `MouseClick`, `MouseEvent`
 
 ### Layout and Arrangement
 
-See the [Layout Deep Dive](layout.md) and the [Arrangement Deep Dive](arrangement.md).
+See the [Layout Deep Dive](layout.md) and [Arrangement Deep Dive](arrangement.md).
+
+#### Position and Size
+
+- [View.X](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_X) - Horizontal position using [Pos](~/api/Terminal.Gui.Pos.yml)
+- [View.Y](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Y) - Vertical position using [Pos](~/api/Terminal.Gui.Pos.yml)
+- [View.Width](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Width) - Width using [Dim](~/api/Terminal.Gui.Dim.yml)
+- [View.Height](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Height) - Height using [Dim](~/api/Terminal.Gui.Dim.yml)
+
+#### Layout Features
+
+- [Dim.Auto](~/api/Terminal.Gui.Dim.yml#Terminal_Gui_Dim_Auto_Terminal_Gui_DimAutoStyle_Terminal_Gui_Dim_Terminal_Gui_Dim_) - Automatic sizing based on content
+- [Pos.AnchorEnd](~/api/Terminal.Gui.Pos.yml#Terminal_Gui_Pos_AnchorEnd_System_Int32_) - Anchor to right/bottom edges
+- [Pos.Align](~/api/Terminal.Gui.Pos.yml) - Align views relative to each other
+- [Pos.Center](~/api/Terminal.Gui.Pos.yml) - Center within SuperView
+- [Dim.Fill](~/api/Terminal.Gui.Dim.yml) - Fill available space
+
+#### Arrangement
+
+- [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) - Controls if View is movable/resizable
+- [ViewArrangement](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) - Flags: Fixed, Movable, Resizable, Overlapped
+
+#### Events
+
+- `LayoutStarted` - Before layout begins
+- `LayoutComplete` - After layout completes
+- `FrameChanged` - When Frame changes
+- `ViewportChanged` - When Viewport changes
 
 ### Drawing
 
 See the [Drawing Deep Dive](drawing.md).
 
+#### Color and Style
+
+- [View.Scheme](~/api/Terminal.Gui.ViewBase.View.yml) - Color scheme for the View
+- [View.SetAttribute](~/api/Terminal.Gui.ViewBase.View.yml) - Sets the attribute for subsequent drawing
+- [View.SetAttributeForRole](~/api/Terminal.Gui.ViewBase.View.yml) - Sets attribute based on [VisualRole](~/api/Terminal.Gui.Drawing.VisualRole.yml)
+
+See the [Scheme Deep Dive](scheme.md) for details on color theming.
+
+#### Drawing Methods
+
+- [View.Draw](~/api/Terminal.Gui.ViewBase.View.yml) - Main drawing method
+- [View.AddRune](~/api/Terminal.Gui.ViewBase.View.yml) - Draws a single Rune
+- [View.AddStr](~/api/Terminal.Gui.ViewBase.View.yml) - Draws a string
+- [View.Move](~/api/Terminal.Gui.ViewBase.View.yml) - Positions the cursor
+- [View.Clear](~/api/Terminal.Gui.ViewBase.View.yml) - Clears the View's content
+
+#### Drawing Events
+
+- `DrawingContent` - Before content is drawn
+- `DrawingContentComplete` - After content is drawn
+- `DrawingAdornments` - Before adornments are drawn
+- `DrawingAdornmentsComplete` - After adornments are drawn
+
+#### Invalidation
+
+- [View.SetNeedsDraw](~/api/Terminal.Gui.ViewBase.View.yml) - Marks View as needing redraw
+- [View.NeedsDraw](~/api/Terminal.Gui.ViewBase.View.yml) - Property indicating if View needs redraw
+
 ### Navigation
 
 See the [Navigation Deep Dive](navigation.md).
 
+- [View.CanFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_CanFocus) - Whether the View can receive keyboard focus
+- [View.HasFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HasFocus) - Whether the View currently has focus
+- [View.TabStop](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_TabStop) - [TabBehavior](~/api/Terminal.Gui.Input.TabBehavior.yml) for tab navigation
+- [View.TabIndex](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_TabIndex) - Order in tab navigation
+- [View.SetFocus](~/api/Terminal.Gui.ViewBase.View.yml) - Gives focus to the View
+
+Events:
+- `HasFocusChanging` - Before focus changes (cancellable)
+- `HasFocusChanged` - After focus changes
+- `Accepting` - When Command.Accept is invoked (typically Enter key)
+- `Accepted` - After Command.Accept completes
+- `Selecting` - When Command.Select is invoked (typically Space or mouse click)
+- `Selected` - After Command.Select completes
+
 ### Scrolling
 
 See the [Scrolling Deep Dive](scrolling.md).
 
-## Modal Views
+- [View.Viewport](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Viewport) - Visible portion of the content area
+- [View.GetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_GetContentSize) - Returns size of scrollable content
+- [View.SetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SetContentSize_System_Nullable_System_Drawing_Size__) - Sets size of scrollable content
+- [View.ScrollHorizontal](~/api/Terminal.Gui.ViewBase.View.yml) - Scrolls content horizontally
+- [View.ScrollVertical](~/api/Terminal.Gui.ViewBase.View.yml) - Scrolls content vertically
+- [View.VerticalScrollBar](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_VerticalScrollBar) - Built-in vertical scrollbar
+- [View.HorizontalScrollBar](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HorizontalScrollBar) - Built-in horizontal scrollbar
+- [View.ViewportSettings](~/api/Terminal.Gui.ViewBase.View.yml) - [ViewportSettingsFlags](~/api/Terminal.Gui.ViewBase.ViewportSettingsFlags.yml) controlling scroll behavior
+
+### Text
+
+- [View.Text](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Text) - The View's text content
+- [View.Title](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Title) - The View's title (shown in Border)
+- [View.TextFormatter](~/api/Terminal.Gui.ViewBase.View.yml) - Handles text formatting and alignment
+- [View.TextDirection](~/api/Terminal.Gui.ViewBase.View.yml) - Text direction (LeftRight, RightToLeft, TopToBottom)
+- [View.TextAlignment](~/api/Terminal.Gui.ViewBase.View.yml) - Text alignment (Left, Centered, Right, Justified)
+- [View.VerticalTextAlignment](~/api/Terminal.Gui.ViewBase.View.yml) - Vertical alignment (Top, Middle, Bottom, Justified)
 
-Views can either be Modal or Non-modal. Modal views take over all user input until the user closes the View. Examples of Modal Views are Toplevel, Dialog, and Wizard. Non-modal views can be used to create a new experience in your application, one where you would have a new top-level menu for example. Setting the `Modal` property on a View to `true` makes it modal.
+---
 
-To run any View (but especially Dialogs, Windows, or Toplevels) modally, invoke the `Application.Run` method on a Toplevel. Use the `Application.RequestStop()` method to terminate the modal execution.
+## View Lifecycle
+
+### 1. Creation
 
 ```csharp
+View view = new ()
+{
+    X = Pos.Center(),
+    Y = Pos.Center(),
+    Width = Dim.Percent(50),
+    Height = Dim.Fill()
+};
+```
+
+### 2. Initialization
+
+When a View is added to a SuperView or when [Application.Run](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_Run_Terminal_Gui_Views_Toplevel_System_Func_System_Exception_System_Boolean__) is called:
+
+1. [BeginInit](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_BeginInit) is called
+2. [EndInit](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_EndInit) is called
+3. [IsInitialized](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_IsInitialized) becomes true
+4. [Initialized](~/api/Terminal.Gui.ViewBase.View.yml) event is raised
+
+### 3. Layout
+
+Layout happens automatically when needed:
+
+1. [View.SetNeedsLayout](~/api/Terminal.Gui.ViewBase.View.yml) marks View as needing layout
+2. [View.Layout](~/api/Terminal.Gui.ViewBase.View.yml) calculates position and size
+3. `LayoutStarted` event is raised
+4. Frame and Viewport are calculated based on X, Y, Width, Height
+5. SubViews are laid out
+6. `LayoutComplete` event is raised
+
+### 4. Drawing
 
+Drawing happens automatically when needed:
+
+1. [View.SetNeedsDraw](~/api/Terminal.Gui.ViewBase.View.yml) marks View as needing redraw
+2. [View.Draw](~/api/Terminal.Gui.ViewBase.View.yml) renders the View
+3. `DrawingContent` event is raised
+4. [View.OnDrawingContent](~/api/Terminal.Gui.ViewBase.View.yml) is called (override to draw custom content)
+5. `DrawingContentComplete` event is raised
+6. Adornments are drawn
+7. SubViews are drawn
+
+### 5. Input Processing
+
+Input is processed in this order:
+
+1. **Keyboard**: Key → KeyBindings → Command → Command Handlers → Events
+2. **Mouse**: MouseEvent → MouseBindings → Command → Command Handlers → Events
+
+### 6. Disposal
+
+```csharp
+view.Dispose();
 ```
 
-There is no return value from running modally, so the modal view must have a mechanism to indicate the reason the modal was closed. In the case above, the `okpressed` value is set to true if the user pressed or selected the `Ok` button.
+- Raises [View.Disposing](~/api/Terminal.Gui.ViewBase.View.yml) event
+- Disposes adornments, scrollbars, SubViews
+- Cleans up event handlers and resources
+
+---
 
-### Dialogs
+## Subsystems
 
-[Dialogs](~/api/Terminal.Gui.Views.Dialog.yml) are Modal [Windows](~/api/Terminal.Gui.Views.Window.yml) that are centered in the middle of the screen and are intended to be used modally - that is, they run, and they are expected to return a result before resuming execution of the application.
+### Commands
 
-Dialogs expose an API for adding buttons and managing the layout such that buttons are at the bottom of the dialog (e.g. [`AddButton`](https://migueldeicaza.github.io/gui.cs/api/Terminal.Gui.Dialog.yml#Terminal_Gui_Dialog_AddButton_Terminal_Gui_Button_)).
+See the [Command Deep Dive](command.md) for complete details.
+
+Views use a command pattern for handling input:
 
-Example:
 ```csharp
-bool okpressed = false;
-var ok = new Button() { Title = "Ok" };
-var cancel = new Button() { Title = "Cancel" };
-var dialog = new Dialog () { Text = "Are you sure you want to quit?", Title = "Quit", Buttons = { ok, cancel } };
+// Add a command the view supports
+view.AddCommand (Command.Accept, () => 
+{
+    // Handle the Accept command
+    return true;
+});
+
+// Bind a key to the command
+view.KeyBindings.Add (Key.Enter, Command.Accept);
+
+// Bind a mouse action to the command
+view.MouseBindings.Add (MouseFlags.Button1Clicked, Command.Select);
 ```
 
-Which will show something like this:
+### Input
 
+#### Keyboard
+
+See the [Keyboard Deep Dive](keyboard.md) for complete details.
+
+The keyboard subsystem processes key presses through:
+
+1. [View.KeyDown](~/api/Terminal.Gui.ViewBase.View.yml) event (cancellable)
+2. [View.OnKeyDown](~/api/Terminal.Gui.ViewBase.View.yml) virtual method
+3. [View.KeyBindings](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_KeyBindings) - Converts keys to commands
+4. Command handlers (registered via [View.AddCommand](~/api/Terminal.Gui.ViewBase.View.yml))
+5. [View.KeyUp](~/api/Terminal.Gui.ViewBase.View.yml) event
+
+#### Mouse
+
+See the [Mouse Deep Dive](mouse.md) for complete details.
+
+The mouse subsystem processes mouse events through:
+
+1. [View.MouseEvent](~/api/Terminal.Gui.ViewBase.View.yml) event (low-level)
+2. [View.OnMouseEvent](~/api/Terminal.Gui.ViewBase.View.yml) virtual method
+3. [View.MouseEnter](~/api/Terminal.Gui.ViewBase.View.yml) / [View.MouseLeave](~/api/Terminal.Gui.ViewBase.View.yml) events
+4. [View.MouseBindings](~/api/Terminal.Gui.ViewBase.View.yml) - Converts mouse actions to commands
+5. Command handlers
+6. [View.MouseClick](~/api/Terminal.Gui.ViewBase.View.yml) event (high-level)
+
+### Layout
+
+See the [Layout Deep Dive](layout.md) for complete details.
+
+Layout is declarative using [Pos](~/api/Terminal.Gui.Pos.yml) and [Dim](~/api/Terminal.Gui.Dim.yml):
+
+```csharp
+var label = new Label { Text = "Name:" };
+var textField = new TextField 
+{ 
+    X = Pos.Right(label) + 1,
+    Y = Pos.Top(label),
+    Width = Dim.Fill()
+};
 ```
-+- Quit -----------------------------------------------+
-|            Are you sure you want to quit?            |
-|                                                      |
-|                  [ Ok ] [ Cancel ]                   |
-+------------------------------------------------------+
+
+The layout system automatically:
+- Calculates Frame based on X, Y, Width, Height
+- Handles Adornment thickness
+- Calculates Viewport
+- Lays out SubViews recursively
+
+### Drawing
+
+See the [Drawing Deep Dive](drawing.md) for complete details.
+
+Views draw themselves using viewport-relative coordinates:
+
+```csharp
+protected override bool OnDrawingContent()
+{
+    // Draw at viewport coordinates (0,0)
+    Move(0, 0);
+    SetAttribute(new Attribute(Color.White, Color.Blue));
+    AddStr("Hello, Terminal.Gui!");
+    
+    return true;
+}
+```
+
+Key drawing concepts:
+- [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) - For drawing lines with auto-joining
+- [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml) - Color and text style
+- [TextStyle](~/api/Terminal.Gui.Drawing.TextStyle.yml) - Bold, Italic, Underline, etc.
+- [Gradient](~/api/Terminal.Gui.Drawing.Gradient.yml) / [GradientFill](~/api/Terminal.Gui.Drawing.GradientFill.yml) - Color gradients
+
+### Navigation
+
+See the [Navigation Deep Dive](navigation.md) for complete details.
+
+Navigation controls keyboard focus movement:
+
+- [View.CanFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_CanFocus) - Whether View can receive focus
+- [View.TabStop](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_TabStop) - [TabBehavior](~/api/Terminal.Gui.Input.TabBehavior.yml) (NoStop, TabStop, TabGroup)
+- [View.TabIndex](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_TabIndex) - Tab order within SuperView
+- [View.SetFocus](~/api/Terminal.Gui.ViewBase.View.yml) - Requests focus
+- [View.AdvanceFocus](~/api/Terminal.Gui.ViewBase.View.yml) - Moves focus to next/previous View
+
+### Scrolling
+
+See the [Scrolling Deep Dive](scrolling.md) for complete details.
+
+Scrolling is built into every View:
+
+```csharp
+// Set content size larger than viewport
+view.SetContentSize(new Size(100, 100));
+
+// Scroll the content
+view.Viewport = view.Viewport with { Location = new Point(10, 10) };
+
+// Or use helper methods
+view.ScrollVertical(5);
+view.ScrollHorizontal(3);
+
+// Enable scrollbars
+view.VerticalScrollBar.Visible = true;
+view.HorizontalScrollBar.Visible = true;
 ```
 
-### Wizards
+---
 
-[Wizards](~/api/Terminal.Gui.Views.Wizard.yml) are Dialogs that let users step through a series of steps to complete a task. 
+## Common View Patterns
 
+### Creating a Custom View
+
+```csharp
+public class MyCustomView : View
+{
+    public MyCustomView()
+    {
+        // Set up default size
+        Width = Dim.Auto();
+        Height = Dim.Auto();
+        
+        // Can receive focus
+        CanFocus = true;
+        
+        // Add supported commands
+        AddCommand(Command.Accept, HandleAccept);
+        
+        // Configure key bindings
+        KeyBindings.Add(Key.Enter, Command.Accept);
+    }
+    
+    protected override bool OnDrawingContent()
+    {
+        // Draw custom content using viewport coordinates
+        Move(0, 0);
+        SetAttributeForRole(VisualRole.Normal);
+        AddStr("My custom content");
+        
+        return true; // Handled
+    }
+    
+    private bool HandleAccept()
+    {
+        // Handle the Accept command
+        // Raise events, update state, etc.
+        return true; // Handled
+    }
+}
 ```
-╔╡Gandolf - The last step╞════════════════════════════════════╗
-║                                     The wizard is complete! ║
-║☐ Enable Final Final Step                                    ║
-║                                     Press the Finish        ║
-║                                     button to continue.     ║
-║                                                             ║
-║                                     Pressing ESC will       ║
-║                                     cancel the wizard.      ║
-║                                                             ║
-║                                                             ║
-║─────────────────────────────────────────────────────────────║
-║⟦ Back ⟧                                         ⟦► Finish ◄⟧║
-╚═════════════════════════════════════════════════════════════╝
+
+### Adding SubViews
+
+```csharp
+var container = new View
+{
+    Width = Dim.Fill(),
+    Height = Dim.Fill()
+};
+
+var button1 = new Button { Text = "OK", X = 2, Y = 2 };
+var button2 = new Button { Text = "Cancel", X = Pos.Right(button1) + 2, Y = 2 };
+
+container.Add(button1, button2);
 ```
 
+### Using Adornments
+
+```csharp
+var view = new View
+{
+    BorderStyle = LineStyle.Double,
+    Title = "My View"
+};
 
-## Application Concepts 
+// Configure border
+view.Border.Thickness = new Thickness(1);
+view.Border.Settings = BorderSettings.Title;
 
-  * *TopLevel* - The v1 term used to describe a view that can have a MenuBar and/or StatusBar. In v2, we will delete the `TopLevel` class and ensure ANY View can have a menu bar and/or status bar (via `Adornments`).
-    * NOTE: There will still be an `Application.Top` which is the [View](~/api/Terminal.Gui.ViewBase.View.yml) that is the root of the `Application`'s view hierarchy.
+// Add padding
+view.Padding.Thickness = new Thickness(1);
+
+// Add margin
+view.Margin.Thickness = new Thickness(2);
+```
 
-  * *Runnable* - TBD
+### Implementing Scrolling
 
-  * *Modal* - *Modal* - The term used when describing a [View](~/api/Terminal.Gui.Viewbase.View.yml) that was created using the `Application.Run(view)` or `Application.Run<T>` APIs. When a View is running as a modal, user input is restricted to just that View until `Application.Run` exits. A `Modal` View has its own `RunState`. 
-    * In v1, classes derived from `Dialog` were originally thought to only work modally. However, `Wizard` proved that a `Dialog`-based class can also work non-modally. 
-    * In v2, we will simplify the `Dialog` class, and let any class be run via `Applicaiton.Run`. The `Modal` property will be set by `Application.Run` so the class can detect it is running modally if it needs to. 
+```csharp
+var view = new View
+{
+    Width = 40,
+    Height = 20
+};
+
+// Set content larger than viewport
+view.SetContentSize(new Size(100, 100));
+
+// Enable scrollbars with auto-show
+view.VerticalScrollBar.AutoShow = true;
+view.HorizontalScrollBar.AutoShow = true;
+
+// Add key bindings for scrolling
+view.KeyBindings.Add(Key.CursorUp, Command.ScrollUp);
+view.KeyBindings.Add(Key.CursorDown, Command.ScrollDown);
+view.KeyBindings.Add(Key.CursorLeft, Command.ScrollLeft);
+view.KeyBindings.Add(Key.CursorRight, Command.ScrollRight);
+
+// Add command handlers
+view.AddCommand(Command.ScrollUp, () => { view.ScrollVertical(-1); return true; });
+view.AddCommand(Command.ScrollDown, () => { view.ScrollVertical(1); return true; });
+```
+
+---
+
+## Modal Views
+
+Views can run modally (exclusively capturing all input until closed). See [Toplevel](~/api/Terminal.Gui.Views.Toplevel.yml) for details.
+
+### Running a View Modally
+
+```csharp
+var dialog = new Dialog
+{
+    Title = "Confirmation",
+    Width = Dim.Percent(50),
+    Height = Dim.Percent(50)
+};
+
+// Add content...
+var label = new Label { Text = "Are you sure?", X = Pos.Center(), Y = 1 };
+dialog.Add(label);
+
+// Run modally - blocks until closed
+Application.Run(dialog);
+
+// Dialog has been closed
+```
+
+### Modal View Types
+
+- **[Toplevel](~/api/Terminal.Gui.Views.Toplevel.yml)** - Base class for modal views, can fill entire screen
+- **[Window](~/api/Terminal.Gui.Views.Window.yml)** - Overlapped container with border and title
+- **[Dialog](~/api/Terminal.Gui.Views.Dialog.yml)** - Modal Window, centered with button support
+- **[Wizard](~/api/Terminal.Gui.Views.Wizard.yml)** - Multi-step modal dialog
+
+### Dialog Example
+
+[Dialogs](~/api/Terminal.Gui.Views.Dialog.yml) are Modal [Windows](~/api/Terminal.Gui.Views.Window.yml) centered on screen:
+
+```csharp
+bool okPressed = false;
+var ok = new Button { Text = "Ok" };
+ok.Accepting += (s, e) => { okPressed = true; Application.RequestStop(); };
+
+var cancel = new Button { Text = "Cancel" };
+cancel.Accepting += (s, e) => Application.RequestStop();
+
+var dialog = new Dialog 
+{ 
+    Title = "Quit",
+    Width = 50,
+    Height = 10
+};
+dialog.Add(new Label { Text = "Are you sure you want to quit?", X = Pos.Center(), Y = 2 });
+dialog.AddButton(ok);
+dialog.AddButton(cancel);
+
+Application.Run(dialog);
+
+if (okPressed)
+{
+    // User clicked OK
+}
+```
+
+Which displays:
+
+```
+╔═ Quit ═══════════════════════════════════════════╗
+║                                                  ║
+║          Are you sure you want to quit?         ║
+║                                                  ║
+║                                                  ║
+║                                                  ║
+║                [ Ok ]  [ Cancel ]                ║
+╚══════════════════════════════════════════════════╝
+```
+
+### Wizard Example
+
+[Wizards](~/api/Terminal.Gui.Views.Wizard.yml) let users step through multiple pages:
+
+```csharp
+var wizard = new Wizard { Title = "Setup Wizard" };
+
+var step1 = new WizardStep { Title = "Welcome" };
+step1.Add(new Label { Text = "Welcome to the wizard!", X = 1, Y = 1 });
+
+var step2 = new WizardStep { Title = "Configuration" };
+step2.Add(new TextField { X = 1, Y = 1, Width = 30 });
+
+wizard.AddStep(step1);
+wizard.AddStep(step2);
+
+Application.Run(wizard);
+```
+
+---
+
+## Advanced Topics
+
+### View Diagnostics
+
+[View.Diagnostics](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Diagnostics) - [ViewDiagnosticFlags](~/api/Terminal.Gui.ViewBase.ViewDiagnosticFlags.yml) for debugging:
+
+- `Ruler` - Shows a ruler around the View
+- `DrawIndicator` - Shows an animated indicator when drawing
+- `FramePadding` - Highlights the Frame with color
+
+### View States
+
+- [View.Enabled](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Enabled) - Whether the View is enabled
+- [View.Visible](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Visible) - Whether the View is visible
+- [View.CanFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_CanFocus) - Whether the View can receive focus
+- [View.HasFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HasFocus) - Whether the View currently has focus
+
+### Shadow Effects
+
+[View.ShadowStyle](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_ShadowStyle) - [ShadowStyle](~/api/Terminal.Gui.ViewBase.ShadowStyle.yml) for drop shadows:
+
+```csharp
+view.ShadowStyle = ShadowStyle.Transparent;
+```
 
+---
+
+## See Also
+
+- **[Views Overview](views.md)** - Complete list of all built-in Views
+- **[Layout Deep Dive](layout.md)** - Detailed layout system documentation
+- **[Drawing Deep Dive](drawing.md)** - Drawing system and color management
+- **[Keyboard Deep Dive](keyboard.md)** - Keyboard input handling
+- **[Mouse Deep Dive](mouse.md)** - Mouse input handling
+- **[Navigation Deep Dive](navigation.md)** - Focus and navigation system
+- **[Scrolling Deep Dive](scrolling.md)** - Scrolling and viewport management
+- **[Command Deep Dive](command.md)** - Command pattern and bindings
+- **[Arrangement Deep Dive](arrangement.md)** - Movable and resizable views
+- **[Configuration Deep Dive](config.md)** - Configuration and persistence
+- **[Scheme Deep Dive](scheme.md)** - Color theming

+ 684 - 51
docfx/docs/arrangement.md

@@ -1,102 +1,735 @@
-# View Layout Arrangement
+# View Arrangement Deep Dive
 
-Terminal.Gui provides a feature of Layout known as **Arrangement**, which controls how the user can use the mouse and keyboard to arrange views and enables either **Tiled** or **Overlapped** layouts. Arrangement is a sub-topic of [Layout](layout.md).
+Terminal.Gui provides a powerful **Arrangement** system that enables users to interactively move and resize views using the keyboard and mouse. This system supports both **Tiled** and **Overlapped** layout modes, allowing for flexible UI organization.
 
-## Arrangement Taxonomy & Lexicon
+See the [Layout Deep Dive](layout.md) for the broader layout system context.
+
+## Table of Contents
+
+- [Overview](#overview)
+- [Arrangement Modes](#arrangement-modes)
+- [Arrange Mode (Interactive)](#arrange-mode-interactive)
+- [Tiled vs Overlapped Layouts](#tiled-vs-overlapped-layouts)
+- [Movable Views](#movable-views)
+- [Resizable Views](#resizable-views)
+- [Creating Resizable Splitters](#creating-resizable-splitters)
+- [Modal Views](#modal-views)
+- [Runnable Views](#runnable-views)
+- [Examples](#examples)
+
+---
+
+## Overview
+
+The [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) property controls how users can arrange views within their [SuperView](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperView). The [ViewArrangement](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) enum provides flags that can be combined to specify arrangement behavior.
+
+### Arrangement Lexicon
 
 [!INCLUDE [Arrangement Lexicon](~/includes/arrangement-lexicon.md)]
 
-## Arrangement
+### ViewArrangement Flags
+
+The [ViewArrangement](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) enum supports these flags (can be combined):
+
+- **Fixed** (0) - View cannot be moved or resized (default)
+- **Movable** (1) - View can be moved by the user
+- **LeftResizable** (2) - Left edge can be resized
+- **RightResizable** (4) - Right edge can be resized
+- **TopResizable** (8) - Top edge can be resized
+- **BottomResizable** (16) - Bottom edge can be resized
+- **Resizable** (30) - All edges can be resized (combines all resize flags)
+- **Overlapped** (32) - View overlaps other views (enables Z-order)
+
+---
+
+## Arrangement Modes
+
+### Fixed (Default)
+
+Views with [ViewArrangement.Fixed](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) cannot be moved or resized by the user:
+
+```csharp
+var view = new View
+{
+    Arrangement = ViewArrangement.Fixed // Default
+};
+```
+
+### Movable
+
+Views with [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) can be dragged with the mouse or moved with keyboard:
+
+```csharp
+var window = new Window
+{
+    Title = "Movable Window",
+    Arrangement = ViewArrangement.Movable
+};
+```
+
+**User Interaction:**
+- **Mouse**: Drag the top [Border](~/api/Terminal.Gui.ViewBase.Border.yml)
+- **Keyboard**: Press `Ctrl+F5` to enter Arrange Mode, use arrow keys to move
+
+### Resizable
+
+Views with [ViewArrangement.Resizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) can be resized by the user:
+
+```csharp
+var window = new Window
+{
+    Title = "Resizable Window",
+    Arrangement = ViewArrangement.Resizable
+};
+```
+
+**User Interaction:**
+- **Mouse**: Drag any border edge
+- **Keyboard**: Press `Ctrl+F5` to enter Arrange Mode, press `Tab` to cycle resize handles
+
+### Movable and Resizable
+
+Combine flags for full desktop-like experience:
+
+```csharp
+var window = new Window
+{
+    Title = "Movable and Resizable",
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable
+};
+```
+
+**Note:** When both `Movable` and `Resizable` are set, the top edge cannot be resized (Movable takes precedence).
+
+### Individual Edge Resizing
+
+For fine-grained control, use individual edge flags:
+
+```csharp
+// Only bottom edge resizable
+var view = new View
+{
+    Arrangement = ViewArrangement.BottomResizable
+};
+
+// Left and right edges resizable
+var view2 = new View
+{
+    Arrangement = ViewArrangement.LeftResizable | ViewArrangement.RightResizable
+};
+```
+
+---
+
+## Arrange Mode (Interactive)
+
+**Arrange Mode** is an interactive mode for arranging views using the keyboard. It is activated by pressing the **Arrange Key** (default: `Ctrl+F5`, configurable via [Application.ArrangeKey](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_ArrangeKey)).
+
+### Entering Arrange Mode
+
+When the user presses `Ctrl+F5`:
+
+1. Visual indicators appear on arrangeable views
+2. If [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), a move indicator (`◊`) appears in top-left corner
+3. If [ViewArrangement.Resizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), pressing `Tab` cycles to resize indicators
+4. Arrow keys move or resize the view
+5. Press `Esc`, `Ctrl+F5`, or click outside to exit
+
+### Arrange Mode Indicators
+
+The [Border](~/api/Terminal.Gui.ViewBase.Border.yml) shows visual indicators based on arrangement options:
+
+| Arrangement Flag | Indicator | Location |
+|------------------|-----------|----------|
+| Movable | `◊` (Glyphs.Move) | Top-left corner |
+| Resizable | `⇲` (Glyphs.SizeBottomRight) | Bottom-right corner |
+| LeftResizable | `↔` (Glyphs.SizeHorizontal) | Left edge, centered |
+| RightResizable | `↔` (Glyphs.SizeHorizontal) | Right edge, centered |
+| TopResizable | `↕` (Glyphs.SizeVertical) | Top edge, centered |
+| BottomResizable | `↕` (Glyphs.SizeVertical) | Bottom edge, centered |
+
+### Keyboard Controls in Arrange Mode
+
+- **Arrow Keys** - Move or resize based on active mode
+- **Tab** - Cycle between move and resize modes (if both available)
+- **Shift+Tab** - Cycle backwards
+- **Esc** - Exit Arrange Mode
+- **Ctrl+F5** - Exit Arrange Mode
+
+### Requirements for Arrangement
+
+For a View to be arrangeable:
+
+1. Must be part of a [SuperView](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperView)
+2. Position and dimensions must be independent of other SubViews
+3. Must have [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) flags set
+4. Typically needs a [Border](~/api/Terminal.Gui.ViewBase.Border.yml) for mouse interaction
 
-Describes the feature of [Layout](layout.md) which controls how the user can use the mouse and keyboard to arrange views and enables either **Tiled** or **Overlapped** layouts. The @Terminal.Gui.ViewBase.View.Arrangement property controls the arrangement behavior for each view.
+---
 
-## Arrange Mode
+## Tiled vs Overlapped Layouts
 
-The Arrange Modes are set via the @Terminal.Gui.ViewBase.View.Arrangement property. When a user presses `Ctrl+F5` (configurable via the @Terminal.Gui.App.Application.ArrangeKey property) the application goes into **Arrange Mode**. 
+### Tiled Layout
 
-In this mode, indicators are displayed on an arrangeable view indicating which aspect of the View can be arranged:
-- If @Terminal.Gui.ViewBase.ViewArrangement.Movable, a `◊` will be displayed in the top-left corner of the @Terminal.Gui.ViewBase.View.Border
-- If @Terminal.Gui.ViewBase.ViewArrangement.Resizable, pressing `Tab` (or `Shift+Tab`) will cycle to an indicator in the bottom-right corner of the Border
+In **Tiled** layouts, SubViews typically do not overlap. There is no Z-order; all views are at the same layer.
 
-The up/down/left/right cursor keys will act appropriately. `Esc`, `Ctrl+F5` or clicking outside of the Border will exit Arrange Mode.
+```csharp
+var container = new View { Arrangement = ViewArrangement.Fixed };
 
-## Modal
+var view1 = new View { X = 0, Y = 0, Width = 20, Height = 10 };
+var view2 = new View { X = 21, Y = 0, Width = 20, Height = 10 };
 
-A modal view is one that is run as an "application" via @Terminal.Gui.App.Application.Run(System.Func{System.Exception,System.Boolean},Terminal.Gui.Drivers.IConsoleDriver) where `Modal == true`. 
+container.Add(view1, view2);
+// Views are side-by-side, non-overlapping
+```
 
-`Dialog`, `MessageBox`, and `Wizard` are the prototypical examples. When run this way, there IS a `z-order` but it is highly-constrained: the modal view has a z-order of 1 and everything else is at 0.
+**Characteristics:**
+- Default mode for most TUI applications
+- Views use [Pos](~/api/Terminal.Gui.Pos.yml) and [Dim](~/api/Terminal.Gui.Dim.yml) for relative positioning
+- No Z-order management needed
+- More predictable layout behavior
 
-## Movable
+### Overlapped Layout
 
-Describes a View that can be moved by the user using the keyboard or mouse. **Movable** is enabled on a per-View basis by setting the @Terminal.Gui.ViewBase.ViewArrangement.Movable flag on @Terminal.Gui.ViewBase.View.Arrangement. 
+In **Overlapped** layouts, SubViews can overlap with Z-order determining visual stacking.
 
-Dragging on the top @Terminal.Gui.ViewBase.View.Border of a View will move such a view. Pressing `Ctrl+F5` will activate **Arrange Mode** letting the user move the view with the up/down/left/right cursor keys.
+Enable overlapped mode with [ViewArrangement.Overlapped](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml):
 
-## Overlapped
+```csharp
+var container = new View 
+{ 
+    Arrangement = ViewArrangement.Overlapped 
+};
 
-A form of layout where SubViews of a View are visually arranged such that their Frames overlap. In Overlap view arrangements there is a Z-axis (Z-order) in addition to the X and Y dimension. The Z-order indicates which Views are shown above other views. 
+var window1 = new Window 
+{ 
+    X = 5, Y = 3, Width = 40, Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Overlapped
+};
+
+var window2 = new Window 
+{ 
+    X = 15, Y = 8, Width = 40, Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Overlapped
+};
+
+container.Add(window1, window2);
+// window2 will overlap window1
+```
 
-**Overlapped** is enabled on a per-View basis by setting the @Terminal.Gui.ViewBase.ViewArrangement.Overlapped flag on @Terminal.Gui.ViewBase.View.Arrangement.
+**Characteristics:**
+- Z-order determined by SubViews collection order
+- Later views appear above earlier views
+- Tab navigation constrained to current overlapped view
+- Use `Ctrl+Tab` / `Ctrl+Shift+Tab` to switch between overlapped views
 
-## Resizable
+---
+
+## Movable Views
+
+Views with [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) can be repositioned by the user.
+
+### Enabling Movable
+
+```csharp
+var window = new Window
+{
+    Title = "Drag Me!",
+    X = 10,
+    Y = 5,
+    Width = 40,
+    Height = 15,
+    Arrangement = ViewArrangement.Movable,
+    BorderStyle = LineStyle.Single
+};
+```
 
-Describes a View that can be sized by the user using the keyboard or mouse. **Resizable** is enabled on a per-View basis by setting the @Terminal.Gui.ViewBase.ViewArrangement.Resizable flag on @Terminal.Gui.ViewBase.View.Arrangement. 
+### Moving with Mouse
 
-Dragging on the left, right, or bottom @Terminal.Gui.ViewBase.View.Border of a View will size that side of such a view. Pressing `Ctrl+F5` will activate **Arrange Mode** letting the user size the view with the up/down/left/right cursor keys.
+- **Click and drag** the top [Border](~/api/Terminal.Gui.ViewBase.Border.yml) to move the view
+- The view's [Frame](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Frame) updates as it moves
+- Release the mouse to complete the move
 
-## Tiled
+### Moving with Keyboard
 
-A form of layout where SubViews of a View are visually arranged such that their Frames do not typically overlap. With **Tiled** views, there is no 'z-order` to the SubViews of a View. 
+1. Press `Ctrl+F5` to enter **Arrange Mode**
+2. A move indicator (`◊`) appears in the top-left corner
+3. Use **arrow keys** to move the view
+4. Press `Esc` or `Ctrl+F5` to exit Arrange Mode
 
-In most use-cases, subviews do not overlap with each other (the exception being when it's done intentionally to create some visual effect). As a result, the default layout for most TUI apps is "tiled", and by default @Terminal.Gui.ViewBase.View.Arrangement is set to @Terminal.Gui.ViewBase.ViewArrangement.Fixed.
+---
 
-### Creating a Resizable Splitter
+## Resizable Views
 
-A common pattern in tiled layouts is to create a resizable splitter between two views. This can be achieved using the @Terminal.Gui.ViewBase.ViewArrangement.LeftResizable, @Terminal.Gui.ViewBase.ViewArrangement.RightResizable, @Terminal.Gui.ViewBase.ViewArrangement.TopResizable, or @Terminal.Gui.ViewBase.ViewArrangement.BottomResizable flags.
+Views with resizable flags can be resized by the user on specific edges.
 
-Here's an example of creating a horizontal resizable splitter between two views:
+### All Edges Resizable
+
+```csharp
+var window = new Window
+{
+    Title = "Resize Me!",
+    Arrangement = ViewArrangement.Resizable,
+    BorderStyle = LineStyle.Single
+};
+```
+
+### Specific Edge Resizable
+
+```csharp
+// Only right and bottom edges resizable
+var view = new View
+{
+    Arrangement = ViewArrangement.RightResizable | ViewArrangement.BottomResizable,
+    BorderStyle = LineStyle.Single
+};
+```
+
+### Resizing with Mouse
+
+- **Click and drag** any enabled border edge
+- Resize indicators appear on hover
+- The view's [Width](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Width) and [Height](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Height) update
+
+### Resizing with Keyboard
+
+1. Press `Ctrl+F5` to enter **Arrange Mode**
+2. Press `Tab` to cycle to resize mode
+3. Resize indicator (`⇲`) appears
+4. Use **arrow keys** to resize
+5. Press `Esc` or `Ctrl+F5` to exit
+
+---
+
+## Creating Resizable Splitters
+
+A common pattern in tiled layouts is creating a resizable splitter between two panes.
+
+### Horizontal Splitter (Left/Right Panes)
 
 ```csharp
-// Create left pane that fills remaining space
 View leftPane = new ()
 {
     X = 0,
     Y = 0,
-    Width = Dim.Fill (Dim.Func (_ => rightPane.Frame.Width)),
-    Height = Dim.Fill (),
-    CanFocus = true
+    Width = Dim.Fill(Dim.Func(_ => rightPane.Frame.Width)),
+    Height = Dim.Fill(),
+    BorderStyle = LineStyle.Single
 };
 
-// Create right pane with resizable left border (acts as splitter)
 View rightPane = new ()
 {
-    X = Pos.Right (leftPane) - 1,
+    X = Pos.Right(leftPane) - 1,
     Y = 0,
-    Width = Dim.Fill (),
-    Height = Dim.Fill (),
+    Width = Dim.Fill(),
+    Height = Dim.Fill(),
     Arrangement = ViewArrangement.LeftResizable,
     BorderStyle = LineStyle.Single,
-    SuperViewRendersLineCanvas = true,
-    CanFocus = true
+    SuperViewRendersLineCanvas = true
+};
+rightPane.Border.Thickness = new Thickness(1, 0, 0, 0); // Only left border
+
+container.Add(leftPane, rightPane);
+```
+
+**How it works:**
+- `rightPane` has [ViewArrangement.LeftResizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) - its left border is draggable
+- `leftPane` uses [Dim.Fill](~/api/Terminal.Gui.Dim.yml) with a function to fill remaining space
+- `SuperViewRendersLineCanvas = true` ensures proper line rendering
+- Only the left border is visible, acting as the splitter
+
+### Vertical Splitter (Top/Bottom Panes)
+
+```csharp
+View topPane = new ()
+{
+    X = 0,
+    Y = 0,
+    Width = Dim.Fill(),
+    Height = Dim.Fill(Dim.Func(_ => bottomPane.Frame.Height)),
+    BorderStyle = LineStyle.Single
+};
+
+View bottomPane = new ()
+{
+    X = 0,
+    Y = Pos.Bottom(topPane) - 1,
+    Width = Dim.Fill(),
+    Height = Dim.Fill(),
+    Arrangement = ViewArrangement.TopResizable,
+    BorderStyle = LineStyle.Single,
+    SuperViewRendersLineCanvas = true
 };
-rightPane.Border!.Thickness = new (1, 0, 0, 0); // Only left border
+bottomPane.Border.Thickness = new Thickness(1, 0, 0, 0); // Only top border
 
-container.Add (leftPane, rightPane);
+container.Add(topPane, bottomPane);
 ```
 
-In this example:
-- The `rightPane` has `ViewArrangement.LeftResizable` which makes its left border draggable
-- The left border acts as a splitter that users can drag to resize both panes
-- The `leftPane` uses `Dim.Fill` with a function that subtracts the `rightPane`'s width to automatically fill the remaining space
-- The `rightPane` has `SuperViewRendersLineCanvas = true` to ensure the border is rendered properly
-- Only the left border is shown by setting `Border.Thickness` to `(1, 0, 0, 0)`
+---
+
+## Modal Views
+
+**Modal** views run as exclusive applications that capture all user input until closed.
+
+See the [Multitasking Deep Dive](multitasking.md) for complete details on modal execution.
+
+### What Makes a View Modal
+
+A view is modal when:
+- Run via [Application.Run](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_Run_Terminal_Gui_Views_Toplevel_System_Func_System_Exception_System_Boolean__)
+- [Toplevel.Modal](~/api/Terminal.Gui.Views.Toplevel.yml#Terminal_Gui_Views_Toplevel_Modal) = `true`
+
+### Modal Characteristics
+
+- **Exclusive Input** - All keyboard and mouse input goes to the modal view
+- **Constrained Z-Order** - Modal view has Z-order of 1, everything else at 0
+- **Blocks Execution** - `Application.Run` blocks until [Application.RequestStop](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_RequestStop_Terminal_Gui_Views_Toplevel_) is called
+- **Own RunState** - Each modal view has its own [RunState](~/api/Terminal.Gui.App.RunState.yml)
+
+### Modal View Types
+
+- [Dialog](~/api/Terminal.Gui.Views.Dialog.yml) - Centered modal window with button support
+- [MessageBox](~/api/Terminal.Gui.Views.MessageBox.yml) - Simple message dialogs
+- [Wizard](~/api/Terminal.Gui.Views.Wizard.yml) - Multi-step modal dialogs
+
+### Modal Example
+
+```csharp
+var dialog = new Dialog
+{
+    Title = "Confirm",
+    Width = 40,
+    Height = 10
+};
+
+var label = new Label 
+{ 
+    Text = "Are you sure?", 
+    X = Pos.Center(), 
+    Y = 2 
+};
+dialog.Add(label);
+
+var ok = new Button { Text = "OK" };
+ok.Accepting += (s, e) => Application.RequestStop();
+dialog.AddButton(ok);
+
+// Run modally - blocks until closed
+Application.Run(dialog);
+
+// Dialog has been closed
+```
+
+---
+
+## Runnable Views
+
+**Runnable** views are those run via [Application.Run](~/api/Terminal.Gui.App.Application.yml). Each non-modal Runnable view operates as a self-contained "application" with its own [RunState](~/api/Terminal.Gui.App.RunState.yml).
+
+See the [Multitasking Deep Dive](multitasking.md) for complete details.
+
+### Non-Modal Runnable Views
+
+```csharp
+var toplevel = new Toplevel
+{
+    Modal = false // Non-modal
+};
+
+// Runs as independent application
+Application.Run(toplevel);
+```
+
+**Characteristics:**
+- Has its own `RunState`
+- Events dispatched independently
+- Can run on separate threads
+- See `BackgroundWorkerCollection` for multi-threaded examples
+
+### Modal vs Non-Modal Runnable
+
+| Aspect | Modal | Non-Modal |
+|--------|-------|-----------|
+| Input | Exclusive | Shared |
+| Z-Order | Constrained (1 vs 0) | Full Z-order support |
+| Blocks Execution | Yes | No |
+| Use Case | Dialogs, confirmations | Multi-window apps |
+
+---
+
+## Tiled vs Overlapped Layouts
+
+### Tiled Layout (Default)
+
+SubViews do not overlap, positioned side-by-side or top-to-bottom:
+
+```csharp
+var container = new View();
+
+var left = new View 
+{ 
+    X = 0, 
+    Y = 0, 
+    Width = Dim.Percent(50), 
+    Height = Dim.Fill() 
+};
+
+var right = new View 
+{ 
+    X = Pos.Right(left), 
+    Y = 0, 
+    Width = Dim.Fill(), 
+    Height = Dim.Fill() 
+};
+
+container.Add(left, right);
+```
+
+**Benefits:**
+- Simpler layout logic
+- No Z-order management
+- More predictable behavior
+- Standard for most TUI applications
+
+### Overlapped Layout
+
+SubViews can overlap with Z-order determining which is on top:
+
+```csharp
+var container = new View 
+{ 
+    Arrangement = ViewArrangement.Overlapped 
+};
+
+var window1 = new Window 
+{ 
+    X = 5, 
+    Y = 3, 
+    Width = 40, 
+    Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Overlapped
+};
+
+var window2 = new Window 
+{ 
+    X = 15, 
+    Y = 8, 
+    Width = 40, 
+    Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Overlapped
+};
+
+container.Add(window1, window2);
+// window2 appears on top of window1
+```
+
+**Z-Order:**
+- Order in [View.SubViews](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SubViews) determines Z-order
+- Later views appear above earlier views
+- Use [View.BringSubviewToFront](~/api/Terminal.Gui.ViewBase.View.yml) to change Z-order
+
+**Navigation:**
+- `Tab` / `Shift+Tab` - Navigate within current overlapped view
+- `Ctrl+Tab` (`Ctrl+PageDown`) - Switch to next overlapped view
+- `Ctrl+Shift+Tab` (`Ctrl+PageUp`) - Switch to previous overlapped view
+
+---
+
+## Examples
+
+### Example 1: Movable and Resizable Window
+
+```csharp
+using Terminal.Gui;
+
+Application.Init();
+
+var window = new Window
+{
+    Title = "Drag and Resize Me! (Ctrl+F5 for keyboard mode)",
+    X = Pos.Center(),
+    Y = Pos.Center(),
+    Width = 50,
+    Height = 15,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable,
+    BorderStyle = LineStyle.Double
+};
+
+var label = new Label
+{
+    Text = "Try dragging the border with mouse\nor press Ctrl+F5!",
+    X = Pos.Center(),
+    Y = Pos.Center()
+};
+window.Add(label);
+
+Application.Run(window);
+Application.Shutdown();
+```
+
+### Example 2: Horizontal Resizable Splitter
+
+```csharp
+Application.Init();
+
+var top = new Toplevel();
+
+var leftPane = new FrameView
+{
+    Title = "Left Pane",
+    X = 0,
+    Y = 0,
+    Width = Dim.Fill(Dim.Func(_ => rightPane.Frame.Width)),
+    Height = Dim.Fill()
+};
+
+var rightPane = new FrameView
+{
+    Title = "Right Pane (drag left edge)",
+    X = Pos.Right(leftPane) - 1,
+    Y = 0,
+    Width = Dim.Fill(),
+    Height = Dim.Fill(),
+    Arrangement = ViewArrangement.LeftResizable,
+    SuperViewRendersLineCanvas = true
+};
+rightPane.Border.Thickness = new Thickness(1, 0, 0, 0);
+
+top.Add(leftPane, rightPane);
+
+Application.Run(top);
+Application.Shutdown();
+```
+
+### Example 3: Overlapped Windows
+
+```csharp
+Application.Init();
+
+var desktop = new Toplevel 
+{ 
+    Arrangement = ViewArrangement.Overlapped 
+};
+
+var window1 = new Window
+{
+    Title = "Window 1",
+    X = 5,
+    Y = 3,
+    Width = 40,
+    Height = 12,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable | ViewArrangement.Overlapped
+};
+
+var window2 = new Window
+{
+    Title = "Window 2 (overlaps Window 1)",
+    X = 15,
+    Y = 8,
+    Width = 40,
+    Height = 12,
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable | ViewArrangement.Overlapped
+};
+
+desktop.Add(window1, window2);
+
+Application.Run(desktop);
+Application.Shutdown();
+```
+
+### Example 4: Custom Arrange Key
+
+```csharp
+using Terminal.Gui;
+using Terminal.Gui.Configuration;
+
+// Change the arrange key
+Application.ArrangeKey = Key.F2;
+
+var window = new Window
+{
+    Title = "Press F2 to enter arrange mode",
+    Arrangement = ViewArrangement.Movable | ViewArrangement.Resizable
+};
+
+Application.Run(window);
+```
+
+---
+
+## Advanced Topics
+
+### Constraints and Limitations
+
+Arrangement only works when:
+
+1. **View has a SuperView** - Root views cannot be arranged
+2. **Independent Position/Size** - Views with [Pos.Align](~/api/Terminal.Gui.Pos.yml) or complex [Dim](~/api/Terminal.Gui.Dim.yml) constraints may not resize properly
+3. **Border Required** - Mouse-based arrangement requires a visible [Border](~/api/Terminal.Gui.ViewBase.Border.yml)
+
+### SuperViewRendersLineCanvas
+
+When creating splitters, set [View.SuperViewRendersLineCanvas](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_SuperViewRendersLineCanvas) = `true`:
+
+```csharp
+rightPane.SuperViewRendersLineCanvas = true;
+```
+
+This ensures [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) properly handles line intersections at borders.
+
+### Z-Order Management
+
+For overlapped views, manage Z-order with:
+
+```csharp
+// Bring a view to the front
+container.BringSubviewToFront(window1);
+
+// Send a view to the back
+container.SendSubviewToBack(window2);
+
+// Check current order
+int index = container.SubViews.IndexOf(window1);
+```
+
+### Arrangement Events
+
+Monitor arrangement changes by handling layout events:
+
+```csharp
+view.FrameChanged += (s, e) =>
+{
+    Console.WriteLine($"View moved/resized to {e.NewValue}");
+};
+
+view.LayoutComplete += (s, e) =>
+{
+    // Layout has completed after arrangement change
+};
+```
+
+---
+
+## See Also
 
-For a vertical splitter (top and bottom panes), use `ViewArrangement.TopResizable` or `ViewArrangement.BottomResizable` instead.
+- **[Layout Deep Dive](layout.md)** - Overall layout system
+- **[View Deep Dive](View.md)** - View base class
+- **[Multitasking Deep Dive](multitasking.md)** - Modal and runnable views
+- **[Drawing Deep Dive](drawing.md)** - LineCanvas and borders
+- **[Configuration Deep Dive](config.md)** - Configuring Application.ArrangeKey
 
-## Runnable
+### API Reference
 
-Today, Overlapped and Runnable are intrinsically linked. A runnable view is one where `Application.Run(Toplevel)` is called. Each *Runnable* view where (`Modal == false`) has it's own `RunState` and is, effectively, a self-contained "application". 
+- [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement)
+- [ViewArrangement](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml)
+- [Border](~/api/Terminal.Gui.ViewBase.Border.yml)
+- [Application.ArrangeKey](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_ArrangeKey)
+- [Toplevel.Modal](~/api/Terminal.Gui.Views.Toplevel.yml#Terminal_Gui_Views_Toplevel_Modal)
 
-`Application.Run()` non-preemptively dispatches events (screen, keyboard, mouse, Timers, and Idle handlers) to the associated `Toplevel`. It is possible for such a `Toplevel` to create a thread and call `Application.Run(someotherToplevel)` on that thread, enabling pre-emptive user-interface multitasking (`BackgroundWorkerCollection` does this).
+### UICatalog Examples
 
+The UICatalog application demonstrates arrangement:
 
+- **Arrangement Editor** - Interactive arrangement demonstration
+- **Overlapped** scenario - Shows overlapped window management
+- **Splitter** examples - Various splitter configurations

+ 807 - 217
docfx/docs/config.md

@@ -1,380 +1,970 @@
-# Configuration Management
+# Configuration Management Deep Dive
 
-Terminal.Gui provides persistent configuration settings via the [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) class.
+Terminal.Gui provides a comprehensive configuration system that allows users and developers to customize application behavior and appearance through JSON configuration files. The [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) enables persistent settings, themes, and application-specific preferences.
 
-## Configuration Lexicon and Taxonomy
+## Table of Contents
 
-[!INCLUDE [Config Lexicon](~/includes/config-lexicon.md)]
+- [Overview](#overview)
+- [Getting Started](#getting-started)
+- [Configuration Scopes](#configuration-scopes)
+- [Configuration Locations and Precedence](#configuration-locations-and-precedence)
+- [Themes and Schemes](#themes-and-schemes)
+- [Defining Configuration Properties](#defining-configuration-properties)
+- [Loading and Applying Configuration](#loading-and-applying-configuration)
+- [Events](#events)
+- [What Can Be Configured](#what-can-be-configured)
+- [Configuration File Format](#configuration-file-format)
+- [Best Practices](#best-practices)
 
-# Fundamentals
+---
 
-The `ConfigurationManager` class provides a way to store and retrieve configuration settings for an application. The configuration is stored in JSON documents, which can be located in the user's home directory, the current working directory, in memory, or as a resource within the application's main assembly.
+## Overview
 
-Settings are defined in JSON format, according to this schema: https://gui-cs.github.io/Terminal.GuiV2Docs/schemas/tui-config-schema.json.
+The [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) provides:
 
-Terminal.Gui library developers can define settings in code and set the default values in the Terminal.Gui assembly's resources (e.g. `Terminal.Gui.Resources.config.json`).
+- **Persistent Settings** - User preferences stored in JSON files
+- **Theme System** - Named collections of visual settings
+- **Scheme Management** - Color and text style definitions
+- **Configuration Precedence** - Layered configuration from multiple sources
+- **Runtime Configuration** - In-memory configuration without files
+- **AOT Compatible** - Works with Native AOT compilation
 
-Terminal.Gui application developers can define settings in their apps' code and set the default values in their apps' resources (e.g. `Resources/config.json`) or by setting @Terminal.Gui.Configuration.ConfigurationManager.RuntimeConfig to string containing JSON.
+### Key Features
 
-Users can change settings on a global or per-application basis by providing JSON formatted configuration files. The configuration files can be placed in at .tui folder in the user's home directory (e.g. `C:/Users/username/.tui`, or `/usr/username/.tui`) or the folder where the Terminal.Gui application was launched from (e.g. `./.tui`).
+- JSON-based configuration with schema validation
+- Multiple configuration locations (user home, app directory, resources)
+- Process-wide settings using static properties
+- Built-in themes (Default, Dark, Light, etc.)
+- Custom glyphs and Unicode characters
+- Event-driven configuration changes
 
-## CM is Disabled by Default
+---
 
-The `ConfigurationManager` must be enabled explicitly by calling @Terminal.Gui.Configuration.ConfigurationManager.Enable(Terminal.Gui.Configuration.ConfigLocations) in an application's `Main` method.
+## Getting Started
 
-```csharp
-// Enable configuration with all sources  
-ConfigurationManager.Enable(ConfigLocations.All);
-```
+### Enabling Configuration
 
-If `ConfigurationManager.Enable()` is not called (`ConfigurationManager.IsEnabled` is 'false'), all configuration settings are ignored and ConfigurationManager will effectively be a no-op. All `[ConfigurationProperty]` properties will initially be their hard-coded default values. 
+**ConfigurationManager is disabled by default** and must be explicitly enabled:
 
-Other than that, no other ConfigurationManager APIs will have any effect.
-
-## Loading and Applying Configuration
+```csharp
+using Terminal.Gui.Configuration;
 
-Optionally, developers can more granularly control the loading and applying of configuration by calling the `Load` and `Apply` methods directly.
+class Program
+{
+    static void Main()
+    {
+        // Enable configuration with all sources
+        ConfigurationManager.Enable(ConfigLocations.All);
+        
+        Application.Init();
+        // ... rest of app
+    }
+}
+```
 
-When a configuration has been loaded, the @Terminal.Gui.Configuration.ConfigurationManager.Apply method must be called to apply the settings to the application. This method uses reflection to find all static fields decorated with the `[ConfigurationProperty]` attribute and applies the settings to the corresponding properties.
+### Quick Example
 
 ```csharp
-// Load the configuration from just the users home directory.
-ConfigurationManager.Enable(ConfigLocations.HardCoded);
-ConfigurationManager.Load(ConfigLocations.GlobalHome);
+// Enable configuration
+ConfigurationManager.Enable(ConfigLocations.All);
+
+// Listen for configuration changes
+ConfigurationManager.Applied += (sender, e) => 
+{
+    Console.WriteLine("Configuration applied!");
+};
+
+// Switch themes
+ThemeManager.Theme = "Dark";
 ConfigurationManager.Apply();
 ```
 
-> [!IMPORTANT]
-> Configuration Settings Apply at the Process Level. 
-> Configuration settings are applied at the process level, which means that they are applied to all applications that are part of the same process. This is due to the fact that configuration properties are defined as static fields, which are static for the process.
+---
+
+## Configuration Scopes
 
-## Configuration Types and Scopes
+Terminal.Gui uses three configuration scopes, each serving a different purpose:
 
-Terminal.Gui supports three main configuration scopes. See the section below titled [What Can Be Configured](#what-can-be-configured) for more details.
+### 1. SettingsScope
 
-### SettingsScope
+System-level settings that affect Terminal.Gui behavior. Only Terminal.Gui library developers can define [SettingsScope](~/api/Terminal.Gui.Configuration.SettingsScope.yml) properties.
 
-System-level settings that affect Terminal.Gui behavior:
 ```csharp
-[ConfigurationProperty (Scope = typeof (SettingsScope))]
-public static int MaxSearchResults { get; set; } = 10000;
+[ConfigurationProperty(Scope = typeof(SettingsScope))]
+public static bool Force16Colors { get; set; } = false;
 ```
 
-### ThemeScope
-Visual appearance settings that can be themed:
+**Examples:**
+- `Application.QuitKey` - Default key to quit applications
+- `Application.Force16Colors` - Force 16-color mode
+- `Key.Separator` - Character separating keys in key combinations
+
+### 2. ThemeScope
+
+Visual appearance settings that can be themed. Only Terminal.Gui library developers can define [ThemeScope](~/api/Terminal.Gui.Configuration.ThemeScope.yml) properties.
+
 ```csharp
- [ConfigurationProperty (Scope = typeof (ThemeScope))]
- public new static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
+[ConfigurationProperty(Scope = typeof(ThemeScope))]
+public static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
 ```
 
-### AppSettingsScope (default)
-Application-specific settings:
+**Examples:**
+- `Window.DefaultBorderStyle` - Default border style for windows
+- `Dialog.DefaultShadow` - Default shadow style for dialogs
+- `Schemes` - Color schemes for the theme
+
+### 3. AppSettingsScope (Default)
+
+Application-specific settings. Application developers can define [AppSettingsScope](~/api/Terminal.Gui.Configuration.AppSettingsScope.yml) properties for their apps.
+
 ```csharp
 [ConfigurationProperty] // AppSettingsScope is default
-public static string MyAppSetting { get; set; } = "default";
+public static string MyAppSetting { get; set; } = "default value";
 ```
 
-## Configuration Precedence
+**Important:** 
+- App developers **cannot** define `SettingsScope` or `ThemeScope` properties
+- AppSettings property names must be globally unique (automatically prefixed with class name)
+
+---
+
+## Configuration Locations and Precedence
+
+Configuration is loaded from multiple locations with increasing precedence (higher numbers override lower):
+
+### ConfigLocations Enum
+
+[ConfigLocations](~/api/Terminal.Gui.Configuration.ConfigLocations.yml) specifies where configuration can be loaded from:
+
+1. **[ConfigLocations.HardCoded](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)** (Lowest Precedence)
+   - Default values in code (static property initializers)
+   - Always available, even when ConfigurationManager is disabled
+
+2. **[ConfigLocations.LibraryResources](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - Settings in `Terminal.Gui.dll` resources (`Terminal.Gui.Resources.config.json`)
+   - Defines default themes and settings for the library
+
+3. **[ConfigLocations.Runtime](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - Settings in [ConfigurationManager.RuntimeConfig](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml#Terminal_Gui_Configuration_ConfigurationManager_RuntimeConfig) string property
+   - In-memory configuration without files
+
+4. **[ConfigLocations.AppResources](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - App-specific resources (`MyApp.Resources.config.json` or `Resources/config.json`)
+   - Embedded in the application assembly
+
+5. **[ConfigLocations.AppHome](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - App-specific file in user's home directory (`~/.tui/MyApp.config.json`)
+
+6. **[ConfigLocations.AppCurrent](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - App-specific file in current directory (`./.tui/MyApp.config.json`)
+
+7. **[ConfigLocations.GlobalHome](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)**
+   - Global file in user's home directory (`~/.tui/config.json`)
+
+8. **[ConfigLocations.GlobalCurrent](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)** (Highest Precedence)
+   - Global file in current directory (`./.tui/config.json`)
+
+### Precedence Diagram
 
 ```mermaid
 graph TD
-    A[Hard-coded Defaults] --> B[Terminal.Gui Defaults]
-    B --> C[Runtime Config]
-    C --> D[App Resources]
-    D --> E[App Home Directory]
-    E --> F[App Current Directory]
-    F --> G[Global Home Directory]
-    G --> H[Global Current Directory]
+    A[1. Hard-coded Defaults] --> B[2. Library Resources]
+    B --> C[3. Runtime Config]
+    C --> D[4. App Resources]
+    D --> E[5. App Home Directory]
+    E --> F[6. App Current Directory]
+    F --> G[7. Global Home Directory]
+    G --> H[8. Global Current Directory]
+    
+    style A fill:#f9f9f9
+    style H fill:#90EE90
 ```
 
-Settings are applied using the following precedence (higher precedence settings overwrite lower precedence settings):
+### File Locations
 
-1. @Terminal.Gui.Configuration.ConfigLocations.HardCoded Hard-coded default values in any static property decorated with the `[ConfigurationProperty]` attribute.
+**Global Settings** (`config.json`):
+- Windows: `C:\Users\username\.tui\config.json`
+- macOS/Linux: `~/.tui/config.json` or `./.tui/config.json`
 
-2. @Terminal.Gui.Configuration.ConfigLocations.LibraryResources - Default settings in the Terminal.Gui assembly -- Lowest precedence.
+**App-Specific Settings** (`AppName.config.json`):
+- Windows: `C:\Users\username\.tui\UICatalog.config.json`
+- macOS/Linux: `~/.tui/UICatalog.config.json` or `./.tui/UICatalog.config.json`
 
-3. @Terminal.Gui.Configuration.ConfigLocations.Runtime - Settings stored in the @Terminal.Gui.Configuration.ConfigurationManager.RuntimeConfig static property.
+---
 
-4. @Terminal.Gui.Configuration.ConfigLocations.AppResources - App settings in app resources (`Resources/config.json`).
+## Themes and Schemes
 
-5. @Terminal.Gui.Configuration.ConfigLocations.AppHome - App-specific settings in the users's home directory (`~/.tui/appname.config.json`). 
+### Theme System
 
-6. @Terminal.Gui.Configuration.ConfigLocations.AppCurrent - App-specific settings in the directory the app was launched from (`./.tui/appname.config.json`).
+A **Theme** is a named collection of visual settings bundled together. Terminal.Gui includes several built-in themes.
 
-7. @Terminal.Gui.Configuration.ConfigLocations.GlobalHome - Global settings in the the user's home directory (`~/.tui/config.json`).
+#### Built-in Themes
 
-8. @Terminal.Gui.Configuration.ConfigLocations.GlobalCurrent - Global settings in the directory the app was launched from (`./.tui/config.json`) --- Hightest precedence.
+- **Default** - The default Terminal.Gui theme (matches hard-coded defaults)
+- **Dark** - Dark color scheme with heavy borders
+- **Light** - Light color scheme
+- **TurboPascal 5** - Classic Turbo Pascal IDE colors
+- **And more** - See `Terminal.Gui/Resources/config.json` for all built-in themes
 
+#### Using Themes
 
-The [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) will look for configuration files in the `.tui` folder in the user's home directory (e.g. `C:/Users/username/.tui` or `/usr/username/.tui`), the folder where the Terminal.Gui application was launched from (e.g. `./.tui`), or as a resource within the Terminal.Gui application's main assembly.
+```csharp
+// Get current theme
+ThemeScope currentTheme = ThemeManager.GetCurrentTheme();
 
-Settings that will apply to all applications (global settings) reside in files named `config.json`. Settings that will apply to a specific Terminal.Gui application reside in files named `appname.config.json`, where *appname* is the assembly name of the application (e.g. `UICatalog.config.json`).
+// Get all available themes
+Dictionary<string, ThemeScope> themes = ThemeManager.GetThemes();
+
+// Get theme names
+ImmutableList<string> themeNames = ThemeManager.GetThemeNames();
 
+// Switch themes
+ThemeManager.Theme = "Dark";
+ConfigurationManager.Apply();
 
-## Configuration Events
+// Listen for theme changes
+ThemeManager.ThemeChanged += (sender, e) => 
+{
+    // Update UI based on new theme
+};
+```
 
-The ConfigurationManager provides several events to track configuration changes:
+### Scheme System
+
+A **Scheme** defines the colors and text styles for a specific UI context (e.g., Dialog, Menu, TopLevel).
+
+See the [Scheme Deep Dive](scheme.md) for complete details on the scheme system.
+
+#### Built-in Schemes
+
+[Schemes](~/api/Terminal.Gui.Drawing.Schemes.yml) enum defines the standard schemes:
+
+- **TopLevel** - Top-level application windows
+- **Base** - Default for most views
+- **Dialog** - Dialogs and message boxes
+- **Menu** - Menus and status bars
+- **Error** - Error messages and dialogs
+
+#### Working with Schemes
 
 ```csharp
-// Called after configuration is applied
-ConfigurationManager.Applied += (sender, e) => {
-    // Handle configuration changes
-};
+// Get all schemes for current theme
+Dictionary<string, Scheme> schemes = SchemeManager.GetCurrentSchemes();
+
+// Get specific scheme
+Scheme dialogScheme = SchemeManager.GetScheme(Schemes.Dialog);
 
-// Called when the active theme changes
-ConfigurationManager.ThemeChanged += (sender, e) => {
-    // Handle theme changes
+// Get scheme names
+ImmutableList<string> schemeNames = SchemeManager.GetSchemeNames();
+
+// Add custom scheme
+SchemeManager.AddScheme("MyScheme", new Scheme
+{
+    Normal = new Attribute(Color.White, Color.Blue),
+    Focus = new Attribute(Color.Black, Color.Cyan)
+});
+
+// Listen for scheme changes
+SchemeManager.CollectionChanged += (sender, e) => 
+{
+    // Handle scheme changes
 };
 ```
 
+#### Scheme Structure
 
-## How Settings are Defined 
+Each [Scheme](~/api/Terminal.Gui.Drawing.Scheme.yml) maps [VisualRole](~/api/Terminal.Gui.Drawing.VisualRole.yml) to [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml):
 
-Application developers define settings by decorating static properties with the `[ConfigurationProperty]` attribute.
+```json
+{
+  "TopLevel": {
+    "Normal": {
+      "Foreground": "BrightGreen",
+      "Background": "Black",
+      "Style": "None"
+    },
+    "Focus": {
+      "Foreground": "White",
+      "Background": "Cyan",
+      "Style": "Bold"
+    },
+    "HotNormal": {
+      "Foreground": "Yellow",
+      "Background": "Black"
+    },
+    "HotFocus": {
+      "Foreground": "Blue",
+      "Background": "Cyan",
+      "Style": "Underline"
+    },
+    "Disabled": {
+      "Foreground": "DarkGray",
+      "Background": "Black",
+      "Style": "Faint"
+    }
+  }
+}
+```
+
+---
+
+## Defining Configuration Properties
+
+### Basic Property Definition
+
+Application developers define settings using the [ConfigurationPropertyAttribute](~/api/Terminal.Gui.Configuration.ConfigurationPropertyAttribute.yml):
 
 ```csharp
-class MyApp
+public class MyApp
 {
     [ConfigurationProperty]
     public static string MySetting { get; set; } = "Default Value";
+    
+    [ConfigurationProperty]
+    public static int MaxItems { get; set; } = 100;
 }
 ```
 
-Configuration Properties must be `public` or `internal` `static` properties.
+**Requirements:**
+- Must be `public` or `internal`
+- Must be `static`
+- Must be a property (not a field)
+- Must have a default value
 
-The above example will define a configuration property in the `AppSettings` scope. The name of the property will be `MyApp.MySetting` and will appear in JSON as:
+### Property Naming
 
-```json
+AppSettings properties are automatically prefixed with the class name to ensure global uniqueness:
+
+```csharp
+// Code
+public class MyApp
 {
-    "AppSettings": {
-      "MyApp.MySetting": "Default Value"
-    }
+    [ConfigurationProperty]
+    public static string MySetting { get; set; } = "value";
+}
+
+// JSON
+{
+  "AppSettings": {
+    "MyApp.MySetting": "value"
+  }
 }
 ```
 
-`AppSettings` property names must be globally unique. To ensure this, the name of the AppSettings property is the name of the property prefixed with a period and the full name of the class that holds it. In the example above, the AppSettings property is named `MyApp.MySetting`.
+### Scope Specification
+
+Use the `Scope` parameter to specify non-default scopes (Terminal.Gui library only):
+
+```csharp
+// SettingsScope - Library-wide settings
+[ConfigurationProperty(Scope = typeof(SettingsScope))]
+public static bool Force16Colors { get; set; } = false;
+
+// ThemeScope - Visual settings
+[ConfigurationProperty(Scope = typeof(ThemeScope))]
+public static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
 
-Terminal.Gui library developers can use the `SettingsScope` and `ThemeScope` attributes to define settings and themes for the terminal.Gui library.
+// AppSettingsScope - Application settings (default)
+[ConfigurationProperty] // or explicitly: Scope = typeof(AppSettingsScope)
+public static string MyAppSetting { get; set; } = "default";
+```
+
+### Omit Class Name (Advanced)
 
-> [!IMPORTANT] 
-App developers cannot define `SettingScope` or `ThemeScope` properties.
+For library developers only, use `OmitClassName = true` for cleaner JSON:
 
 ```csharp
-    /// <summary>
-    ///     Gets or sets whether <see cref="Button"/>s are shown with a shadow effect by default.
-    /// </summary>
-    [ConfigurationProperty (Scope = typeof (ThemeScope))]
-    public static ShadowStyle DefaultShadow { get; set; } = ShadowStyle.None;
+[ConfigurationProperty(Scope = typeof(ThemeScope), OmitClassName = true)]
+public static Dictionary<string, Scheme> Schemes { get; set; } = new();
 ```
 
-# Sample Code
+---
 
-The `UICatalog` application provides an example of how to use the [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) class to load and save configuration files. 
+## Loading and Applying Configuration
 
-The `Configuration Editor` Scenario provides an editor that allows users to edit the configuration files. UI Catalog also uses a file system watcher to detect changes to the configuration files to tell [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) to reload them; allowing users to change settings without having to restart the application.
+### Enable with Load and Apply
 
-The `Themes` Scenario in the UI Catalog provides a viewer for the themes defined in the configuration files.
+The simplest approach - enable and load in one call:
 
-# What Can Be Configured
+```csharp
+ConfigurationManager.Enable(ConfigLocations.All);
+```
 
-`ConfigurationManager` provides the following features:
+This:
+1. Enables ConfigurationManager
+2. Loads configuration from all locations
+3. Applies settings to the application
 
-1) **Settings**. Settings are applied to the [`Application`](~/api/Terminal.Gui.App.Application.yml) class. Settings are accessed via the `Settings` property of [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml). E.g. `Settings["Application.QuitKey"]`
-2) **Themes**. Themes are a named collection of settings impacting how applications look. The default theme is named "Default". Two other built-in themes are provided: "Dark", and "Light". Additional themes can be defined in the configuration files. `Settings ["Themes"]` is a dictionary of theme names to theme settings.
-3) **AppSettings**. Applications can use the [`ConfigurationManager`](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) to store and retrieve application-specific settings.
+### Granular Control
 
-Methods for discovering what can be configured are available in the `ConfigurationManager` class:
+For more control, use [Load](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml#Terminal_Gui_Configuration_ConfigurationManager_Load_Terminal_Gui_Configuration_ConfigLocations_) and [Apply](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml#Terminal_Gui_Configuration_ConfigurationManager_Apply) separately:
 
-- Call @Terminal.Gui.Configuration.ConfigurationManager.GetHardCodedConfig()
-- Search the source code for `[ConfigurationProperty]` 
+```csharp
+// Enable without loading
+ConfigurationManager.Enable(ConfigLocations.None);
 
-For complete schema details and examples, refer to:
-- Schema: https://gui-cs.github.io/Terminal.GuiV2Docs/schemas/tui-config-schema.json
-- Default configuration: Terminal.Gui/Resources/config.json
+// Load from specific locations
+ConfigurationManager.Load(ConfigLocations.GlobalHome | ConfigLocations.AppResources);
 
-## Themes
+// Apply settings
+ConfigurationManager.Apply();
+```
 
-A Theme is a named collection of settings that impact the visual style of Terminal.Gui applications. The default theme is named "Default". The built-in configuration within the Terminal.Gui library defines two more themes: "Dark", and "Light". Additional themes can be defined in the configuration files. The JSON property `Theme` defines the name of the theme that will be used. If the theme is not found, the default theme will be used.
+### Runtime Configuration
 
-Themes support defining Schemes (a set of colors and styles that define the appearance of views) as well as various default settings for Views. Both the default color schemes and user-defined color schemes can be configured. See [Schemes](~/api/Terminal.Gui.Drawing.Schemes.yml) for more information.
+Set configuration directly in code without files:
 
-### Theme Configuration
+```csharp
+ConfigurationManager.RuntimeConfig = @"
+{
+  ""Application.QuitKey"": ""Ctrl+Q"",
+  ""Application.Force16Colors"": true
+}";
 
-Themes provide a way to bundle visual settings together. When @Terminal.Gui.Configuration.ConfigurationManager.Apply is called, the theme settings are applied to the application. 
+ConfigurationManager.Enable(ConfigLocations.Runtime);
+```
 
-```json
-// ...
- "Dark": {
-   "Dialog.DefaultButtonAlignment": "End",
-   "Dialog.DefaultButtonAlignmentModes": "AddSpaceBetweenItems",
-   "Dialog.DefaultBorderStyle": "Heavy",
-   "Dialog.DefaultShadow": "Transparent",
-   "FrameView.DefaultBorderStyle": "Single",
-   "Window.DefaultBorderStyle": "Single",
-   "MessageBox.DefaultButtonAlignment": "Center",
-   "MessageBox.DefaultBorderStyle": "Heavy",
-   "Button.DefaultShadow": "Opaque",
-   "Schemes": [
-     {
-       "TopLevel": {
-         "Normal": {
-           "Foreground": "LightGray",
-           "Background": "Black",
-           "Style": "None"
-         },
-// etc...
-```
-
-Only properties that are defined in the theme will be applied, meaning that themes can be used to override the a previously applied theme.
-
-To ensure a theme inherits from the default theme, first apply the default theme, then apply the new theme, like this:
-
-```csharp
-// Apply the default theme
-  ThemeManager.Theme = "Default";
-ConfigurationManager.Apply();
+### Reset to Defaults
 
-// Apply the new theme
-ThemeManager.Theme = "MyCustomTheme";
-ConfigurationManager.Apply();
+Reset all settings to hard-coded defaults:
+
+```csharp
+ConfigurationManager.ResetToHardCodedDefaults();
 ```
 
-### Glyphs
+---
+
+## Events
+
+The ConfigurationManager provides events to track configuration changes:
+
+### Applied Event
+
+Raised after configuration is applied to the application:
+
+```csharp
+ConfigurationManager.Applied += (sender, e) => 
+{
+    // Configuration has been applied
+    // Update UI or refresh views
+};
+```
 
-Themes support changing the standard set of glyphs used by views (e.g. the default indicator for [Button](~/api/Terminal.Gui.Views.Button.yml)) and line drawing (e.g. [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml)).
+### ThemeChanged Event
 
+Raised when the active theme changes:
 
-The value can be either a decimal number or a string. The string may be:
+```csharp
+ThemeManager.ThemeChanged += (sender, e) => 
+{
+    // Theme has changed
+    // Refresh all views to use new theme
+    Application.Top?.SetNeedsDraw();
+};
+```
+
+### CollectionChanged Event
+
+Raised when schemes collection changes:
+
+```csharp
+SchemeManager.CollectionChanged += (sender, e) => 
+{
+    // Schemes have changed
+};
+```
+
+---
+
+## What Can Be Configured
+
+### Application Settings
+
+System-wide settings from [SettingsScope](~/api/Terminal.Gui.Configuration.SettingsScope.yml):
+
+```json
+{
+  "Application.QuitKey": "Esc",
+  "Application.Force16Colors": false,
+  "Application.IsMouseDisabled": false,
+  "Application.ArrangeKey": "Ctrl+F5",
+  "Application.NextTabKey": "Tab",
+  "Application.PrevTabKey": "Shift+Tab",
+  "Application.NextTabGroupKey": "F6",
+  "Application.PrevTabGroupKey": "Shift+F6",
+  "Key.Separator": "+"
+}
+```
+
+### View-Specific Settings
+
+Settings for individual View types from [ThemeScope](~/api/Terminal.Gui.Configuration.ThemeScope.yml):
+
+```json
+{
+  "Window.DefaultBorderStyle": "Single",
+  "Window.DefaultShadow": "None",
+  "Dialog.DefaultBorderStyle": "Heavy",
+  "Dialog.DefaultShadow": "Transparent",
+  "Dialog.DefaultButtonAlignment": "End",
+  "FrameView.DefaultBorderStyle": "Rounded",
+  "Button.DefaultShadow": "None",
+  "PopoverMenu.DefaultKey": "Shift+F10",
+  "FileDialog.MaxSearchResults": 10000
+}
+```
+
+### Glyphs
 
-- A Unicode char (e.g. "☑")
-- A hex value in U+ format (e.g. "U+2611")
-- A hex value in UTF-16 format (e.g. "\\u2611")
+Customize the Unicode characters used for drawing:
 
 ```json
+{
   "Glyphs.RightArrow": "►",
   "Glyphs.LeftArrow": "U+25C4",
   "Glyphs.DownArrow": "\\u25BC",
-  "Glyphs.UpArrow": 965010
+  "Glyphs.UpArrow": 965010,
+  "Glyphs.LeftBracket": "[",
+  "Glyphs.RightBracket": "]",
+  "Glyphs.Checked": "☑",
+  "Glyphs.UnChecked": "☐",
+  "Glyphs.Selected": "◉",
+  "Glyphs.UnSelected": "○"
+}
 ```
 
-The `UI Catalog` application defines a `UICatalog` Theme. Look at the UI Catalog's `./Resources/config.json` file to see how to define a theme.
-
-### Theme and Scheme Management
+Glyphs can be specified as:
+- Unicode character: `"►"`
+- U+ format: `"U+25C4"`
+- UTF-16 format: `"\\u25BC"`
+- Decimal codepoint: `965010`
 
-Terminal.Gui provides two key managers for handling visual themes and schemes:
+### Discovering Configuration Properties
 
-The ThemeManager provides convenient methods for working with themes:
+To find all available configuration properties:
 
 ```csharp
-// Get the currently active theme
-ThemeScope currentTheme = ThemeManager.GetCurrentTheme();
+// Get hard-coded configuration
+SettingsScope hardCoded = ConfigurationManager.GetHardCodedConfig();
 
-// Get all available themes
-Dictionary<string, ThemeScope> themes = ThemeManager.GetThemes();
+// Iterate through all properties
+foreach (var property in hardCoded)
+{
+    Console.WriteLine($"{property.Key} = {property.Value}");
+}
+```
 
-// Get list of theme names
-ImmutableList<string> themeNames = ThemeManager.GetThemeNames();
+Or search the source code for `[ConfigurationProperty]` attributes.
 
-// Get/Set current theme name
-string currentThemeName = ThemeManager.GetCurrentThemeName();
-ThemeManager.Theme = "Dark"; // Switch themes
+---
 
-// Listen for theme changes
-ThemeManager.ThemeChanged += (sender, e) => {
-    // Handle theme changes
-};
+## Themes and Schemes
+
+### Theme Structure
+
+A theme is a named collection bundling visual settings and schemes:
+
+```json
+{
+  "Themes": [
+    {
+      "Dark": {
+        "Dialog.DefaultBorderStyle": "Heavy",
+        "Dialog.DefaultShadow": "Transparent",
+        "Window.DefaultBorderStyle": "Single",
+        "Button.DefaultShadow": "Opaque",
+        "Schemes": [
+          {
+            "TopLevel": {
+              "Normal": { "Foreground": "BrightGreen", "Background": "Black" },
+              "Focus": { "Foreground": "White", "Background": "Cyan" }
+            },
+            "Dialog": {
+              "Normal": { "Foreground": "Black", "Background": "Gray" }
+            }
+          }
+        ]
+      }
+    }
+  ]
+}
 ```
 
-### SchemeManager
+### Creating Custom Themes
 
-The SchemeManager handles schemes within themes. Each theme contains multiple schemes for different UI contexts:
+Custom themes can be defined in configuration files:
+
+```json
+{
+  "Themes": [
+    {
+      "MyCustomTheme": {
+        "Window.DefaultBorderStyle": "Double",
+        "Dialog.DefaultShadow": "Opaque",
+        "Schemes": [
+          {
+            "Base": {
+              "Normal": {
+                "Foreground": "Cyan",
+                "Background": "Black",
+                "Style": "Bold"
+              }
+            }
+          }
+        ]
+      }
+    }
+  ]
+}
+```
+
+Then activate the theme:
 
 ```csharp
-// Get current schemes
-Dictionary<string, Scheme> schemes = SchemeManager.GetCurrentSchemes();
+ThemeManager.Theme = "MyCustomTheme";
+ConfigurationManager.Apply();
+```
 
-// Get list of scheme names
-ImmutableList<string> schemeNames = SchemeManager.GetSchemeNames();
+### Theme Inheritance
 
-// Access specific schemes
-Scheme topLevelScheme = SchemeManager.GetScheme("TopLevel");
+Themes only override specified properties. To build on an existing theme:
 
-// Listen for scheme changes
-SchemeManager.CollectionChanged += (sender, e) => {
-    // Handle scheme changes
-};
+```csharp
+// Start with default theme
+ThemeManager.Theme = "Default";
+ConfigurationManager.Apply();
+
+// Apply custom theme (overrides only what's specified)
+ThemeManager.Theme = "MyCustomTheme";
+ConfigurationManager.Apply();
 ```
 
-### Built-in Schemes
+### TextStyle in Schemes
 
-The following Schemes are available by default:
+Each [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml) in a scheme now includes [TextStyle](~/api/Terminal.Gui.Drawing.TextStyle.yml):
 
-- **TopLevel**: Used for the application's top-level windows
-- **Base**: Default scheme for most views
-- **Dialog**: Used for dialogs and message boxes
-- **Menu**: Used for menus and status bars
-- **Error**: Used for error messages and dialogs
+```json
+{
+  "Normal": {
+    "Foreground": "White",
+    "Background": "Blue",
+    "Style": "Bold, Underline"
+  }
+}
+```
+
+Available styles (combinable):
+- `None`
+- `Bold`
+- `Faint`
+- `Italic`
+- `Underline`
+- `Blink`
+- `Reverse`
+- `Strikethrough`
 
-Each Scheme defines the attributes for different VisualRoles.
+---
 
-## Application Settings
+## Configuration File Format
 
-Terminal.Gui provides several top-level application settings:
+### Schema
+
+All configuration files must conform to the JSON schema:
+
+**Schema URL:** https://gui-cs.github.io/Terminal.Gui/schemas/tui-config-schema.json
+
+### Root Structure
 
 ```json
 {
-  "Key.Separator": "+",
-  "Application.ArrangeKey": "Ctrl+F5",
+  "$schema": "https://gui-cs.github.io/Terminal.Gui/schemas/tui-config-schema.json",
+  
+  // SettingsScope properties
+  "Application.QuitKey": "Esc",
   "Application.Force16Colors": false,
-  "Application.IsMouseDisabled": false,
-  "Application.NextTabGroupKey": "F6",
-  "Application.NextTabKey": "Tab",
-  "Application.PrevTabGroupKey": "Shift+F6",
-  "Application.PrevTabKey": "Shift+Tab",
-  "Application.QuitKey": "Esc"
+  
+  // Current theme name
+  "Theme": "Dark",
+  
+  // Theme definitions
+  "Themes": [
+    {
+      "Dark": {
+        // ThemeScope properties
+        "Window.DefaultBorderStyle": "Single",
+        // Schemes
+        "Schemes": [ ... ]
+      }
+    }
+  ],
+  
+  // AppSettings
+  "AppSettings": {
+    "MyApp.MySetting": "value"
+  }
 }
 ```
 
-### View-Specific Settings
+### Complete Example
 
-Examples of settings that control specific view behaviors:
+See the default configuration file:
 
-```json
+[!code-json[config.json](../../Terminal.Gui/Resources/config.json)]
+
+---
+
+## Best Practices
+
+### For Application Developers
+
+**1. Enable Early**
+
+Enable ConfigurationManager at the start of `Main()`, before `Application.Init()`:
+
+```csharp
+static void Main()
 {
-  "PopoverMenu.DefaultKey": "Shift+F10",
-  "FileDialog.MaxSearchResults": 10000,
-  "FileDialogStyle.DefaultUseColors": false,
-  "FileDialogStyle.DefaultUseUnicodeCharacters": false
+    ConfigurationManager.Enable(ConfigLocations.All);
+    Application.Init();
+    // ...
 }
 ```
 
-### Key Bindings
+**2. Use AppSettings for App Configuration**
+
+```csharp
+public class MyApp
+{
+    [ConfigurationProperty]
+    public static bool ShowWelcomeMessage { get; set; } = true;
+    
+    [ConfigurationProperty]
+    public static string DefaultDirectory { get; set; } = "";
+}
+```
+
+**3. Ship Default Configuration as Resource**
+
+Include a `Resources/config.json` file in your app:
+
+```xml
+<ItemGroup>
+  <EmbeddedResource Include="Resources\config.json" />
+</ItemGroup>
+```
+
+**4. Handle Configuration Changes**
+
+```csharp
+ConfigurationManager.Applied += (sender, e) => 
+{
+    // Refresh UI when configuration changes
+    RefreshAllViews();
+};
+```
+
+### For Library Developers
+
+**1. Use Appropriate Scopes**
+
+- `SettingsScope` - For system-wide behavior
+- `ThemeScope` - For visual appearance that should be themeable
+- Don't use `AppSettingsScope` in library code
+
+**2. Provide Meaningful Defaults**
+
+```csharp
+[ConfigurationProperty(Scope = typeof(ThemeScope))]
+public static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
+```
+
+**3. Document Configuration Properties**
+
+```csharp
+/// <summary>
+///     Gets or sets the default border style for all Windows.
+/// </summary>
+[ConfigurationProperty(Scope = typeof(ThemeScope))]
+public static LineStyle DefaultBorderStyle { get; set; } = LineStyle.Single;
+```
+
+### Process-Wide Settings
+
+> [!IMPORTANT]
+> Configuration settings are applied at the **process level**. 
+> 
+> Since configuration properties are static, changes affect all applications in the same process. This is typically not an issue for normal applications, but can affect scenarios with:
+> - Multiple Terminal.Gui apps in the same process
+> - Unit tests running in parallel
+> - Hot reload scenarios
 
-> [!WARNING]
->  Configuration Manager support for key bindings is not yet implemented.
+---
 
-Key bindings are defined in the `KeyBindings` property of the configuration file. The value is an array of objects, each object defining a key binding. The key binding object has the following properties:
+## Advanced Topics
 
-- `Key`: The key to bind to. The format is a string describing the key (e.g. "q", "Q,  "Ctrl+Q"). Function keys are specified as "F1", "F2", etc. 
+### JSON Error Handling
 
-# Error Handling
+Control how JSON parsing errors are handled:
 
 ```json
 {
-  "ConfigurationManager.ThrowOnJsonErrors": false
+  "ConfigurationManager.ThrowOnJsonErrors": true
 }
 ```
 
-Set to `true` to throw exceptions on JSON parsing errors instead of silent failures.
+- `false` (default) - Silent failures, errors logged
+- `true` - Throws exceptions on JSON parsing errors
+
+### Manually Trigger Updates
+
+Update ConfigurationManager to reflect current static property values:
+
+```csharp
+// Change a setting programmatically
+Application.QuitKey = Key.Q.WithCtrl;
+
+// Update ConfigurationManager to reflect the change
+ConfigurationManager.UpdateToCurrentValues();
+
+// Save to file (if needed)
+string json = ConfigurationManager.Serialize();
+File.WriteAllText("my-config.json", json);
+```
+
+### Disable ConfigurationManager
+
+Disable and optionally reset to defaults:
+
+```csharp
+// Disable but keep current settings
+ConfigurationManager.Disable(resetToHardCodedDefaults: false);
+
+// Disable and reset to hard-coded defaults
+ConfigurationManager.Disable(resetToHardCodedDefaults: true);
+```
+
+### File System Watching
+
+Watch for configuration file changes:
+
+```csharp
+var watcher = new FileSystemWatcher(
+    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".tui"));
+watcher.Filter = "*.json";
+watcher.Changed += (s, e) => 
+{
+    ConfigurationManager.Load(ConfigLocations.GlobalHome);
+    ConfigurationManager.Apply();
+};
+watcher.EnableRaisingEvents = true;
+```
+
+See UICatalog's `ConfigurationEditor` scenario for a complete example.
+
+---
+
+## Examples
+
+### Example 1: Simple Theme Switching
+
+```csharp
+using Terminal.Gui;
+using Terminal.Gui.Configuration;
+
+ConfigurationManager.Enable(ConfigLocations.All);
+Application.Init();
+
+var themeSelector = new ComboBox
+{
+    X = 1,
+    Y = 1,
+    Width = 20
+};
+themeSelector.SetSource(ThemeManager.GetThemeNames());
+themeSelector.SelectedItemChanged += (s, e) =>
+{
+    ThemeManager.Theme = e.Value.ToString();
+    ConfigurationManager.Apply();
+};
+
+Application.Run(new Window { Title = "Theme Demo" }).Add(themeSelector);
+Application.Shutdown();
+```
+
+### Example 2: Custom Application Settings
+
+```csharp
+public class MyApp
+{
+    [ConfigurationProperty]
+    public static string LastOpenedFile { get; set; } = "";
+    
+    [ConfigurationProperty]
+    public static int WindowWidth { get; set; } = 80;
+    
+    [ConfigurationProperty]
+    public static int WindowHeight { get; set; } = 25;
+}
+
+// Enable and use
+ConfigurationManager.Enable(ConfigLocations.All);
+
+// Settings are automatically loaded and applied
+var window = new Window
+{
+    Width = MyApp.WindowWidth,
+    Height = MyApp.WindowHeight
+};
+
+// Later, save updated settings
+MyApp.WindowWidth = 100;
+ConfigurationManager.UpdateToCurrentValues();
+// Could save to file here
+```
+
+### Example 3: Runtime Configuration
+
+```csharp
+ConfigurationManager.RuntimeConfig = @"
+{
+  ""Application.QuitKey"": ""Ctrl+Q"",
+  ""Application.Force16Colors"": true,
+  ""Theme"": ""Dark""
+}";
+
+ConfigurationManager.Enable(ConfigLocations.Runtime);
+
+// Settings are now applied
+// QuitKey is Ctrl+Q
+// 16-color mode is forced
+// Dark theme is active
+```
+
+---
+
+## See Also
 
-# Configuration File Schema
+- **[Scheme Deep Dive](scheme.md)** - Color scheme details
+- **[Drawing Deep Dive](drawing.md)** - Color and attribute system
+- **[View Deep Dive](View.md)** - View configuration properties
+- **[Theme Schema](https://gui-cs.github.io/Terminal.Gui/schemas/tui-config-schema.json)** - JSON schema for validation
+- **[Default Config](../../Terminal.Gui/Resources/config.json)** - Complete default configuration
 
-Settings are defined in JSON format, according to the schema found here:
+### UICatalog Examples
 
-https://gui-cs.github.io/Terminal.Gui/schemas/tui-config-schema.json
+The UICatalog application demonstrates configuration management:
 
-## The Default Config File
+- **Configuration Editor** - Interactive editor for configuration files
+- **Themes** - Theme viewer and selector
+- **File System Watcher** - Automatic reload on configuration file changes
 
-To illustrate the syntax, the below is the `config.json` file found in `Terminal.Gui.dll`:
+### API Reference
 
-[!code-json[config.json](../../Terminal.Gui/Resources/config.json)]
+- [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml)
+- [ConfigLocations](~/api/Terminal.Gui.Configuration.ConfigLocations.yml)
+- [SettingsScope](~/api/Terminal.Gui.Configuration.SettingsScope.yml)
+- [ThemeScope](~/api/Terminal.Gui.Configuration.ThemeScope.yml)
+- [AppSettingsScope](~/api/Terminal.Gui.Configuration.AppSettingsScope.yml)
+- [ThemeManager](~/api/Terminal.Gui.Configuration.ThemeManager.yml)
+- [SchemeManager](~/api/Terminal.Gui.Configuration.SchemeManager.yml)
+- [ConfigurationPropertyAttribute](~/api/Terminal.Gui.Configuration.ConfigurationPropertyAttribute.yml)

+ 25 - 7
docfx/docs/drivers.md

@@ -151,7 +151,7 @@ When `Application.Shutdown()` is called:
 
 ### IConsoleDriver
 
-The main driver interface that applications interact with. Provides:
+The main driver interface that the framework uses internally. Provides:
 
 - **Screen Management**: `Screen`, `Cols`, `Rows`, `Contents`
 - **Drawing Operations**: `AddRune()`, `AddStr()`, `Move()`, `FillRect()`
@@ -161,6 +161,12 @@ The main driver interface that applications interact with. Provides:
 - **Events**: `KeyDown`, `KeyUp`, `MouseEvent`, `SizeChanged`
 - **Platform Features**: `SupportsTrueColor`, `Force16Colors`, `Clipboard`
 
+**Note:** The driver is internal to Terminal.Gui. View classes should not access `Driver` directly. Instead:
+- Use @Terminal.Gui.App.Application.Screen to get screen dimensions
+- Use @Terminal.Gui.ViewBase.View.Move for positioning (with viewport-relative coordinates)
+- Use @Terminal.Gui.ViewBase.View.AddRune and @Terminal.Gui.ViewBase.View.AddStr for drawing
+- ViewBase infrastructure classes (in `Terminal.Gui/ViewBase/`) can access Driver when needed for framework implementation
+
 ### IConsoleDriverFacade
 
 Extended interface for v2 drivers that exposes the internal components:
@@ -215,18 +221,23 @@ This ensures Terminal.Gui applications can be debugged directly in Visual Studio
 - Captures output for verification
 - Always used when `Application._forceFakeConsole` is true
 
-## Example: Accessing Driver Components
+## Example: Checking Driver Capabilities
 
 ```csharp
 Application.Init();
 
-// Access the driver
-IConsoleDriver driver = Application.Driver;
+// The driver is internal - access through Application properties
+// Check screen dimensions
+var screenWidth = Application.Screen.Width;
+var screenHeight = Application.Screen.Height;
+
+// Check if 24-bit color is supported
+bool supportsTrueColor = Application.Driver?.SupportsTrueColor ?? false;
 
-// Check if it's a v2 driver with facade
-if (driver is IConsoleDriverFacade facade)
+// Access advanced components (for framework/infrastructure code only)
+if (Application.Driver is IConsoleDriverFacade facade)
 {
-    // Access individual components
+    // Access individual components for advanced scenarios
     IInputProcessor inputProcessor = facade.InputProcessor;
     IOutputBuffer outputBuffer = facade.OutputBuffer;
     IWindowSizeMonitor sizeMonitor = facade.WindowSizeMonitor;
@@ -239,6 +250,11 @@ if (driver is IConsoleDriverFacade facade)
 }
 ```
 
+**Important:** View subclasses should not access `Application.Driver`. Use the View APIs instead:
+- `View.Move(col, row)` for positioning
+- `View.AddRune()` and `View.AddStr()` for drawing
+- `Application.Screen` for screen dimensions
+
 ## Custom Drivers
 
 To create a custom driver, implement `IComponentFactory<T>`:
@@ -275,6 +291,8 @@ Application.Init();
 
 Terminal.Gui v1 drivers that implement `IConsoleDriver` but not `IConsoleDriverFacade` are still supported through a legacy compatibility layer. However, they do not benefit from the v2 architecture improvements (multi-threading, component separation, etc.).
 
+**Note**: The legacy `MainLoop` infrastructure (including the `MainLoop` class, `IMainLoopDriver` interface, and `FakeMainLoop`) has been removed in favor of the modern architecture. All drivers now use the `MainLoopCoordinator` and `ApplicationMainLoop` system exclusively.
+
 ## See Also
 
 - @Terminal.Gui.Drivers - API Reference

+ 38 - 9
docfx/docs/migratingfromv1.md

@@ -81,7 +81,7 @@ When measuring the screen space taken up by a `string` you can use the extension
 + myString.GetColumns();
 ```
 
-## `View Life Cycle Management
+## View Life Cycle Management
 
 In v1, @Terminal.Gui.View was derived from `Responder` which supported `IDisposable`. In v2, `Responder` has been removed and @Terminal.Gui.View is the base-class supporting `IDisposable`. 
 
@@ -187,7 +187,7 @@ The API for handling keyboard input is significantly improved. See [Keyboard API
 + Application.KeyDown(object? sender, Key e)
 ```
 
-## **@"Terminal.Gui.Input.Command" has been expanded and simplified
+## @Terminal.Gui.Input.Command has been expanded and simplified
 
 In v1, the `Command` enum had duplicate entries and inconsistent naming. In v2 it has been both expanded and simplified.
 
@@ -225,7 +225,7 @@ The cursor and focus system has been redesigned in v2 to be more consistent and
 
 ### Cursor
 
-In v1, whether the cursor (the flashing caret) was visible or not was controlled by `View.CursorVisibility` which was an enum extracted from Ncruses/Terminfo. It only works in some cases on Linux, and only partially with `WindowsDriver`. The position of the cursor was the same as `ConsoleDriver.Row`/`Col` and determined by the last call to `ConsoleDriver.Move`. `View.PositionCursor()` could be overridden by views to cause `Application` to call `ConsoleDriver.Move` on behalf of the app and to manage setting `CursorVisibility`. This API was confusing and bug-prone.
+In v1, whether the cursor (the flashing caret) was visible or not was controlled by `View.CursorVisibility` which was an enum extracted from Ncruses/Terminfo. It only works in some cases on Linux, and only partially with `WindowsDriver`. The position of the cursor was determined by the last call to the driver's Move method. `View.PositionCursor()` could be overridden by views to cause `Application` to call the driver's positioning method on behalf of the app and to manage setting `CursorVisibility`. This API was confusing and bug-prone.
 
 In v2, the API is (NOT YET IMPLEMENTED) simplified. A view simply reports the style of cursor it wants and the Viewport-relative location:
 
@@ -237,7 +237,7 @@ In v2, the API is (NOT YET IMPLEMENTED) simplified. A view simply reports the st
 	- If `null` the default cursor style is used.
 	- If `{}` specifies the style of cursor. See [cursor.md](cursor.md) for more.
 * `Application` now has APIs for querying available cursor styles.
-* The details in `ConsoleDriver` are no longer available to applications.	
+* The driver details are no longer directly accessible to View subclasses.	
 
 #### How to Fix (Cursor API)
 
@@ -245,6 +245,26 @@ In v2, the API is (NOT YET IMPLEMENTED) simplified. A view simply reports the st
 * Set @Terminal.Gui.ViewBase.View.CursorVisibility to the cursor style you want to use.
 * Remove any overrides of `OnEnter` and `OnLeave` that explicitly change the cursor.
 
+### Driver Access
+
+In v1, Views could access `Driver` directly (e.g., `Driver.Move()`, `Driver.Rows`, `Driver.Cols`). In v2, `Driver` is internal and View subclasses should not access it directly. ViewBase provides all necessary abstractions for Views to function without needing direct driver access.
+
+#### How to Fix (Driver Access)
+
+* Replace `Driver.Rows` and `Driver.Cols` with @Terminal.Gui.App.Application.Screen.Height and @Terminal.Gui.App.Application.Screen.Width
+* Replace direct `Driver.Move(screenX, screenY)` calls with @Terminal.Gui.ViewBase.View.Move using viewport-relative coordinates
+* Use @Terminal.Gui.ViewBase.View.AddRune and @Terminal.Gui.ViewBase.View.AddStr for drawing
+* ViewBase infrastructure classes (in `Terminal.Gui/ViewBase/`) can still access Driver for framework implementation needs
+
+```diff
+- if (x >= Driver.Cols) return;
++ if (x >= Application.Screen.Width) return;
+
+- Point screenPos = ViewportToScreen(new Point(col, row));
+- Driver.Move(screenPos.X, screenPos.Y);
++ Move(col, row);  // Move handles viewport-to-screen conversion
+```
+
 ### Focus
 
 See [navigation.md](navigation.md) for more details.
@@ -286,7 +306,7 @@ In v2, this is made consistent and configurable:
 - `Key.CursorDown` - Operates identically to `Application.NextTabStopKey`.
 - `Key.CursorLeft` - Operates identically to `Application.PrevTabStopKey`.
 - `Key.CursorUp` - Operates identically to `Application.PrevTabStopKey`.
-- `Application.NextTabGroupKey` (`Key.F6`) - Navigates to the next view in the view-hierarchy that is a `TabGroup` (see below). If there is no next, the first view which is a `TabGroup`` will gain focus.
+- `Application.NextTabGroupKey` (`Key.F6`) - Navigates to the next view in the view-hierarchy that is a `TabGroup` (see below). If there is no next, the first view which is a `TabGroup` will gain focus.
 - `Application.PrevTabGroupKey` (`Key.F6.WithShift`) - Opposite of `Application.NextTabGroupKey`.
 
 `F6` was chosen to match [Windows](https://learn.microsoft.com/en-us/windows/apps/design/input/keyboard-accelerators#common-keyboard-accelerators)
@@ -316,7 +336,7 @@ Alternatively, if you want to have key events as well as mouse events to fire an
 
 Previously events in Terminal.Gui used a mixture of `Action` (no arguments), `Action<string>` (or other raw datatype) and `Action<EventArgs>`. Now all events use the `EventHandler<EventArgs>` [standard .net design pattern](https://learn.microsoft.com/en-us/dotnet/csharp/event-pattern#event-delegate-signatures).
 
-For example, `event Action`<long> TimeoutAdded` has become `event EventHandler<TimeoutEventArgs> TimeoutAdded`
+For example, `event Action<long> TimeoutAdded` has become `event EventHandler<TimeoutEventArgs> TimeoutAdded`
 
 This change was made for the following reasons:
 
@@ -436,17 +456,26 @@ Additionally, the `Toggle` event was renamed `CheckStateChanging` and made cance
 +cb.AdvanceCheckState ();
 ```
 
-## `MainLoop` is no longer accessible from `Application`
+## `MainLoop` has been removed from `Application`
 
-In v1, you could add timeouts via `Application.MainLoop.AddTimeout` among other things.  In v2, the `MainLoop` object is internal to `Application` and methods previously accessed via `MainLoop` can now be accessed directly via `Application`
+In v1, you could add timeouts via `Application.MainLoop.AddTimeout` and access the `MainLoop` object directly. In v2, the legacy `MainLoop` class has been completely removed as part of the architectural modernization. Timeout functionality and other features previously accessed via `MainLoop` are now available directly through `Application` or `ApplicationImpl`.
 
 ### How to Fix
 
+Replace any `Application.MainLoop` references:
+
 ```diff
 - Application.MainLoop.AddTimeout (TimeSpan time, Func<MainLoop, bool> callback)
 + Application.AddTimeout (TimeSpan time, Func<bool> callback)
 ```
 
+```diff
+- Application.MainLoop.Wakeup ()
++ // No replacement needed - wakeup is handled automatically by the modern architecture
+```
+
+**Note**: The legacy `MainLoop` infrastructure (including `IMainLoopDriver` and `FakeMainLoop`) has been removed. The modern v2 architecture uses `ApplicationImpl`, `MainLoopCoordinator`, and `ApplicationMainLoop` instead.
+
 ## `SendSubViewXXX` renamed and corrected
 
 In v1, the `View` methods to move SubViews within the SubViews list were poorly named and actually operated in reverse of what their names suggested.
@@ -496,4 +525,4 @@ new (
 
 * In v1, `Application.End` called `Dispose ()` on @Terminal.Gui.App.Application.Top (via `Runstate.Toplevel`). This was incorrect as it meant that after `Application.Run` returned, `Application.Top` had been disposed, and any code that wanted to interrogate the results of `Run` by accessing `Application.Top` only worked by accident. This is because GC had not actually happened; if it had the application would have crashed. In v2 `Application.End` does NOT call `Dispose`, and it is the caller to `Application.Run` who is responsible for disposing the `Toplevel` that was either passed to `Application.Run (View)` or created by `Application.Run<T> ()`.
 
-* Any code that creates a `Toplevel`, either by using `top = new()` or by calling either `top = Application.Run ()` or `top = ApplicationRun<T>()` must call `top.Dispose` when complete. The exception to this is if `top` is passed to `myView.Add(top)` making it a subview of `myView`. This is because the semantics of `Add` are that the `myView` takes over responsibility for the subviews lifetimes. Of course, if someone calls `myView.Remove(top)` to remove said subview, they then re-take responsbility for `top`'s lifetime and they must call `top.Dispose`.
+* Any code that creates a `Toplevel`, either by using `top = new()` or by calling either `top = Application.Run ()` or `top = ApplicationRun<T>()` must call `top.Dispose` when complete. The exception to this is if `top` is passed to `myView.Add(top)` making it a subview of `myView`. This is because the semantics of `Add` are that the `myView` takes over responsibility for the subviews lifetimes. Of course, if someone calls `myView.Remove(top)` to remove said subview, they then re-take responsbility for `top`'s lifetime and they must call `top.Dispose`.

+ 4 - 4
docfx/docs/multitasking.md

@@ -89,7 +89,7 @@ public class ClockView : View
         Add(timeLabel);
         
         // Update every second
-        timerToken = Application.MainLoop.AddTimeout(
+        timerToken = Application.AddTimeout(
             TimeSpan.FromSeconds(1), 
             UpdateTime
         );
@@ -105,7 +105,7 @@ public class ClockView : View
     {
         if (disposing && timerToken != null)
         {
-            Application.MainLoop.RemoveTimeout(timerToken);
+            Application.RemoveTimeout(timerToken);
         }
         base.Dispose(disposing);
     }
@@ -220,7 +220,7 @@ Task.Run(() =>
 ### ❌ Don't: Forget to clean up timers
 ```csharp
 // Memory leak - timer keeps running after view is disposed
-Application.MainLoop.AddTimeout(TimeSpan.FromSeconds(1), UpdateStatus);
+Application.AddTimeout(TimeSpan.FromSeconds(1), UpdateStatus);
 ```
 
 ### ✅ Do: Remove timers in Dispose
@@ -229,7 +229,7 @@ protected override void Dispose(bool disposing)
 {
     if (disposing && timerToken != null)
     {
-        Application.MainLoop.RemoveTimeout(timerToken);
+        Application.RemoveTimeout(timerToken);
     }
     base.Dispose(disposing);
 }

+ 116 - 56
docfx/docs/newinv2.md

@@ -18,32 +18,44 @@ This architectural shift has resulted in the removal of thousands of lines of re
 ## Modern Look & Feel - Technical Details
 
 ### TrueColor Support
-- **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 `ConsoleDriver` 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.
-- **Usage**: See the `ColorPicker` view for an example of how TrueColor is leveraged to provide a rich color selection UI.
+
+See the [Drawing Deep Dive](drawing.md) for complete details on the color system.
+
+- **Implementation**: v2 introduces 24-bit color support by extending the [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml) class to handle RGB values, with fallback to 16-color mode for older terminals. This is evident in the [IConsoleDriver](~/api/Terminal.Gui.Drivers.IConsoleDriver.yml) 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](~/api/Terminal.Gui.Drawing.Color.yml) struct in v2 supports direct RGB input, and drivers handle the translation to terminal capabilities via [IConsoleDriver.SupportsTrueColor](~/api/Terminal.Gui.Drivers.IConsoleDriver.yml#Terminal_Gui_Drivers_IConsoleDriver_SupportsTrueColor).
+- **Usage**: See the [ColorPicker](~/api/Terminal.Gui.Views.ColorPicker.yml) view for an example of how TrueColor is leveraged to provide a rich color selection UI.
 
 ### Enhanced Borders and Padding (Adornments)
-- **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 `Border` property of type `Border`, which is itself a configurable entity with properties like `Thickness` and `Effect3D`.
+
+See the [Layout Deep Dive](layout.md) for complete details on the adornments system.
+
+- **Implementation**: v2 introduces a new [Adornment](~/api/Terminal.Gui.ViewBase.Adornment.yml) class hierarchy, with [Margin](~/api/Terminal.Gui.ViewBase.Margin.yml), [Border](~/api/Terminal.Gui.ViewBase.Border.yml), and [Padding](~/api/Terminal.Gui.ViewBase.Padding.yml) 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](~/api/Terminal.Gui.ViewBase.View.yml) had rudimentary border support via properties like `BorderStyle`. In v2, [View](~/api/Terminal.Gui.ViewBase.View.yml) has a [View.Border](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Border) property of type [Border](~/api/Terminal.Gui.ViewBase.Border.yml), which is itself a configurable entity with properties like [Thickness](~/api/Terminal.Gui.Drawing.Thickness.yml), [Border.LineStyle](~/api/Terminal.Gui.ViewBase.Border.yml#Terminal_Gui_ViewBase_Border_LineStyle), and [Border.Settings](~/api/Terminal.Gui.ViewBase.Border.yml#Terminal_Gui_ViewBase_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
-- **Implementation**: v2 adds a `ConfigurationManager` that supports loading and saving color schemes from configuration files. Themes are applied via `ColorScheme` objects, which can be customized per view or globally.
-- **Impact**: Unlike v1, where color schemes were static or required manual override, v2 enables end-users to personalize the UI without code changes, enhancing accessibility and user preference support.
+### User Configurable Color Themes and Text Styles
+
+See the [Configuration Deep Dive](config.md) and [Scheme Deep Dive](scheme.md) for complete details.
+
+- **Implementation**: v2 adds a [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) that supports loading and saving color schemes from configuration files. Themes are applied via [Scheme](~/api/Terminal.Gui.Drawing.Scheme.yml) objects, which can be customized per view or globally. Each [Attribute](~/api/Terminal.Gui.Drawing.Attribute.yml) in a [Scheme](~/api/Terminal.Gui.Drawing.Scheme.yml) now includes a [TextStyle](~/api/Terminal.Gui.Drawing.TextStyle.yml) 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.
+- **Implementation**: v2 improves Unicode handling by correctly managing wide characters in text rendering and input processing. The [TextFormatter](~/api/Terminal.Gui.Text.TextFormatter.yml) 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
-- **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` to draw clean, connected lines, a feature absent in v1.
+
+See the [Drawing Deep Dive](drawing.md) for complete details on LineCanvas and the drawing system.
+
+- **Implementation**: A new [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) 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](~/api/Terminal.Gui.Drawing.LineCanvas.yml) is used internally by views like [Border](~/api/Terminal.Gui.ViewBase.Border.yml) and [Line](~/api/Terminal.Gui.Views.Line.yml) 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`.
+- **Change**: v2 revisits every public API, consolidating redundant methods and properties. For example, v1 had multiple focus-related methods scattered across [View](~/api/Terminal.Gui.ViewBase.View.yml) and [Application](~/api/Terminal.Gui.App.Application.yml); v2 centralizes these in [ApplicationNavigation](~/api/Terminal.Gui.App.ApplicationNavigation.yml).
 - **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.
 
@@ -63,112 +75,160 @@ This architectural shift has resulted in the removal of thousands of lines of re
 - **Impact**: Developers can predict when resources are released, reducing bugs related to dangling references or uninitialized states.
 
 ### Adornments Framework
-- **Technical Detail**: Adornments are implemented as nested views that surround the content area, each with its own drawing and layout logic. For instance, `Border` can draw 3D effects or custom glyphs.
-- **Code Change**: In v2, `View` has properties like `Margin`, `Border`, and `Padding`, each configurable independently, unlike v1's limited border support.
+
+See the [Layout Deep Dive](layout.md) and [View Deep Dive](View.md) 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](~/api/Terminal.Gui.ViewBase.Border.yml) supports multiple [LineStyle](~/api/Terminal.Gui.Drawing.LineStyle.yml) options (Single, Double, Heavy, Rounded, Dashed, Dotted) with automatic line intersection handling via [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml).
+- **Code Change**: In v2, [View](~/api/Terminal.Gui.ViewBase.View.yml) has properties [View.Margin](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Margin), [View.Border](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Border), and [View.Padding](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_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](scrolling.md) and [Layout Deep Dive](layout.md) 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 `Viewport` rectangle representing the visible portion of a potentially larger content area defined by `GetContentSize()`. Changing `Viewport.Location` scrolls the content.
-- **Code Example**: In v2, `TextView` uses this to handle large text buffers without additional wrapper views.
+- **v2 Solution**: Every [View](~/api/Terminal.Gui.ViewBase.View.yml) in v2 has a [View.Viewport](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Viewport) rectangle representing the visible portion of a potentially larger content area defined by [View.GetContentSize](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_GetContentSize). Changing `Viewport.Location` scrolls the content.
+- **Code Example**: In v2, [TextView](~/api/Terminal.Gui.Views.TextView.yml) 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. `VerticalScrollBar` and `HorizontalScrollBar` properties on `View` enable scroll bars with minimal code.
+- **Change**: v2 replaces `ScrollBarView` with [ScrollBar](~/api/Terminal.Gui.Views.ScrollBar.yml), a cleaner implementation integrated with the built-in scrolling system. [View.VerticalScrollBar](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_VerticalScrollBar) and [View.HorizontalScrollBar](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_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
-- **DimAuto**: Automatically sizes views based on content or subviews, reducing manual layout calculations.
-- **PosAnchorEnd**: Allows anchoring to the right or bottom of a superview, enabling flexible layouts not easily achievable in v1.
-- **PosAlign**: Provides alignment options (left, center, right) for multiple views, streamlining UI design.
+
+See the [Layout Deep Dive](layout.md) and [DimAuto Deep Dive](dimauto.md) for complete details.
+
+- **[Dim.Auto](~/api/Terminal.Gui.Dim.yml#Terminal_Gui_Dim_Auto_Terminal_Gui_DimAutoStyle_Terminal_Gui_Dim_Terminal_Gui_Dim_)**: Automatically sizes views based on content or subviews, reducing manual layout calculations.
+- **[Pos.AnchorEnd](~/api/Terminal.Gui.Pos.yml#Terminal_Gui_Pos_AnchorEnd_System_Int32_)**: Allows anchoring to the right or bottom of a superview, enabling flexible layouts not easily achievable in v1.
+- **[Pos.Align](~/api/Terminal.Gui.Pos.yml)**: 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
-- **Technical Detail**: The `Arrangement` property on `View` supports flags like `Movable`, `Resizable`, and `Overlapped`, enabling dynamic UI interactions via keyboard and mouse.
-- **Code Example**: `Window` in v2 uses `Arrangement` to allow dragging and resizing, a feature requiring custom logic in v1.
+
+See the [Arrangement Deep Dive](arrangement.md) for complete details.
+
+- **Technical Detail**: The [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) property supports flags like [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), [ViewArrangement.Resizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), and [ViewArrangement.Overlapped](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml), enabling dynamic UI interactions via keyboard and mouse.
+- **Code Example**: [Window](~/api/Terminal.Gui.Views.Window.yml) in v2 uses [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_Arrangement) to allow dragging and resizing, a feature requiring custom logic in v1.
 - **Impact**: Developers can create desktop-like experiences in the terminal with minimal effort.
 
 ### Keyboard Navigation Overhaul
-- **v1 Issue**: Navigation was inconsistent, with coupled concepts like `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`.
+
+See the [Navigation Deep Dive](navigation.md) for complete details on the navigation system.
+
+- **v1 Issue**: Navigation was inconsistent, with coupled concepts like [View.CanFocus](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_CanFocus) and `TabStop` leading to unpredictable focus behavior.
+- **v2 Solution**: v2 decouples these concepts, introduces [TabBehavior](~/api/Terminal.Gui.Input.TabBehavior.yml) enum for clearer intent (`TabStop`, `TabGroup`, `NoStop`), and centralizes navigation logic in [ApplicationNavigation](~/api/Terminal.Gui.App.ApplicationNavigation.yml).
 - **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 `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.
+- **Implementation**: Any view can be made resizable or movable by setting [View.Arrangement](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_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](~/api/Terminal.Gui.Views.Window.yml) in v1.
 
 ## New and Improved Built-in Views - Detailed Analysis
 
+See the [Views Overview](views.md) for a complete catalog of all built-in views.
+
 ### New Views
-- **DatePicker**: Provides a calendar-based date selection UI, leveraging v2's improved drawing and navigation systems.
-- **Slider**: A new control for range selection, using `LineCanvas` for smooth rendering and supporting TrueColor for visual feedback.
-- **Shortcut**: An opinionated view for command display with key bindings, simplifying status bar or toolbar creation.
-- **Bar**: A foundational view for horizontal or vertical layouts of `Shortcut` or other items, used in `StatusBar`, `MenuBar`, and `PopoverMenu`.
-- **FileDialog**: Modernized with a `TreeView` for navigation, icons using Unicode glyphs, and search functionality, far surpassing v1's basic dialog.
-- **ColorPicker**: Leverages TrueColor for a comprehensive color selection experience, supporting multiple color models (HSV, RGB, HSL).
+
+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`, `MenuBarv2`, 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](CharacterMap.md).
+- **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).
+- **Menuv2 System** (MenuBarv2, PopoverMenu): A completely redesigned menu system built on the `Bar` infrastructure, providing a more flexible and visually appealing menu experience.
+- **NumericUpDown<T>**: 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
-- **ScrollView**: Deprecated in favor of built-in scrolling on `View`, reducing complexity and view hierarchy depth.
-- **TableView**: Now supports generic collections, checkboxes, and tree structures, moving beyond v1's `DataTable` limitation, with improved rendering performance.
-- **StatusBar**: Rebuilt on `Bar`, providing a more flexible and visually appealing status display.
+
+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](tableview.md).
+- **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
-- **Implementation**: Uses the `Border` adornment to render 3D effects or custom styles, configurable per view.
-- **Impact**: Adds visual depth to UI elements, making applications feel more polished compared to v1's flat borders.
+
+See the [Drawing Deep Dive](drawing.md) for complete details on borders and LineCanvas.
+
+- **Implementation**: Uses the [Border](~/api/Terminal.Gui.ViewBase.Border.yml) adornment with [LineStyle](~/api/Terminal.Gui.Drawing.LineStyle.yml) options and [LineCanvas](~/api/Terminal.Gui.Drawing.LineCanvas.yml) for automatic line intersection handling.
+- **Impact**: Adds visual polish to UI elements, making applications feel more refined compared to v1's basic borders.
 
 ### Gradient
-- **Implementation**: A new `Gradient` API allows rendering color transitions across view elements, using TrueColor for smooth effects.
+
+See the [Drawing Deep Dive](drawing.md) for complete details on gradients and fills.
+
+- **Implementation**: [Gradient](~/api/Terminal.Gui.Drawing.Gradient.yml) and [GradientFill](~/api/Terminal.Gui.Drawing.GradientFill.yml) 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
-- **Technical Detail**: `ConfigurationManager` in v2 uses JSON or other formats to persist settings like themes, key bindings, and view properties to disk.
-- **Code Change**: Unlike v1, where settings were ephemeral or hardcoded, v2 provides a centralized system for loading/saving configurations.
+
+See the [Configuration Deep Dive](config.md) for complete details on the configuration system.
+
+- **Technical Detail**: [ConfigurationManager](~/api/Terminal.Gui.Configuration.ConfigurationManager.yml) in v2 uses JSON to persist settings like themes, key bindings, and view properties to disk via [SettingsScope](~/api/Terminal.Gui.Configuration.SettingsScope.yml) and [ConfigLocations](~/api/Terminal.Gui.Configuration.ConfigLocations.yml).
+- **Code Change**: Unlike v1, where settings were ephemeral or hardcoded, v2 provides a centralized system for loading/saving configurations using the [ConfigurationManagerAttribute](~/api/Terminal.Gui.Configuration.ConfigurationManagerAttribute.yml).
 - **Impact**: Allows for user-specific customizations and library-wide settings without recompilation, enhancing flexibility.
 
 ## Logging & Metrics - Debugging and Performance
-- **Implementation**: v2 introduces a multi-level logging system for internal operations (e.g., rendering, input handling) and metrics for performance tracking (e.g., frame rate, redraw times).
-- **Impact**: Developers can diagnose issues like slow redraws or terminal compatibility problems, a capability absent in v1, reducing guesswork in debugging.
+
+See the [Logging Deep Dive](logging.md) for complete details on the logging and metrics system.
+
+- **Implementation**: v2 introduces a multi-level logging system via [Logging](~/api/Terminal.Gui.App.Logging.yml) for internal operations (e.g., rendering, input handling) using Microsoft.Extensions.Logging.ILogger, and metrics for performance tracking via [Logging.Meter](~/api/Terminal.Gui.App.Logging.yml#Terminal_Gui_App_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).
-- **Code Change**: New rendering logic in console drivers detects terminal support and handles Sixel data transmission.
+- **Technical Detail**: v2 supports the Sixel protocol for rendering images and animations directly in compatible terminals (e.g., Windows Terminal, xterm) via [SixelEncoder](~/api/Terminal.Gui.Drawing.SixelEncoder.yml).
+- **Code Change**: New rendering logic in console drivers detects terminal support via [SixelSupportDetector](~/api/Terminal.Gui.Drawing.SixelSupportDetector.yml) and handles Sixel data transmission through [SixelToRender](~/api/Terminal.Gui.Drawing.SixelToRender.yml).
 - **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](keyboard.md) and [Command Deep Dive](command.md) 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.
+- **Change**: Replaces v1's `KeyEvent` struct with a [Key](~/api/Terminal.Gui.Input.Key.yml) 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 and customize responses easily.
-- **Example**: `TextField` in v2 binds `Key.Tab` to text insertion rather than focus change, customizable by developers.
+- **Implementation**: v2 introduces a binding system mapping keys to [Command](~/api/Terminal.Gui.Input.Command.yml) enums via [View.KeyBindings](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_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](~/api/Terminal.Gui.ViewBase.View.yml) and customize responses easily.
+- **Example**: [TextField](~/api/Terminal.Gui.Views.TextField.yml) 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 `Toplevel` views.
+- **Change**: Changed from `Ctrl+Q` in v1 to `Esc` in v2 for closing apps or [Toplevel](~/api/Terminal.Gui.Views.Toplevel.yml) views, accessible via [Application.QuitKey](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_QuitKey).
 - **Impact**: Aligns with common user expectations, improving UX consistency across terminal applications.
 
 ## Updated Mouse API - Enhanced Interaction
 
-### MouseEvent Class
-- **Change**: Replaces `MouseEventEventArgs` with `MouseEvent`, providing a cleaner structure for mouse data (position, flags).
+See the [Mouse Deep Dive](mouse.md) for complete details on mouse handling.
+
+### MouseEventArgs Class
+- **Change**: Replaces v1's `MouseEventEventArgs` with [MouseEventArgs](~/api/Terminal.Gui.Input.MouseEventArgs.yml), providing a cleaner structure for mouse data (position, flags via [MouseFlags](~/api/Terminal.Gui.Input.MouseFlags.yml)).
 - **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, double-clicks, and movement, with flags for button states.
+- **Implementation**: v2 offers specific events for clicks ([View.MouseClick](~/api/Terminal.Gui.ViewBase.View.yml)), double-clicks, and movement, with [MouseFlags](~/api/Terminal.Gui.Input.MouseFlags.yml) 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
-- **Highlight**: Views can visually respond to mouse hover or click via the `Highlight` event.
-- **Continuous Presses**: Setting `WantContinuousButtonPresses = true` repeats `Command.Accept` during button hold, useful for sliders or buttons.
+- **Highlight**: Views can visually respond to mouse hover or click via the [View.Highlight](~/api/Terminal.Gui.ViewBase.View.yml) event and [View.HighlightStyle](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_HighlightStyle) property.
+- **Continuous Presses**: Setting [View.WantContinuousButtonPresses](~/api/Terminal.Gui.ViewBase.View.yml#Terminal_Gui_ViewBase_View_WantContinuousButtonPresses) = true repeats [Command.Accept](~/api/Terminal.Gui.Input.Command.yml) during button hold, useful for sliders or buttons.
 - **Impact**: Enhances interactive feedback, making terminal UIs feel more responsive.
 
 ## 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.
-- **Impact**: Simplifies deployment for environments requiring AOT (e.g., .NET Native), a feature not explicitly supported in v1, reducing runtime overhead.
+- **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](~/api/Terminal.Gui.Configuration.SourceGenerationContext.yml) 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
 

+ 6 - 6
docfx/includes/arrangement-lexicon.md

@@ -1,10 +1,10 @@
 | Term | Meaning |
 |:-----|:--------|
-| **Arrange Mode** | Interactive mode activated via `Ctrl+F5` that displays indicators on arrangeable views and allows keyboard-based arrangement. |
+| **Arrange Mode** | Interactive mode activated via `Ctrl+F5` (configurable via [Application.ArrangeKey](~/api/Terminal.Gui.App.Application.yml#Terminal_Gui_App_Application_ArrangeKey)) that displays indicators on arrangeable views and allows keyboard-based arrangement. |
 | **Arrangement** | The feature of [Layout](~/docs/layout.md) which controls how the user can use the mouse and keyboard to arrange views and enables either **Tiled** or **Overlapped** layouts. |
-| **Modal** | A view run as an "application" via @Terminal.Gui.App.Application.Run where `Modal == true`. Has constrained z-order with modal view at z-order 1. |
-| **Movable** | A View that can be moved by the user using keyboard or mouse. Enabled by setting @Terminal.Gui.ViewBase.ViewArrangement.Movable flag. |
-| **Overlapped** | Layout where SubViews have overlapping Frames with Z-order determining visual stacking. Enabled by @Terminal.Gui.ViewBase.ViewArrangement.Overlapped flag. |
-| **Resizable** | A View that can be resized by the user using keyboard or mouse. Enabled by setting @Terminal.Gui.ViewBase.ViewArrangement.Resizable flag. |
+| **Modal** | A view run as an "application" via [Application.Run](~/api/Terminal.Gui.App.Application.yml) where `Modal == true`. Has constrained z-order with modal view at z-order 1. |
+| **Movable** | A View that can be moved by the user using keyboard or mouse. Enabled by setting [ViewArrangement.Movable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) flag. |
+| **Overlapped** | Layout where SubViews have overlapping Frames with Z-order determining visual stacking. Enabled by [ViewArrangement.Overlapped](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) flag. |
+| **Resizable** | A View that can be resized by the user using keyboard or mouse. Enabled by setting [ViewArrangement.Resizable](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml) flag. |
 | **Runnable** | A view where `Application.Run(Toplevel)` is called. Each non-modal Runnable view has its own `RunState` and operates as a self-contained application. |
-| **Tiled** | Layout where SubViews typically do not overlap, with no z-order. Default layout mode set to @Terminal.Gui.ViewBase.ViewArrangement.Fixed. |
+| **Tiled** | Layout where SubViews typically do not overlap, with no z-order. Default layout mode set to [ViewArrangement.Fixed](~/api/Terminal.Gui.ViewBase.ViewArrangement.yml). |

BIN
local_packages/Terminal.Gui.2.0.0.nupkg


BIN
local_packages/Terminal.Gui.2.0.0.snupkg