// Package termstate is a headless terminal emulator that follows one // pseudo-terminal's output stream and can write a snapshot: an escape // sequence stream that brings a freshly reset terminal to the same state // (main screen with bounded scrollback, the alternate screen when it is in // use, cursor, pen, scroll region, character sets and terminal modes). // // It interprets what xterm-compatible programs write (the subset of xterm // that full-screen programs use, the same one the app's emulator follows); // it never answers queries, since the clients' emulators do. It is built for // throughput: a line scrolled off the top is moved, not copied, and blank // cells past a line's written part are not stored. package termstate // Color is a cell colour: 0 is the default colour, colorIndexed|n is // palette entry n, colorRGB|0xRRGGBB a direct colour. type Color uint32 const ( colorIndexed Color = 1 << 24 colorRGB Color = 2 << 24 colorKind Color = 3 << 24 ) // Attribute flags of a cell (SGR). const ( attrBold uint16 = 1 << iota attrFaint attrItalic attrBlink attrInverse attrHidden attrStrike attrOverline // The underline style (SGR 4:n, 1 to 5) is held in three bits. attrUnderlineShift = 13 attrUnderlineMask = 7 << attrUnderlineShift ) // Attr is the pen a cell was written with. type Attr struct { Fg, Bg Color Flags uint16 } func (a Attr) underline() int { return int(a.Flags&attrUnderlineMask) >> attrUnderlineShift } func (a *Attr) setUnderline(style int) { a.Flags = a.Flags&^attrUnderlineMask | uint16(style&7)<= to { return } l.dropMarks(from, to) if bg == 0 && to >= len(l.cells) { if from < len(l.cells) { l.cells = l.cells[:from] } return } l.ensure(to) fill := Cell{A: Attr{Bg: bg}} for i := from; i < to; i++ { l.cells[i] = fill } } func (l *line) dropMarks(from, to int) { if l.marks == nil { return } for x := range l.marks { if x >= from && x < to { delete(l.marks, x) } } } // repair blanks half of a wide character whose other half is gone, at x. func (l *line) repair(x int) { if x < 0 || x >= len(l.cells) { return } switch l.cells[x].Kind { case cellWideTail: if x == 0 || l.cells[x-1].Kind != cellWide { l.clearCell(x) } case cellWide: if x+1 >= len(l.cells) || l.cells[x+1].Kind != cellWideTail { l.clearCell(x) } } } // clearCell blanks the cell at x, keeping its background. func (l *line) clearCell(x int) { l.cells[x] = Cell{A: Attr{Bg: l.cells[x].A.Bg}} if l.marks != nil { delete(l.marks, x) } } // truncate cuts the row at width cols. func (l *line) truncate(cols int) { if len(l.cells) > cols { l.cells = l.cells[:cols] l.dropMarks(cols, int(^uint(0)>>1)) l.repair(cols - 1) } } // empty reports whether nothing visible is on the row. func (l *line) empty() bool { for i := range l.cells { if l.cells[i] != (Cell{}) { return false } } return true }