Files
Terminal.Gui/docfx/docs/View.md
Copilot afa7da3ae5 Fixes #4078 - Implement automatic URL detection with OSC 8 hyperlinks at driver level (#4340)
* Initial plan

* Enable VT processing in WindowsOutput to support hyperlink detection

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Address code review feedback - track VT enablement and add error handling

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Revert VT processing changes - investigating actual root cause

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Implement OSC 8 hyperlink support in Attribute and OutputBase

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Implement automatic URL detection with OSC 8 at driver level

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Fix OSC 8 URL wrapping to handle ANSI escape sequences properly

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Update newinv2.md

Terminal.Gui v2 introduces a reimagined architecture, removing redundant and overly complex code from v1. Key changes include:

- Added TrueColor support with 24-bit RGB handling.
- Introduced modular adornments framework (Margin, Border, Padding).
- Enhanced Unicode and wide character support for internationalization.
- Simplified API with centralized navigation and modern .NET standards.
- Added built-in scrolling via `Viewport` and improved `ScrollBar`.
- Introduced new views (Bar, CharMap, ColorPicker, etc.) and enhanced existing ones.
- Added `ConfigurationManager` for customizable themes and settings.
- Improved visual fidelity with `LineCanvas`, gradients, and borders.
- Introduced logging, metrics, and Sixel image support.
- Enhanced keyboard and mouse APIs for better interaction handling.
- Ensured AOT compatibility for simplified deployment.

These changes modernize the library, improve usability, and expand its capabilities for terminal-based applications.

* Remove automatic URL detection - reverting to clean state

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Revamp View.md documentation for clarity and depth

Comprehensively restructured and enhanced the `View.md` documentation for the `Terminal.Gui` library to improve usability and completeness.

- Added a Table of Contents for easier navigation.
- Rewrote the "View Hierarchy" section to clarify terminology and key properties, with links to relevant API references.
- Expanded "View Composition" and "Core Concepts" sections with detailed explanations of layers, adornments, and scrolling.
- Detailed the "View Lifecycle" with step-by-step processes and code examples for initialization, layout, drawing, input handling, and disposal.
- Reorganized and expanded the "Subsystems" section, covering commands, input handling, layout, drawing, navigation, and scrolling.
- Updated the "Modal Views" section with examples for dialogs, wizards, and modal view types.
- Introduced a "Common View Patterns" section with practical examples for creating custom views, adding subviews, and implementing scrolling.
- Added an "Advanced Topics" section covering diagnostics, view states, and shadow effects.
- Included numerous inline code examples to illustrate key concepts.
- Concluded with a "See Also" section linking to related deep-dive documentation.

These changes significantly improve the structure, clarity, and accessibility of the documentation, making it easier for developers to understand and use the library effectively.

* Restore working automatic URL detection with fix for URLs containing ANSI sequences

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Fix URL regex to handle underscores and trailing punctuation + add comprehensive tests

Co-authored-by: tig <585482+tig@users.noreply.github.com>

* Update and expand Configuration Management documentation

The document title was updated to "Configuration Management Deep Dive" to reflect its expanded scope. A new Table of Contents was added for improved navigation. The introduction and "Overview" sections were rewritten to provide a clearer explanation of the `ConfigurationManager` class and its key features.

New sections were added, including "Getting Started," "Themes and Schemes," "Defining Configuration Properties," "Events," and "Best Practices." These sections provide detailed explanations, examples, and recommendations for using the `ConfigurationManager` effectively.

The "Configuration Scopes" and "Configuration Locations and Precedence" sections were restructured and expanded with detailed explanations, diagrams, and examples. Advanced topics such as JSON error handling, runtime configuration, and file system watching were introduced.

The document now includes several new examples, such as theme switching and custom application settings, along with references to related topics and UICatalog examples. The content was reorganized for clarity, with redundant sections removed.

* Refactor and expand Arrangement system documentation

