screenmodel

package
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package screenmodel owns Sidecar's byte-fed pane screen model.

It is the ONLY package permitted to import github.com/charmbracelet/x/vt. Everything it exposes is Sidecar-shaped: canonical Cell values, a Frame that can populate tty.ControlSnapshot, and plain bools/ints for cursor and mode state. No vt.Emulator, uv.Cell, or ansi.Mode value ever crosses the package boundary, so the dependency can be replaced or deleted without touching workspace code.

Ownership

A Model is single-actor: exactly one goroutine may call Seed, Write, Resize, Frame, or Close at a time. The type does not serialize for you. It detects violations instead — a concurrent entry returns ErrConcurrentUse rather than corrupting emulator state — so a misuse shows up as a loud error in tests instead of a rare rendering bug.

Status

Slice 0 of docs/plans/active/td-64c916-byte-fed-tmux-screen-model.md. There is deliberately no UI consumer: the model exists so the deterministic byte corpus can be run against it with tmux as the oracle. Known emulator gaps are recorded in the slice 0 evidence document rather than patched here.

Index

Constants

View Source
const DefaultScrollback = 10000

DefaultScrollback is the number of scrolled-off lines the model retains. It bounds memory and matches the emulator's own default.

Variables

View Source
var (
	// ErrConcurrentUse means two goroutines entered the model at once. The
	// model is single-actor by contract; this is a caller bug, and the second
	// caller is refused rather than allowed to interleave with emulator state.
	ErrConcurrentUse = errors.New("screenmodel: concurrent use of a single-actor model")
	// ErrClosed means the model has been closed.
	ErrClosed = errors.New("screenmodel: model is closed")
	// ErrInvalidGeometry means a caller passed impossible dimensions. It is a
	// rejection, not a fault: the model is unchanged and the call can be
	// retried with real geometry.
	ErrInvalidGeometry = errors.New("screenmodel: invalid geometry")
	// ErrModelFault means the emulator panicked or produced impossible state.
	// A faulted model stays faulted: the consumer must fall back to capture and
	// reseed. It must never take down the control reader or the UI loop.
	ErrModelFault = errors.New("screenmodel: model fault")
)

Errors returned by a Model.

View Source
var BlankCell = Cell{Grapheme: " ", Width: 1}

BlankCell is an unwritten cell: a default-styled space.

View Source
var Continuation = Cell{Grapheme: "", Width: 0}

Continuation is the second column of a wide cell.

Functions

func FormatMismatches

func FormatMismatches(ms []Mismatch, limit int) string

FormatMismatches renders up to limit mismatches for a failure message.

func Signatures

func Signatures(ms []Mismatch) []string

Signatures returns the sorted-unique signature set of a mismatch list.

Types

type Attr

type Attr uint16

Attr is a bitmask of the SGR text attributes Sidecar cares about. The values are Sidecar's own; they are translated from the emulator's representation so that a dependency swap cannot silently renumber them.

const (
	AttrBold Attr = 1 << iota
	AttrFaint
	AttrItalic
	AttrBlink
	AttrRapidBlink
	AttrReverse
	AttrConceal
	AttrStrikethrough
)

Text attributes.

func (Attr) String

func (a Attr) String() string

String renders the attribute set as a stable, human-readable list. It is used by the comparator's diff output, never as a wire format.

type Cell

type Cell struct {
	// Grapheme is the cell's content as a single grapheme cluster. An empty
	// string with Width 0 is the continuation column of a wide cell.
	Grapheme string
	// Width is the cell's mono-spaced width: 1 for ordinary cells, 2 for wide
	// ones, 0 for a wide cell's continuation column.
	Width int

	Fg             Color
	Bg             Color
	UnderlineColor Color
	Underline      Underline
	Attrs          Attr

	// LinkURL and LinkParams carry an OSC 8 hyperlink. LinkParams holds the
	// raw parameter list (typically "id=...").
	LinkURL    string
	LinkParams string
}

