Skip to content

TerminalWidgetHandle

Namespace: Hex1b

Assembly: Hex1b.dll

A handle that connects a Hex1bTerminal to a TerminalWidget for embedding child terminal sessions within a TUI application.

csharp
public sealed class TerminalWidgetHandle : ICellImpactAwarePresentationAdapter, ITerminalLifecycleAwarePresentationAdapter, IHex1bTerminalPresentationAdapter, IAsyncDisposable

Inheritance

ObjectTerminalWidgetHandle

Implements

Constructors

TerminalWidgetHandle(int, int)

Creates a new TerminalWidgetHandle with the specified dimensions.

Parameters:

  • width (Int32): Initial width in columns.
  • height (Int32): Initial height in rows.
csharp
public TerminalWidgetHandle(int width = 80, int height = 24)

Properties

Capabilities

Capability hints that inform optimization strategies.

Returns: TerminalCapabilities

csharp
public TerminalCapabilities Capabilities { get; }

CopyModeCursorPosition

Gets the copy mode cursor position in virtual buffer coordinates, or null if not in copy mode.

Returns: Nullable<BufferPosition>

csharp
public BufferPosition? CopyModeCursorPosition { get; }

CopyModeState

Gets the current copy mode state.

Returns: CopyModeState

csharp
public CopyModeState CopyModeState { get; }

CurrentScrollbackOffset

Gets or sets the current scrollback offset, synced from the TerminalNode. Used for translating mouse coordinates to virtual buffer positions.

Returns: Int32

csharp
public int CurrentScrollbackOffset { get; set; }

CursorShape

Gets the current cursor shape requested by the child process.

Returns: CursorShape

csharp
public CursorShape CursorShape { get; }

CursorVisible

Gets whether the cursor is currently visible.

Returns: Boolean

csharp
public bool CursorVisible { get; }

CursorX

Gets the current cursor X position (0-based).

Returns: Int32

csharp
public int CursorX { get; }

CursorY

Gets the current cursor Y position (0-based).

Returns: Int32

csharp
public int CursorY { get; }

ExitCode

Gets the exit code of the terminal process, if it has completed.

Returns: Nullable<Int32>

csharp
public int? ExitCode { get; }

Height

Gets the current height of the terminal in rows.

Returns: Int32

csharp
public int Height { get; }

IconName

Gets the current icon name set by OSC 0 or OSC 1 sequences from the child process.

Returns: String

csharp
public string IconName { get; }

InAlternateScreen

Gets whether the child process is currently using the alternate screen buffer (mode 1049). When true, scrollback viewing is disabled because alternate screen programs (vim, less, etc.) manage their own scrolling.

Returns: Boolean

csharp
public bool InAlternateScreen { get; }

IsInCopyMode

Gets whether copy mode is currently active. When active, output from the child process is queued rather than applied to the screen buffer, and the selection cursor can be navigated independently.

Returns: Boolean

csharp
public bool IsInCopyMode { get; }

IsRunning

Gets whether the terminal is currently running.

Returns: Boolean

csharp
public bool IsRunning { get; }

MouseTrackingEnabled

Gets whether the child process has enabled mouse tracking. Mouse events are only forwarded to the child when this is true.

Returns: Boolean

csharp
public bool MouseTrackingEnabled { get; }

ScrollbackCount

Gets the number of rows currently in the scrollback buffer. Returns 0 if scrollback is not enabled.

Returns: Int32

csharp
public int ScrollbackCount { get; }

Selection

Gets the current text selection, or null if copy mode is not active.

Returns: TerminalSelection

csharp
public TerminalSelection? Selection { get; }

State

Gets the current lifecycle state of the terminal session.

Returns: TerminalState

csharp
public TerminalState State { get; }

VirtualBufferHeight

Gets the total number of rows in the virtual buffer (scrollback + screen).

Returns: Int32

csharp
public int VirtualBufferHeight { get; }

Width

Gets the current width of the terminal in columns.

Returns: Int32

csharp
public int Width { get; }

WindowTitle

Gets the current window title set by OSC 0 or OSC 2 sequences from the child process.

Returns: String

csharp
public string WindowTitle { get; }

Methods

CopySelection()

Copies the currently selected text and exits copy mode. Raises with the selected text.

Returns: String

The selected text, or null if no selection is active.

csharp
public string? CopySelection()

DisposeAsync()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.

Returns: ValueTask

A task that represents the asynchronous dispose operation.

csharp
public ValueTask DisposeAsync()

EnterCopyMode()

