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

527 lines
12 KiB
Go

package termstate
import (
"strings"
"github.com/mattn/go-runewidth"
)
// DefaultScrollback is how many lines scrolled off the main screen a
// terminal keeps (and a snapshot redraws).
const DefaultScrollback = 1000
// cursor is the cursor with what DECSC saves alongside it.
type cursor struct {
x, y int
pen Attr
// wrap: the last column was written; the next character wraps first.
wrap bool
origin bool
charsets [2]byte
shift int // 0: G0 is in use, 1: G1 (SO)
}
// screen is the main or the alternate screen.
type screen struct {
lines []*line
// saved is the DECSC cursor of this screen (valid once set).
saved cursor
savedValid bool
}
// modes are the terminal modes a snapshot restores.
type modes struct {
appCursor, reverse, autowrap, cursorBlink, cursorVisible bool
appKeypad, insert, newline, focus, bracketedPaste, altScroll bool
// mouse is the tracking mode (9, 1000, 1001, 1002, 1003, or 0) and
// mouseEncoding the coordinate encoding (1005, 1006, 1015, or 0); as in
// xterm, setting one replaces the previous one.
mouse, mouseEncoding int
}
// Terminal is the emulated state of one pseudo-terminal.
type Terminal struct {
p parser
cols, rows int
main, alt screen
scr *screen
cur cursor
// top and bottom are the scroll region's rows (inclusive).
top, bottom int
m modes
// cursorShape is the DECSCUSR parameter (0: the default).
cursorShape int
tabs []bool
title string
lastChar rune
// history holds the lines scrolled off the main screen, oldest first,
// in a ring of at most limit lines starting at head.
history []*line
head int
limit int
}
var widths = &runewidth.Condition{EastAsianWidth: false, StrictEmojiNeutral: true}
// New returns a terminal of cols x rows that keeps scrollback lines.
func New(cols, rows, scrollback int) *Terminal {
cols, rows = max(cols, 1), max(rows, 1)
t := &Terminal{cols: cols, rows: rows, limit: max(scrollback, 0)}
t.main.lines = newLines(rows)
t.alt.lines = newLines(rows)
t.reset()
return t
}
func newLines(n int) []*line {
lines := make([]*line, n)
for i := range lines {
lines[i] = &line{}
}
return lines
}
// reset is RIS: everything but the scrollback and the title.
func (t *Terminal) reset() {
for _, l := range t.main.lines {
l.reset()
}
for _, l := range t.alt.lines {
l.reset()
}
t.main.savedValid, t.alt.savedValid = false, false
t.scr = &t.main
t.cur = cursor{charsets: [2]byte{'B', 'B'}}
t.top, t.bottom = 0, t.rows-1
t.m = modes{autowrap: true, cursorVisible: true}
t.cursorShape = 0
t.resetTabs()
}
// softReset is DECSTR.
func (t *Terminal) softReset() {
t.m.insert, t.m.appCursor, t.m.appKeypad = false, false, false
t.m.autowrap, t.m.cursorVisible = true, true
t.cur.origin, t.cur.pen, t.cur.wrap = false, Attr{}, false
t.cur.charsets, t.cur.shift = [2]byte{'B', 'B'}, 0
t.top, t.bottom = 0, t.rows-1
t.scr.saved, t.scr.savedValid = cursor{charsets: [2]byte{'B', 'B'}}, true
}
func (t *Terminal) resetTabs() {
t.tabs = make([]bool, t.cols)
for x := 8; x < t.cols; x += 8 {
t.tabs[x] = true
}
}
// Size is the terminal's columns and rows.
func (t *Terminal) Size() (cols, rows int) { return t.cols, t.rows }
// AltScreen reports whether the alternate screen is in use.
func (t *Terminal) AltScreen() bool { return t.scr == &t.alt }
// Text is the screen in use as text, one line per row without trailing
// blanks.
func (t *Terminal) Text() string {
rows := make([]string, len(t.scr.lines))
var b []rune
for y, l := range t.scr.lines {
b = b[:0]
for _, c := range l.cells {
switch {
case c.Kind == cellWideTail:
case c.R == 0:
b = append(b, ' ')
default:
b = append(b, c.R)
}
}
rows[y] = strings.TrimRight(string(b), " ")
}
return strings.Join(rows, "\n")
}
// Write interprets output of the program.
func (t *Terminal) Write(data []byte) {
for i := 0; i < len(data); i++ {
b := data[i]
if t.p.st == stGround && t.p.utfNeed == 0 && b >= 0x20 && b < 0x7F {
j := i + 1
for j < len(data) && data[j] >= 0x20 && data[j] < 0x7F {
j++
}
t.printASCII(data[i:j])
i = j - 1
continue
}
t.advance(b)
}
}
// control executes a C0 control character.
func (t *Terminal) control(b byte) {
switch b {
case 0x08: // BS
t.cur.wrap = false
if t.cur.x > 0 {
t.cur.x--
}
case 0x09: // HT
t.tab(1)
case 0x0A, 0x0B, 0x0C: // LF, VT, FF
t.lineFeed()
if t.m.newline {
t.cur.x = 0
}
case 0x0D: // CR
t.cur.x, t.cur.wrap = 0, false
case 0x0E: // SO
t.cur.shift = 1
case 0x0F: // SI
t.cur.shift = 0
}
}
func (t *Terminal) tab(n int) {
x := t.cur.x
for ; n > 0 && x < t.cols-1; n-- {
x++
for x < t.cols-1 && !t.tabs[x] {
x++
}
}
t.cur.x = x
t.cur.wrap = false
}
func (t *Terminal) backTab(n int) {
x := t.cur.x
for ; n > 0 && x > 0; n-- {
x--
for x > 0 && !t.tabs[x] {
x--
}
}
t.cur.x, t.cur.wrap = x, false
}
// lineFeed moves down a row, scrolling the region at its bottom margin.
// It reports whether the row changed (the cursor moved or the row scrolled
// up): below the region, the last row stays.
func (t *Terminal) lineFeed() bool {
t.cur.wrap = false
switch {
case t.cur.y == t.bottom:
t.scrollUp(1)
case t.cur.y < t.rows-1:
t.cur.y++
default:
return false
}
return true
}
func (t *Terminal) reverseIndex() {
t.cur.wrap = false
switch {
case t.cur.y == t.top:
t.scrollDown(1)
case t.cur.y > 0:
t.cur.y--
}
}
// scrollUp moves the scroll region's rows up n, adding blank rows (default
// background, as the app's emulator does) at its bottom. Rows leaving the
// top of the main screen go to the scrollback.
func (t *Terminal) scrollUp(n int) {
t.shiftUp(t.top, n, t.top == 0 && t.scr == &t.main)
}
// shiftUp moves rows top to the region's bottom up n; the rows leaving at
// top go to the scrollback when keep is set.
func (t *Terminal) shiftUp(top, n int, keep bool) {
bottom := t.bottom
n = min(n, bottom-top+1)
lines := t.scr.lines
for i := 0; i < n; i++ {
gone := lines[top]
copy(lines[top:bottom], lines[top+1:bottom+1])
if keep {
gone = t.keep(gone)
}
gone.reset()
lines[bottom] = gone
}
// Rows that wrapped into a row now gone no longer continue.
t.unpair(top - 1)
if bottom-n >= top {
t.unpair(bottom - n)
}
}
func (t *Terminal) unpair(y int) {
if y >= 0 && y < len(t.scr.lines) {
t.scr.lines[y].cont = false
}
}
// keep adds l to the scrollback and returns a line to reuse in its place
// (the one the full scrollback drops, or a new one).
func (t *Terminal) keep(l *line) *line {
if t.limit == 0 {
return l
}
if len(t.history) < t.limit {
t.history = append(t.history, l)
return &line{}
}
old := t.history[t.head]
t.history[t.head] = l
t.head = (t.head + 1) % len(t.history)
return old
}
// scrollDown moves the scroll region's rows down n, adding blank rows at
// its top.
func (t *Terminal) scrollDown(n int) {
top, bottom := t.top, t.bottom
n = min(n, bottom-top+1)
lines := t.scr.lines
for i := 0; i < n; i++ {
gone := lines[bottom]
copy(lines[top+1:bottom+1], lines[top:bottom])
gone.reset()
lines[top] = gone
}
t.unpair(top - 1)
t.unpair(bottom)
}
// scrollbackLen is the number of lines in the scrollback.
func (t *Terminal) scrollbackLen() int { return len(t.history) }
// scrollbackLine is scrollback line i, oldest first.
func (t *Terminal) scrollbackLine(i int) *line {
return t.history[(t.head+i)%len(t.history)]
}
// popScrollback takes the newest scrollback line back (a taller screen).
func (t *Terminal) popScrollback() *line {
n := len(t.history)
if n == 0 {
return nil
}
if t.head != 0 {
// Unroll the ring so the newest line is last.
t.history = append(t.history[t.head:], t.history[:t.head]...)
t.head = 0
}
l := t.history[n-1]
t.history = t.history[:n-1]
return l
}
// clearScrollback is ED 3.
func (t *Terminal) clearScrollback() {
t.history, t.head = nil, 0
}
func (t *Terminal) charset() byte { return t.cur.charsets[t.cur.shift] }
// printASCII writes a run of printable ASCII characters.
func (t *Terminal) printASCII(s []byte) {
for len(s) > 0 {
if t.charset() != 'B' || t.m.insert || !t.m.autowrap {
for _, b := range s {
t.print(rune(b))
}
return
}
if t.cur.wrap {
t.wrapLine()
}
l := t.scr.lines[t.cur.y]
x := t.cur.x
n := min(len(s), t.cols-x)
l.ensure(x + n)
if l.cells[x].Kind == cellWideTail && x > 0 {
l.clearCell(x - 1)
}
cells := l.cells[x : x+n]
pen := t.cur.pen
for i, b := range s[:n] {
cells[i] = Cell{R: rune(b), A: pen}
}
l.repair(x + n)
if l.marks != nil {
l.dropMarks(x, x+n)
}
t.lastChar = rune(s[n-1])
if x+n >= t.cols {
t.cur.x, t.cur.wrap = t.cols-1, true
} else {
t.cur.x = x + n
}
s = s[n:]
}
}
// wrapLine moves to the next row's start, marking the row as continued.
func (t *Terminal) wrapLine() {
l := t.scr.lines[t.cur.y]
t.cur.x = 0
if t.lineFeed() {
l.cont = true
}
}
// decSpecial is the DEC Special Graphics set for 0x5F to 0x7E.
var decSpecial = []rune(" ◆▒␉␌␍␊°±␤␋┘┐┌└┼⎺⎻─⎼⎽├┤┴┬│≤≥π≠£·")
// print writes one character at the cursor.
func (t *Terminal) print(r rune) {
switch t.charset() {
case '0':
if r >= 0x5F && r <= 0x7E {
r = decSpecial[r-0x5F]
}
case 'A':
if r == '#' {
r = '£'
}
}
w := 1
if r >= 0x7F {
w = widths.RuneWidth(r)
}
if w == 0 {
t.mark(r)
return
}
if t.cur.wrap && t.m.autowrap {
t.wrapLine()
}
t.cur.wrap = false
if w == 2 && t.cur.x == t.cols-1 {
if t.cols < 2 {
return
}
if t.m.autowrap {
edge := t.scr.lines[t.cur.y]
edge.blank(t.cur.x, t.cur.x+1, t.cur.pen.Bg)
edge.repair(t.cur.x - 1)
t.wrapLine()
} else {
t.cur.x--
}
}
l := t.scr.lines[t.cur.y]
x := t.cur.x
if t.m.insert {
t.insertCells(w)
}
l.ensure(x + w)
if l.cells[x].Kind == cellWideTail && x > 0 {
l.clearCell(x - 1)
}
l.cells[x] = Cell{R: r, A: t.cur.pen}
if w == 2 {
l.cells[x].Kind = cellWide
l.cells[x+1] = Cell{A: t.cur.pen, Kind: cellWideTail}
}
l.repair(x + w)
if l.marks != nil {
l.dropMarks(x, x+w)
}
t.lastChar = r
if x+w >= t.cols {
t.cur.x = t.cols - 1
t.cur.wrap = t.m.autowrap
} else {
t.cur.x = x + w
}
}
// mark draws a combining character on the last written cell.
func (t *Terminal) mark(r rune) {
x := t.cur.x
if !t.cur.wrap {
x--
}
l := t.scr.lines[t.cur.y]
if x >= 0 && x < len(l.cells) && l.cells[x].Kind == cellWideTail {
x--
}
if x < 0 || x >= len(l.cells) {
return
}
if l.marks == nil {
l.marks = map[int]string{}
}
if len(l.marks[x]) < 32 {
l.marks[x] += string(r)
}
}
// insertCells is ICH: n blanks at the cursor, the rest of the row shifts
// right (what passes the edge is lost).
func (t *Terminal) insertCells(n int) {
l := t.scr.lines[t.cur.y]
x := t.cur.x
if x >= len(l.cells) {
return
}
n = min(n, t.cols-x)
l.ensure(min(len(l.cells)+n, t.cols))
copy(l.cells[x+n:], l.cells[x:])
l.blank(x, x+n, t.cur.pen.Bg)
l.repair(x - 1)
l.repair(x + n)
// A wide character pushed to the edge lost its tail.
l.repair(len(l.cells) - 1)
l.marks = nil
}
// deleteCells is DCH: n cells at the cursor go, the rest shifts left.
func (t *Terminal) deleteCells(n int) {
l := t.scr.lines[t.cur.y]
x := t.cur.x
t.cur.wrap = false
if x >= len(l.cells) && t.cur.pen.Bg == 0 {
return
}
n = min(n, t.cols-x)
l.ensure(t.cols)
copy(l.cells[x:], l.cells[x+n:])
l.blank(t.cols-n, t.cols, t.cur.pen.Bg)
l.repair(x - 1)
l.repair(x)
l.repair(t.cols - n - 1)
l.marks = nil
}
// insertLines is IL: n blank rows at the cursor's row within the scroll
// region, pushing the rows below down.
func (t *Terminal) insertLines(n int) {
if t.cur.y < t.top || t.cur.y > t.bottom {
return
}
top := t.top
t.top = t.cur.y
t.scrollDown(n)
t.top = top
t.cur.x, t.cur.wrap = 0, false
}
// deleteLines is DL: n rows at the cursor's row go, the region below moves
// up (nothing reaches the scrollback).
func (t *Terminal) deleteLines(n int) {
if t.cur.y < t.top || t.cur.y > t.bottom {
return
}
t.shiftUp(t.cur.y, n, false)
t.cur.x, t.cur.wrap = 0, false
}