diff --git a/app/test/third_party_xterm/write_path_test.dart b/app/test/third_party_xterm/write_path_test.dart new file mode 100644 index 00000000..ccb36366 --- /dev/null +++ b/app/test/third_party_xterm/write_path_test.dart @@ -0,0 +1,226 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +/// Every cell of every line, the cursor and the wrap flags: what two +/// terminals must agree on to have drawn the same output. +List state(Terminal terminal) { + final buffer = terminal.buffer; + final cells = [buffer.height, buffer.cursorX, buffer.cursorY]; + final cell = CellData.empty(); + for (var y = 0; y < buffer.height; y++) { + final line = buffer.lines[y]; + cells.add(line.isWrapped); + for (var x = 0; x < line.length; x++) { + line.getCellData(x, cell); + cells.addAll([ + cell.foreground, + cell.background, + cell.flags, + cell.content, + ]); + } + } + return cells; +} + +// Sized before the scrollback shrinks: the default 24 rows must fit first. +Terminal make({int width = 10, int height = 4, int maxLines = 50}) => + Terminal(maxLines: 100) + ..resize(width, height) + ..maxLines = maxLines; + +void main() { + group('printable ASCII runs', () { + // [setup] goes through the parser in both terminals; [text] is written + // as one run in the first and one character at a time through + // Buffer.writeChar (the path every character took before) in the other. + void same(String setup, String text, {int width = 10}) { + final fast = make(width: width)..write(setup); + final slow = make(width: width)..write(setup); + fast.write(text); + for (final unit in text.codeUnits) { + slow.buffer.writeChar(unit); + } + expect(state(fast), state(slow), reason: '$setup | $text'); + } + + test('wrap across rows and into the scrollback', () { + same('', 'abcdefghij' * 7 + 'xyz'); + same('abc', 'defghijklmnopqrstuvwxyz0123456789'); + same('\x1b[3;1H', 'a' * 95); + }); + + test('a full row waits at the last column, as one character does', () { + same('', 'abcdefghij'); + same('abcdefghi', 'j'); + same('abcdefghij', 'k'); + }); + + test('without autowrap', () { + same('\x1b[?7l', 'abcdefghijklmnop'); + same('\x1b[?7lab', 'cdefghijklmnop'); + }); + + test('in the cursor style (colours, bold, links)', () { + same('\x1b[1;31;44m', 'styled text that wraps'); + same('\x1b]8;;https://example.com\x1b\\', 'linked text'); + }); + + test('over a wide character', () { + // Writing over the second column of a wide character blanks its + // first; over the first column, as before. + same('中文\r\x1b[C', 'ab'); + same('中文\r', 'abc'); + }); + + test('in the DEC line drawing set', () { + same('\x1b(0', 'lqqk xx mqqj'); + }); + + test('in insert mode the run shifts nothing (as one character)', () { + same('hello\r\x1b[4h', 'ab'); + }); + }); + + test('a run and the characters around it parse as before', () { + final terminal = make(width: 20); + terminal.write('ab\x1b[31mcd\x1b[0méf\u{1F600}g\r\nnext'); + final buffer = terminal.buffer; + expect(buffer.lines[0].getText(), 'abcdéf\u{1F600}g'); + expect(buffer.lines[0].getForeground(2), CellColor.named | 1); + expect(buffer.lines[0].getForeground(4), 0); + expect(buffer.lines[1].getText().trimRight(), 'next'); + }); + + test('a sequence split between writes resumes (rollback)', () { + final terminal = make(width: 20); + terminal.write('ab\x1b[3'); + terminal.write('1mcd\x1b'); + terminal.write('[0me'); + final line = terminal.buffer.lines[0]; + expect(line.getText().trimRight(), 'abcde'); + expect(line.getForeground(1), 0); + expect(line.getForeground(2), CellColor.named | 1); + expect(line.getForeground(4), 0); + }); + + test('a surrogate pair is one character; split halves are not', () { + final terminal = make(width: 20); + terminal.write('a\u{1F600}b'); + final line = terminal.buffer.lines[0]; + expect(line.getCodePoint(1), 0x1F600); + expect(line.getWidth(1), 2); + expect(line.getCodePoint(3), 'b'.codeUnitAt(0)); + expect(terminal.buffer.cursorX, 4); + }); + + test('REP repeats the last character of a run', () { + final terminal = make(width: 20); + terminal.write('xyz\x1b[3b'); + expect(terminal.buffer.lines[0].getText().trimRight(), 'xyzzzz'); + }); + + group('lines leaving the scrollback are reused', () { + test('as empty lines: output keeps its text, wraps and widths', () { + final terminal = make(width: 10, height: 3, maxLines: 6); + final reference = make(width: 10, height: 3, maxLines: 1000); + final output = [ + for (var i = 0; i < 40; i++) + i.isEven + ? '\x1b[4${i % 8}mline $i that wraps\x1b[0m\r\n' + : '中$i\r\n', + ].join(); + terminal.write(output); + reference.write(output); + final buffer = terminal.buffer; + expect(buffer.height, 6); + final tail = reference.buffer.height - 6; + for (var y = 0; y < 6; y++) { + final line = buffer.lines[y]; + final expected = reference.buffer.lines[tail + y]; + expect(line.getText(), expected.getText(), reason: 'row $y'); + expect(line.isWrapped, expected.isWrapped, reason: 'row $y'); + expect(line.getTrimmedLength(), expected.getTrimmedLength()); + for (var x = 0; x < 10; x++) { + expect(line.getBackground(x), expected.getBackground(x)); + expect(line.getWidth(x), expected.getWidth(x)); + } + } + }); + + test('a reused line has a new version, so its picture is redrawn', () { + final terminal = make(width: 10, height: 2, maxLines: 2); + terminal.write('a\r\nb'); + final top = terminal.buffer.lines[0]; + final version = top.version; + terminal.write('\r\nc'); + expect(identical(terminal.buffer.lines[1], top), isTrue); + expect(top.version, isNot(version)); + expect(top.getText().trimRight(), 'c'); + }); + + test('a line with an anchor (a selection end) leaves detached', () { + final terminal = make(width: 10, height: 2, maxLines: 2); + terminal.write('a\r\nb'); + final top = terminal.buffer.lines[0]; + final anchor = terminal.buffer.createAnchor(0, 0); + terminal.write('\r\nc'); + expect(anchor.attached, isFalse); + expect(top.attached, isFalse); + expect(top.getText().trimRight(), 'a'); + expect(terminal.buffer.lines[1].getText().trimRight(), 'c'); + }); + + test('a top scroll region feeding a full scrollback wraps around', () { + // Line feeds at the bottom of a region that starts at the top insert + // into the scrollback rather than push; well past its capacity. + String screen(Terminal terminal) => [ + for (var y = 0; y < 4; y++) + terminal.buffer.lines[terminal.buffer.scrollBack + y] + .getText() + .trimRight(), + ].join('|'); + final small = make(width: 10, height: 4, maxLines: 8); + final large = make(width: 10, height: 4, maxLines: 1000); + for (final terminal in [small, large]) { + terminal.write('\x1b[1;3r\x1b[4;1Hstatus\x1b[1;1H'); + for (var i = 0; i < 50; i++) { + terminal.write('\x1b[3;1Hrow $i\n'); + } + } + expect(small.buffer.height, 8); + expect(screen(small), screen(large)); + for (var y = 0; y < 8; y++) { + expect(small.buffer.lines[y].index, y); + } + }); + + test('in a scroll region on the alternate screen', () { + final terminal = make(width: 10, height: 4); + terminal.write('\x1b[?1049h\x1b[2;3r\x1b[1;1Htop\x1b[4;1Hbottom'); + terminal.write('\x1b[2;1H\x1b[41mone\r\n\x1b[0mtwo\r\nthree\r\nfour'); + final buffer = terminal.buffer; + String row(int y) => buffer.lines[y].getText().trimRight(); + expect([row(0), row(1), row(2), row(3)], [ + 'top', + 'three', + 'four', + 'bottom', + ]); + // The reused lines carry nothing of what scrolled out. + expect(buffer.lines[2].getBackground(0), 0); + expect(buffer.lines[2].getBackground(9), 0); + }); + }); + + test('a write without notify leaves notifying to the host', () { + final terminal = make(); + var heard = 0; + terminal.addListener(() => heard++); + terminal.write('quiet', notify: false); + expect(heard, 0); + terminal.write('loud'); + expect(heard, 1); + expect(terminal.buffer.lines[0].getText().trimRight(), 'quietloud'); + }); +} diff --git a/app/third_party/xterm/lib/src/core/buffer/buffer.dart b/app/third_party/xterm/lib/src/core/buffer/buffer.dart index 75cbe370..4bb6d794 100644 --- a/app/third_party/xterm/lib/src/core/buffer/buffer.dart +++ b/app/third_party/xterm/lib/src/core/buffer/buffer.dart @@ -179,6 +179,42 @@ class Buffer { } } + /// Writes the printable ASCII characters of [text] from [start] to [end] + /// (exclusive), exactly as [writeChar] would one at a time, a row's worth + /// at once. Such a character never joins a grapheme cluster and is one + /// column wide. + void writeAscii(String text, int start, int end) { + if (!charset.isAscii) { + for (var i = start; i < end; i++) { + writeChar(text.codeUnitAt(i)); + } + return; + } + final style = terminal.cursor; + final width = viewWidth; + var i = start; + while (i < end) { + if (_cursorX >= width) { + index(); + setCursorX(0); + if (terminal.autoWrapMode) { + currentLine.isWrapped = true; + } + } + final line = currentLine; + final x = _cursorX; + // Overwriting the second column of a wide character blanks its first. + if (x > 0 && line.getWidth(x - 1) == 2) { + line.eraseCell(x - 1, style); + } + var count = end - i; + if (count > width - x) count = width - x; + line.setAsciiCells(x, text, i, count, style); + _cursorX = x + count; + i += count; + } + } + /// The line at the current cursor position. BufferLine get currentLine { return lines[absoluteCursorY]; @@ -265,11 +301,14 @@ class Buffer { } void scrollUp(int lines) { + // The line a one-line scroll (a line feed at the bottom of a region) + // drops is cleared and reused as the new bottom line. + final out = lines == 1 ? _reusable(this.lines[absoluteMarginTop]) : null; for (var i = absoluteMarginTop; i <= absoluteMarginBottom; i++) { if (i <= absoluteMarginBottom - lines) { this.lines[i] = this.lines[i + lines]; } else { - this.lines[i] = _newEmptyLine(); + this.lines[i] = out ?? _newEmptyLine(); } } } @@ -285,7 +324,12 @@ class Buffer { if (isInVerticalMargin) { if (_cursorY == _marginBottom) { if (marginTop == 0 && !isAltBuffer) { - lines.insert(absoluteMarginBottom + 1, _newEmptyLine()); + final at = absoluteMarginBottom + 1; + if (at == lines.length) { + _pushLine(); + } else { + lines.insert(at, _newEmptyLine()); + } } else { scrollUp(1); } @@ -301,7 +345,7 @@ class Buffer { if (isAltBuffer) { scrollUp(1); } else { - lines.push(_newEmptyLine()); + _pushLine(); } } else { // there're still lines so we simply move cursor down. @@ -561,6 +605,23 @@ class Buffer { return line; } + /// Adds an empty line below the others. When the scrollback is full the + /// oldest line, which this drops, is cleared and reused: streaming output + /// then allocates no lines. + void _pushLine() { + final oldest = lines.isFull ? _reusable(lines[0]) : null; + lines.push(oldest ?? _newEmptyLine()); + } + + /// [line], about to leave the buffer, cleared for reuse as an empty line, + /// or null when something still points into it (an anchor: a selection + /// or highlight end), which must see it detached. + BufferLine? _reusable(BufferLine line) { + if (line.anchors.isNotEmpty) return null; + line.clear(viewWidth); + return line; + } + static final defaultWordSeparators = { 0, r' '.codeUnitAt(0), diff --git a/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart b/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart index a3dcc303..ead2e909 100644 --- a/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart +++ b/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart @@ -35,6 +35,14 @@ int? joinPreviousCell( int width, ) { if (cursorX <= 0) return width == 0 ? 0 : null; + // Most characters can only start a cell; tell them apart before reading + // the cell before the cursor. + if (width != 0 && + !UnicodeWidth.isRegionalIndicator(codePoint) && + !UnicodeWidth.isEmojiModifier(codePoint) && + !UnicodeWidth.isPictographic(codePoint)) { + return null; + } var x = (cursorX > viewWidth ? viewWidth : cursorX) - 1; // The second column of a wide character: its cluster is one to the left. if (x > 0 && line.getContent(x) == 0 && line.getWidth(x - 1) == 2) x--; diff --git a/app/third_party/xterm/lib/src/core/buffer/line.dart b/app/third_party/xterm/lib/src/core/buffer/line.dart index 20bdf679..0fe133bf 100644 --- a/app/third_party/xterm/lib/src/core/buffer/line.dart +++ b/app/third_party/xterm/lib/src/core/buffer/line.dart @@ -89,6 +89,7 @@ class BufferLine with IndexedItem { CellData createCellData(int index) { final cellData = CellData.empty(); + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = cellData.foreground; _data[offset + _cellBackground] = cellData.background; @@ -99,21 +100,25 @@ class BufferLine with IndexedItem { void setForeground(int index, int value) { _version++; + _touch(index); _data[index * _cellSize + _cellForeground] = value; } void setBackground(int index, int value) { _version++; + _touch(index); _data[index * _cellSize + _cellBackground] = value; } void setAttributes(int index, int value) { _version++; + _touch(index); _data[index * _cellSize + _cellAttributes] = value; } void setContent(int index, int value) { _version++; + _touch(index); _data[index * _cellSize + _cellContent] = value; } @@ -124,6 +129,7 @@ class BufferLine with IndexedItem { void setCell(int index, int char, int witdh, CursorStyle style) { _version++; + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = style.foreground; _data[offset + _cellBackground] = style.background; @@ -131,8 +137,79 @@ class BufferLine with IndexedItem { _data[offset + _cellContent] = char | (witdh << CellContent.widthShift); } + /// Sets [count] cells from [index] to the one-column characters of [text] + /// from [start] (printable ASCII, so no width lookup) in [style]. + void setAsciiCells( + int index, + String text, + int start, + int count, + CursorStyle style, + ) { + _version++; + _touch(index + count - 1); + final data = _data; + final foreground = style.foreground; + final background = style.background; + final attrs = style.attrs; + const oneColumn = 1 << CellContent.widthShift; + var offset = index * _cellSize; + final end = start + count; + for (var i = start; i < end; i++) { + data[offset + _cellForeground] = foreground; + data[offset + _cellBackground] = background; + data[offset + _cellAttributes] = attrs; + data[offset + _cellContent] = text.codeUnitAt(i) | oneColumn; + offset += _cellSize; + } + } + + /// Makes this an empty, unwrapped line of [length] cells, as a new line, + /// so a line leaving the buffer can be reused instead of allocating one. + /// The version keeps counting, so nothing drawn from the old cells is + /// mistaken for the new ones. + void clear(int length) { + _version++; + isWrapped = false; + final size = _calcCapacity(length) * _cellSize; + if (size > _data.length) { + _data = Uint32List(size); + } else { + // Only the cells written since the line was made or cleared need + // clearing: a line of output usually fills a few of its columns. A + // long run is copied from zeros (a memory move, where fillRange is a + // loop); up to 64 cells are quicker set in place (compiled to + // JavaScript, setRange makes a view of each array). + final used = _dirty * _cellSize; + if (used <= 256) { + final data = _data; + for (var i = 0; i < used; i++) { + data[i] = 0; + } + } else { + if (_zeros.length < used) _zeros = Uint32List(_data.length); + _data.setRange(0, used, _zeros); + } + } + _dirty = 0; + _length = length; + } + + /// Cells from this index on have never been written since the line was + /// made or cleared: they are all zero. + int _dirty = 0; + + @pragma('vm:prefer-inline') + @pragma('dart2js:prefer-inline') + void _touch(int index) { + if (index >= _dirty) _dirty = index + 1; + } + + static var _zeros = Uint32List(0); + void setCellData(int index, CellData cellData) { _version++; + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = cellData.foreground; _data[offset + _cellBackground] = cellData.background; @@ -142,6 +219,7 @@ class BufferLine with IndexedItem { void eraseCell(int index, CursorStyle style) { _version++; + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = style.foreground; _data[offset + _cellBackground] = style.background; @@ -151,6 +229,7 @@ class BufferLine with IndexedItem { void resetCell(int index) { _version++; + _touch(index); final offset = index * _cellSize; _data[offset + _cellForeground] = 0; _data[offset + _cellBackground] = 0; @@ -185,6 +264,7 @@ class BufferLine with IndexedItem { assert(count >= 0 && start + count <= _length); style ??= CursorStyle.empty; + _touch(_length - 1); if (start + count < _length) { final moveStart = start * _cellSize; @@ -220,6 +300,7 @@ class BufferLine with IndexedItem { void insertCells(int start, int count, [CursorStyle? style]) { _version++; style ??= CursorStyle.empty; + _touch(_length - 1); if (start > 0 && getWidth(start - 1) == 2) { eraseCell(start - 1, style); @@ -288,7 +369,7 @@ class BufferLine with IndexedItem { /// Returns the offset of the last cell that has content from the start of /// the line. int getTrimmedLength([int? cols]) { - final maxCols = _data.length ~/ _cellSize; + final maxCols = _dirty; if (cols == null || cols > maxCols) { cols = maxCols; @@ -326,6 +407,7 @@ class BufferLine with IndexedItem { // Uint32List.sublistView(src.data, srcCol * _cellSize, len * _cellSize), // ); + _touch(dstCol + len - 1); var srcOffset = srcCol * _cellSize; var dstOffset = dstCol * _cellSize; diff --git a/app/third_party/xterm/lib/src/core/charset.dart b/app/third_party/xterm/lib/src/core/charset.dart index d062368c..c391ced6 100644 --- a/app/third_party/xterm/lib/src/core/charset.dart +++ b/app/third_party/xterm/lib/src/core/charset.dart @@ -18,6 +18,10 @@ class Charset { _cached = _charsetMap[_currentIndex] ?? asciiTranslator; } + /// Whether characters are written as they are (no designated set such + /// as DEC line drawing is in use). + bool get isAscii => identical(_cached, asciiTranslator); + int translate(int codePoint) { return _cached(codePoint); } diff --git a/app/third_party/xterm/lib/src/core/escape/handler.dart b/app/third_party/xterm/lib/src/core/escape/handler.dart index 68781a22..51e1ddb3 100644 --- a/app/third_party/xterm/lib/src/core/escape/handler.dart +++ b/app/third_party/xterm/lib/src/core/escape/handler.dart @@ -3,6 +3,10 @@ import 'package:xterm/src/core/mouse/mode.dart'; abstract class EscapeHandler { void writeChar(int char); + /// Writes the printable ASCII characters (U+0020-007E) of [data] from + /// [start] to [end] (exclusive), as [writeChar] would one by one. + void writeAscii(String data, int start, int end); + /* SBC */ void bell(); diff --git a/app/third_party/xterm/lib/src/core/escape/parser.dart b/app/third_party/xterm/lib/src/core/escape/parser.dart index 0f795be7..10896214 100644 --- a/app/third_party/xterm/lib/src/core/escape/parser.dart +++ b/app/third_party/xterm/lib/src/core/escape/parser.dart @@ -39,6 +39,8 @@ class EscapeParser { continue; } + if (_processPlain()) continue; + tokenBegin = _queue.totalConsumed; final char = _queue.consume(); @@ -54,19 +56,69 @@ class EscapeParser { } } + /// Handles the plain text at the head of the input, most of any output, + /// straight from the written string: runs of printable ASCII are written + /// at once and C0 controls other than ESC (line feeds, carriage returns) + /// handled as they come. Stops at the end of the string or at anything + /// else (an escape sequence, a character outside ASCII), which the caller + /// parses one at a time. Returns whether anything was handled. + bool _processPlain() { + final block = _queue.block; + final length = block.length; + final first = _queue.offset; + var at = first; + while (at < length) { + final unit = block.codeUnitAt(at); + if (unit >= Ascii.space && unit <= Ascii.tilde) { + var end = at + 1; + while (end < length) { + final next = block.codeUnitAt(end); + if (next < Ascii.space || next > Ascii.tilde) break; + end++; + } + tokenBegin = _queue.totalConsumed; + _queue.skip(end - at); + handler.writeAscii(block, at, end); + at = end; + } else if (unit < Ascii.space && unit != Ascii.ESC) { + tokenBegin = _queue.totalConsumed; + _queue.skip(1); + _processChar(unit); + at++; + // A handler's callback (the bell) wrote more: read it afresh. + if (_queue.offset != at) return true; + } else { + break; + } + } + return at > first; + } + + /// A single character: a C0 control's action, or a character to print. + /// (A switch rather than a table of torn-off handlers: compiled to + /// JavaScript, a call through a tear-off costs several times a direct + /// call, and line feeds and carriage returns come with every line.) void _processChar(int char) { - if (char > _sbcHandlers.maxIndex) { - handler.writeChar(char); - return; + switch (char) { + case 0x07: + handler.bell(); + case 0x08: + handler.backspaceReturn(); + case 0x09: + handler.tab(); + case 0x0a || 0x0b || 0x0c: + handler.lineFeed(); + case 0x0d: + handler.carriageReturn(); + case 0x0e: + handler.shiftOut(); + case 0x0f: + handler.shiftIn(); + case < 0x07: + handler.unkownEscape(char); + default: + handler.writeChar(char); } - - final sbcHandler = _sbcHandlers[char]; - if (sbcHandler == null) { - handler.unkownEscape(char); - return; - } - - sbcHandler(); } /// Processes a sequence of characters that starts with an escape character. @@ -83,6 +135,9 @@ class EscapeParser { return true; } + // CSI, nearly every sequence, without the table's torn-off call. + if (escapeChar == Ascii.openBracket) return _escHandleCSI(); + final escapeHandler = _escHandlers[escapeChar]; if (escapeHandler == null) { @@ -93,18 +148,6 @@ class EscapeParser { return escapeHandler(); } - late final _sbcHandlers = FastLookupTable<_SbcHandler>({ - 0x07: handler.bell, - 0x08: handler.backspaceReturn, - 0x09: handler.tab, - 0x0a: handler.lineFeed, - 0x0b: handler.lineFeed, - 0x0c: handler.lineFeed, - 0x0d: handler.carriageReturn, - 0x0e: handler.shiftOut, - 0x0f: handler.shiftIn, - }); - late final _escHandlers = FastLookupTable<_EscHandler>({ '['.charCode: _escHandleCSI, ']'.charCode: _escHandleOSC, @@ -301,6 +344,12 @@ class EscapeParser { return true; } + // Colours and attributes, the commonest sequence, called directly. + if (finalByte == Ascii.m && _csi.prefix == null) { + _csiHandleSgr(); + return true; + } + final csiHandler = _csiHandlers[finalByte]; if (csiHandler == null) { @@ -1094,12 +1143,21 @@ class _Csi { void reset() { prefix = null; intermediates = 0; - params.clear(); - rawParams.clear(); - rawIsSub.clear(); + _empty(params); + _empty(rawParams); + _empty(rawIsSub); finalByte = 0; } + /// Empties [list] one element at a time: a sequence has a few parameters, + /// and compiled to JavaScript `clear()` (setting an array's length) costs + /// more than every other step of parsing a colour change. + static void _empty(List list) { + while (list.isNotEmpty) { + list.removeLast(); + } + } + void add(int value, bool isSub) { if (rawParams.length >= maxParams) return; rawParams.add(value); @@ -1117,6 +1175,5 @@ class _Csi { /// Returns [true] if the sequence was processed, [false] if it was not. typedef _EscHandler = bool Function(); -typedef _SbcHandler = void Function(); typedef _CsiHandler = void Function(); diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index a031daaf..6e6f1706 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -284,9 +284,14 @@ class Terminal with Observable implements TerminalState, EscapeHandler { /// Writes the data from the underlying program to the terminal. Calling this /// updates the states of the terminal and emits events such as [onBell] or /// [onTitleChange] when the escape sequences in [data] request it. - void write(String data) { + /// + /// Listeners (the view) hear of the change unless [notify] is false: a + /// host writing a large burst in several writes calls [notifyListeners] + /// itself once the view should show it, so the view draws the final state + /// instead of every step. + void write(String data, {bool notify = true}) { _parser.write(data); - notifyListeners(); + if (notify) notifyListeners(); } /// Sends a key event to the underlying program. @@ -470,6 +475,12 @@ class Terminal with Observable implements TerminalState, EscapeHandler { _buffer.writeChar(char); } + @override + void writeAscii(String data, int start, int end) { + _precedingCodepoint = data.codeUnitAt(end - 1); + _buffer.writeAscii(data, start, end); + } + /* SBC */ @override diff --git a/app/third_party/xterm/lib/src/utils/byte_consumer.dart b/app/third_party/xterm/lib/src/utils/byte_consumer.dart index 4a2ad382..622caac1 100644 --- a/app/third_party/xterm/lib/src/utils/byte_consumer.dart +++ b/app/third_party/xterm/lib/src/utils/byte_consumer.dart @@ -1,9 +1,16 @@ import 'dart:collection'; +/// The parser's input: the written strings, read one character at a time. +/// +/// Positions ([length], [totalConsumed], [rollback]) count UTF-16 code +/// units, so a character outside the BMP counts two. A surrogate pair is +/// read as one code point when both halves are in the same write; a lone +/// surrogate is read as itself, as `String.runes` does. Strings are kept as +/// written rather than decoded into lists, so a write allocates nothing. class ByteConsumer { - final _queue = ListQueue>(); + final _queue = ListQueue(); - final _consumed = ListQueue>(); + final _consumed = ListQueue(); var _currentOffset = 0; @@ -13,37 +20,63 @@ class ByteConsumer { void add(String data) { if (data.isEmpty) return; - final runes = data.runes.toList(growable: false); - _queue.addLast(runes); - _length += runes.length; + _queue.addLast(data); + _length += data.length; + } + + /// The string being read, with at least one unit left at [offset]. + /// Only valid while [isNotEmpty]. + String get block { + var data = _queue.first; + while (_currentOffset >= data.length) { + _consumed.add(_queue.removeFirst()); + _currentOffset -= data.length; + data = _queue.first; + } + return data; + } + + /// Where [block] is read next. + int get offset => _currentOffset; + + /// Consumes [units] code units of [block] at once (the caller has read + /// them there). + void skip(int units) { + _currentOffset += units; + _length -= units; + _totalConsumed += units; } int peek() { - final data = _queue.first; - if (_currentOffset < data.length) { - return data[_currentOffset]; - } else { - final result = consume(); - rollback(); - return result; + final data = block; + final unit = data.codeUnitAt(_currentOffset); + if (unit & 0xFC00 == 0xD800 && _currentOffset + 1 < data.length) { + final next = data.codeUnitAt(_currentOffset + 1); + if (next & 0xFC00 == 0xDC00) { + return 0x10000 + ((unit & 0x3FF) << 10) + (next & 0x3FF); + } } + return unit; } int consume() { - final data = _queue.first; - - if (_currentOffset >= data.length) { - _consumed.add(_queue.removeFirst()); - _currentOffset -= data.length; - return consume(); + final data = block; + final unit = data.codeUnitAt(_currentOffset++); + if (unit & 0xFC00 == 0xD800 && _currentOffset < data.length) { + final next = data.codeUnitAt(_currentOffset); + if (next & 0xFC00 == 0xDC00) { + _currentOffset++; + _length -= 2; + _totalConsumed += 2; + return 0x10000 + ((unit & 0x3FF) << 10) + (next & 0x3FF); + } } - _length--; _totalConsumed++; - return data[_currentOffset++]; + return unit; } - /// Rolls back the last [n] call. + /// Rolls back [n] code units. void rollback([int n = 1]) { _currentOffset -= n; _totalConsumed -= n; @@ -55,7 +88,7 @@ class ByteConsumer { } } - /// Rolls back to the state when this consumer had [length] bytes. + /// Rolls back to the state when this consumer had [length] units. void rollbackTo(int length) { rollback(length - _length); } @@ -83,25 +116,3 @@ class ByteConsumer { _length = 0; } } - -// void main() { -// final consumer = ByteConsumer(); -// consumer.add(Uint8List.fromList([1, 2, 3])); -// consumer.add(Uint8List.fromList([4, 5, 6])); - -// while (consumer.isNotEmpty) { -// print(consumer.consume()); -// } - -// consumer.rollback(5); - -// while (consumer.isNotEmpty) { -// print(consumer.consume()); -// } - -// consumer.rollbackTo(3); - -// while (consumer.isNotEmpty) { -// print(consumer.consume()); -// } -// } diff --git a/app/third_party/xterm/lib/src/utils/circular_buffer.dart b/app/third_party/xterm/lib/src/utils/circular_buffer.dart index 3b3ee3a1..34ef86ac 100644 --- a/app/third_party/xterm/lib/src/utils/circular_buffer.dart +++ b/app/third_party/xterm/lib/src/utils/circular_buffer.dart @@ -23,7 +23,11 @@ class IndexAwareCircularBuffer { /// the regular index. @pragma('vm:prefer-inline') int _getCyclicIndex(int index) { - return (_startIndex + index) % _array.length; + // Indexes run from 0 to the capacity (one past the end when pushing), + // so one subtraction wraps them; `%` is a helper call in JavaScript. + final cyclic = _startIndex + index; + final capacity = _array.length; + return cyclic >= capacity ? cyclic - capacity : cyclic; } /// Removes the element at [index] from the list. @@ -196,6 +200,7 @@ class IndexAwareCircularBuffer { if (_length >= _array.length) { _startIndex += 1; + if (_startIndex == _array.length) _startIndex = 0; _absoluteStartIndex += 1; } else { _length++; diff --git a/app/third_party/xterm/lib/src/utils/debugger.dart b/app/third_party/xterm/lib/src/utils/debugger.dart index 8ab4daf3..f5a647b2 100644 --- a/app/third_party/xterm/lib/src/utils/debugger.dart +++ b/app/third_party/xterm/lib/src/utils/debugger.dart @@ -36,7 +36,7 @@ class TerminalDebugger with Observable { final commands = []; void write(String chunk) { - recorded.addAll(chunk.runes); + recorded.addAll(chunk.codeUnits); _parser.write(chunk); notifyListeners(); } @@ -89,6 +89,11 @@ class _TerminalDebuggerHandler implements EscapeHandler { onCommand('writeChar(${String.fromCharCode(char)})'); } + @override + void writeAscii(String data, int start, int end) { + onCommand('writeAscii(${data.substring(start, end)})'); + } + /* SBC */ @override diff --git a/app/third_party/xterm/lib/src/utils/unicode_width.dart b/app/third_party/xterm/lib/src/utils/unicode_width.dart index c0101334..068daca5 100644 --- a/app/third_party/xterm/lib/src/utils/unicode_width.dart +++ b/app/third_party/xterm/lib/src/utils/unicode_width.dart @@ -16,7 +16,12 @@ abstract final class UnicodeWidth { static const _textDefault = 8; static const _modifierBase = 16; - static final Uint8List _bmp = _buildBmp(); + /// The properties of every code point below [_tableEnd]: the BMP and the + /// supplementary plane that holds the emoji. Beyond it, the ranges are + /// searched. + static final Uint8List _table = _buildTable(); + + static const _tableEnd = 0x20000; /// Columns [codePoint] takes alone: 0, 1 or 2. Controls are 0. static int width(int codePoint) { @@ -55,7 +60,7 @@ abstract final class UnicodeWidth { codePoint >= 0x1F1E6 && codePoint <= 0x1F1FF; static int _props(int codePoint) { - if (codePoint < 0x10000) return _bmp[codePoint]; + if (codePoint < _tableEnd) return _table[codePoint]; var props = 0; if (_within(zeroWidthRanges, codePoint)) props |= _zero; if (_within(wideRanges, codePoint)) props |= _wide; @@ -65,12 +70,12 @@ abstract final class UnicodeWidth { return props; } - static Uint8List _buildBmp() { - final table = Uint8List(0x10000); + static Uint8List _buildTable() { + final table = Uint8List(_tableEnd); void mark(List ranges, int bit) { for (var i = 0; i < ranges.length; i += 2) { - if (ranges[i] >= 0x10000) break; - final last = ranges[i + 1] < 0x10000 ? ranges[i + 1] : 0xFFFF; + if (ranges[i] >= _tableEnd) break; + final last = ranges[i + 1] < _tableEnd ? ranges[i + 1] : _tableEnd - 1; for (var cp = ranges[i]; cp <= last; cp++) { table[cp] |= bit; } diff --git a/app/tool/perf/terminal_parse_bench.dart b/app/tool/perf/terminal_parse_bench.dart new file mode 100644 index 00000000..2d44caae --- /dev/null +++ b/app/tool/perf/terminal_parse_bench.dart @@ -0,0 +1,110 @@ +// Emulator parse bench in the Dart VM: feeds generated output into +// `Terminal.write` in the app's feed slices (16 Ki units) and prints MB/s +// per workload. Pure Dart (the emulator core has no Flutter imports). +// +// dart run tool/perf/terminal_parse_bench.dart [--mb 16] [--workloads seq,yes,...] +// +// In V8, as the web build runs it: +// dart compile js -O2 -Dworkloads=seq,yes tool/perf/terminal_parse_bench.dart -o /tmp/parse.js +// node -e "globalThis.self = globalThis; require('/tmp/parse.js')" +// +// Workloads match tool/perf/terminal_stream_bench.dart. +import 'package:xterm/core.dart'; + +void main(List args) { + var megabytes = 16.0; + var workloads = ['seq', 'yes', 'unicode', 'colors', 'screen', 'progress']; + // Compiled to JavaScript (dart compile js, run in node) there are no + // arguments: -Dworkloads=seq,yes picks them. + const only = String.fromEnvironment('workloads'); + if (only.isNotEmpty) workloads = only.split(','); + for (var i = 0; i + 1 < args.length; i++) { + if (args[i] == '--mb') megabytes = double.parse(args[i + 1]); + if (args[i] == '--workloads') workloads = args[i + 1].split(','); + } + for (final workload in workloads) { + final data = generateWorkload(workload, (megabytes * 1e6).round()); + // Warm up, then measure the best of three. + _run(data.substring(0, data.length ~/ 8)); + var best = double.infinity; + for (var round = 0; round < 3; round++) { + final seconds = _run(data); + if (seconds < best) best = seconds; + } + final mb = data.length / 1e6; + // ignore: avoid_print + print( + '{"workload":"$workload","mb":${mb.toStringAsFixed(2)},' + '"seconds":${best.toStringAsFixed(3)},' + '"mbPerSecond":${(mb / best).toStringAsFixed(2)}}', + ); + } +} + +double _run(String data) { + final terminal = Terminal(maxLines: 10000); + terminal.resize(158, 48); + var notified = 0; + terminal.addListener(() => notified++); + const slice = 16 * 1024; + final clock = Stopwatch()..start(); + for (var at = 0; at < data.length; at += slice) { + final end = at + slice < data.length ? at + slice : data.length; + terminal.write(data.substring(at, end)); + } + clock.stop(); + if (notified == 0) throw StateError('no writes'); + return clock.elapsedMicroseconds / 1e6; +} + +/// Generated output of about [size] UTF-16 units, as the web bench makes. +String generateWorkload(String workload, int size) { + final out = StringBuffer(); + var counter = 0; + while (out.length < size) { + counter++; + switch (workload) { + case 'yes': + out.write('y\r\n'); + case 'unicode': + out.write( + '$counter é ñ 中文 \u{1F600} \u{1F44D}\u{1F3FD} ' + '\u{1F1F5}\u{1F1F9} │ ╭─╮ ▓▒░ ' + '\u{E0B0} done\r\n', + ); + case 'colors': + final c = 31 + counter % 7; + out.write( + '\x1b[${c}m$counter\x1b[0m \x1b[1mbold\x1b[0m ' + 'plain text line with some words\r\n', + ); + case 'screen': + out.write('\x1b[H'); + for (var row = 0; row < 48; row++) { + final c = 31 + (row + counter) % 7; + out.write( + '\x1b[${c}m${(counter + row).toString().padLeft(8)}' + '\x1b[0m \x1b[7m cpu ${row % 100}% \x1b[0m ' + '${'process name and arguments ' * 4}\x1b[K\r\n', + ); + } + case 'progress': + if (counter == 1) { + for (var row = 0; row < 47; row++) { + out.write( + '\x1b[3${row % 7 + 1}mline $row\x1b[0m ' + '${'static output that does not change ' * 3}\r\n', + ); + } + } + final done = counter % 50; + out.write( + '\r\x1b[1m[${'#' * done}${'.' * (50 - done)}]\x1b[0m ' + '$counter files', + ); + default: + out.write('$counter\r\n'); + } + } + return out.toString(); +}