Files
pipelines/internal/termstate/parser.go
T
alan e13cb99ade Terminals: keep screen state on the server; snapshot on reload and gaps
A headless xterm-compatible emulator (internal/termstate) follows each
machine terminal's PTY output under the same lock as the 1 MiB tail. A
terminal_output from before the retained tail (new page, reload, gap)
now gets output_snapshot: an escape stream that resets the client and
restores scrollback (1000 lines), main screen, the alternate screen when
in use (via ?1049h so the program's exit brings the shell back), saved
cursors, tabs, scroll region, cursor incl. pending wrap, modes (mouse
tracking/encoding, bracketed paste, DECCKM, keypad, autowrap, origin,
focus, ...), charsets, pen and title, as of output_end; frames continue
there. Reads inside the tail stay raw.

No Go library was adequate: charmbracelet/x/vt and vito/midterm scroll at
0.2-4 MB/s and hide modes/pen/region; vt10x is unmaintained. termstate
runs at 160-200 MB/s.

The app treats a snapshot reply as a replay without the dropped-output
line, and every replay now starts with RIS so stale modes end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:56:49 +00:00

297 lines
5.7 KiB
Go

package termstate
// Parser states (the DEC ANSI parser of vt100.net, with DCS, SOS, PM and
// APC strings ignored as a whole).
const (
stGround uint8 = iota
stEscape
stEscInter
stCSI
stCSIInter
stCSIIgnore
stOSC
stString
)
const (
maxParams = 32
// maxSeq bounds the bytes of an unfinished escape sequence kept for a
// snapshot; longer ones are malformed and only their start is kept.
maxSeq = 256
// maxOSC bounds a kept OSC payload (titles); the rest is dropped.
maxOSC = 4096
)
// params are a CSI sequence's parameters: -1 for an empty one; sub marks
// those introduced by a colon (SGR subparameters).
type params struct {
v [maxParams]int32
sub uint32
n int
}
func (p *params) get(i int, def int) int {
if i >= p.n || p.v[i] < 0 {
return def
}
return int(p.v[i])
}
// count is get with a zero meaning one (counts and positions).
func (p *params) count(i int) int {
if n := p.get(i, 1); n > 0 {
return n
}
return 1
}
func (p *params) isSub(i int) bool { return i < p.n && p.sub&(1<<uint(i)) != 0 }
// parser is the decoding state between writes.
type parser struct {
st uint8
inter byte // the last intermediate byte of an ESC or CSI sequence
prefix byte // a CSI private marker (< = > ?)
strEsc bool // an ESC inside a string: ST if a backslash follows
strKind byte // the introducer of the string being skipped
digits bool // the current parameter has digits
ps params
// seq holds the bytes of the unfinished ESC or CSI sequence.
seq []byte
osc []byte
// An unfinished UTF-8 character: its bytes so far and how many follow.
utf rune
utfNeed int
utfHave int
}
func (t *Terminal) advance(b byte) {
p := &t.p
if p.utfNeed > 0 {
if b&0xC0 == 0x80 {
p.utf = p.utf<<6 | rune(b&0x3F)
p.utfHave++
if p.utfNeed--; p.utfNeed == 0 {
p.utfHave = 0
t.print(p.utf)
}
return
}
p.utfNeed, p.utfHave = 0, 0
t.print(0xFFFD)
}
switch b {
case 0x18, 0x1A: // CAN, SUB abort a sequence
if p.st != stGround {
p.st, p.strEsc = stGround, false
return
}
case 0x1B:
if p.st == stOSC || p.st == stString {
if !p.strEsc {
p.strEsc = true
return
}
}
p.st, p.strEsc, p.inter = stEscape, false, 0
p.seq = append(p.seq[:0], b)
return
}
switch p.st {
case stGround:
t.ground(b)
case stEscape:
t.escape(b)
case stEscInter:
switch {
case b < 0x20:
t.control(b)
case b < 0x30:
p.keep(b)
p.inter = b
default:
p.st = stGround
if b != 0x7F {
t.esc(p.inter, b)
}
}
case stCSI, stCSIInter, stCSIIgnore:
t.csiByte(b)
case stOSC:
if p.strEsc {
p.strEsc = false
p.st = stGround
if b == '\\' {
t.osc(p.osc)
return
}
// ESC then something else: the string ends, a sequence starts.
p.st, p.inter = stEscape, 0
p.seq = append(p.seq[:0], 0x1B)
t.escape(b)
return
}
switch {
case b == 0x07:
p.st = stGround
t.osc(p.osc)
case b < 0x20:
case len(p.osc) < maxOSC:
p.osc = append(p.osc, b)
}
case stString:
if p.strEsc {
p.strEsc = false
p.st = stGround
if b != '\\' {
p.st, p.inter = stEscape, 0
p.seq = append(p.seq[:0], 0x1B)
t.escape(b)
}
}
}
}
func (p *parser) keep(b byte) {
if len(p.seq) < maxSeq {
p.seq = append(p.seq, b)
}
}
func (t *Terminal) ground(b byte) {
p := &t.p
switch {
case b < 0x20:
t.control(b)
case b < 0x7F:
t.print(rune(b))
case b == 0x7F:
case b&0xE0 == 0xC0:
p.utf, p.utfNeed, p.utfHave = rune(b&0x1F), 1, 1
case b&0xF0 == 0xE0:
p.utf, p.utfNeed, p.utfHave = rune(b&0x0F), 2, 1
case b&0xF8 == 0xF0:
p.utf, p.utfNeed, p.utfHave = rune(b&0x07), 3, 1
default:
t.print(0xFFFD)
}
}
func (t *Terminal) escape(b byte) {
p := &t.p
switch {
case b < 0x20:
t.control(b)
return
case b == 0x7F:
return
}
p.keep(b)
switch {
case b < 0x30:
p.inter = b
p.st = stEscInter
case b == '[':
p.st, p.prefix, p.inter, p.digits = stCSI, 0, 0, false
p.ps.n, p.ps.sub = 0, 0
case b == ']':
p.st, p.osc = stOSC, p.osc[:0]
case b == 'P' || b == 'X' || b == '^' || b == '_':
p.st, p.strKind = stString, b
default:
p.st = stGround
t.esc(0, b)
}
}
func (t *Terminal) csiByte(b byte) {
p := &t.p
if b < 0x20 {
t.control(b)
return
}
if b == 0x7F {
return
}
p.keep(b)
if b >= 0x40 {
state := p.st
p.st = stGround
if state != stCSIIgnore {
if p.ps.n > 0 || p.digits {
if !p.digits && p.ps.n < maxParams {
p.ps.v[p.ps.n] = -1
}
p.ps.n = min(p.ps.n+1, maxParams)
}
t.csi(b)
}
return
}
if p.st == stCSIIgnore {
return
}
if b < 0x30 {
p.inter = b
p.st = stCSIInter
return
}
if p.st == stCSIInter {
p.st = stCSIIgnore
return
}
switch {
case b <= '9':
i := p.ps.n
if i >= maxParams {
return
}
if !p.digits {
p.ps.v[i] = 0
p.digits = true
}
if v := p.ps.v[i]*10 + int32(b-'0'); v <= 1<<20 {
p.ps.v[i] = v
}
case b == ';' || b == ':':
i := p.ps.n
if i < maxParams {
if !p.digits {
p.ps.v[i] = -1
}
p.ps.n++
if b == ':' && p.ps.n < maxParams {
p.ps.sub |= 1 << uint(p.ps.n)
}
}
p.digits = false
default: // < = > ?
if p.ps.n == 0 && !p.digits && p.prefix == 0 {
p.prefix = b
} else {
p.st = stCSIIgnore
}
}
}
// pending is what of an unfinished sequence a snapshot ends with, so that
// the bytes after the snapshot's offset complete it; partial is the length
// of an unfinished UTF-8 character, which a snapshot leaves out (it is
// sent again from its first byte).
func (p *parser) pending() (seq []byte, partial int) {
switch p.st {
case stGround:
return nil, p.utfHave
case stOSC:
seq = append([]byte("\x1b]"), p.osc...)
case stString:
seq = []byte{0x1B, p.strKind}
default:
return append([]byte(nil), p.seq...), 0
}
if p.strEsc {
seq = append(seq, 0x1B)
}
return seq, 0
}