Merge branch 'worktree-agent-afe96053a37e02d6f'

This commit is contained in:
2026-11-26 03:27:28 +00:00
23 changed files with 1198 additions and 110 deletions
+11
View File
@@ -55,3 +55,14 @@ Local patches (keep this list current):
reused until the line changes (`ui/row_pictures.dart`,
`BufferLine.version`); glyphs wider than their cells scaled to fit;
`TerminalStyle` and `TerminalTheme` compare by value
- write path: the parser reads written strings directly (`ByteConsumer`
counts UTF-16 units, no rune lists) and handles printable ASCII runs and
C0 controls straight from the string (`EscapeHandler.writeAscii`,
`Buffer.writeAscii`, `BufferLine.setAsciiCells`); a line leaving a full
scrollback or a one-line region scroll is cleared and reused unless it
has anchors (`BufferLine.clear`, which clears only the cells written
since); switch dispatch for C0 and direct calls for CSI/SGR;
`joinPreviousCell` rejects non-joining characters first; width table
covers plane 1; `IndexAwareCircularBuffer.insert` keeps its start index
wrapped; `Terminal.write(notify: false)` lets the host notify once per
frame
+64 -3
View File
@@ -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 = <int>{
0,
r' '.codeUnitAt(0),
@@ -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--;
+83 -1
View File
@@ -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;
+4
View File
@@ -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);
}
@@ -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();
+84 -27
View File
@@ -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<Object> 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();
+13 -2
View File
@@ -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
+55 -44
View File
@@ -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<List<int>>();
final _queue = ListQueue<String>();
final _consumed = ListQueue<List<int>>();
final _consumed = ListQueue<String>();
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());
// }
// }
+6 -1
View File
@@ -23,7 +23,11 @@ class IndexAwareCircularBuffer<T extends IndexedItem> {
/// 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<T extends IndexedItem> {
if (_length >= _array.length) {
_startIndex += 1;
if (_startIndex == _array.length) _startIndex = 0;
_absoluteStartIndex += 1;
} else {
_length++;
+6 -1
View File
@@ -36,7 +36,7 @@ class TerminalDebugger with Observable {
final commands = <TerminalCommand>[];
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
+11 -6
View File
@@ -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<int> 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;
}