Cell is one canonical terminal cell.

This is the unit the fidelity harness compares. It deliberately excludes anything about how a cell would be *spelled* back out as escape bytes: two renderers that disagree about whether to emit SGR 0 before a run are not in disagreement about the screen.

func (Cell) Describe

func (c Cell) Describe() string

Describe renders a cell for diff output. It quotes the grapheme and lists only the non-default properties, so a mismatch report stays readable.

func (Cell) IsBlank

func (c Cell) IsBlank() bool

IsBlank reports whether the cell is an unstyled, unlinked space.

type Color

type Color string

Color is a canonical, comparable color value.

The empty string means "terminal default" (SGR 39/49/59). Palette colors — however they were spelled on the wire, whether SGR 31, SGR 90, or SGR 38;5;1 — normalize to "iN". Direct colors normalize to "#rrggbb". Canonicalizing here is what makes a cell comparison independent of the spelling tmux or the emulator happens to choose when rendering.

const ColorDefault Color = ""

ColorDefault is the terminal's default color.

func IndexedColor

func IndexedColor(i int) Color

IndexedColor returns the canonical form of a 256-color palette entry.

func RGBColor

func RGBColor(r, g, b uint8) Color

RGBColor returns the canonical form of a direct color.

type CursorState

type CursorState struct {
	Row, Col int
	Visible  bool
}

CursorState is the cursor half of a screen assertion, kept separate from the cell grid on purpose: a cursor-only divergence and a content divergence are different failures with different causes.

type CursorStyle

type CursorStyle uint8

CursorStyle is the shape of the cursor.

const (
	CursorBlock CursorStyle = iota
	CursorUnderline
	CursorBar
)

Cursor styles.

type Frame

type Frame struct {
	// Output is exactly the live pane rows. LoadedHistory is kept separate so a
	// frame publication never recopies Sidecar's 600-line history window merely
	// because the cursor or one cell changed. Consumers that still need the old
	// capture-shaped string can call CombinedOutput at that compatibility edge.
	Output        string
	LoadedHistory HistorySnapshot
	CaptureBase   int
	HistorySize   int
	// HasHistory reports whether any scrolled-off lines are loaded.
	HasHistory    bool
	Width, Height int
	CursorRow     int
	CursorCol     int
	CursorVisible bool
	AltScreen     bool
	Mouse         MouseState

	// Cells is the canonical visible grid. It is the fidelity harness's unit
	// of comparison and the future shadow-mode comparison input; the viewport
	// consumes Output.
	Cells Grid

	// CursorStyle and BracketedPaste are model-observed state with no
	// capture-pane equivalent. BracketedPaste is reported for diagnostics
	// only — tmux, not this model, is the authority for paste correctness.
	CursorStyle    CursorStyle
	BracketedPaste bool

	// HardResets is the number of RIS (ESC c) sequences the model has seen
	// since the last seed. It exists so a diagnostic cannot attribute a
	// difference to the RIS defect (slice-0 GAP-8) without positive evidence
	// that a RIS actually happened.
	HardResets int
	// ScrollbackAtCap reports that the emulator's retained scrollback has
	// reached [DefaultScrollback], which is the exact precondition of the
	// absolute-history-drift defect. Without it, an absolute history
	// difference has some other cause.
	ScrollbackAtCap bool
}

Frame is one rendered model snapshot. Its fields are shaped to populate tty.ControlSnapshot without translation, so the existing viewport, history, search, and selection journey keeps working unchanged.

func (Frame) CombinedOutput

func (f Frame) CombinedOutput() string

CombinedOutput returns loaded history followed by the live grid, matching capture-pane -p -e. It is the compatibility seam for diagnostics and the current OutputBuffer until that consumer accepts the two pieces directly.

type Grid

type Grid [][]Cell

Grid is a rectangular grid of canonical cells, row-major.

func DecodeCapture

func DecodeCapture(text string, w, h int) Grid