Enters copy mode: freezes the screen buffer and begins queuing output. The copy mode cursor starts at the bottom-right of the visible screen.

csharp
public void EnterCopyMode()

EnterRawModeAsync(CancellationToken)

Enter raw mode for proper input capture.

Parameters:

Returns: ValueTask

csharp
public ValueTask EnterRawModeAsync(CancellationToken ct = default)

ExitCopyMode()

Exits copy mode: flushes all queued output to the screen buffer and clears the selection.

csharp
public void ExitCopyMode()

ExitRawModeAsync(CancellationToken)

Exit raw mode and restore normal terminal input handling.

Parameters:

Returns: ValueTask

csharp
public ValueTask ExitRawModeAsync(CancellationToken ct = default)

FlushAsync(CancellationToken)

Flush any buffered output immediately.

Parameters:

Returns: ValueTask

csharp
public ValueTask FlushAsync(CancellationToken ct = default)

GetCell(int, int)

Gets the cell at the specified position.

Parameters:

Returns: TerminalCell

csharp
public TerminalCell GetCell(int x, int y)

GetCursorPosition()

Gets the current cursor position in the terminal. Returns (0, 0) if the position cannot be determined.

Returns: ValueTuple<Int32, Int32>

A tuple of (Row, Column), both 0-based.

csharp
public (int Row, int Column) GetCursorPosition()

GetScreenBuffer()

Gets a copy of the current screen buffer.

Returns: TerminalCell[,]

A copy of the screen buffer cells.

csharp
public TerminalCell[,] GetScreenBuffer()

GetScreenBufferSnapshot()

Gets a snapshot of the current screen buffer with its dimensions. This is atomic - the dimensions will always match the buffer.

Returns: ValueTuple<TerminalCell[0:, 0:], Int32, Int32>

A tuple containing the buffer copy, width, and height.

csharp
public (TerminalCell[,] Buffer, int Width, int Height) GetScreenBufferSnapshot()

GetScrollbackSnapshot(int)

Gets a snapshot of the scrollback buffer rows from the underlying terminal. Returns rows ordered oldest to newest.

Parameters:

  • count (Int32): Maximum number of scrollback rows to return.

Returns: ScrollbackRow[]

Array of scrollback rows, or empty if scrollback is not enabled.

csharp
public ScrollbackRow[] GetScrollbackSnapshot(int count)

GetVirtualCell(int, int)

Gets a cell from the virtual buffer (scrollback + screen unified view). Virtual row 0 is the oldest scrollback row; scrollbackCount+screenHeight-1 is the last screen row.

Parameters:

  • virtualRow (Int32): The virtual row index.
  • column (Int32): The column index.

Returns: Nullable<TerminalCell>

The cell at that position, or null if out of bounds.

csharp
public TerminalCell? GetVirtualCell(int virtualRow, int column)

MouseSelect(int, int, MouseAction, SelectionMode)

Handles mouse-driven selection. Translates local terminal coordinates to virtual buffer positions and manages the selection state machine (down/drag/up). Only enters copy mode when the user actually drags (not on a single click). When dragging outside the viewport, auto-scrolls every 500ms.

Parameters:

  • localX (Int32): X coordinate relative to the terminal widget bounds.
  • localY (Int32): Y coordinate relative to the terminal widget bounds.
  • action (MouseAction): The mouse action (Down records anchor, Drag starts selection, Up finalizes).
  • mode (SelectionMode): The selection mode to use.
csharp
public void MouseSelect(int localX, int localY, MouseAction action, SelectionMode mode)

MoveCopyModeCursor(int, int)

Moves the copy mode cursor by the specified row and column deltas. Clamps to buffer bounds and scrolls the viewport to keep the cursor visible.

Parameters:

csharp
public void MoveCopyModeCursor(int rowDelta, int colDelta)

MoveWordBackward()

Moves the copy mode cursor backward to the previous word boundary.

csharp
public void MoveWordBackward()

MoveWordForward()

Moves the copy mode cursor forward to the next word boundary.

csharp
public void MoveWordForward()

ReadInputAsync(CancellationToken)

Receive input (keystrokes, mouse events as ANSI sequences) FROM the user.

Parameters:

Returns: ValueTask<Byte>>

Raw input bytes from the user, or empty when disconnected.

csharp
public ValueTask<ReadOnlyMemory<byte>> ReadInputAsync(CancellationToken ct = default)

Reset()

Resets the terminal state to NotStarted. Used when restarting a terminal.

csharp
public void Reset()