Updated the title to "View Arrangement Deep Dive" and added a Table of Contents for better navigation. Expanded the "Overview" section and restructured "Arrangement Modes" with detailed examples. Added new sections for "Arrange Mode (Interactive)," "Movable Views," "Resizable Views," and "Creating Resizable Splitters," with practical code samples.

Enhanced "Tiled vs Overlapped Layouts" and "Modal Views" sections, and introduced "Runnable Views" to explain non-modal behavior. Expanded the "Examples" section with multiple use cases and added advanced topics like Z-order management and arrangement events.

Updated `arrangement-lexicon.md` with API links for key terms. Improved formatting and consistency throughout the document to enhance clarity and usability.

* Update CONTRIBUTING.md references and add critical note

Updated the reference to `CONTRIBUTING.md` to use a relative
path (`../CONTRIBUTING.md`) for accurate resolution. Enhanced
instructions for AI agents, including CoPilot and Cursor, to
strictly follow the updated guidelines. Added a **CRITICAL**
note requiring CoPilot to internalize and adhere to the
guidelines, including when operating in Agent mode.

* Refactor URL handling and add OSC 8 hyperlink support

Replaced `UrlRegex` with the new `Osc8UrlLinker` utility to handle URL detection and wrapping with OSC 8 hyperlink sequences, improving modularity and maintainability. Updated `OutputBase` to use `Osc8UrlLinker.WrapOsc8` for URL processing and removed legacy `WrapUrlsWithHyperlinks` logic.

Added the `Osc8UrlLinker` class with robust URL parsing, support for allowed schemes, and handling of edge cases like trailing punctuation and ANSI escape sequences. Improved performance with efficient `StringBuilder` usage.

Enhanced `AnimationScenario` to ensure URLs with underscores are drawn correctly. Improved code readability by renaming constants, simplifying nullable handling, and updating documentation.

Replaced legacy `UrlDetectionTests` with `Osc8UrlLinkerTests`, covering standalone URLs, URLs in text, multiple URLs, and edge cases. Verified hyperlink wrapping correctness and visible content integrity.

Updated `Terminal.sln.ToDo.DotSettings` to disable auto-opening of the Stack Trace Explorer. Cleaned up unused code, enabled nullable reference types, and improved XML documentation formatting.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: tig <585482+tig@users.noreply.github.com>
Co-authored-by: Tig <tig@users.noreply.github.com>
2025-10-26 13:03:17 -06:00

26 KiB

View Deep Dive

View 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.

See the Views Overview for a catalog of all built-in View subclasses.

Table of Contents


View Hierarchy

Terminology

  • View - 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
  • SuperView - The View that contains SubViews. Each View has a 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 - Read-only list of all SubViews added to this View
  • View.SuperView - The View's container (null if the View has no container)
  • View.Id - Unique identifier for the View (should be unique among siblings)
  • View.Data - Arbitrary data attached to the View

View Composition

Views are composed of several nested layers that define how they are positioned, drawn, and scrolled:

[!INCLUDE View Composition]

The Layers

  1. Frame - The outermost rectangle defining the View's location and size relative to the SuperView's content area
  2. Margin - Adornment that provides spacing between the View and other SubViews
  3. Border - Adornment that draws the visual border and title
  4. Padding - Adornment that provides spacing between the border and the viewport
  5. 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)

See the Layout Deep Dive 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
// 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 with a size larger than the Viewport
  2. Change Viewport.Location to scroll the content

See the Scrolling Deep Dive for complete details.

Adornments

Adornments are special Views that surround the content:

  • Margin - Transparent spacing outside the Border
  • Border - Visual frame with LineStyle, title, and arrangement UI
  • Padding - Spacing inside the Border, outside the Viewport

Each adornment has a Thickness that defines the width of each side (Top, Right, Bottom, Left).

See the Layout Deep Dive for complete details on adornments.


View Lifecycle

Initialization

Views implement ISupportInitializeNotification:

  1. Constructor - Creates the View and sets up default state
  2. BeginInit - Signals initialization is starting
  3. EndInit - Signals initialization is complete; raises View.Initialized event
  4. IsInitialized - Property indicating if initialization is complete

Disposal

