Skip to content

terminal 实验性 ​

实验性

本包属于实验层:任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。

go
import "github.com/tangoui/tango/ui/terminal"

本页由 site/tools/apigen 从源码注释生成(按 darwin 构建标签选文件),请勿手改。

Package terminal is a terminal component: it connects a Conn, the program end of a terminal such as a pseudo-terminal, to the emulator in ui/terminal/vt.

Terminal owns the emulator and a read loop that feeds the program's output into it. The view locks the emulator with Terminal.Lock to draw it, and sends keys and pastes with Terminal.Send.

Experimental: this package's API may change in any 0.x release (see docs/release.md, "API 稳定性").

变量 ​

go
var (
	// SchemeDark is xterm.js 6's default theme: white on black, a 30%
	// white selection (the defaults in src/browser/services/ThemeService.ts)
	// and the default ANSI palette.
	SchemeDark = Scheme{
		Background: theme.Hex("#000000"), Foreground: theme.Hex("#ffffff"),
		Cursor: theme.Hex("#ffffff"), CursorText: theme.Hex("#000000"),
		Selection: theme.RGBA(255, 255, 255, .3),
		Palette:   xtermANSI,
	}
	// SchemeLight is xterm.js's default palette with the default colors
	// inverted (xterm.js has no light theme of its own): black on white,
	// a 30% black selection.
	SchemeLight = Scheme{
		Background: theme.Hex("#ffffff"), Foreground: theme.Hex("#000000"),
		Cursor: theme.Hex("#000000"), CursorText: theme.Hex("#ffffff"),
		Selection: theme.RGBA(0, 0, 0, .3),
		Palette:   xtermANSI,
	}
	// SchemeSolarizedLight is Solarized light: base00 on base3, base2
	// selection.
	SchemeSolarizedLight = Scheme{
		Background: solBase3, Foreground: solBase00,
		Cursor: solBase00, CursorText: solBase3,
		Selection: solBase2,
		Palette:   solPalette,
	}
	// SchemeSolarizedDark is Solarized dark: base0 on base03, base02
	// selection.
	SchemeSolarizedDark = Scheme{
		Background: solBase03, Foreground: solBase0,
		Cursor: solBase0, CursorText: solBase03,
		Selection: solBase02,
		Palette:   solPalette,
	}
	// SchemeDracula is Dracula (official spec, draculatheme.com/spec).
	SchemeDracula = Scheme{
		Background: theme.Hex("#282a36"), Foreground: theme.Hex("#f8f8f2"),
		Cursor: theme.Hex("#f8f8f2"), CursorText: theme.Hex("#282a36"),
		Selection: theme.Hex("#44475a"),
		Palette: [16]theme.Color{
			theme.Hex("#21222c"), theme.Hex("#ff5555"), theme.Hex("#50fa7b"), theme.Hex("#f1fa8c"),
			theme.Hex("#bd93f9"), theme.Hex("#ff79c6"), theme.Hex("#8be9fd"), theme.Hex("#f8f8f2"),
			theme.Hex("#6272a4"), theme.Hex("#ff6e6e"), theme.Hex("#69ff94"), theme.Hex("#ffffa5"),
			theme.Hex("#d6acff"), theme.Hex("#ff92df"), theme.Hex("#a4ffff"), theme.Hex("#ffffff"),
		},
	}
)

Built-in schemes.

函数 ​

func ResolveColor ​

go
func ResolveColor(c vt.Color, s *Scheme, fg bool) theme.Color

ResolveColor returns the color c draws with under scheme s. The default color is s.Foreground when fg is true, else s.Background; indexes 0–15 are s.Palette, 16–231 the xterm 6×6×6 cube, 232–255 the 24-step gray ramp (8 + 10·(n−232)); RGB colors are returned as they are.

类型 ​

CellPosition ​

go
type CellPosition struct {
	Row, Column int
}

CellPosition identifies a terminal cell. Rows are stable while retained in the buffer, including when the viewport scrolls. Columns are zero-based. Requery positions after resizing the terminal or resetting its screen.

CellRange ​

go
type CellRange struct {
	Start, End CellPosition
}

CellRange spans cells in row-major order with an exclusive End.

Conn ​