Resize(int, int)

Resizes the terminal buffer.

Parameters:

csharp
public void Resize(int newWidth, int newHeight)

SendEventAsync(Hex1bEvent, CancellationToken)

Sends an input event (key or mouse) to the terminal's workload (e.g., child process). Mouse events are only forwarded if the child process has enabled mouse tracking.

Parameters:

Returns: Task

A task that completes when the event has been sent.

csharp
public Task SendEventAsync(Hex1bEvent evt, CancellationToken ct = default)

SendKeyEventAsync(Hex1bKeyEvent, CancellationToken)

Sends a key event to the terminal's workload (e.g., child process).

Parameters:

Returns: Task

A task that completes when the event has been sent.

csharp
[Obsolete("Use SendEventAsync instead.")]
public Task SendKeyEventAsync(Hex1bKeyEvent keyEvent, CancellationToken ct = default)

SetCopyModeCursorPosition(int, int)

Moves the copy mode cursor to an absolute position. Clamps to buffer bounds and scrolls the viewport to keep the cursor visible.

Parameters:

csharp
public void SetCopyModeCursorPosition(int row, int column)

StartOrToggleSelection(SelectionMode)

Starts or toggles selection in the specified mode. If already selecting in the same mode, clears the selection.

Parameters:

csharp
public void StartOrToggleSelection(SelectionMode mode)

WriteOutputAsync(ReadOnlyMemory<byte>, CancellationToken)

Fallback for when the terminal doesn't support cell impacts. This should rarely be called since ICellImpactAwarePresentationAdapter.WriteOutputWithImpactsAsync is the preferred path.

Parameters:

Returns: ValueTask

csharp
public ValueTask WriteOutputAsync(ReadOnlyMemory<byte> data, CancellationToken ct = default)

WriteOutputWithImpactsAsync(IReadOnlyList<AppliedToken>, CancellationToken)

Receives pre-processed cell impacts from the terminal's ANSI parsing logic. This is the main entry point for output - the terminal calls this instead of WriteOutputAsync when it detects we implement ICellImpactAwarePresentationAdapter.

Parameters:

Returns: ValueTask

csharp
public ValueTask WriteOutputWithImpactsAsync(IReadOnlyList<AppliedToken> appliedTokens, CancellationToken ct = default)

Events

CopyModeChanged

Raised when copy mode is entered or exited.

Returns: Action<Boolean>

csharp
public event Action<bool>? CopyModeChanged

CopyModeInput

Raised when a key is pressed while in copy mode. The consumer handles the key mapping (e.g., vi keys, arrow keys) and calls the appropriate navigation/selection methods on this handle. The bool parameter should be set to true if the key was handled.

Returns: Func<Hex1bEvent, Boolean>

csharp
public event Func<Hex1bEvent, bool>? CopyModeInput

Disconnected

Raised when the presentation layer disconnects (e.g., terminal closed, WebSocket dropped).

Returns: Action

csharp
public event Action? Disconnected

IconNameChanged

Event raised when the icon name changes (OSC 0 or OSC 1 from child process).

Returns: Action<String>

csharp
public event Action<string>? IconNameChanged

OutputReceived

Event raised when new output has been written to the buffer. TerminalNode subscribes to this to trigger re-renders.

Returns: Action

csharp
public event Action? OutputReceived

Resized

Raised when the presentation layer is resized by the user.

Returns: Action<Int32, Int32>

csharp
public event Action<int, int>? Resized

StateChanged

Event raised when the terminal state changes.

Returns: Action<TerminalState>

csharp
public event Action<TerminalState>? StateChanged

TextCopied

Raised when text is copied via copy mode. Subscribers should send the text to the system clipboard (e.g., via OSC 52).

Returns: Action<String>

csharp
public event Action<string>? TextCopied

WindowTitleChanged

Event raised when the window title changes (OSC 0 or OSC 2 from child process).

Returns: Action<String>

csharp
public event Action<string>? WindowTitleChanged

Remarks

The TerminalWidgetHandle implements to receive pre-processed cell impacts directly from the terminal's ANSI parsing logic. This eliminates the need to duplicate parsing code while maintaining a screen buffer that the TerminalWidget can render from.

Usage:

csharp
var terminal = Hex1bTerminal.CreateBuilder()
    .WithPtyProcess("bash")
    .WithTerminalWidget(out var bashHandle)
    .Build();

_ = terminal.RunAsync(appCt);

// In widget tree:
ctx.Terminal(bashHandle);

Released under the MIT License.