Views are IDisposable:

  • Call View.Dispose to clean up resources
  • The View.Disposing 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.

Input Handling

Keyboard

See the Keyboard Deep Dive.

Mouse

See the Mouse Deep Dive.

Layout and Arrangement

See the Layout Deep Dive and Arrangement Deep Dive.

Position and Size

Layout Features

Arrangement

Events

  • LayoutStarted - Before layout begins
  • LayoutComplete - After layout completes
  • FrameChanged - When Frame changes
  • ViewportChanged - When Viewport changes

Drawing

See the Drawing Deep Dive.

Color and Style

See the Scheme Deep Dive for details on color theming.

Drawing Methods

Drawing Events

  • DrawingContent - Before content is drawn
  • DrawingContentComplete - After content is drawn
  • DrawingAdornments - Before adornments are drawn
  • DrawingAdornmentsComplete - After adornments are drawn

Invalidation

Navigation

See the Navigation Deep Dive.

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.

Text


View Lifecycle

1. Creation

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 is called:

  1. BeginInit is called
  2. EndInit is called
  3. IsInitialized becomes true
  4. Initialized event is raised

3. Layout

Layout happens automatically when needed:

  1. View.SetNeedsLayout marks View as needing layout
  2. View.Layout 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 marks View as needing redraw
  2. View.Draw renders the View
  3. DrawingContent event is raised
  4. View.OnDrawingContent 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

view.Dispose();
  • Raises View.Disposing event
  • Disposes adornments, scrollbars, SubViews
  • Cleans up event handlers and resources

Subsystems

Commands

See the Command Deep Dive for complete details.

Views use a command pattern for handling input:

// 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);

Input

Keyboard

See the Keyboard Deep Dive for complete details.

The keyboard subsystem processes key presses through:

  1. View.KeyDown event (cancellable)
  2. View.OnKeyDown virtual method
  3. View.KeyBindings - Converts keys to commands
  4. Command handlers (registered via View.AddCommand)
  5. View.KeyUp event

Mouse

See the Mouse Deep Dive for complete details.

The mouse subsystem processes mouse events through:

  1. View.MouseEvent event (low-level)
  2. View.OnMouseEvent virtual method
  3. View.MouseEnter / View.MouseLeave events
  4. View.MouseBindings - Converts mouse actions to commands
  5. Command handlers
  6. View.MouseClick event (high-level)

Layout

See the Layout Deep Dive for complete details.

Layout is declarative using Pos and Dim:

var label = new Label { Text = "Name:" };
var textField = new TextField 
{ 
    X = Pos.Right(label) + 1,
    Y = Pos.Top(label),
    Width = Dim.Fill()
};

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 for complete details.

Views draw themselves using viewport-relative coordinates:

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:

Navigation

See the Navigation Deep Dive for complete details.

Navigation controls keyboard focus movement:

Scrolling

See the Scrolling Deep Dive for complete details.

Scrolling is built into every View:

// 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;

Common View Patterns

Creating a Custom View

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
    }
}

Adding SubViews

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

var view = new View
{
    BorderStyle = LineStyle.Double,
    Title = "My View"
};

// Configure border
view.Border.Thickness = new Thickness(1);
view.Border.Settings = BorderSettings.Title;

// Add padding
view.Padding.Thickness = new Thickness(1);

// Add margin
view.Margin.Thickness = new Thickness(2);

Implementing Scrolling

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 for details.

Running a View Modally

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 - Base class for modal views, can fill entire screen
  • Window - Overlapped container with border and title
  • Dialog - Modal Window, centered with button support
  • Wizard - Multi-step modal dialog

Dialog Example

Dialogs are Modal Windows centered on screen:

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 let users step through multiple pages:

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 - ViewDiagnosticFlags for debugging:

  • Ruler - Shows a ruler around the View
  • DrawIndicator - Shows an animated indicator when drawing
  • FramePadding - Highlights the Frame with color

View States

Shadow Effects

View.ShadowStyle - ShadowStyle for drop shadows:

view.ShadowStyle = ShadowStyle.Transparent;

See Also