go
type Conn interface {
	io.Reader // the program's output
	io.Writer // input to the program: keys, pastes and replies
	// Resize tells the program the terminal's new size in cells and
	// pixels.
	Resize(cols, rows, widthPx, heightPx int) error
	// Close closes the connection. It must unblock a pending Read and a
	// pending Write, as closing an os.File, a pipe or a net.Conn does;
	// [Terminal.Close] waits for both to return.
	Close() error
}

Conn is the other end of a terminal: the program's output and input streams.

CursorShape ​

go
type CursorShape string

CursorShape is the shape of a terminal caret.

go
const (
	CursorBlock     CursorShape = "block"     // fills the cell
	CursorUnderline CursorShape = "underline" // along the cell's bottom
	CursorBar       CursorShape = "bar"       // along the cell's left edge
)

LinkHit ​

go
type LinkHit struct {
	Target string
	Range  CellRange
}

LinkHit is a matched target and its range in the terminal grid.

LinkMatch ​

go
type LinkMatch struct {
	From, To int
	Target   string
}

LinkMatch identifies a link in a logical line by its UTF-8 byte offsets [From, To). An empty Target uses the matched text.

LogicalLine ​

go
type LogicalLine struct {
	Text string
	// contains filtered or unexported fields
}

LogicalLine is the text of a terminal line including its soft wraps. A trailing run of blank cells is omitted.

func (LogicalLine) Range ​

go
func (l LogicalLine) Range(from, to int) (CellRange, bool)

Range maps a nonempty UTF-8 byte interval in Text to a cell range, expanding partial grapheme cells to whole cells.

Options ​

go
type Options struct {
	Conn Conn
	// Scrollback is the number of lines kept after they scroll off the
	// top. 0 means the default, 10 000; a negative value keeps none.
	Scrollback int
	// PredictiveEcho enables speculative display for this terminal. See
	// [Terminal.SetPredictiveEcho].
	PredictiveEcho bool
	// OnExit is called once, from the read goroutine, when the read loop
	// ends: err is nil at EOF or when [Terminal.Close] ended it,
	// otherwise the read error. It may call [Terminal.Close].
	OnExit func(err error)
}

Options configures a Terminal.

Scheme ​

go
type Scheme struct {
	Background, Foreground theme.Color
	Cursor                 theme.Color
	CursorText             theme.Color // the character under a block cursor
	Selection              theme.Color // selected cells (may be translucent)
	// SelectionForeground overrides the selected glyph color. Zero alpha
	// preserves ANSI colors with translucent selection, or uses Foreground
	// with opaque selection.
	SelectionForeground theme.Color
	Palette             [16]theme.Color
}

Scheme is a terminal color scheme: the default colors and the 16 ANSI colors (0–7 normal, 8–15 bright). Indexed colors 16–255 are computed with the xterm formula.

SendResult ​

go
type SendResult struct {
	AcceptedBytes int
	Truncated     bool
}

SendResult reports how much interactive input was accepted.

Terminal ​

go
type Terminal struct {
	// contains filtered or unexported fields
}

Terminal connects a Conn to a vt.Terminal. A read goroutine feeds the program's output to the emulator under a mutex; the view holds the same mutex, via Terminal.Lock, while it reads the emulator.

Replies the emulator generates (cursor position reports and the like) and the input Terminal.Send is given go to the program through one FIFO queue drained by a writer goroutine, so neither the read loop nor the UI thread ever waits for the program to read its input, and replies and input reach the program in the order they were made.

func New ​

go
func New(o Options) *Terminal

New returns a Terminal for o.Conn. It does not start reading; the view calls Terminal.Start once it knows its size.

func (*Terminal) Close ​

go
func (t *Terminal) Close() error

Close stops the writer, closes the Conn and waits for the read loop and the writer to end; it relies on Conn.Close unblocking a pending Read and Write. It is safe to call more than once, concurrently, before Start and from OnExit; every call returns the first call's result.

func (*Terminal) Exited ​

go
func (t *Terminal) Exited() (bool, error)

Exited reports whether the read loop has ended and, if it ended with an error other than EOF, the error. It does not take the emulator lock.

func (*Terminal) Lock ​

go
func (t *Terminal) Lock() *vt.Terminal

Lock locks the emulator and returns it. The caller must call Terminal.Unlock when done and must not keep the pointer past it.

func (*Terminal) Resize ​

go
func (t *Terminal) Resize(cols, rows, wpx, hpx int)

