Documentation
¶
Overview ¶
Package terminal draws a grid of cells and reads keys, the pointer and resizes: direct ANSI on a terminal, with cell-level diffing and no allocation a frame, and the same Terminal over a host that draws the cells itself: a browser page, which New's Terminal opens at Init on js/wasm, a desktop window or an Android view (NewWithHost). README.md holds the rest.
Index ¶
- func CellColors(c Cell) (fg, bg color.RGB)
- func CellFrame(dst []byte, cells []Cell, cols, rows int, changed []uint64, ...) []byte
- func ChangedCells(dst []uint64, a, b []Cell) []uint64
- func EmergencyReset(w io.Writer)
- func KeyName(k Key) string
- func OneColumn(r rune) bool
- func RGBTo256(c color.RGB) uint8
- func RuneFrame(dst []byte, cells []Cell, cols, rows int, changed []uint64) []byte
- func WarmPalette256()
- func WindowSize(f *os.File) (w, h int, ok bool)
- type Attr
- type Backend
- type Cell
- type ColorMode
- type Event
- type EventType
- type FrameEncoder
- type Frames
- type Host
- type HostKeys
- type Key
- type KeyAction
- type KeyHolds
- type KeyReport
- type KeySource
- type Modifier
- type MouseAction
- type MouseButton
- type MouseMode
- type ResizeEvent
- type Surface
- type Terminal
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CellColors ¶ added in v0.7.0
CellColors is a cell's foreground and background as a drawer paints them: reverse swaps the two and dim halves the foreground; no other style reaches a drawer
func CellFrame ¶ added in v0.7.0
func CellFrame(dst []byte, cells []Cell, cols, rows int, changed []uint64, id func(rune) uint32) []byte
CellFrame appends a frame as little-endian 32-bit words: cols, rows and the count of records, then a record for each cell changed marks, or for every cell when changed is nil: its index, the id of its rune (a drawer's name for the glyph), and its foreground and background as ARGB
func ChangedCells ¶ added in v0.6.5
ChangedCells returns, in dst's storage, a bit for each cell where a and b differ: bit i&63 of word i>>6 for cell i of the first min(len(a), len(b)), the bits past them clear. A frame's changed cells are the bits set against the frame before; built with GOEXPERIMENT=simd, cells compare as vectors.
func EmergencyReset ¶
EmergencyReset attempts to restore terminal to sane state Call this from panic recovery if Fini() cannot be called normally. Given a redirected stdout, it writes to the controlling terminal instead.
func KeyName ¶
KeyName returns the canonical string name for a Key constant Returns empty string for KeyNone and KeyRune
func OneColumn ¶ added in v0.6.6
OneColumn reports whether a cell draws r as itself, in one column; Flush draws any other rune as a space or U+FFFD
func RGBTo256 ¶
RGBTo256 delegates to the color package's perceptual quantizer. Exists to preserve terminal API backwards-compatibility.
func RuneFrame ¶ added in v0.7.0
RuneFrame is a CellFrame whose ids are the runes a Terminal's Flush would draw, for a drawer that keeps glyphs of its own
func WarmPalette256 ¶
func WarmPalette256()
WarmPalette256 delegates to the color package's lazily evaluated 256-color LUT builder. Exists to preserve terminal API backwards-compatibility.
Types ¶
type Attr ¶
type Attr uint16
Attr represents text attributes and how to read a cell's colors (bitmask)
const ( AttrNone Attr = 0 AttrBold Attr = 1 << 0 AttrDim Attr = 1 << 1 AttrItalic Attr = 1 << 2 AttrUnderline Attr = 1 << 3 AttrBlink Attr = 1 << 4 AttrReverse Attr = 1 << 5 AttrFg256 Attr = 1 << 6 // Fg.R is 256-color palette index AttrBg256 Attr = 1 << 7 // Bg.R is 256-color palette index AttrFgDefault Attr = 1 << 8 // Fg is the terminal's own (SGR 39); Fg is ignored AttrBgDefault Attr = 1 << 9 // Bg is the terminal's own (SGR 49); Bg is ignored )
const ( AttrFgColor Attr = AttrFg256 | AttrFgDefault AttrBgColor Attr = AttrBg256 | AttrBgDefault )
AttrFgColor and AttrBgColor mask the bits that say how to read Fg and Bg
const AttrStyle Attr = AttrBold | AttrDim | AttrItalic | AttrUnderline | AttrBlink | AttrReverse
AttrStyle masks only the style bits (excludes color mode flags)
type Backend ¶
type Backend interface {
Init() error
Fini()
Size() (width, height int)
Write(p []byte) error
// Read blocks until input is available, wait passes or Wake is called, and
// returns no data for the last two; a negative wait never passes. The data
// is valid until the next Read.
Read(wait time.Duration) ([]byte, error)
// Wake makes the Read in progress return, or the next one if none is.
Wake()
// SetResizeHandler is called once, after Init, with what a new size goes to
SetResizeHandler(handler func(width, height int))
}
Backend is the terminal a Terminal writes bytes to and reads them from: the tty or console New opens, or a caller's own for NewWithBackend
type ColorMode ¶
type ColorMode uint8
ColorMode indicates terminal color capability
func DetectColorMode ¶
func DetectColorMode() ColorMode
DetectColorMode determines terminal color capability from environment: 16 colors on text consoles, true color where announced, else 256. It reports what the terminal can show; New also honors NO_COLOR.
type Event ¶
type Event struct {
Type EventType
Key Key
Rune rune
Modifiers Modifier
Action KeyAction // For EventKey: KeyPress unless the terminal reports releases
Lost bool // For a KeyRelease the package made for a hold whose own release can't arrive
Width int // For EventResize
Height int // For EventResize
Err error // For EventError
Text string // For EventPaste: the pasted bytes as sent, controls included
Focused bool // For EventFocus: whether the terminal now has focus
Report KeyReport // For EventKeyReport: what the terminal now reports of each key
Source KeySource // For EventKeyReport: the source releases come from, zero for presses
// Mouse event fields
MouseX int
MouseY int
MouseBtn MouseButton
MouseAction MouseAction
Touch bool // A touch, from a host that reads one; terminals report none
}
Event represents a terminal input event
type EventType ¶
type EventType uint8
EventType distinguishes input event categories
const ( EventKey EventType = iota EventResize EventPaste // Bracketed paste, Text holds it EventMouse // SGR mouse reporting EventError // Read error EventClosed // Input closed EventFocus // The terminal gained or lost focus, while it reports releases through its protocol EventKeyReport // What a SetKeyReport ask came to: Report through Source )
type FrameEncoder ¶ added in v0.7.0
FrameEncoder appends to dst a frame of cols by rows cells as its drawer reads one: the cells changed marks, as ChangedCells does, or every cell for a nil changed
type Frames ¶ added in v0.7.0
type Frames struct {
// contains filtered or unexported fields
}
Frames hands the frames a Surface receives to a drawer in another runtime, a Java view's thread or a browser page: Flush keeps the newest, Take encodes the cells changed since the frame the drawer holds, and Blocked is how long the oldest frame not taken has waited. Any goroutine may call any method.
func NewFrames ¶ added in v0.7.0
func NewFrames(encode FrameEncoder) *Frames
NewFrames takes frames for a drawer that reads them as encode writes them, nil for RuneFrame
func (*Frames) Blocked ¶ added in v0.7.0
Blocked is how long the oldest frame the drawer has not taken has waited
func (*Frames) Flush ¶ added in v0.7.0
Flush keeps a frame of width by height cells as the newest, replacing one not yet taken; a frame short of its own size is dropped, as a terminal drops one
func (*Frames) SetEncoder ¶ added in v0.7.0
func (f *Frames) SetEncoder(encode FrameEncoder)
SetEncoder is for a drawer whose glyphs changed, which voids the frame it holds: the newest frame is its to take again, every cell as encode writes it
type Host ¶ added in v0.7.0
type Host interface {
Surface
Size() (cols, rows int)
Blocked() time.Duration // how long it has held a frame it has not drawn
Events() <-chan Event
// SetPointerMode selects the pointer events reported: none, buttons and
// drags, or every motion as well
SetPointerMode(enabled, motion bool)
// SetKeyReport is answered with an EventKeyReport on Events, as HostKeys.Ask posts
SetKeyReport(report KeyReport, allow KeySource) error
}
Host is a screen with its player's keys and pointer that is open already and speaks in cells and Events itself: a window, a page, a phone's view. Its Events carry a resize as an EventResize, and Size is the grid it then holds.
type HostKeys ¶ added in v0.7.0
type HostKeys struct {
Post func(Event)
// contains filtered or unexported fields
}
HostKeys is the key report of a host that reads its platform's own key events, a window, a page or a phone, and posts them as a terminal would: presses until a game asks for releases, then each key's press, repeats and release, paired by the host's code for the physical key. Post takes the events it makes and is set before use; any goroutine may call any method.
func (*HostKeys) Ask ¶ added in v0.7.0
Ask answers a game's SetKeyReport with an EventKeyReport: releases when it asks a host for them and this one can tell a release from a repeat, presses otherwise, which ends every hold as lost
func (*HostKeys) Down ¶ added in v0.7.0
Down is the key code names going down as ev, or repeating while held; with releases reported its Up ends the hold
func (*HostKeys) Held ¶ added in v0.7.0
Held reports whether the key code names is down, for a host whose keyboard repeats a held key as more presses
func (*HostKeys) Lost ¶ added in v0.7.0
func (k *HostKeys) Lost()
Lost ends every hold as lost: the host's keys went to something else
type Key ¶
type Key uint16
Key represents a parsed input key
const ( KeyNone Key = iota KeyRune // Printable character (check Event.Rune) // Control keys KeyEscape KeyEnter KeyTab KeyBacktab // Shift+Tab KeyShiftTab // Same as KeyBacktab,for clarity KeyBackspace KeyDelete KeySpace // Navigation KeyUp KeyDown KeyLeft KeyRight KeyHome KeyEnd KeyPageUp KeyPageDown KeyInsert // Function keys KeyF1 KeyF2 KeyF3 KeyF4 KeyF5 KeyF6 KeyF7 KeyF8 KeyF9 KeyF10 KeyF11 KeyF12 // Ctrl+letter (Ctrl+A = 0x01, Ctrl+Z = 0x1A) KeyCtrlA KeyCtrlB KeyCtrlC KeyCtrlD KeyCtrlE KeyCtrlF KeyCtrlG KeyCtrlH // Often same as Backspace KeyCtrlI // Often same as Tab KeyCtrlJ // Often same as Enter KeyCtrlK KeyCtrlL KeyCtrlM // Often same as Enter KeyCtrlN KeyCtrlO KeyCtrlP KeyCtrlQ KeyCtrlR KeyCtrlS KeyCtrlT KeyCtrlU KeyCtrlV KeyCtrlW KeyCtrlX KeyCtrlY KeyCtrlZ // Ctrl+special KeyCtrlSpace // Ctrl+@ / Ctrl+Space (Ctrl+@ produces NUL byte 0x00) KeyCtrlBackslash KeyCtrlBracketLeft KeyCtrlBracketRight KeyCtrlCaret KeyCtrlUnderscore )
Key constants - designed for expansion
func ControlKey ¶ added in v0.4.1
ControlKey is the key a terminal reads for Ctrl with a printable character: the control byte that pair sends, parsed as input parsing reads it. Letters of either case, space and '@', '[' '\' ']' '^' '_', '-' and '/' as '_', and the digits 2 to 7 have one; ok is false for any other character.
type KeyAction ¶ added in v0.5.0
type KeyAction uint8
KeyAction is what happened to a key. Only a terminal reporting releases (see SetKeyReport) tells them apart; elsewhere every key event is a press, and a key held down arrives as more presses at the keyboard's repeat rate.
type KeyHolds ¶ added in v0.5.0
type KeyHolds struct {
// contains filtered or unexported fields
}
KeyHolds pairs key releases with their presses. A source names each physical key by a code of its own (a console keycode, a protocol key number, a host's keycode); KeyHolds hands its reports on as Events, a release carrying what its press carried, so letting go of Shift first still releases 'A', not 'a'. The zero value is ready to use; it is not safe for concurrent use.
func (*KeyHolds) Held ¶ added in v0.5.0
Held reports whether the key code names is down: a source that repeats a held key as more presses, as the consoles do, tells its repeats apart by it
func (*KeyHolds) ReleaseAll ¶ added in v0.5.0
ReleaseAll ends every hold, sending a Lost release for each, oldest first: focus left, the console switched away, or releases stopped
func (*KeyHolds) Report ¶ added in v0.5.0
Report hands on one report of the key code names through send, ev the key as the source reads it, its Action set: a press starts a hold, a release ends it, a repeat passes as it is. A report the holds contradict means the source lost one: a press of a key held first ends that hold with a Lost release, a repeat of a key not held is a press, and a release of one is dropped.
type KeyReport ¶ added in v0.5.0
type KeyReport uint8
KeyReport is how much a terminal reports of each key
type KeySource ¶ added in v0.5.0
type KeySource uint8
KeySource is where key releases come from (bitmask). SetKeyReport tries the sources a game allows in the order below; a terminal with none of them reports presses, as every terminal does until a game asks.
const ( // KeySourceConsole is the kernel console's own keyboard, switched to raw // keycodes while releases are asked for: the Linux console on the VT the // game runs on, and FreeBSD's vt(4). Never over ssh, where the keyboard is // the far terminal's. KeySourceConsole KeySource = 1 << iota // KeySourceProtocol is the terminal's key event protocol (CSI u with event // types), found by asking the terminal whether it has one: Alacritty 0.13 // and later, and any terminal that answers the same. Over ssh too. KeySourceProtocol // KeySourceHost is a host that reads its platform's own key events, such as // a window or a browser, and builds Events itself, as HostKeys does; only a // Terminal over a Host reports it. KeySourceHost )
type MouseAction ¶
type MouseAction uint8
MouseAction represents the type of mouse event
const ( MouseActionNone MouseAction = iota MouseActionPress MouseActionRelease MouseActionMove MouseActionDrag )
func (MouseAction) String ¶
func (a MouseAction) String() string
String returns human-readable action name
type MouseButton ¶
type MouseButton uint8
MouseButton represents mouse button identity
const ( MouseBtnNone MouseButton = iota MouseBtnLeft MouseBtnMiddle MouseBtnRight MouseBtnWheelUp MouseBtnWheelDown MouseBtnBack // Button 8, a mouse's back side button MouseBtnForward // Button 9, its forward side button MouseBtnWheelLeft // A wheel tilted left, or a touchpad swiped so MouseBtnWheelRight // A wheel tilted right, or a touchpad swiped so )
func (MouseButton) String ¶
func (b MouseButton) String() string
String returns human-readable button name
type ResizeEvent ¶
type Surface ¶ added in v0.7.0
type Surface interface {
ColorMode() ColorMode
Flush(cells []Cell, width, height int)
Sync() // the next frame is drawn whole
}
Surface is what a finished frame is handed to: a Terminal, or a host drawing the same cells, a window, a page or a phone's view. Flush must not wait on what draws; a frame held there is dropped for a newer one
type Terminal ¶
type Terminal interface {
// Init enters raw mode, alternate screen buffer, hides cursor
Init() error
// Fini restores terminal state. Safe to call multiple times
Fini()
Size() (width, height int)
ResizeChan() <-chan ResizeEvent
ColorMode() ColorMode
// Flush hands a frame to the terminal; cells are row-major: cells[y*width + x].
// It never waits on the terminal: while the last write is still out, the frame
// is held and drawn once that write returns, a newer one replacing it
Flush(cells []Cell, width, height int)
// Blocked reports how long the terminal has held the write in flight, zero
// while output drains. A terminal that stops reading (a hidden tab, a client
// that went away, flow control) shows here instead of as a caller that waits
Blocked() time.Duration
// Clear fills screen with specified background color
Clear(bg color.RGB)
// SetCursorVisible shows/hides cursor
SetCursorVisible(visible bool)
// MoveCursor positions cursor (0-indexed)
MoveCursor(x, y int)
// Sync forces full redraw
Sync()
// PollEvent blocks until next input event
PollEvent() Event
// PostEvent injects a synthetic event
PostEvent(Event)
// SetMouseMode enables/disables mouse event reporting
// Modes can be combined: MouseModeClick | MouseModeDrag
SetMouseMode(mode MouseMode) error
// SetPasteMode turns bracketed paste on or off: on, a paste arrives as
// one EventPaste rather than as keys, so its newlines don't press Enter
SetPasteMode(on bool) error
// SetKeyReport asks for keys at level report and returns at once: releases
// come through the first source in allow the terminal has, the console before
// the protocol, and KeyReportPresses gives the source up. An EventKeyReport
// follows with what the terminal reports now, asks not yet acted on answered
// together by the latest; a change of source ends the holds it leaves as Lost
SetKeyReport(report KeyReport, allow KeySource) error
}
Terminal provides low-level terminal access; it is a Surface
func New ¶
New creates a Terminal on the tty, or in a browser on the page its Init opens. Without a mode it uses DetectColorMode's, or ColorModeNone when NO_COLOR is set; an explicit mode overrides both, as a --color=always or never would, except on a page, which is truecolor
func NewWithBackend ¶ added in v0.4.0
NewWithBackend creates a Terminal over b in color mode c, for a pipe, an in-process emulator or a test standing in for the tty. b must not be nil; the Terminal calls its Init on Init and its Fini on Fini, and writes to it on its own goroutine as New's does
func NewWithHost ¶ added in v0.7.0
NewWithHost creates a Terminal over h, open already: Init opens nothing, and Fini calls h's Close when it has one. A host draws no cursor of its own, and its paste is one EventPaste whatever the paste mode
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package android is the Go half of an Android view showing a Terminal's cells: the grid its pixels hold, its keys, touches and text as Events, the frames its drawer takes and the texture it paints them from.
|
Package android is the Go half of an Android view showing a Terminal's cells: the grid its pixels hold, its keys, touches and text as Events, the frames its drawer takes and the texture it paints them from. |
|
cmd
|
|
|
example-inline
command
|
|
|
example-keys
command
keys — shows each key event the terminal reports, for trying key releases where a game runs: a Linux or FreeBSD console, Alacritty, ssh, tmux.
|
keys — shows each key event the terminal reports, for trying key releases where a game runs: a Linux or FreeBSD console, Alacritty, ssh, tmux. |
|
example-tui
command
fv, file voyager: an lf / midnight-commander / xxd hybrid, the demo of the terminal, tui and color packages.
|
fv, file voyager: an lf / midnight-commander / xxd hybrid, the demo of the terminal, tui and color packages. |
|
Package glyph is a bitmap font of several cell sizes, its strikes; the software raster that draws a cell grid with one, which a host shows as it is or checks a cell drawer of its own against; and what a drawer in another runtime paints from, a strike as one texture and frames encoded for it, as README.md lays out.
|
Package glyph is a bitmap font of several cell sizes, its strikes; the software raster that draws a cell grid with one, which a host shows as it is or checks a cell drawer of its own against; and what a drawer in another runtime paints from, a strike as one texture and frames encoded for it, as README.md lays out. |
|
Package inline renders styled text and in-place progress in the normal terminal scrollback: no raw mode, no alternate screen, no input handling, no cursor hiding.
|
Package inline renders styled text and in-place progress in the normal terminal scrollback: no raw mode, no alternate screen, no input handling, no cursor hiding. |
|
internal
|
|
|
env
Package env reads what the environment says about a terminal's colors, for terminal and inline alike
|
Package env reads what the environment says about a terminal's colors, for terminal and inline alike |
|
window
module
|