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>
This commit is contained in:
2026-11-26 00:56:49 +00:00
parent fc5d3bc42b
commit e13cb99ade
24 changed files with 2788 additions and 15 deletions
@@ -27,6 +27,7 @@ class ChatShellRun {
this.outputEnd = 0,
this.outputBytes = 0,
this.gap = false,
this.snapshot = false,
this.terminal = false,
this.cols = 0,
this.rows = 0,
@@ -59,6 +60,11 @@ class ChatShellRun {
/// stretch of what the command wrote.
final bool gap;
/// True when [output] starts with the server's redraw of the terminal's
/// state at [outputStart] (screens, scrollback, cursor and modes) instead
/// of raw output: nothing earlier is missing from what it shows.
final bool snapshot;
/// True when the command runs in a pseudo-terminal of [cols] x [rows]:
/// [output] is then the raw terminal stream and it accepts typed input
/// while it runs. Older runs (and servers without terminals) are plain.
@@ -78,7 +84,7 @@ class ChatShellRun {
final bool purged;
/// Whether earlier output is not shown here.
bool get truncated => outputStart > 0 || gap;
bool get truncated => !snapshot && (outputStart > 0 || gap);
ChatShellRunState get state => switch (status) {
'running' => ChatShellRunState.running,
@@ -144,6 +150,7 @@ class ChatShellRun {
? next.outputBytes
: outputBytes,
gap: gap,
snapshot: snapshot,
terminal: next.terminal || terminal,
cols: next.cols == 0 ? cols : next.cols,
rows: next.rows == 0 ? rows : next.rows,
@@ -180,6 +187,7 @@ class ChatShellRun {
outputEnd: end,
outputBytes: end > outputBytes ? end : outputBytes,
gap: gap || dropped || (!contiguous && offset > 0),
snapshot: snapshot && contiguous && !dropped,
terminal: terminal,
cols: cols,
rows: rows,
@@ -96,8 +96,12 @@ class ChatShellTerminalSession {
}
/// Draws [run]'s held output from scratch: on open, after a gap and after
/// a readback replaced the card's copy. Answers the emulator gives to old
/// queries in that output are not sent: the process asked them long ago.
/// a readback replaced the card's copy. A machine terminal's read from
/// before the server's tail is the server's snapshot
/// ([ChatShellRun.snapshot]), which resets the emulator and restores the
/// screens, scrollback, cursor and modes; it is drawn the same way.
/// Answers the emulator gives to old queries in that output are not sent:
/// the process asked them long ago.
/// A large output is drawn in slices across turns of the event loop
/// (ChatShellTerminalFeed), so it never stalls the UI.
void replay(ChatShellRun run) {
@@ -109,6 +113,9 @@ class ChatShellTerminalSession {
terminal.useMainBuffer();
terminal.buffer.clear();
terminal.buffer.setCursor(0, 0);
// A full reset (RIS): modes a program set in the output drawn before
// (mouse reporting, bracketed paste, the alternate screen) end too.
terminal.write('\x1bc');
terminal.setCursorVisibleMode(true);
terminal.write('\x1b[0m');
if (run.truncated) {
+15 -2
View File
@@ -25,17 +25,29 @@ class TerminalStream {
int end = 0;
String stream = '';
/// Whether [text] starts with the server's snapshot of the terminal's
/// state at [start] rather than raw output (until its start is dropped).
bool snapshot = false;
/// Whether nothing was received yet.
bool get empty => stream.isEmpty && end == 0;
/// Replaces the held copy with a read of the server's retained tail,
/// covering bytes [outputStart, outputEnd) (the server's offsets: the
/// text's own UTF-8 length differs where invalid bytes were replaced).
void reset(String output, int outputStart, int outputEnd, String name) {
/// text's own UTF-8 length differs where invalid bytes were replaced), or
/// with its [snapshot] of the terminal at [outputStart].
void reset(
String output,
int outputStart,
int outputEnd,
String name, {
bool snapshot = false,
}) {
text = output;
start = outputStart;
end = outputEnd;
stream = name;
this.snapshot = snapshot;
_bound();
}
@@ -59,6 +71,7 @@ class TerminalStream {
if (unit >= 0xDC00 && unit <= 0xDFFF) cut++;
final dropped = text.substring(0, cut);
text = text.substring(cut);
snapshot = false;
// The server's offsets are not re-derived from the text: only the
// dropped part is measured (approximately, for replaced bytes).
start += utf8.encode(dropped).length;
+7 -2
View File
@@ -81,6 +81,7 @@ class TerminalTab extends ChangeNotifier {
output: _stream.text,
outputStart: _stream.start,
outputEnd: _stream.end,
snapshot: _stream.snapshot,
terminal: true,
cols: _info.cols,
rows: _info.rows,
@@ -156,8 +157,12 @@ class TerminalTab extends ChangeNotifier {
// The server counts this connection's window from the reply's end.
_window = (record['window'] as num?)?.toInt() ?? 0;
_acked = end;
if (after == null || start > _stream.end) {
_stream.reset(output, start, end, info.stream);
// A read from before the server's retained tail (a new page, a reload,
// a gap) is its snapshot of the terminal: the screens, scrollback,
// cursor and modes as of the reply's end.
final snapshot = record['output_snapshot'] == true;
if (after == null || start > _stream.end || snapshot) {
_stream.reset(output, start, end, info.stream, snapshot: snapshot);
session.replay(_run());
} else {
_append(output, start, end);
+71 -1
View File
@@ -198,6 +198,73 @@ Emulator (`chat_shell_terminal_feed_test.dart`, 896 KiB replay): one
synchronous write 160 ms; sliced, the same 161 ms over 20 turns, the
longest turn 12.5 ms.
## Screen state across reloads (2026-11-26)
The server keeps each machine terminal's *state*, not only its bytes, so
a client that attaches late is brought to the exact current screen.
- `internal/termstate` is a headless xterm-compatible emulator (own code;
see "Why not a library" below). `terminal_process.go` feeds it every PTY
read under `p.mu`, the same lock as the 1 MiB tail, so its state always
belongs to the tail's end; `applySize` resizes it with the PTY.
- `terminal_output` whose `after` is before the retained tail (the newest
1 MiB; a missing `after` counts as 0) gets `output_snapshot: true`:
`output` is the emulator's snapshot and `output_start == output_end`
is the offset it describes; the frames that follow start there, and the
flow window counts from it as from any reply (`terminal_screen.go`). A
read inside the tail (an ordinary resume, or a stream not longer than
1 MiB) is raw bytes as before.
- The snapshot (`termstate.Snapshot`) is an escape stream for a reset
terminal: `RIS` + `ED 3`, the title (OSC 2), the inactive alternate
screen if it holds anything (`?47h` … `?47l`), the last 1000 scrollback
lines and the main screen row by row (soft wraps wrap again), then, if
the alternate screen is in use, the main screen's saved cursor and
`?1049h` (so the program's exit restores it) and the alternate screen
drawn row by row; then the saved cursor(s), tab stops, scroll region,
origin mode, the cursor (a pending wrap is recreated by rewriting the
last cell; the cell before the cursor is rewritten when it holds the last
character, for REP), modes (DECCKM, DECKPAM, autowrap, IRM, LNM, reverse
video, cursor blink/visibility/shape, mouse tracking 9/1000-1003 and
encoding 1005/1006/1015, focus 1004, bracketed paste 2004, 1007), G0/G1
character sets and SO, the pen (SGR incl. 256/RGB colours and underline
styles) and the start of an unfinished escape sequence or OSC string. An
unfinished UTF-8 character is left out (`output_end` is before it; the
next frame carries it whole).
- Client: `TerminalTab._read` resets its held copy and replays when the
reply is a snapshot (`TerminalStream.snapshot`, `ChatShellRun.snapshot`:
no "earlier output was dropped" line). `ChatShellTerminalSession.replay`
now writes RIS before any replay, so a raw replay no longer inherits
stale mouse/paste/alt-screen modes either.
- Chat shell interactive commands are not covered: their readbacks come
from the run record (DB snapshot every 2 s of the raw tail) on a
separate path; they get only the RIS-on-replay change.
Why not a library: `github.com/charmbracelet/x/vt` v0.1.0 (MIT, active)
keeps scroll region, pen and modes private and scrolls by copying cells:
measured 0.2-1 MB/s for `seq` and 4.5 MB/s for wrapping text, 33 MB/s for
redraws. `github.com/vito/midterm` v0.2.5 (MIT): 1-4 MB/s scrolling,
ignores keypad and most modes. `github.com/hinshun/vt10x`: unmaintained
since 2022, no scrollback or bracketed paste. termstate moves rows by
pointer, keeps blank cells implicit and recycles evicted scrollback rows.
Measured (`go test ./internal/termstate -bench .`, Ryzen 7 5800X, 8 MB
each, 32 KiB writes): `seq` 190 MB/s, coloured full-screen redraws 160-165
MB/s, wrapping mixed text 172-180 MB/s, at 80x24 and 200x50; a snapshot of
1000 full 200-column scrollback rows: 2 ms, 229 KiB (seq: 9 KiB; a 40-row
TUI: 4-39 KiB). Cells: 230 KiB per terminal for `seq`, up to 5.9 MB at
200 columns with 1000 full rows. End to end (`TestMeasureTerminalStream`,
same machine, two runs each, before → after): seq 20.8/22.8 → 25.0/25.3
MB/s, cat 80/102 → 80/76 MB/s, yes 10.4/11.4 → 10.4/10.7 MB/s, echo
median 0.36/0.41 → 0.48/0.38 ms: no measurable cost.
Known gaps: origin mode with the cursor outside the scroll region (a DECRC
can leave it there) is not recreated; hyperlinks (OSC 8), palette changes
(OSC 4/10/11), DECSLRM and kitty keyboard modes are not tracked; DECSC's
origin flag is not saved (as in the app's emulator); scrolled-in rows are
blank in the default colour (as in the app's emulator, not xterm's BCE).
The server emulates at the PTY size; a client drawing at another size gets
the snapshot at the PTY's.
## Login and lifetime (server)
- `internal/server/terminal_login.go`. A terminal runs, in its PTY,
@@ -276,7 +343,10 @@ longest turn 12.5 ms.
- Server: `internal/protocol/terminal.go`, `message.go`;
`internal/pipeline/terminals.go`, `store.go`;
`internal/server/terminal_{manager,supervise,process,login,legacy_tmux,clients,title,cwd,handlers}.go`,
`internal/server/terminal_{manager,supervise,process,login,legacy_tmux,clients,title,cwd,handlers,flow,screen}.go`,
`internal/termstate/` (headless emulator and snapshots; tests
`snapshot_test.go`, `random_test.go`, `bench_test.go`),
`terminal_screen_test.go`,
`websocket.go`, `cmd/pipelines-server/main.go`; tests `terminal_ws_test.go`,
`terminal_login_test.go`, `terminal_lifetime_test.go`, `terminal_legacy_tmux_test.go`,
`internal/pipeline/terminals_test.go`; `docs/cli.md`.
@@ -28,6 +28,12 @@ class TerminalGateway implements ApiGateway {
/// where runs of invalid bytes became one shorter replacement character).
final Map<String, int> byteShift = {};
/// A terminal's state as the server's snapshot: when set, a read from
/// before [snapshotFrom] gets it (as of the output's end) instead of raw
/// output.
final Map<String, String> snapshots = {};
int snapshotFrom = 1 << 30;
@override
Stream<JsonMap> get frames => _frames.stream;
@@ -56,6 +62,19 @@ class TerminalGateway implements ApiGateway {
final text = output[id] ?? '';
final bytes = utf8.encode(text);
final start = after.clamp(0, bytes.length);
final snapshot = snapshots[id];
if (withOutput && snapshot != null && after < snapshotFrom) {
final end = bytes.length + (byteShift[id] ?? 0);
return {
...terminals[id]!,
'stream': stream,
'output': snapshot,
'output_start': end,
'output_end': end,
'output_snapshot': true,
if (window > 0) 'window': window,
};
}
return {
...terminals[id]!,
'stream': stream,
@@ -0,0 +1,149 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
import 'package:pipelines_app/features/terminal/terminal_tab.dart';
import 'package:xterm/core.dart';
import 'terminal_fixtures.dart';
/// What the server's emulator (internal/termstate) writes for a 40x8
/// terminal where a shell ran twelve commands and then nvim, which set
/// mouse, bracketed paste and application cursor/keypad modes on the
/// alternate screen.
const _snapshot =
'\x1bc\x1b[3J\x1b]2;nvim notes.txt\x07'
'\$ echo 1\r\n1\r\n\$ echo 2\r\n2\r\n\$ echo 3\r\n3\r\n\$ echo 4\r\n4\r\n'
'\$ echo 5\r\n5\r\n\$ echo 6\r\n6\r\n\$ echo 7\r\n7\r\n\$ echo 8\r\n8\r\n'
'\$ echo 9\r\n9\r\n\$ echo 10\r\n10\r\n\$ echo 11\r\n11\r\n'
'\$ echo 12\r\n12\r\n\$ nvim notes.txt\r\n'
'\x1b[8;1H\x1b[?1049h\x1b[1;1H\x1b[0;1;34mFRAME\x1b[2;1H\x1b[0mline two'
'\x1b[8;1H\x1b[0;7m-- INSERT --\x1b[2;9H\x1b[?1h\x1b=\x1b[?25l'
'\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[0m';
/// What nvim writes as it exits, then the shell.
const _exit =
'\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?1l\x1b>\x1b[?25h\x1b[?1049l'
'\$ ls\r\nnotes.txt\r\n\$ ';
/// The rows on screen (not the scrollback), trailing blanks trimmed.
List<String> rows(Terminal terminal) {
final buffer = terminal.buffer;
final top = buffer.height - terminal.viewHeight;
return [
for (var y = top; y < buffer.height; y++)
buffer.lines[y].getText().trimRight(),
];
}
void main() {
late TerminalGateway mac;
late TerminalHub hub;
setUp(() {
mac = TerminalGateway()..window = 1 << 18;
hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')]));
});
tearDown(() async {
hub.dispose();
await mac.close();
});
Future<void> settle() async {
for (var i = 0; i < 5; i++) {
await Future<void>.delayed(Duration.zero);
}
}
/// A terminal whose stream is longer than the server's tail.
void longTerminal(String raw) {
mac.add('term_a', text: raw);
mac.terminals['term_a']!['cols'] = 40;
mac.terminals['term_a']!['rows'] = 8;
}
void expectNvim(TerminalTab tab) {
final terminal = tab.session.terminal;
expect(terminal.isUsingAltBuffer, isTrue);
expect(rows(terminal), [
'FRAME',
'line two',
'',
'',
'',
'',
'',
'-- INSERT --',
]);
expect(terminal.buffer.cursorX, 8);
expect(terminal.buffer.cursorY, 1);
expect(terminal.mouseMode, MouseMode.upDownScrollDrag);
expect(terminal.mouseReportMode, MouseReportMode.sgr);
expect(terminal.bracketedPasteMode, isTrue);
expect(terminal.cursorKeysMode, isTrue);
expect(terminal.appKeypadMode, isTrue);
expect(terminal.cursorVisibleMode, isFalse);
expect(tab.title, 'nvim notes.txt');
}
void expectShellAfterExit(TerminalTab tab) {
final terminal = tab.session.terminal;
expect(terminal.isUsingAltBuffer, isFalse);
expect(rows(terminal), [
r'$ echo 11',
'11',
r'$ echo 12',
'12',
r'$ nvim notes.txt',
r'$ ls',
'notes.txt',
r'$',
]);
// The shell's history above the screen came back with it.
expect(terminal.buffer.lines[0].getText().trimRight(), r'$ echo 1');
expect(terminal.mouseMode, MouseMode.none);
expect(terminal.bracketedPasteMode, isFalse);
expect(terminal.cursorKeysMode, isFalse);
expect(terminal.cursorVisibleMode, isTrue);
}
test('a reload draws the snapshot: the program on the alternate screen, '
'its modes, and the shell underneath once it exits', () async {
longTerminal('x' * 3000);
mac.snapshots['term_a'] = _snapshot;
hub.activate();
await settle();
final tab = hub.tabs.single;
expect(mac.bodies('terminal_output').single['after'], isNull);
expect(tab.session.end, 3000);
expectNvim(tab);
// No "earlier output was dropped" line: the snapshot misses nothing.
expect(
tab.session.terminal.mainBuffer.lines[0].getText(),
isNot(contains('dropped')),
);
mac.write('term_a', _exit);
await settle();
expectShellAfterExit(tab);
});
test('after a gap the snapshot replaces what the tab drew, modes '
'included', () async {
longTerminal('stale\x1b[?1000h\x1b[?1049h');
hub.activate();
await settle();
final tab = hub.tabs.single;
expect(tab.session.terminal.mouseMode, MouseMode.upDownScroll);
final held = tab.session.end;
// The tab falls behind past the server's tail, which now starts later.
mac.write('term_a', 'y' * 5000, push: false);
mac.snapshots['term_a'] = _snapshot;
mac.snapshotFrom = held + 100;
final end = held + 5000;
mac.pushOutput('term_a', 'z', end, end: end + 1);
await settle();
expect(mac.bodies('terminal_output').last['after'], held);
expectNvim(tab);
mac.write('term_a', _exit);
await settle();
expectShellAfterExit(tab);
});
}
+9 -2
View File
@@ -1330,8 +1330,15 @@ app's terminal panel). Every request carries `terminal_request`
- `terminal_output {terminal_id, after, flow?}` replies with the retained
output (1 MiB tail) from byte `after` of the stream named `stream`, covering
bytes `[output_start, output_end)`; the output frames that follow the reply
start at `output_end`. Opening or reading subscribes the connection to the
terminal's output frames.
start at `output_end`. When `after` is before the retained tail (or
missing) and the stream is longer than the tail, the reply carries
`output_snapshot: true` instead: `output` is the server's redraw of the
terminal as of `output_end` (= `output_start`): a reset, the scrollback
(last 1000 lines), the main screen, the alternate screen when in use, the
cursor, modes (mouse, bracketed paste, cursor keys, keypad, ...) and pen,
from a headless emulator the server feeds with the terminal's output. A
client writes it into its emulator as it would a replay. Opening or
reading subscribes the connection to the terminal's output frames.
- `terminal_ack {terminal_id, after}` (flow-controlled subscriptions only):
the connection has drawn the output up to byte `after`. Not logged.
- `terminal_close {terminal_id}` kills the login or shell.
+1 -1
View File
@@ -11,6 +11,7 @@ require (
github.com/charmbracelet/x/ansi v0.10.1
github.com/coder/websocket v1.8.15
github.com/hashicorp/mdns v1.0.7
github.com/mattn/go-runewidth v0.0.16
github.com/miekg/dns v1.1.72
github.com/muesli/termenv v0.16.0
github.com/pmezard/go-difflib v1.0.0
@@ -42,7 +43,6 @@ require (
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
+11 -3
View File
@@ -31,9 +31,11 @@ const (
// terminal is its first active client. The reply echoes the terminal.
TerminalResize = "terminal_resize"
// TerminalOutput reads one terminal with its retained output from the
// absolute byte After on (all of it when After precedes the retained
// tail; OutputStart says where it starts). It also subscribes the
// connection to the terminal's terminal_event output frames.
// absolute byte After on (OutputStart says where it starts). When After
// precedes the retained tail (the newest TerminalRetained bytes; a stream
// no longer than that is read whole), the reply is a snapshot of the
// terminal's state instead (OutputSnapshot). It also subscribes the connection to the terminal's
// terminal_event output frames.
TerminalOutput = "terminal_output"
// TerminalClose ends a terminal: its login or shell is killed
// and its record removed. The reply echoes the last record.
@@ -127,6 +129,12 @@ type TerminalRecord struct {
OutputEnd int64 `json:"output_end"`
Output string `json:"output,omitempty"`
OutputStart int64 `json:"output_start,omitempty"`
// OutputSnapshot marks a terminal_output reply whose Output is not raw
// output but the server's redraw of the terminal as of OutputEnd (which
// OutputStart equals): it resets the emulator and restores the
// scrollback, the screens, the cursor and the modes. A client writes it
// into a reset emulator as it would a replay.
OutputSnapshot bool `json:"output_snapshot,omitempty"`
// Window is set on the terminal_open and terminal_output replies of a
// flow-controlled subscription: the bytes the server sends past the
// last terminal_ack. Its absence means the server takes no acks.
+1
View File
@@ -287,6 +287,7 @@ func (p *terminalProcess) applySize(cols, rows int) error {
cols, rows = chatShellTerminalSize(cols, rows)
p.mu.Lock()
p.record.Cols, p.record.Rows = cols, rows
p.screen.Resize(cols, rows)
terminal := p.pty
p.mu.Unlock()
if terminal != nil {
+12 -1
View File
@@ -11,6 +11,7 @@ import (
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/termstate"
)
// terminalProcess is one terminal this server process holds: running (its
@@ -20,6 +21,8 @@ type terminalProcess struct {
mu sync.Mutex
record protocol.TerminalRecord
out *chatShellOutput
// screen follows the output (terminal_screen.go).
screen *termstate.Terminal
titles terminalTitles
// login follows the output until the login completes; loginChanged is
// signalled when it changes.
@@ -54,6 +57,7 @@ func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess {
return &terminalProcess{
record: record,
out: newChatShellOutput(protocol.TerminalRetained),
screen: termstate.New(record.Cols, record.Rows, termstate.DefaultScrollback),
input: make(chan []byte, protocol.ChatShellInputQueue),
done: make(chan struct{}),
views: map[*terminalView]struct{}{},
@@ -87,10 +91,16 @@ func (p *terminalProcess) snapshot(output bool, after int64) protocol.TerminalRe
}
// snapshotLocked is snapshot with p.mu held. The output ends at OutputEnd:
// an incomplete trailing character waits for the next frame.
// an incomplete trailing character waits for the next frame. A read from
// before the retained tail gets the screen's snapshot instead of the tail
// (terminal_screen.go).
func (p *terminalProcess) snapshotLocked(output bool, after int64) protocol.TerminalRecord {
record := p.record
record.OutputEnd = p.out.total
if output && after < p.retainedFromLocked() {
p.screenLocked(&record)
return record
}
if output {
from := max(after, p.out.start)
text, start, end, ok := p.out.chunk(from, p.out.total, protocol.TerminalRetained, p.outDone)
@@ -150,6 +160,7 @@ func (p *terminalProcess) read(terminal *os.File, titled func(string)) {
if n > 0 {
p.mu.Lock()
p.out.write(buffer[:n])
p.screen.Write(buffer[:n])
p.pokeViewsLocked()
if p.login.feed(buffer[:n]) {
select {
+37
View File
@@ -0,0 +1,37 @@
package server
import "git.a-wan.net/alan/pipelines/internal/protocol"
// A machine terminal's output also feeds a headless emulator
// (internal/termstate), under the same lock as the retained tail, so its
// state always belongs to the tail's end. A client that reads from before
// the tail (a new page, a reload, a reconnect after the tail moved on, a
// gap) would otherwise redraw from an arbitrary cut: a full-screen program
// that wrote more than the tail since it started would land on the main
// screen, and its modes (mouse, bracketed paste, cursor keys, ...) would be
// lost. Such a read gets the emulator's snapshot instead: an escape
// sequence stream that resets the client's emulator and redraws the
// scrollback, the main screen, the alternate screen when in use, the
// cursor, the modes and the pen, as of OutputEnd; the frames that follow
// start there. A read inside the tail (an ordinary resume, or a stream not
// longer than the tail) gets the raw bytes as before.
// retainedFromLocked is where the retained tail starts: the newest
// TerminalRetained bytes (the buffer may hold more until it compacts).
func (p *terminalProcess) retainedFromLocked() int64 {
return max(p.out.start, p.out.total-protocol.TerminalRetained)
}
// screenLocked sets record's output to the screen's snapshot. p.mu is held.
func (p *terminalProcess) screenLocked(record *protocol.TerminalRecord) {
snap, partial := p.screen.Snapshot()
end := p.out.total
if !p.outDone {
// An unfinished character is left out of the snapshot and sent
// whole in the next frame.
end -= int64(partial)
}
record.Output = validChatShellText(snap)
record.OutputStart, record.OutputEnd = end, end
record.OutputSnapshot = true
}
+75
View File
@@ -0,0 +1,75 @@
//go:build darwin || linux
package server
import (
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/termstate"
)
// tuiCommand enters the alternate screen, sets mouse, bracketed paste and
// application cursor/keypad modes, writes more than the retained tail
// there, draws a last frame and waits for a line; then it restores the
// modes, leaves the alternate screen and prints a marker. The markers are
// computed, so the command's own echo does not contain them.
const tuiCommand = `echo before-$((1))tui; ` +
`printf '\033[?1049h\033[?1000h\033[?1006h\033[?2004h\033[?1h\033=\033[H\033[2J'; ` +
`head -c 1300000 /dev/zero | tr '\0' x; ` +
`printf '\033[H\033[2JFRAME-%s\033[24;1Hstatus-%s' $((7)) $((8)); read x; ` +
`printf '\033[?2004l\033[?1006l\033[?1000l\033[?1l\033>\033[?1049l'; echo after-$((2))tui` + "\r"
// A client that attaches (a reload, or one that fell behind the retained
// tail) while a full-screen program runs gets the terminal's state, not the
// tail: the program's screen on the alternate screen with its modes, and
// the shell's screen underneath, which the program's exit brings back.
func TestTerminalSnapshotAfterReload(t *testing.T) {
terminalHome(t)
ctx, conns := dialTerminalConns(t, 2, 60*time.Second)
term := openLoggedIn(t, ctx, conns[0], true)
reader := &terminalReader{t: t, ctx: ctx, conn: conns[0], id: term.ID, end: term.OutputEnd, ack: true}
typeInto(t, ctx, conns[0], term.ID, tuiCommand)
reader.until("status-8", nil)
// The reload: no After at all, and one far before the tail.
var reply *protocol.TerminalRecord
for _, after := range []int64{0, 5} {
reply = terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalOutput, "reload", protocol.TerminalRequest{TerminalID: term.ID, After: after, Flow: true})).Terminal
if !reply.OutputSnapshot || reply.OutputStart != reply.OutputEnd || reply.OutputEnd != reader.end || reply.Window != protocol.TerminalFlowWindow {
t.Fatalf("after %d: reply start %d end %d (reader at %d) snapshot %v window %d", after, reply.OutputStart, reply.OutputEnd, reader.end, reply.OutputSnapshot, reply.Window)
}
}
for _, want := range []string{"\x1b[?1049h", "\x1b[?1000h", "\x1b[?1006h", "\x1b[?2004h", "\x1b[?1h", "\x1b=", "FRAME-7", "status-8", "before-1tui"} {
if !strings.Contains(reply.Output, want) {
t.Fatalf("snapshot lacks %q", want)
}
}
if len(reply.Output) > 64<<10 {
t.Fatalf("snapshot is %d bytes", len(reply.Output))
}
// A resume inside the tail is raw output, as before.
if resume := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalOutput, "resume", protocol.TerminalRequest{TerminalID: term.ID, After: reply.OutputEnd, Flow: true})).Terminal; resume.OutputSnapshot || resume.Output != "" {
t.Fatalf("resume = %+v", resume)
}
screen := termstate.New(term.Cols, term.Rows, termstate.DefaultScrollback)
screen.Write([]byte(reply.Output))
if !screen.AltScreen() || !strings.HasPrefix(screen.Text(), "FRAME-7") || !strings.Contains(screen.Text(), "status-8") {
t.Fatalf("snapshot screen (alt %v):\n%s", screen.AltScreen(), screen.Text())
}
// The program exits; the frames continue exactly after the snapshot.
typeInto(t, ctx, conns[0], term.ID, "\r")
late := &terminalReader{t: t, ctx: ctx, conn: conns[1], id: term.ID, end: reply.OutputEnd, ack: true}
late.until("after-2tui", nil)
if late.gaps != 0 {
t.Fatalf("frames after the snapshot skipped %d bytes", late.gaps)
}
screen.Write([]byte(late.text.String()))
text := screen.Text()
if screen.AltScreen() || !strings.Contains(text, "before-1tui") || !strings.Contains(text, "after-2tui") || strings.Contains(text, "FRAME-7") || strings.Contains(text, "xxxx") {
t.Fatalf("main screen after the exit (alt %v):\n%s", screen.AltScreen(), text)
}
}
+60
View File
@@ -0,0 +1,60 @@
package termstate
import (
"fmt"
"math/rand"
"strings"
"testing"
)
// Workloads of the throughput the terminal output path sustains (about 30
// MB/s): `seq`, a full-screen program redrawing coloured frames, long
// wrapping lines of mixed text.
func workloads() map[string][]byte {
var b strings.Builder
for i := 1; b.Len() < 8<<20; i++ {
fmt.Fprintf(&b, "%d\r\n", i)
}
seq := b.String()
b.Reset()
r := rand.New(rand.NewSource(1))
b.WriteString("\x1b[?1049h")
for b.Len() < 8<<20 {
fmt.Fprintf(&b, "\x1b[%d;%dH\x1b[38;5;%dm\x1b[48;2;%d;%d;%dm%s\x1b[0m", r.Intn(50)+1, r.Intn(150)+1, r.Intn(256), r.Intn(256), r.Intn(256), r.Intn(256), strings.Repeat("x", r.Intn(40)))
}
tui := b.String()
b.Reset()
for b.Len() < 8<<20 {
b.WriteString("the quick brown fox jumps over the lazy dog ünïcödé 日本語 ")
}
return map[string][]byte{"seq": []byte(seq), "tui": []byte(tui), "text": []byte(b.String())}
}
func BenchmarkWrite(b *testing.B) {
loads := workloads()
for _, name := range []string{"seq", "tui", "text"} {
for _, size := range [][2]int{{80, 24}, {200, 50}} {
data := loads[name]
b.Run(fmt.Sprintf("%s/%dx%d", name, size[0], size[1]), func(b *testing.B) {
b.SetBytes(int64(len(data)))
for b.Loop() {
term := New(size[0], size[1], DefaultScrollback)
for i := 0; i < len(data); i += 32 << 10 {
term.Write(data[i:min(i+32<<10, len(data))])
}
}
})
}
}
}
// A snapshot of a full scrollback of wide rows.
func BenchmarkSnapshot(b *testing.B) {
term := New(200, 50, DefaultScrollback)
term.Write(workloads()["text"])
snap, _ := term.Snapshot()
b.ReportMetric(float64(len(snap)), "bytes")
for b.Loop() {
term.Snapshot()
}
}
+171
View File
@@ -0,0 +1,171 @@
// 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)<<attrUnderlineShift
}
// Cell kinds: a wide character takes its cell and a tail cell after it.
const (
cellNarrow uint8 = iota
cellWide
cellWideTail
)
// Cell is one character cell. R is 0 for a blank (never written or erased)
// cell, which still carries the background it was erased with.
type Cell struct {
R rune
A Attr
Kind uint8
}
// line is one row. Cells past len(cells) are blank with the default pen.
type line struct {
cells []Cell
// cont: the row was filled and the text went on in the next row (a soft
// wrap), so the two are one logical line.
cont bool
// marks are combining characters drawn on the cell at a column.
marks map[int]string
}
func (l *line) reset() {
l.cells = l.cells[:0]
l.cont = false
l.marks = nil
}
// ensure makes at least n cells addressable.
func (l *line) ensure(n int) {
if n <= len(l.cells) {
return
}
if n <= cap(l.cells) {
old := len(l.cells)
l.cells = l.cells[:n]
clear(l.cells[old:])
return
}
grown := make([]Cell, n, max(n, 2*cap(l.cells)))
copy(grown, l.cells)
l.cells = grown
}
// blank fills [from, to) with blank cells of background bg, truncating
// instead when the default background reaches the end.
func (l *line) blank(from, to int, bg Color) {
if from >= 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
}
+519
View File
@@ -0,0 +1,519 @@
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()
}
+105
View File
@@ -0,0 +1,105 @@
package termstate
import (
"fmt"
"strings"
)
// dump describes everything a snapshot restores, normalised where two
// states look and behave the same: a never-written cell and a written space
// of the same pen, trailing blanks, a soft wrap into an empty row, and the
// content of the screen not in use.
func dump(t *Terminal) string {
var b strings.Builder
fmt.Fprintf(&b, "size %dx%d alt=%v region=%d-%d title=%q shape=%d\n", t.cols, t.rows, t.scr == &t.alt, t.top, t.bottom, t.title, t.cursorShape)
c := t.cur
fmt.Fprintf(&b, "cursor %d,%d wrap=%v origin=%v pen=%+v charsets=%c%c shift=%d\n", c.x, c.y, c.wrap, c.origin, c.pen, c.charsets[0], c.charsets[1], c.shift)
fmt.Fprintf(&b, "modes %+v\n", t.m)
for _, s := range []*screen{&t.main, &t.alt} {
if s.savedValid {
fmt.Fprintf(&b, "saved %d,%d pen=%+v\n", s.saved.x, s.saved.y, s.saved.pen)
} else {
b.WriteString("saved none\n")
}
}
fmt.Fprintf(&b, "tabs %v\n", t.tabs)
var main []*line
for i := 0; i < t.scrollbackLen(); i++ {
main = append(main, t.scrollbackLine(i))
}
fmt.Fprintf(&b, "scrollback %d\n", t.scrollbackLen())
main = append(main, t.main.lines...)
for i, l := range main {
cont := l.cont && i+1 < len(main) && !blankLine(main[i+1])
b.WriteString(dumpLine(l, cont))
}
{
b.WriteString("alt\n")
for _, l := range t.alt.lines {
b.WriteString(dumpLine(l, false))
}
}
return b.String()
}
func dumpLine(l *line, cont bool) string {
cells := make([]Cell, len(l.cells))
copy(cells, l.cells)
for i := range cells {
if cells[i].R == 0 && cells[i].Kind == cellNarrow {
cells[i].R = ' '
}
}
for len(cells) > 0 && cells[len(cells)-1] == (Cell{R: ' '}) {
cells = cells[:len(cells)-1]
}
var b strings.Builder
if cont {
b.WriteString("+")
}
pen := Attr{}
for x, c := range cells {
if c.A != pen {
fmt.Fprintf(&b, "{%x/%x/%x}", c.A.Fg, c.A.Bg, c.A.Flags)
pen = c.A
}
switch c.Kind {
case cellWideTail:
b.WriteString("~")
default:
b.WriteRune(c.R)
}
if m := l.marks[x]; m != "" {
b.WriteString("<" + m + ">")
}
}
b.WriteString("|\n")
return b.String()
}
func text(t *Terminal) string { return t.Text() }
// history is the scrollback's text, oldest first.
func history(t *Terminal) []string {
var lines []string
for i := 0; i < t.scrollbackLen(); i++ {
var b strings.Builder
for _, c := range t.scrollbackLine(i).cells {
if c.R != 0 && c.Kind != cellWideTail {
b.WriteRune(c.R)
}
}
lines = append(lines, b.String())
}
return lines
}
// blankLine: nothing but spaces and never-written cells of the default pen.
func blankLine(l *line) bool {
for _, c := range l.cells {
if c != (Cell{}) && c != (Cell{R: ' '}) {
return false
}
}
return len(l.marks) == 0
}
+296
View File
@@ -0,0 +1,296 @@
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
}
+100
View File
@@ -0,0 +1,100 @@
package termstate
import (
"fmt"
"math/rand"
"strings"
"testing"
)
// randomOutput mixes text and the sequences full-screen programs write.
func randomOutput(r *rand.Rand, n int) []byte {
pieces := []func() string{
func() string {
s := strings.Repeat(string(rune('a'+r.Intn(26))), 1+r.Intn(30))
if r.Intn(4) == 0 {
// A repeat follows the character it repeats.
s += fmt.Sprintf("\x1b[%db", r.Intn(30))
}
return s
},
func() string { return []string{"日本", "é", "é", "😀", "€", "​"}[r.Intn(6)] },
func() string { return []string{"\r", "\n", "\r\n", "\t", "\b", "\x0e", "\x0f", "\x07"}[r.Intn(8)] },
func() string { return fmt.Sprintf("\x1b[%d;%dH", r.Intn(12), r.Intn(30)) },
func() string { return fmt.Sprintf("\x1b[%d%c", r.Intn(4), "ABCDEFGIJKLMPSTXZ@`adeg"[r.Intn(23)]) },
func() string { return fmt.Sprintf("\x1b[%d;%dr", r.Intn(10), r.Intn(12)) },
func() string {
return fmt.Sprintf("\x1b[%sm", []string{"0", "1", "4:3", "7", "31", "38;5;99", "48;2;1;2;3", "38:2::4:5:6", "22;24;27", "44", ""}[r.Intn(11)])
},
func() string {
modes := []int{1, 5, 6, 7, 12, 25, 47, 66, 1000, 1002, 1003, 1004, 1006, 1015, 1047, 1048, 1049, 2004}
return fmt.Sprintf("\x1b[?%d%c", modes[r.Intn(len(modes))], "hl"[r.Intn(2)])
},
func() string {
return []string{"\x1b[4h", "\x1b[4l", "\x1b[20h", "\x1b[20l", "\x1b[3 q", "\x1b[!p"}[r.Intn(6)]
},
func() string {
return []string{"\x1b7", "\x1b8", "\x1bD", "\x1bE", "\x1bM", "\x1bH", "\x1b=", "\x1b>", "\x1b(0", "\x1b(B", "\x1b)0", "\x1b#8"}[r.Intn(12)]
},
func() string {
return []string{"\x1b]2;t\x07", "\x1b]0;title\x1b\\", "\x1bPq#0;1\x1b\\", "\x1b_apc\x1b\\", "\x1b[>4;1m", "\x1b[?u"}[r.Intn(6)]
},
func() string { return "\x1bc" },
}
var b strings.Builder
for b.Len() < n {
i := r.Intn(len(pieces))
if i == len(pieces)-1 && r.Intn(20) != 0 {
continue
}
b.WriteString(pieces[i]())
}
return []byte(b.String())
}
// Snapshots of random output at random cuts reproduce the state, and the
// rest of the output then gives the same state as writing it all.
func TestSnapshotRandomOutput(t *testing.T) {
for seed := int64(0); seed < 500; seed++ {
r := rand.New(rand.NewSource(seed))
stream := randomOutput(r, 3000)
cols, rows := 10+r.Intn(30), 3+r.Intn(10)
whole := New(cols, rows, 20)
whole.Write(stream)
for k := 0; k < 8; k++ {
cut := r.Intn(len(stream) + 1)
term := New(cols, rows, 20)
term.Write(stream[:cut])
if term.cur.origin && (term.cur.y < term.top || term.cur.y > term.bottom) {
// Origin mode with the cursor outside the scroll region (a
// DECRC can leave it there) has no sequence to recreate it.
continue
}
rep := replica(term, stream[:cut])
sameState(t, fmt.Sprintf("seed %d cut %d", seed, cut), term, rep)
rep.Write(stream[cut:])
sameState(t, fmt.Sprintf("seed %d cut %d then rest", seed, cut), whole, rep)
}
}
}
// Arbitrary bytes and resizes never panic.
func TestArbitraryBytes(t *testing.T) {
r := rand.New(rand.NewSource(1))
term := New(13, 5, 7)
buf := make([]byte, 4096)
for i := 0; i < 400; i++ {
r.Read(buf)
for j := range buf {
if r.Intn(4) == 0 {
buf[j] = "\x1b[;?0123456789mHJKr\x07\n\r"[r.Intn(21)]
}
}
term.Write(buf)
if i%50 == 0 {
term.Resize(1+r.Intn(40), 1+r.Intn(20))
}
snap, _ := term.Snapshot()
New(term.cols, term.rows, 7).Write(snap)
}
}
+76
View File
@@ -0,0 +1,76 @@
package termstate
// Resize changes the terminal's size without reflowing, as the app's live
// emulator does: narrowing cuts rows (scrollback too) at the new width;
// fewer rows move the rows above the cursor into the scrollback (main
// screen) so the cursor's row stays on screen; more rows bring scrollback
// back. The scroll region becomes the whole screen.
func (t *Terminal) Resize(cols, rows int) {
cols, rows = max(cols, 1), max(rows, 1)
if cols == t.cols && rows == t.rows {
return
}
if cols < t.cols {
for _, lines := range [][]*line{t.main.lines, t.alt.lines, t.history} {
for _, l := range lines {
l.truncate(cols)
}
}
}
mainY, altY := &t.main.saved.y, &t.alt.saved.y
if t.scr == &t.main {
mainY = &t.cur.y
} else {
altY = &t.cur.y
}
t.main.lines = t.resizeRows(t.main.lines, rows, cols, mainY, true)
t.alt.lines = t.resizeRows(t.alt.lines, rows, cols, altY, false)
// The last row's continuation (if any) is gone.
t.main.lines[rows-1].cont, t.alt.lines[rows-1].cont = false, false
old := t.tabs
t.cols, t.rows = cols, rows
t.resetTabs()
copy(t.tabs, old)
t.top, t.bottom = 0, rows-1
t.cur.x, t.cur.y = min(t.cur.x, cols-1), min(max(t.cur.y, 0), rows-1)
t.cur.wrap = t.cur.wrap && t.cur.x == cols-1
for _, s := range []*screen{&t.main, &t.alt} {
s.saved.x, s.saved.y = min(s.saved.x, cols-1), min(max(s.saved.y, 0), rows-1)
}
}
// resizeRows gives one screen rows rows, keeping the row at *anchor
// visible and moving it with the content.
func (t *Terminal) resizeRows(lines []*line, rows, cols int, anchor *int, main bool) []*line {
n := len(lines)
if rows < n {
push := min(max(0, *anchor-(rows-1)), n-rows)
for _, l := range lines[:push] {
if main {
t.keep(l)
}
}
*anchor -= push
return append([]*line(nil), lines[push:push+rows]...)
}
resized := make([]*line, 0, rows)
if main {
var back []*line
for len(back) < rows-n {
l := t.popScrollback()
if l == nil {
break
}
back = append(back, l)
}
for i := len(back) - 1; i >= 0; i-- {
resized = append(resized, back[i])
}
*anchor += len(back)
}
resized = append(resized, lines...)
for len(resized) < rows {
resized = append(resized, &line{})
}
return resized
}
+347
View File
@@ -0,0 +1,347 @@
package termstate
import "strconv"
// Snapshot returns an escape sequence stream that brings a terminal of the
// same size, from any state, to this one: it resets the terminal (RIS and
// ED 3), draws the scrollback and the main screen row by row (soft-wrapped
// rows wrap again), switches to the alternate screen and draws it when that
// is in use, then restores the saved cursors, tab stops, scroll region,
// cursor (including a pending wrap), modes, character sets, pen and title.
// It ends with the start of a sequence still unfinished in the output, so
// the bytes written next complete it.
//
// partial is how many of the newest bytes written are an unfinished UTF-8
// character, which the stream leaves out: the caller sends those bytes again
// after it.
func (t *Terminal) Snapshot() (out []byte, partial int) {
w := &snapWriter{t: t}
w.raw("\x1bc\x1b[3J")
if t.title != "" {
w.raw("\x1b]2;" + t.title + "\x07")
}
if t.scr != &t.alt && (t.alt.savedValid || !emptyRows(t.alt.lines)) {
// The alternate screen not in use: what a switch with 47 or 1047
// (which do not clear it) would show again.
w.raw("\x1b[?47h")
w.altScreen()
if t.alt.savedValid {
w.saved(&t.alt, "\x1b7")
}
w.raw("\x1b[?47l\x1b[H")
}
w.mainScreen()
if t.scr == &t.alt {
if t.main.savedValid {
// 1049 saves the main screen's cursor as it switches.
w.saved(&t.main, "\x1b[?1049h")
} else {
// Nothing saved: switch without saving (the reset cleared it).
w.raw("\x1b[?47h")
}
w.altScreen()
if t.alt.savedValid {
w.saved(&t.alt, "\x1b7")
}
} else if t.main.savedValid {
w.saved(&t.main, "\x1b7")
}
w.tabs()
if t.top != 0 || t.bottom != t.rows-1 {
w.raw("\x1b[" + strconv.Itoa(t.top+1) + ";" + strconv.Itoa(t.bottom+1) + "r")
}
w.cursor()
w.modes()
w.pen(t.cur.pen)
seq, partial := t.p.pending()
w.b = append(w.b, seq...)
return w.b, partial
}
type snapWriter struct {
t *Terminal
b []byte
cur Attr
}
func (w *snapWriter) raw(s string) { w.b = append(w.b, s...) }
func (w *snapWriter) num(n int) { w.b = strconv.AppendInt(w.b, int64(n), 10) }
// goTo is CUP to row, col (zero-based, absolute).
func (w *snapWriter) goTo(row, col int) {
w.raw("\x1b[")
w.num(row + 1)
w.b = append(w.b, ';')
w.num(col + 1)
w.b = append(w.b, 'H')
}
// mainScreen writes the scrollback then the main screen's rows, each after
// a line break unless the row before wrapped into it.
func (w *snapWriter) mainScreen() {
t := w.t
n := t.scrollbackLen()
total := n + len(t.main.lines)
at := func(i int) *line {
if i < n {
return t.scrollbackLine(i)
}
return t.main.lines[i-n]
}
for i := 0; i < total; i++ {
l := at(i)
wraps := l.cont && i+1 < total
w.row(l, wraps)
if wraps && at(i+1).empty() {
// Wrap into the empty row with a space, then erase it again.
w.pen(Attr{})
w.raw(" \b\x1b[K")
}
if !wraps && i+1 < total {
if w.cur.Bg != 0 {
// A scrolled-in row takes the pen's background.
w.pen(Attr{})
}
w.raw("\r\n")
}
}
}
// altScreen draws each row of the alternate screen at its position.
func (w *snapWriter) altScreen() {
for y, l := range w.t.alt.lines {
if len(l.cells) == 0 {
continue
}
w.goTo(y, 0)
w.row(l, false)
}
}
// row writes l's cells from the cursor at its start; full writes every
// column (blank ones as spaces), so the next character wraps.
func (w *snapWriter) row(l *line, full bool) {
n := len(l.cells)
if full {
n = w.t.cols
} else {
for n > 0 && l.cells[n-1] == (Cell{}) {
n--
}
}
for x := 0; x < n; x++ {
var c Cell
if x < len(l.cells) {
c = l.cells[x]
}
if c.Kind == cellWideTail {
continue
}
w.cell(l, x, c)
}
}
func (w *snapWriter) cell(l *line, x int, c Cell) {
w.pen(c.A)
if c.R == 0 {
w.b = append(w.b, ' ')
} else {
w.b = append(w.b, string(c.R)...)
}
if l.marks != nil {
w.b = append(w.b, l.marks[x]...)
}
}
// saved places the cursor, pen and character sets of a saved cursor of
// screen s and writes then (which saves them), then sets ASCII again for
// what follows. (Origin mode saved with a cursor is not restored.)
func (w *snapWriter) saved(s *screen, then string) {
c := s.saved
w.place(s.lines[c.y], c.y, c.x, c.wrap, false)
w.pen(c.pen)
w.charsets(c)
w.raw(then)
if c.charsets != [2]byte{'B', 'B'} || c.shift != 0 {
w.raw("\x1b(B\x1b)B\x0f")
}
}
func (w *snapWriter) charsets(c cursor) {
if g := c.charsets[0]; g != 'B' {
w.raw("\x1b(" + string(rune(g)))
}
if g := c.charsets[1]; g != 'B' {
w.raw("\x1b)" + string(rune(g)))
}
if c.shift == 1 {
w.raw("\x0e")
}
}
// tabs sets the tab stops when they are not the default ones.
func (w *snapWriter) tabs() {
t := w.t
custom := false
for x, set := range t.tabs {
if set != (x > 0 && x%8 == 0) {
custom = true
break
}
}
if !custom {
return
}
w.raw("\x1b[3g")
for x, set := range t.tabs {
if set {
w.goTo(0, x)
w.raw("\x1bH")
}
}
}
// cursor places the cursor (in origin mode, after setting it).
func (w *snapWriter) cursor() {
t := w.t
row := t.cur.y
if t.cur.origin {
w.raw("\x1b[?6h")
row -= t.top
}
w.place(t.scr.lines[t.cur.y], row, t.cur.x, t.cur.wrap, true)
}
// place moves the cursor to column x of row (a CUP row) showing l. A
// pending wrap is recreated by writing the last column's cell again; with
// repeat, the cell before the cursor is written again when it holds the
// last character written, so a repeat (REP) that follows repeats it.
func (w *snapWriter) place(l *line, row, x int, wrap, repeat bool) {
t := w.t
at := func(x int) Cell {
if x < len(l.cells) {
return l.cells[x]
}
return Cell{}
}
if wrap {
x = t.cols - 1
if at(x).Kind == cellWideTail && x > 0 {
x--
}
w.goTo(row, x)
w.cell(l, x, at(x))
return
}
last := x - 1
if last > 0 && at(last).Kind == cellWideTail {
last--
}
c := at(max(last, 0))
if !repeat || last < 0 || c.R == 0 || c.R != t.lastChar || (c.Kind == cellWide && last+2 != x) {
w.goTo(row, x)
return
}
w.goTo(row, last)
w.cell(l, last, c)
}
func (w *snapWriter) modes() {
t := w.t
m := t.m
flag := func(on bool, s string) {
if on {
w.raw(s)
}
}
flag(!m.autowrap, "\x1b[?7l")
flag(m.insert, "\x1b[4h")
flag(m.newline, "\x1b[20h")
flag(m.appCursor, "\x1b[?1h")
flag(m.appKeypad, "\x1b=")
flag(m.reverse, "\x1b[?5h")
flag(m.cursorBlink, "\x1b[?12h")
flag(!m.cursorVisible, "\x1b[?25l")
for _, mode := range []int{m.mouse, m.mouseEncoding} {
if mode != 0 {
w.raw("\x1b[?")
w.num(mode)
w.b = append(w.b, 'h')
}
}
flag(m.focus, "\x1b[?1004h")
flag(m.bracketedPaste, "\x1b[?2004h")
flag(m.altScroll, "\x1b[?1007h")
if t.cursorShape != 0 {
w.raw("\x1b[")
w.num(t.cursorShape)
w.raw(" q")
}
w.charsets(t.cur)
}
// pen switches the written pen to a.
func (w *snapWriter) pen(a Attr) {
if a == w.cur {
return
}
w.cur = a
w.raw("\x1b[0")
flags := []struct {
bit uint16
code string
}{
{attrBold, ";1"}, {attrFaint, ";2"}, {attrItalic, ";3"}, {attrBlink, ";5"},
{attrInverse, ";7"}, {attrHidden, ";8"}, {attrStrike, ";9"}, {attrOverline, ";53"},
}
for _, f := range flags {
if a.Flags&f.bit != 0 {
w.raw(f.code)
}
}
switch u := a.underline(); u {
case 0:
case 1:
w.raw(";4")
default:
w.raw(";4:")
w.num(u)
}
w.color(a.Fg, 30, 90, "38")
w.color(a.Bg, 40, 100, "48")
w.b = append(w.b, 'm')
}
func (w *snapWriter) color(c Color, base, bright int, extended string) {
switch c & colorKind {
case colorIndexed:
n := int(c & 0xFF)
w.b = append(w.b, ';')
switch {
case n < 8:
w.num(base + n)
case n < 16:
w.num(bright + n - 8)
default:
w.raw(extended + ";5;")
w.num(n)
}
case colorRGB:
w.raw(";" + extended + ";2;")
w.num(int(c>>16) & 0xFF)
w.b = append(w.b, ';')
w.num(int(c>>8) & 0xFF)
w.b = append(w.b, ';')
w.num(int(c) & 0xFF)
}
}
func emptyRows(lines []*line) bool {
for _, l := range lines {
if len(l.cells) > 0 {
return false
}
}
return true
}
+163
View File
@@ -0,0 +1,163 @@
package termstate
import (
"fmt"
"math/rand"
"strings"
"testing"
)
// replica is a fresh terminal of t's size brought to t's state by t's
// snapshot (and the unfinished character the snapshot leaves out).
func replica(t *Terminal, written []byte) *Terminal {
snap, partial := t.Snapshot()
r := New(t.cols, t.rows, t.limit)
// Whatever state it was in before, the snapshot resets it first.
r.Write([]byte("\x1b[?1049h\x1b[?1000h\x1b[5;9r\x1b[31mjunk\x1b(0"))
r.Write(snap)
r.Write(written[len(written)-partial:])
return r
}
func sameState(t *testing.T, what string, want, got *Terminal) {
t.Helper()
w, g := dump(want), dump(got)
if w == g {
return
}
wl, gl := strings.Split(w, "\n"), strings.Split(g, "\n")
for i := range min(len(wl), len(gl)) {
if wl[i] != gl[i] {
t.Fatalf("%s: line %d differs:\nwant %s\ngot %s", what, i, wl[i], gl[i])
}
}
t.Fatalf("%s: dumps differ in length %d vs %d", what, len(wl), len(gl))
}
// shellThenTUI is a shell session (history past the scrollback), then a
// full-screen program that sets mouse, bracketed paste, application
// cursor and keypad modes, a scroll region and colours and draws frames
// until it has written more than limit bytes.
func shellThenTUI(limit int) (shell, tui []byte) {
var b strings.Builder
for i := 0; i < 3000; i++ {
fmt.Fprintf(&b, "$ echo line %d\r\nline %d\r\n", i, i)
}
b.WriteString("$ nvim\r\n")
shell = []byte(b.String())
b.Reset()
b.WriteString("\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[?1h\x1b=\x1b[?25l\x1b[2 q\x1b]2;nvim file.go\x07")
r := rand.New(rand.NewSource(7))
for frame := 0; b.Len() < limit; frame++ {
b.WriteString("\x1b[1;23r\x1b[H\x1b[2J")
for y := 1; y <= 23; y++ {
fmt.Fprintf(&b, "\x1b[%d;1H\x1b[38;5;%dm\x1b[48;2;%d;%d;%dm%4d \x1b[0;1m%s\x1b[0m", y, r.Intn(256), r.Intn(256), r.Intn(256), r.Intn(256), frame*23+y, strings.Repeat("é日x", r.Intn(20)))
}
fmt.Fprintf(&b, "\x1b[r\x1b[24;1H\x1b[7m-- INSERT -- frame %d\x1b[K\x1b[0m\x1b[5;7H", frame)
}
return shell, []byte(b.String())
}
// A full-screen program that wrote more than the retained tail is
// restored exactly: its screen and modes, and underneath the shell's
// screen and scrollback, which its exit brings back.
func TestSnapshotRestoresFullScreenProgramAndShell(t *testing.T) {
shell, tui := shellThenTUI(1200 << 10)
term := New(80, 24, DefaultScrollback)
term.Write(shell)
term.Write(tui)
if len(tui) <= 1<<20 || term.scr != &term.alt {
t.Fatalf("tui wrote %d bytes, alt=%v", len(tui), term.scr == &term.alt)
}
r := replica(term, tui)
sameState(t, "after snapshot", term, r)
if !r.m.bracketedPaste || r.m.mouse != 1002 || r.m.mouseEncoding != 1006 || !r.m.appCursor || !r.m.appKeypad || r.m.cursorVisible || r.title != "nvim file.go" {
t.Fatalf("modes = %+v title %q", r.m, r.title)
}
// The program exits: the shell's screen and history come back.
exit := []byte("\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?1l\x1b>\x1b[?25h\x1b[?1049l$ ls\r\nfile.go\r\n$ ")
term.Write(exit)
r.Write(exit)
sameState(t, "after exit", term, r)
screen := text(r)
if !strings.Contains(screen, "line 2999") || !strings.Contains(screen, "$ nvim") || !strings.Contains(screen, "file.go") || strings.Contains(screen, "INSERT") {
t.Fatalf("main screen after exit:\n%s", screen)
}
h := history(r)
if len(h) != DefaultScrollback || !strings.HasPrefix(h[len(h)-1], "line ") {
t.Fatalf("scrollback %d lines, last %q", len(h), h[len(h)-1])
}
}
// Wrapped rows, wide and combining characters, a pending wrap, DEC line
// drawing, origin mode, tab stops, insert mode and the saved cursor.
func TestSnapshotRestoresCursorAndModes(t *testing.T) {
term := New(20, 6, 50)
stream := []byte("" +
"0123456789abcdefghijKLMNO\r\n" + // wraps
"wide 日本語 é \x1b[4:3mcurly\x1b[24m\r\n" +
"\x1b(0lqqk\x1b(B \x0e\x1b)0abc\x0f\r\n" +
"\x1b[3g\x1b[1;4H\x1bH\x1b[1;11H\x1bH" +
"\x1b[44m\x1b[2K\x1b[0m\x1b[3;18H\x1b7\x1b[31;1m" +
"\x1b[2;5r\x1b[?6h\x1b[4h\x1b[20h\x1b[?7h\x1b[5 q" +
"\x1b[1;1Hxyz\x1b[4;16H\x1b[33;3mendof")
term.Write(stream)
if !term.cur.wrap {
t.Fatalf("no pending wrap: cursor %+v", term.cur)
}
r := replica(term, stream)
sameState(t, "snapshot", term, r)
more := []byte("Q\r\n\tT\x1b8W\x1b[2;1H\x1b[L")
term.Write(more)
r.Write(more)
sameState(t, "after more", term, r)
}
// A snapshot taken between any two bytes of the output, followed by the
// rest of the output, ends in the state of the whole output: unfinished
// escape sequences, strings and characters at the cut are completed.
func TestSnapshotAtEveryCut(t *testing.T) {
stream := []byte("ab\x1b[1;31mred\x1b[0m é日\r\n\x1b]2;titéle\x07\x1b]0;x\x1b\\" +
"\x1bP1$qm\x1b\\\x1b[?2004h\x1b[38:2::10:20:30mrgb\x1b[38;5;200mpal\x1b[m" +
"\x1b[?1049h\x1b[5;5Halt\x1b[?1000;1006h\x1b7\x1b[10;1H\x1b[K\x1b(0q\x1b(B" +
"\x1b[?1049l\x1b[3Cdone\x1b[2;3r\x1b[2;1H\n\n\n\x1b[r€\r\n")
whole := New(16, 8, 10)
whole.Write(stream)
for cut := 0; cut <= len(stream); cut++ {
term := New(16, 8, 10)
term.Write(stream[:cut])
r := replica(term, stream[:cut])
sameState(t, fmt.Sprintf("cut %d", cut), term, r)
r.Write(stream[cut:])
sameState(t, fmt.Sprintf("cut %d then rest", cut), whole, r)
}
}
// The scrollback is bounded and kept in order across the ring's wrap.
func TestScrollbackRing(t *testing.T) {
term := New(10, 3, 5)
for i := 0; i < 20; i++ {
term.Write([]byte(fmt.Sprintf("l%d\r\n", i)))
}
if got := strings.Join(history(term), ","); got != "l13,l14,l15,l16,l17" {
t.Fatalf("history = %s", got)
}
r := replica(term, nil)
sameState(t, "snapshot", term, r)
}
// Resizing keeps the cursor's row: fewer rows push the top into the
// scrollback, more bring it back; a narrower screen cuts rows.
func TestResize(t *testing.T) {
term := New(10, 4, 100)
term.Write([]byte("a\r\nb\r\nc\r\nd12345678"))
term.Resize(6, 2)
if got := text(term); got != "c\nd12345" || term.cur.y != 1 {
t.Fatalf("shrunk = %q cursor %+v", got, term.cur)
}
term.Resize(6, 4)
if got := text(term); got != "a\nb\nc\nd12345" || term.cur.y != 3 {
t.Fatalf("grown = %q cursor %+v", got, term.cur)
}
sameState(t, "snapshot", term, replica(term, nil))
}
+526
View File
@@ -0,0 +1,526 @@
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
}