Resize resizes the emulator to cols×rows cells and tells the program the new size, in cells and pixels. A Conn implementation must let Close unblock a concurrent Resize; Resize is never called while holding the lifecycle mutex. A Conn error is ignored. Resize does nothing after Close has returned; one that races Close may still reach the Conn after it was closed (see resizeConn).

func (*Terminal) Send ​

go
func (t *Terminal) Send(b []byte)

Send queues b, encoded input such as keys or a paste, for the program and returns at once; the writer goroutine writes it after the replies and input queued before it. b is copied. At most 8 MB of input is queued: while the program is not reading its input, a Send that does not fit is dropped whole (never split, so no escape sequence is cut). Replies have an allowance of their own, so queued input never keeps the program's output from being read. Input sent before Start waits for it; input sent after Close, or after the program's output has ended, is dropped.

func (*Terminal) SendInput ​

go
func (t *Terminal) SendInput(b []byte) SendResult

SendInput queues interactive input without consuming the reserved key allowance with a large paste. Small protocol inputs can use the reserve; larger payloads must fit the normal queue limit or are rejected whole.

func (*Terminal) SetPredictiveEcho ​

go
func (t *Terminal) SetPredictiveEcho(on bool)

SetPredictiveEcho enables or disables speculative display for this terminal. It is off by default. After a real echo confirms input on the current line, the view can preview single printable ASCII keystrokes until the program echoes them. Other input, unexpected output and a timeout discard the preview. The setting is safe to change concurrently.

func (*Terminal) Snapshot ​

go
func (t *Terminal) Snapshot() vt.Snapshot

Snapshot returns a read-only copy of the emulator state for painting. The VT lock is held only while copying; callers must release the returned snapshot when done.

func (*Terminal) Start ​

go
func (t *Terminal) Start(cols, rows int, invalidate func())

Start sizes the emulator and the program to cols×rows and starts the read loop. invalidate is called, from the read goroutine, after each batch of output; it must be safe to call from any goroutine. Start does nothing if the Terminal was already started or closed.

The initial Conn.Resize error is ignored: the program then simply runs at the Conn's previous size, and a failing Conn also fails Read, which ends the loop and reports the error through OnExit.

func (*Terminal) Unlock ​

go
func (t *Terminal) Unlock()

Unlock unlocks the emulator locked by Terminal.Lock.

ViewW ​

go
type ViewW struct {
	// contains filtered or unexported fields
}

ViewW is the terminal view of a Terminal: it draws the emulator's viewport in a monospace grid, sends keys, typed text and pastes to the program, selects and copies with the mouse, and scrolls the scrollback with the wheel, Shift+PageUp / Shift+PageDown and an overlay scrollbar.

Keyboard: while focused the view captures Tab (Context.CaptureTab) and Esc (Context.ClaimEscape), so both go to the program; leave the terminal with Ctrl+Tab or Ctrl+Shift+Tab. "Esc then Tab leaves" does not apply inside a terminal. Application shortcuts are Cmd+C (copy the selection), Cmd+V (paste), Cmd+A (select all) and Cmd+K (clear the screen and the scrollback) on macOS, and Ctrl+Shift+C/V/A/K plus Ctrl+Insert / Shift+Insert elsewhere; every other key goes to vt.EncodeKey. On macOS Option composes characters unless ViewW.OptionAsMeta is set. Keys pressed during an IME composition go to the input method; the composition is drawn at the cursor and sent once committed. Input scrolls the view back to the bottom and clears the selection.

Show a Terminal in at most one view: the view takes the emulator's redraw records (TakeDirty, TakeScroll) each frame.

Input is queued and the frame never waits for the program; while it is not reading, sends that would exceed the 8 MB queue are dropped whole (see Terminal.Send).

func View ​

go
func View(c *ui.Context, t *Terminal) *ViewW

View shows t. Call it every frame; the application owns t and closes it. The first frame starts t's read loop at the view's size.

func (*ViewW) Box ​

go
func (w *ViewW) Box() *ui.Box

Box returns the view's box (ID, rect).

func (*ViewW) CellAt ​

go
func (w *ViewW) CellAt(p geom.Point) (CellPosition, bool)

CellAt returns the cell under p in window coordinates using the view's last layout. Both halves of a wide character resolve to its first cell.

func (*ViewW) Clear ​

go
func (w *ViewW) Clear()

Clear clears scrollback and keeps the cursor's current line at the top.

func (*ViewW) ClearSearch ​

go
func (w *ViewW) ClearSearch()

ClearSearch ends the search and removes its highlight.

func (*ViewW) CopySelection ​

go
func (w *ViewW) CopySelection()

CopySelection copies the current selection if it has text.

func (*ViewW) Cursor ​

go
func (w *ViewW) Cursor(shape CursorShape, blink bool) *ViewW

Cursor sets the default caret shape and blink preference for this view. The default is a steady block. DECSCUSR can override both settings.

func (*ViewW) FontFamily ​

go
func (w *ViewW) FontFamily(families string) *ViewW

FontFamily sets the preferred comma-separated font families for this view. Missing fonts or glyphs fall back to Tango's monospace chain. Use monospace families to fit the terminal grid.

func (*ViewW) FontSize ​

go
func (w *ViewW) FontSize(px float32) *ViewW

FontSize sets the cell font size in logical pixels (default: the terminal token's ContentFontSize, 13); values <= 0 are ignored.

func (*ViewW) Layout ​

go
func (w *ViewW) Layout(opts ...layout.Option) *ViewW

Layout applies layout options to the view's box (it grows by default).

func (*ViewW) LinkAt ​

go
func (w *ViewW) LinkAt(p geom.Point) (LinkHit, bool)

LinkAt returns the link under p in window coordinates, independent of whether OnOpenLink is set.

func (*ViewW) LinkMatcher ​

go
func (w *ViewW) LinkMatcher(match func(string) []LinkMatch) *ViewW

LinkMatcher replaces the standard URL and path matcher for this view. The function receives the whole logical line. Return matches in priority order. A nil matcher restores standard matching.

func (*ViewW) LogicalLineAt ​

go
func (w *ViewW) LogicalLineAt(p geom.Point) (LogicalLine, bool)

LogicalLineAt returns the complete retained logical line under p in window coordinates, even if part of it is outside the viewport.

go
func (w *ViewW) OnOpenLink(fn func(target string)) *ViewW

OnOpenLink sets the callback for a primary click on a link. A drag or a modified click selects text instead. The application opens the target, which may be a URL or a filesystem path.

func (*ViewW) OnPaste ​

go
func (w *ViewW) OnPaste(fn func(text string, submit func(string))) *ViewW

OnPaste intercepts nonempty text from native Paste, keyboard paste shortcuts and ViewW.Paste. The handler runs on the UI thread with the emulator unlocked. Call submit once on the UI thread, immediately or after confirmation, with the original or rewritten text. Omitting the call cancels the paste. A nil handler submits the original text.

func (*ViewW) OptionAsMeta ​

go
func (w *ViewW) OptionAsMeta(on bool) *ViewW

OptionAsMeta makes Option on macOS act as Meta (Alt: an Esc prefix) instead of composing characters (default false). Other platforms always send Alt as Meta.

func (*ViewW) Paste ​

go
func (w *ViewW) Paste(text string)

Paste requests a paste through the view's OnPaste handler. The accepted text is encoded using the terminal's bracketed-paste mode at submission.

func (*ViewW) Scheme ​

go
func (w *ViewW) Scheme(s Scheme) *ViewW

Scheme sets the color scheme this frame (default: the colors of the theme's terminal token).

func (*ViewW) Search ​

go
func (w *ViewW) Search(query string, caseSensitive bool) (count, at int)

Search runs query and highlights the first hit. It returns the number of hits and the 1-based position of the current one (0, 0 when none). An empty query clears the hits. The view need not be painting.

func (*ViewW) SearchInfo ​

go
func (w *ViewW) SearchInfo() (count, at int)

SearchInfo returns the hit count and 1-based current position, or 0, 0 when no search is active or it has no hits.

func (*ViewW) SearchStep ​

go
func (w *ViewW) SearchStep(dir int) (count, at int)

SearchStep moves to the next (dir > 0) or previous (dir < 0) hit, wrapping around, and returns the count and 1-based position.

func (*ViewW) SelectAll ​

go
func (w *ViewW) SelectAll()

SelectAll selects retained history and the active rows through the last content or cursor row.

func (*ViewW) SelectedText ​

go
func (w *ViewW) SelectedText() string

SelectedText returns the text that CopySelection would copy, joining soft wraps and using the platform's newline for hard line breaks.

func (*ViewW) Selection ​

go
func (w *ViewW) Selection() (CellRange, bool)

Selection returns the current range, widened to whole glyph cells and clipped to retained history. It includes selected blank cells.

以 MIT 许可发布