DecodeCapture converts capture-pane -e output into a w x h canonical grid.

func DecodeCaptureExtent

func DecodeCaptureExtent(text string, w, h int) (Grid, []int)

DecodeCaptureExtent decodes a capture and also reports, per row, the column its content ended at.

The extent matters because `capture-pane -e` is lossy at the end of a row. tmux trims trailing blank cells but keeps whatever SGR change it had already emitted, so a row that ends "…ESC[48;2;20;22;27m" is indistinguishable between "the rest of this row is blank in that background" (what nvim, fzf and every full-screen application with a painted background actually mean) and "that SGR belongs to the next row's first cell" (what the underline-style fixture actually means — both were observed against tmux 3.6b). Neither interpretation can be assumed, so the comparator treats the styling of cells at or past the extent as unknowable rather than scoring a guess.

func (Grid) Height

func (g Grid) Height() int

Height returns the number of rows.

func (Grid) Normalize

func (g Grid) Normalize(w, h int) Grid

Normalize returns a copy of the grid padded to exactly h rows of w cells, filling with blanks.

Padding matters because tmux's capture-pane trims trailing blank cells from every line: a short captured row and a full model row can describe exactly the same screen. Normalizing both sides before comparison keeps that formatting difference from reading as a fidelity failure.

func (Grid) Width

func (g Grid) Width() int

Width returns the width of the widest row, or 0 for an empty grid.

type HistorySnapshot

type HistorySnapshot struct {
	// contains filtered or unexported fields
}

HistorySnapshot is an immutable view of the loaded main-screen history at one frame. The snapshot owns its slice header while the model may append to the shared backing array. Its byte bounds never change; compaction allocates a new backing buffer so older frames remain valid.

func (HistorySnapshot) Output

func (h HistorySnapshot) Output() string

Output renders the loaded history in capture-pane shape. It allocates only when a compatibility consumer explicitly asks for the combined legacy form; ordinary frame publication and the future incremental viewport do not.

func (HistorySnapshot) Rows

func (h HistorySnapshot) Rows() int

Rows reports the number of loaded history rows.

type Mismatch

type Mismatch struct {
	// Kind is a coarse class: "cell", "cursor", "mode", "geometry", "history".
	Kind string
	// Field names the specific property, e.g. "grapheme", "bg", "attrs".
	Field string
	// Row and Col locate a cell mismatch; both are -1 for non-cell kinds.
	Row, Col int
	// Want is the oracle's value, Got the model's.
	Want, Got string
}

Mismatch is one canonical difference between two screens.

func CompareCursor

func CompareCursor(want, got CursorState) []Mismatch

CompareCursor compares two cursor states.

func CompareGrids

func CompareGrids(want, got Grid, w, h int) []Mismatch

CompareGrids compares two canonical grids cell by cell.

This is the canonical cell comparator: it compares grapheme, cell width, foreground/background/underline color, attributes, underline style, and hyperlink. It deliberately does NOT compare rendered string spelling — two renderers may legitimately emit different escape byte sequences for the same screen. Cursor position, cursor visibility, and modes are separate assertions; see CompareCursor and CompareModes.

Both grids are normalized to w x h first, so a capture that trimmed trailing blanks compares equal to a fully populated model row.

func CompareModes

func CompareModes(want, got ModeState) []Mismatch

CompareModes compares two mode states. Fields the caller does not want asserted should be equal on both sides.

func (Mismatch) Signature

func (m Mismatch) Signature() string

Signature reduces a mismatch to a stable class, dropping coordinates and values. The corpus runner uses it to assert that the *set* of documented upstream gaps is exactly what is observed — so a fixed defect and a new one both fail the test.

func (Mismatch) String

func (m Mismatch) String() string

String renders one mismatch for a test failure message.

type ModeState

type ModeState struct {
	AltScreen     bool
	MouseAny      bool
	MouseSGR      bool
	BracketedPast bool
}

ModeState is the mode half of a screen assertion.

