Files
pipelines/internal/termstate/csi.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

520 lines
9.9 KiB
Go

package termstate
import (
"strconv"
"strings"
)
// esc runs an ESC sequence with at most one intermediate byte.
func (t *Terminal) esc(inter, final byte) {
switch inter {
case 0:
case '(', ')':
if final == '0' || final == 'A' || final == 'B' {
t.cur.charsets[inter-'('] = final
}
return
case '#':
if final == '8' {
t.alignmentTest()
}
return
default:
return
}
switch final {
case '7':
t.saveCursor()
case '8':
t.restoreCursor()
case 'D':
t.lineFeed()
case 'E':
t.lineFeed()
t.cur.x = 0
case 'H':
t.tabs[t.cur.x] = true
case 'M':
t.reverseIndex()
case 'c':
t.reset()
case '=':
t.m.appKeypad = true
case '>':
t.m.appKeypad = false
}
}
func (t *Terminal) saveCursor() {
t.scr.saved, t.scr.savedValid = t.cur, true
}
// restoreCursor is DECRC. As in the app's emulator, origin mode is not part
// of what it restores.
func (t *Terminal) restoreCursor() {
origin := t.cur.origin
if t.scr.savedValid {
t.cur = t.scr.saved
} else {
t.cur = cursor{charsets: [2]byte{'B', 'B'}}
}
t.cur.origin = origin
t.cur.x, t.cur.y = min(t.cur.x, t.cols-1), min(t.cur.y, t.rows-1)
}
// alignmentTest is DECALN: the screen fills with E.
func (t *Terminal) alignmentTest() {
t.top, t.bottom = 0, t.rows-1
for _, l := range t.scr.lines {
l.reset()
l.ensure(t.cols)
for x := range l.cells {
l.cells[x] = Cell{R: 'E'}
}
}
t.cur.x, t.cur.y, t.cur.wrap = 0, 0, false
}
// csi runs a CSI sequence.
func (t *Terminal) csi(final byte) {
p := &t.p.ps
switch t.p.prefix {
case 0:
case '?':
if t.p.inter == 0 && (final == 'h' || final == 'l') {
for i := 0; i < p.n; i++ {
t.setDecMode(p.get(i, 0), final == 'h')
}
}
return
default:
return
}
switch t.p.inter {
case 0:
case ' ':
if final == 'q' {
t.cursorShape = p.get(0, 0)
}
return
case '!':
if final == 'p' {
t.softReset()
}
return
default:
return
}
switch final {
case '@':
t.insertCells(p.count(0))
case 'A':
t.moveRows(-p.count(0))
case 'B', 'e':
t.moveRows(p.count(0))
case 'C', 'a':
t.moveTo(t.cur.x+p.count(0), t.cur.y)
case 'D':
t.moveTo(t.cur.x-p.count(0), t.cur.y)
case 'E':
t.moveRows(p.count(0))
t.cur.x = 0
case 'F':
t.moveRows(-p.count(0))
t.cur.x = 0
case 'G', '`':
t.moveTo(p.count(0)-1, t.cur.y)
case 'H', 'f':
t.position(p.count(0)-1, p.count(1)-1)
case 'd':
t.position(p.count(0)-1, t.cur.x)
case 'I':
t.tab(p.count(0))
case 'Z':
t.backTab(p.count(0))
case 'J':
t.eraseDisplay(p.get(0, 0))
case 'K':
t.eraseLine(p.get(0, 0))
case 'L':
t.insertLines(p.count(0))
case 'M':
t.deleteLines(p.count(0))
case 'P':
t.deleteCells(p.count(0))
case 'S':
if p.n <= 1 {
t.scrollUp(p.count(0))
}
case 'T':
if p.n <= 1 {
t.scrollDown(p.count(0))
}
case 'X':
n := min(p.count(0), t.cols-t.cur.x)
l := t.scr.lines[t.cur.y]
l.blank(t.cur.x, t.cur.x+n, t.cur.pen.Bg)
l.repair(t.cur.x - 1)
l.repair(t.cur.x + n)
t.cur.wrap = false
case 'b':
if t.lastChar != 0 {
for n := min(p.count(0), 65535); n > 0; n-- {
t.print(t.lastChar)
}
}
case 'g':
switch p.get(0, 0) {
case 0:
t.tabs[t.cur.x] = false
case 3:
clear(t.tabs)
}
case 'h', 'l':
for i := 0; i < p.n; i++ {
switch p.get(i, 0) {
case 4:
t.m.insert = final == 'h'
case 20:
t.m.newline = final == 'h'
}
}
case 'm':
t.sgr()
case 'r':
top, bottom := p.count(0)-1, p.get(1, t.rows)
if bottom <= 0 || bottom > t.rows {
bottom = t.rows
}
if top < bottom-1 {
t.top, t.bottom = top, bottom-1
t.position(0, 0)
}
case 's':
t.saveCursor()
case 'u':
t.restoreCursor()
}
}
// moveRows moves the cursor n rows, stopping at the scroll region's margin
// when it starts inside the region.
func (t *Terminal) moveRows(n int) {
y, lo, hi := t.cur.y+n, 0, t.rows-1
if t.cur.y >= t.top && t.cur.y <= t.bottom {
lo, hi = t.top, t.bottom
}
t.cur.y = min(max(y, lo), hi)
t.cur.wrap = false
}
func (t *Terminal) moveTo(x, y int) {
t.cur.x = min(max(x, 0), t.cols-1)
t.cur.y = min(max(y, 0), t.rows-1)
t.cur.wrap = false
}
// position is CUP: relative to the scroll region in origin mode.
func (t *Terminal) position(row, col int) {
if t.cur.origin {
t.moveTo(col, min(t.top+row, t.bottom))
return
}
t.moveTo(col, row)
}
func (t *Terminal) eraseDisplay(mode int) {
bg := t.cur.pen.Bg
lines := t.scr.lines
switch mode {
case 0:
t.eraseLine(0)
for y := t.cur.y + 1; y < t.rows; y++ {
lines[y].reset()
lines[y].blank(0, t.cols, bg)
}
case 1:
t.eraseLine(1)
for y := 0; y < t.cur.y; y++ {
lines[y].reset()
lines[y].blank(0, t.cols, bg)
}
case 2:
for _, l := range lines {
l.reset()
l.blank(0, t.cols, bg)
}
case 3:
t.clearScrollback()
}
t.cur.wrap = false
}
func (t *Terminal) eraseLine(mode int) {
l := t.scr.lines[t.cur.y]
x := t.cur.x
switch mode {
case 0:
l.blank(x, t.cols, t.cur.pen.Bg)
l.repair(x - 1)
l.cont = false
case 1:
l.blank(0, x+1, t.cur.pen.Bg)
l.repair(x + 1)
case 2:
l.reset()
l.blank(0, t.cols, t.cur.pen.Bg)
}
t.cur.wrap = false
}
// setDecMode sets or resets DEC private mode n.
func (t *Terminal) setDecMode(n int, on bool) {
switch n {
case 1:
t.m.appCursor = on
case 5:
t.m.reverse = on
case 6:
t.cur.origin = on
t.position(0, 0)
case 7:
t.m.autowrap = on
if !on {
t.cur.wrap = false
}
case 12:
t.m.cursorBlink = on
case 25:
t.m.cursorVisible = on
case 66:
t.m.appKeypad = on
case 9, 1000, 1001, 1002, 1003:
if on {
t.m.mouse = n
} else {
t.m.mouse = 0
}
case 1005, 1006, 1015:
if on {
t.m.mouseEncoding = n
} else {
t.m.mouseEncoding = 0
}
case 1004:
t.m.focus = on
case 1007:
t.m.altScroll = on
case 2004:
t.m.bracketedPaste = on
case 47:
t.useScreen(on)
case 1047:
if !on && t.scr == &t.alt {
t.clearAlt()
}
t.useScreen(on)
case 1048:
if on {
t.saveCursor()
} else {
t.restoreCursor()
}
case 1049:
if on {
if t.scr != &t.alt {
t.saveCursor()
t.useScreen(true)
t.clearAlt()
}
} else if t.scr == &t.alt {
t.useScreen(false)
t.restoreCursor()
}
}
}
func (t *Terminal) useScreen(alt bool) {
if alt {
t.scr = &t.alt
} else {
t.scr = &t.main
}
t.cur.wrap = false
}
func (t *Terminal) clearAlt() {
for _, l := range t.alt.lines {
l.reset()
}
}
// sgr applies SGR parameters to the pen.
func (t *Terminal) sgr() {
p := &t.p.ps
pen := &t.cur.pen
if p.n == 0 {
*pen = Attr{}
return
}
for i := 0; i < p.n; i++ {
code := p.get(i, 0)
// Colon subparameters belong to the parameter before them.
subs := i + 1
for subs < p.n && p.isSub(subs) {
subs++
}
switch {
case code == 0:
*pen = Attr{}
case code == 1:
pen.Flags |= attrBold
case code == 2:
pen.Flags |= attrFaint
case code == 3:
pen.Flags |= attrItalic
case code == 4:
style := 1
if subs > i+1 {
style = p.get(i+1, 1)
}
if style > 5 {
style = 1
}
pen.setUnderline(style)
case code == 5 || code == 6:
pen.Flags |= attrBlink
case code == 7:
pen.Flags |= attrInverse
case code == 8:
pen.Flags |= attrHidden
case code == 9:
pen.Flags |= attrStrike
case code == 21:
pen.setUnderline(2)
case code == 22:
pen.Flags &^= attrBold | attrFaint
case code == 23:
pen.Flags &^= attrItalic
case code == 24:
pen.setUnderline(0)
case code == 25:
pen.Flags &^= attrBlink
case code == 27:
pen.Flags &^= attrInverse
case code == 28:
pen.Flags &^= attrHidden
case code == 29:
pen.Flags &^= attrStrike
case code >= 30 && code <= 37:
pen.Fg = colorIndexed | Color(code-30)
case code == 39:
pen.Fg = 0
case code >= 40 && code <= 47:
pen.Bg = colorIndexed | Color(code-40)
case code == 49:
pen.Bg = 0
case code == 53:
pen.Flags |= attrOverline
case code == 55:
pen.Flags &^= attrOverline
case code >= 90 && code <= 97:
pen.Fg = colorIndexed | Color(code-90+8)
case code >= 100 && code <= 107:
pen.Bg = colorIndexed | Color(code-100+8)
case code == 38 || code == 48 || code == 58:
var c Color
var ok bool
if subs > i+1 {
c, ok = t.colorFrom(i+1, subs, true)
} else {
var used int
c, used, ok = t.semicolonColor(i + 1)
subs = i + 1 + used
}
if ok {
switch code {
case 38:
pen.Fg = c
case 48:
pen.Bg = c
}
}
}
i = subs - 1
}
}
// colorFrom reads an extended colour from parameters [from, to): 5;n, or
// 2;r;g;b (with a colour space before r in the colon form when there are
// five of them).
func (t *Terminal) colorFrom(from, to int, colon bool) (Color, bool) {
p := &t.p.ps
switch p.get(from, -1) {
case 5:
if to-from >= 2 {
if n := p.get(from+1, 0); n >= 0 && n < 256 {
return colorIndexed | Color(n), true
}
}
case 2:
rgb := from + 1
if colon && to-from >= 5 {
rgb++
}
if to-rgb >= 3 {
r, g, b := p.get(rgb, 0)&0xFF, p.get(rgb+1, 0)&0xFF, p.get(rgb+2, 0)&0xFF
return colorRGB | Color(r<<16|g<<8|b), true
}
}
return 0, false
}
// semicolonColor reads the legacy form 38;5;n or 38;2;r;g;b starting at i,
// returning how many parameters it used.
func (t *Terminal) semicolonColor(i int) (Color, int, bool) {
p := &t.p.ps
switch p.get(i, -1) {
case 5:
if i+2 <= p.n {
c, ok := t.colorFrom(i, i+2, false)
return c, 2, ok
}
case 2:
if i+4 <= p.n {
c, ok := t.colorFrom(i, i+4, false)
return c, 4, ok
}
}
return 0, p.n - i, false
}
// osc runs an OSC string: the window title is kept.
func (t *Terminal) osc(data []byte) {
s := string(data)
code, rest, ok := strings.Cut(s, ";")
if !ok {
return
}
if n, err := strconv.Atoi(code); err == nil && (n == 0 || n == 2) {
t.title = sanitizeTitle(rest)
}
}
// sanitizeTitle drops control characters (a title is written back inside an
// OSC string) and bounds it.
func sanitizeTitle(s string) string {
s = strings.ToValidUTF8(s, "")
var b strings.Builder
for _, r := range s {
if r < 0x20 || r == 0x7F || (r >= 0x80 && r < 0xA0) {
continue
}
if b.Len() >= 1024 {
break
}
b.WriteRune(r)
}
return b.String()
}