type Model

type Model struct {
	// contains filtered or unexported fields
}

Model is a byte-fed screen model for one tmux pane.

Single-actor: one goroutine at a time. See the package doc.

func New

func New(width, height int) *Model

New creates a model for a pane of the given size.

func (*Model) Close

func (m *Model) Close()

Close releases the model. It is idempotent and terminal.

Close deliberately does not go through [Model.do]: do refuses a closed or faulted model before it runs the closure, and a fault is precisely the state a consumer closes from. Release therefore has to bypass the sticky-error check, or a faulted pane would keep its emulator's pipe and buffers alive for the lifetime of the process. The single-actor guard still applies — calling Close concurrently with another operation is the same caller bug it always was — and an emulator panic during release is swallowed rather than escaping into the caller's goroutine.

func (*Model) Footprint

func (m *Model) Footprint() int64

Footprint estimates the memory the model retains: the live grid plus the scrollback it has accumulated. Reported by the shadow-mode diagnostics.

func (*Model) Frame

func (m *Model) Frame() (Frame, error)

Frame renders the current model state.

func (*Model) Resize

func (m *Model) Resize(width, height int) error

Resize resizes the model's grid. Callers resize tmux first and pass the authoritative resulting geometry.

func (*Model) Seed

func (m *Model) Seed(s Seed) error

Seed bootstraps the model from a tmux capture plus metadata, discarding all previous state.

func (*Model) Write

func (m *Model) Write(p []byte) error

Write feeds raw pane bytes to the model. Partial sequences are fine: the emulator's parser holds state across calls.

type MouseState

type MouseState struct {
	X10         bool // DECSET 9
	Normal      bool // DECSET 1000
	Highlight   bool // DECSET 1001
	ButtonEvent bool // DECSET 1002
	AnyEvent    bool // DECSET 1003
	SGR         bool // DECSET 1006, an encoding rather than a tracking mode
}

MouseState mirrors the mouse tracking modes an application has enabled. These are plain bools on purpose: no ansi.Mode value escapes this package.

func (MouseState) Any

func (m MouseState) Any() bool

Any reports whether any mouse *tracking* mode is on. It is the model's analogue of tmux's #{mouse_any_flag}, which is why the SGR encoding mode is excluded: enabling SGR encoding alone does not make an application mouse-aware.

type PaneModel

type PaneModel interface {
	Seed(Seed) error
	Write([]byte) error
	Resize(width, height int) error
	Frame() (Frame, error)
	Close()
}

PaneModel is the behavior contract the workspace will eventually depend on. Only this interface may be referenced outside the package; the concrete Model and the emulator behind it stay here.

type Seed

type Seed struct {
	Output string
	// MainOutput is the saved main-screen capture returned by `capture-pane -a`
	// while Output contains the active alternate grid. It is populated only when
	// AltScreen is true. Seeding both grids is what lets a later DECSET 1049 exit
	// restore the same main screen tmux restores.
	MainOutput    string
	MainCursorRow int
	MainCursorCol int
	// HistorySize is tmux's history_size for the pane. The absolute base of the
	// loaded history is not taken from the caller: it is derived from the rows
	// Output actually carried, so the two can never disagree (see Seed).
	HistorySize   int
	HistoryLimit  int
	Width, Height int
	CursorRow     int
	CursorCol     int
	CursorVisible bool
	AltScreen     bool
	Mouse         MouseState
}

Seed is the state a model is bootstrapped from when Sidecar attaches to a pane that is already running. Output is a bounded `capture-pane -e` rendering; everything else comes from tmux format metadata captured in the same transaction.

type Underline

type Underline uint8

Underline is the underline style of a cell.

const (
	UnderlineNone Underline = iota
	UnderlineSingle
	UnderlineDouble
	UnderlineCurly
	UnderlineDotted
	UnderlineDashed
)

Underline styles.

func (Underline) String

func (u Underline) String() string

String names the underline style for diff output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL