The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
perf(desktop): redraw only terminal lines that changed (#304)
0xken1597c58af62c14
diff --git a/desktop/test/terminal_line_paint_cache_test.dart b/desktop/test/terminal_line_paint_cache_test.dartnew file mode 100644index 000000000..3491f30f8--- /dev/null+++ b/desktop/test/terminal_line_paint_cache_test.dart@@ -0,0 +1,439 @@+import 'dart:typed_data';+import 'dart:ui';++import 'package:flutter/painting.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:xterm/src/ui/line_picture_cache.dart';+import 'package:xterm/src/ui/painter.dart';+import 'package:xterm/xterm.dart';++TerminalPainter _painter({TerminalTheme? theme}) => TerminalPainter(+ theme: theme ?? TerminalThemes.defaultTheme,+ textStyle: const TerminalStyle(),+ textScaler: TextScaler.noScaling,+ );++/// A screen exercising everything a line can draw: colours, inverse, faint,+/// bold/italic/underline, wide CJK, emoji, block glyphs, box drawing, RGB.+Terminal _sampleTerminal() {+ final terminal = Terminal(maxLines: 200)..resize(60, 12);+ terminal.write('plain text, then \x1b[31mred\x1b[0m \x1b[42mgreen bg\x1b[0m\r\n');+ terminal.write('\x1b[7minverse\x1b[0m \x1b[2mfaint\x1b[0m \x1b[1mbold\x1b[0m '+ '\x1b[3mitalic\x1b[0m \x1b[4munder line \x1b[0m\r\n');+ terminal.write('wide 漢字テスト emoji 😀 done\r\n');+ terminal.write('blocks ▀▄█▌▐░▒▓ box ┌─┬─┐│ │└─┴─┘\r\n');+ terminal.write('\x1b[38;2;255;128;0;48;2;0;64;128mrgb run\x1b[0m end\r\n');+ terminal.write('\x1b[44m \x1b[0m trailing spaces on blue\r\n');+ return terminal;+}++List<BufferLine> _visible(Terminal terminal) {+ final lines = terminal.buffer.lines;+ final first = lines.length - terminal.viewHeight;+ return [for (var i = 0; i < terminal.viewHeight; i++) lines[first + i]];+}++Future<Uint8List> _render(+ TerminalPainter painter,+ List<BufferLine> lines,+ void Function(Canvas canvas, Offset offset, BufferLine line) paint,+) async {+ final cell = painter.cellSize;+ final width = (lines.first.length * cell.width).ceil();+ final height = (lines.length * cell.height).ceil();+ final recorder = PictureRecorder();+ final canvas = Canvas(recorder);+ canvas.drawRect(+ Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),+ Paint()..color = painter.theme.background,+ );+ for (var i = 0; i < lines.length; i++) {+ paint(canvas, Offset(0, (i * cell.height).truncateToDouble()), lines[i]);+ }+ final image = await recorder.endRecording().toImage(width, height);+ final bytes = await image.toByteData(format: ImageByteFormat.rawRgba);+ image.dispose();+ return bytes!.buffer.asUint8List();+}++/// The renderer before merged backgrounds and glyph runs: each cell's+/// background, then its glyph, one cell at a time.+void _paintCellByCell(+ TerminalPainter painter,+ Canvas canvas,+ Offset offset,+ BufferLine line,+) {+ final cellData = CellData.empty();+ for (var i = 0; i < line.length; i++) {+ line.getCellData(i, cellData);+ painter.paintCell(+ canvas,+ offset.translate(i * painter.cellSize.width, 0),+ cellData,+ );+ if (cellData.content >> CellContent.widthShift == 2) i++;+ }+}++void main() {+ group('BufferLine.paintVersion', () {+ test('ignores a cell rewritten with the value it already has', () {+ final line = BufferLine(10);+ final style = CursorStyle(foreground: 1, background: 2, attrs: 3);+ line.setCell(0, 0x41, 1, style);+ final version = line.paintVersion;+ final text = line.textVersion;++ line.setCell(0, 0x41, 1, style);+ final data = CellData.empty();+ line.getCellData(0, data);+ line.setCellData(0, data);+ line.setForeground(0, 1);++ expect(line.paintVersion, version);+ // Text caches keep their old, unconditional rule.+ expect(line.textVersion, greaterThan(text));+ });++ test('moves on a colour-only change, which textVersion ignores', () {+ final line = BufferLine(10)..setCell(0, 0x41, 1, CursorStyle());+ final version = line.paintVersion;+ final text = line.textVersion;++ line.setForeground(0, 7);+ expect(line.paintVersion, greaterThan(version));+ line.setBackground(0, 7);+ line.setAttributes(0, 7);+ expect(line.paintVersion, version + 3);+ expect(line.textVersion, text);+ });++ test('moves on every edit that reshapes the line', () {+ final style = CursorStyle();+ BufferLine filled() {+ final line = BufferLine(10);+ for (var i = 0; i < 10; i++) {+ line.setCell(i, 0x61 + i, 1, style);+ }+ return line;+ }++ final edits = <String, void Function(BufferLine)>{+ 'insertCells': (l) => l.insertCells(2, 3),+ 'removeCells': (l) => l.removeCells(2, 3),+ 'eraseRange': (l) => l.eraseRange(2, 5, style),+ 'eraseCell': (l) => l.eraseCell(0, style),+ 'resetCell': (l) => l.resetCell(0),+ 'setContent': (l) => l.setContent(0, 0x7a | (1 << CellContent.widthShift)),+ 'setCodePoint': (l) => l.setCodePoint(0, 0x7a),+ 'resize': (l) => l.resize(4),+ 'copyFrom': (l) => l.copyFrom(BufferLine(10), 0, 0, 5),+ };+ for (final MapEntry(key: name, value: edit) in edits.entries) {+ final line = filled();+ final version = line.paintVersion;+ edit(line);+ expect(line.paintVersion, greaterThan(version), reason: name);+ }+ });++ test('a zero-count insert or remove is not a change', () {+ final line = BufferLine(10)..setCell(0, 0x41, 1, CursorStyle());+ final version = line.paintVersion;+ line.insertCells(9, 0);+ line.removeCells(9, 0);+ expect(line.paintVersion, version);+ });+ });++ group('LinePictureCache', () {+ Picture picture() {+ final recorder = PictureRecorder();+ Canvas(recorder).drawRect(const Rect.fromLTWH(0, 0, 1, 1), Paint());+ return recorder.endRecording();+ }++ test('hits while the line is unchanged, misses once it changes', () {+ final cache = LinePictureCache();+ final line = BufferLine(4);+ final drawn = picture();++ cache.beginFrame();+ expect(cache.lookup(line), isNull);+ cache.store(line, drawn);+ cache.endFrame();++ cache.beginFrame();+ expect(cache.lookup(line), same(drawn));+ cache.endFrame();++ line.setCell(0, 0x41, 1, CursorStyle());+ cache.beginFrame();+ expect(cache.lookup(line), isNull);+ cache.endFrame();+ });++ test('keeps only the lines the last frame drew', () {+ final cache = LinePictureCache();+ final kept = BufferLine(4), gone = BufferLine(4);++ cache.beginFrame();+ cache.store(kept, picture());+ cache.store(gone, picture());+ cache.endFrame();+ expect(cache.length, 2);++ cache.beginFrame();+ expect(cache.lookup(kept), isNotNull);+ cache.endFrame();+ expect(cache.length, 1);++ cache.clear();+ expect(cache.length, 0);+ });+ });++ group('TerminalPainter.paintLine', () {+ test('merged backgrounds fill exactly what cell-by-cell painting filled', () async {+ // Backgrounds alone: runs of colours, inverse, a wide cell, gaps.+ final terminal = Terminal(maxLines: 50)..resize(40, 4);+ terminal.write('\x1b[41m \x1b[42m \x1b[0m \x1b[44m \x1b[0m\r\n');+ terminal.write('\x1b[7m \x1b[0m \x1b[48;2;10;20;30m \x1b[48;2;10;20;31m \x1b[0m\r\n');+ terminal.write('\x1b[45m\u3000 \u3000\x1b[0m\r\n');+ final lines = _visible(terminal);+ final painter = _painter();+ final expected = await _render(+ painter,+ lines,+ (canvas, offset, line) => _paintCellByCell(painter, canvas, offset, line),+ );+ expect(await _render(painter, lines, painter.paintLine), expected);+ });++ test('glyphs on coloured backgrounds differ only where they overhang a neighbour', () async {+ // Cell by cell, the next cell's background was drawn over the edge of+ // the glyph before it — but only on a coloured background, never on the+ // default one. Backgrounds first shows that edge on both, alike. The+ // difference is confined to those edges: a sliver of the grid.+ final lines = _visible(_sampleTerminal());+ final painter = _painter();+ final expected = await _render(+ painter,+ lines,+ (canvas, offset, line) => _paintCellByCell(painter, canvas, offset, line),+ );+ final actual = await _render(painter, lines, painter.paintLine);+ var differing = 0;+ for (var i = 0; i < actual.length; i += 4) {+ if (actual[i] != expected[i] ||+ actual[i + 1] != expected[i + 1] ||+ actual[i + 2] != expected[i + 2]) {+ differing++;+ }+ }+ expect(differing / (actual.length / 4), lessThan(0.002));+ });+ });++ group('ASCII runs', () {+ int runsIn(String text, {int cols = 60}) {+ final terminal = Terminal(maxLines: 50)..resize(cols, 3);+ terminal.write(text);+ final painter = _painter();+ final recorder = PictureRecorder();+ painter.paintLine(Canvas(recorder), Offset.zero, terminal.buffer.lines[0]);+ recorder.endRecording().dispose();+ return painter.debugAsciiRunsPainted;+ }++ test('are cut wherever the style or the kind of character changes', () {+ expect(runsIn('plain words here'), 1);+ expect(runsIn('ab\x1b[31mcd\x1b[0mef'), 3);+ expect(runsIn('ab\x1b[1mcd\x1b[0m\x1b[3mef\x1b[0m\x1b[4mgh\x1b[0m'), 4);+ expect(runsIn('ab\x1b[7mcd\x1b[0m\x1b[2mef\x1b[0m'), 3);+ // Wide, non-ASCII and block glyphs stay cell by cell and split the run.+ expect(runsIn('ab漢cd'), 2);+ expect(runsIn('abé cd'), 2);+ expect(runsIn('ab█cd'), 2);+ // A single ASCII cell between two breaks is not a run.+ expect(runsIn('a漢b'), 0);+ });++ test('skip runs of bare spaces but keep underlined ones', () {+ expect(runsIn('\x1b[41m \x1b[0m'), 0);+ expect(runsIn('\x1b[4m \x1b[0m'), 1);+ });++ test('draw what cell-by-cell painting drew', () async {+ final terminal = Terminal(maxLines: 50)..resize(60, 8);+ terminal.write('The quick brown fox jumps over the lazy dog 0123456789\r\n');+ terminal.write('\x1b[31mred \x1b[1mbold \x1b[3mitalic\x1b[0m \x1b[2mfaint\x1b[0m \x1b[7minverse\x1b[0m\r\n');+ terminal.write('\x1b[4munderlined words and trailing \x1b[0m!\r\n');+ terminal.write('\x1b[38;5;208m256-colour\x1b[0m \x1b[38;2;1;2;3;48;2;200;200;200mrgb on rgb\x1b[0m\r\n');+ terminal.write(r'punctuation !"#$%&()*+,-./:;<=>?@[\]^_`{|}~' '\r\n');+ terminal.write('mixed ascii 漢字 and ▀▄ blocks, then ascii again\r\n');+ final lines = _visible(terminal);+ final painter = _painter();+ final expected = await _render(+ painter,+ lines,+ (canvas, offset, line) => _paintCellByCell(painter, canvas, offset, line),+ );+ final actual = await _render(painter, lines, painter.paintLine);+ expect(painter.debugAsciiRunsPainted, greaterThan(10));+ // A run is shaped as one line of text, so an edge (an underline most of+ // all) can antialias a shade differently than cell-sized pieces did —+ // never by more than a faint shade, and never a glyph out of place.+ var differing = 0, largest = 0;+ for (var i = 0; i < actual.length; i++) {+ final delta = (actual[i] - expected[i]).abs();+ if (delta > 0) differing++;+ if (delta > largest) largest = delta;+ }+ expect(largest, lessThanOrEqualTo(16));+ expect(differing / actual.length, lessThan(0.001));+ });+ });++ group('TerminalPainter.paintLineCached', () {+ test('replays pixel for pixel what paintLine draws', () async {+ final terminal = _sampleTerminal();+ final lines = _visible(terminal);+ final direct = _painter();+ final cached = _painter();++ final expected = await _render(direct, lines, direct.paintLine);+ // First frame records, second replays: both must match a direct paint.+ for (var frame = 0; frame < 2; frame++) {+ cached.beginFrame();+ final actual = await _render(cached, lines, cached.paintLineCached);+ cached.endFrame();+ expect(actual, expected, reason: 'frame $frame');+ }+ expect(cached.cachedLineCount, lines.length);+ });++ test('matches a direct paint at a fractional pixel ratio', () async {+ // At 1.5x a line at y = 7 starts half a device pixel into a pixel, and+ // lines are recorded at that phase and moved by whole device pixels.+ // (This software rasterizer honours isAntiAlias: false, so it cannot+ // show the seam an unsnapped block edge leaves under Impeller's MSAA —+ // it guards that the phase handling itself draws the same pixels.)+ final terminal = Terminal(maxLines: 50)..resize(30, 3);+ terminal.write('blocks ▀▄█▌▐ \x1b[41mred\x1b[0m text');+ final line = terminal.buffer.lines[0];+ const ratio = 1.5;++ Future<Uint8List> render(TerminalPainter painter, bool cached) async {+ final recorder = PictureRecorder();+ final canvas = Canvas(recorder)..scale(ratio);+ for (final y in [7.0, 23.0, 7.0]) {+ painter.beginFrame();+ if (cached) {+ painter.paintLineCached(canvas, Offset(0, y), line);+ } else {+ painter.paintLine(canvas, Offset(0, y), line);+ }+ painter.endFrame();+ }+ final image = await recorder.endRecording().toImage(+ (30 * painter.cellSize.width * ratio).ceil(),+ (48 * ratio).ceil(),+ );+ final bytes = await image.toByteData(format: ImageByteFormat.rawRgba);+ image.dispose();+ return bytes!.buffer.asUint8List();+ }++ TerminalPainter at(double ratio) => _painter()..devicePixelRatio = ratio;+ expect(await render(at(ratio), true), await render(at(ratio), false));+ });++ test('redraws a line written since it was recorded', () async {+ final terminal = _sampleTerminal();+ final painter = _painter();++ painter.beginFrame();+ await _render(painter, _visible(terminal), painter.paintLineCached);+ painter.endFrame();++ terminal.write('\x1b[1;1H\x1b[35mCHANGED\x1b[0m');+ final lines = _visible(terminal);+ painter.beginFrame();+ final actual = await _render(painter, lines, painter.paintLineCached);+ painter.endFrame();+ expect(actual, await _render(_painter(), lines, _painter().paintLine));+ });++ test('reuses a line\'s drawing after it scrolls up the screen', () {+ final terminal = Terminal(maxLines: 200)..resize(40, 5);+ for (var i = 0; i < 5; i++) {+ terminal.write('line $i\r\n');+ }+ final painter = _painter();+ final recorder = PictureRecorder();+ final canvas = Canvas(recorder);++ painter.beginFrame();+ for (final line in _visible(terminal)) {+ painter.paintLineCached(canvas, Offset.zero, line);+ }+ painter.endFrame();+ final before = {for (final line in _visible(terminal)) line: line.paintVersion};++ terminal.write('line 5\r\n');+ final after = _visible(terminal);+ // Every line but the newest is an object the last frame already drew,+ // and of those only the row the cursor was on ('line 5') was written.+ final kept = after.where(before.containsKey).toList();+ expect(kept.length, after.length - 1);+ expect(kept.where((line) => line.paintVersion != before[line]).length, 1);+ recorder.endRecording().dispose();+ });++ test('forgets every drawing when the theme changes', () {+ final terminal = _sampleTerminal();+ final painter = _painter();+ final recorder = PictureRecorder();+ final canvas = Canvas(recorder);+ painter.beginFrame();+ for (final line in _visible(terminal)) {+ painter.paintLineCached(canvas, Offset.zero, line);+ }+ painter.endFrame();+ expect(painter.cachedLineCount, greaterThan(0));++ painter.theme = TerminalTheme(+ cursor: const Color(0xFFFFFFFF),+ selection: const Color(0xFFFFFFFF),+ foreground: const Color(0xFF000000),+ background: const Color(0xFFFFFFFF),+ black: const Color(0xFF000000),+ red: const Color(0xFFFF0000),+ green: const Color(0xFF00FF00),+ yellow: const Color(0xFFFFFF00),+ blue: const Color(0xFF0000FF),+ magenta: const Color(0xFFFF00FF),+ cyan: const Color(0xFF00FFFF),+ white: const Color(0xFFFFFFFF),+ brightBlack: const Color(0xFF808080),+ brightRed: const Color(0xFFFF0000),+ brightGreen: const Color(0xFF00FF00),+ brightYellow: const Color(0xFFFFFF00),+ brightBlue: const Color(0xFF0000FF),+ brightMagenta: const Color(0xFFFF00FF),+ brightCyan: const Color(0xFF00FFFF),+ brightWhite: const Color(0xFFFFFFFF),+ searchHitBackground: const Color(0xFFFFFF00),+ searchHitBackgroundCurrent: const Color(0xFFFF0000),+ searchHitForeground: const Color(0xFF000000),+ );+ expect(painter.cachedLineCount, 0);+ painter.devicePixelRatio = 2;+ expect(painter.cachedLineCount, 0);+ recorder.endRecording().dispose();+ });+ });+}+diff --git a/desktop/third_party/xterm/README.autonomous.md b/desktop/third_party/xterm/README.autonomous.mdindex cfb3fd982..f984052fe 100644--- a/desktop/third_party/xterm/README.autonomous.md+++ b/desktop/third_party/xterm/README.autonomous.md@@ -204,3 +204,45 @@ it if one is dropped.follow the text path. Box drawing (U+2500–U+257F) still comes from thefont. Regression: `test/terminal_block_glyph_test.dart`, which alsorasterises through the real painter.++12. **Only lines that changed are drawn again** (`lib/src/core/buffer/line.dart`,+ `lib/src/ui/line_picture_cache.dart`, `lib/src/ui/painter.dart`,+ `lib/src/ui/render.dart`). Every frame with output — and every cursor blink,+ twice a second — drew each visible cell again, one paragraph per glyph,+ though usually one line had changed. `BufferLine.paintVersion` now moves+ whenever anything a line draws changes (colours too, unlike `textVersion`),+ but not when a cell is rewritten with the value it already holds, because a+ TUI redrawing its screen rewrites mostly identical cells. The renderer keeps+ each visible line's drawing as a `Picture` keyed by the line object and+ replays it while the version holds; lines keep their identity as they+ scroll (patch 1), so streaming output records only the newest line. A line+ is recorded at its sub-device-pixel phase and replayed moved by whole device+ pixels, so block-glyph snapping (patch 11) lands exactly where a direct+ paint would put it even at a fractional pixel ratio. The+ cache holds only what the last frame drew and is cleared with the theme,+ font, text scale, pixel ratio, and whenever the view stops rendering.+ Regression: `test/terminal_line_paint_cache_test.dart`, including a+ pixel-for-pixel comparison of replayed and directly painted lines.++13. **A line's backgrounds are filled a run at a time, before its glyphs**+ (`lib/src/ui/painter.dart`). Neighbouring cells with the same background+ colour share one rectangle — the same area, one-pixel overlap included —+ and a single `Paint` serves them all. Painting every background before any+ glyph also means a glyph that overhangs its cell (italic, a wide face) now+ shows over a coloured neighbour just as it always did over the default+ background, instead of being clipped by that neighbour's fill. Regression:+ `test/terminal_line_paint_cache_test.dart` (backgrounds identical to the+ per-cell fill; glyph edges the only difference).++14. **Plain ASCII in one style is drawn as one paragraph**+ (`lib/src/ui/painter.dart`). Two or more neighbouring printable-ASCII,+ single-width cells with the same colours and attributes are laid out and+ drawn together, with ligatures, contextual alternates and kerning disabled+ so each glyph keeps its cell. A weight/slant is only batched when every+ printable ASCII character measures exactly one cell wide in it, so a face+ whose bold or italic runs wider (or a proportional face) stays cell by+ cell. Wide characters, non-ASCII, block glyphs and the substituted U+23FA+ still go through `paintCellForeground`. Runs of bare spaces draw nothing,+ as before; underlined spaces become U+00A0 as in the per-cell path.+ Regression: `test/terminal_line_paint_cache_test.dart` (where runs are cut,+ and a rendering within antialiasing of the per-cell one).diff --git a/desktop/third_party/xterm/lib/src/core/buffer/line.dart b/desktop/third_party/xterm/lib/src/core/buffer/line.dartindex 7ea477ad4..a7070e0d6 100644--- a/desktop/third_party/xterm/lib/src/core/buffer/line.dart+++ b/desktop/third_party/xterm/lib/src/core/buffer/line.dart@@ -38,6 +38,39 @@ class BufferLine with IndexedItem {int get textVersion => _textVersion;int _textVersion = 0;+ /// Changes whenever anything that affects how this line is drawn changes —+ /// text, colours or attributes. A renderer can reuse its drawing of the line+ /// while it holds. Writing a cell with the value it already has does not+ /// count: a TUI repainting its whole screen rewrites mostly identical cells,+ /// and treating those as changes would make every line new on every redraw.+ int get paintVersion => _paintVersion;+ int _paintVersion = 0;++ /// Store one cell's four words, noting in [paintVersion] if any differ.+ @pragma('vm:prefer-inline')+ void _store(int offset, int foreground, int background, int attrs, int content) {+ final data = _data;+ if (data[offset + _cellForeground] == foreground &&+ data[offset + _cellBackground] == background &&+ data[offset + _cellAttributes] == attrs &&+ data[offset + _cellContent] == content) {+ return;+ }+ data[offset + _cellForeground] = foreground;+ data[offset + _cellBackground] = background;+ data[offset + _cellAttributes] = attrs;+ data[offset + _cellContent] = content;+ _paintVersion++;+ }++ /// Store one word of a cell, noting in [paintVersion] if it differs.+ @pragma('vm:prefer-inline')+ void _storeWord(int index, int value) {+ if (_data[index] == value) return;+ _data[index] = value;+ _paintVersion++;+ }+final _anchors = <CellAnchor>[];List<CellAnchor> get anchors => _anchors;@@ -77,29 +110,26 @@ class BufferLine with IndexedItem {CellData createCellData(int index) {_textVersion++;final cellData = CellData.empty();- final offset = index * _cellSize;- _data[offset + _cellForeground] = cellData.foreground;- _data[offset + _cellBackground] = cellData.background;- _data[offset + _cellAttributes] = cellData.flags;- _data[offset + _cellContent] = cellData.content;+ _store(index * _cellSize, cellData.foreground, cellData.background,+ cellData.flags, cellData.content);return cellData;}void setForeground(int index, int value) {- _data[index * _cellSize + _cellForeground] = value;+ _storeWord(index * _cellSize + _cellForeground, value);}void setBackground(int index, int value) {- _data[index * _cellSize + _cellBackground] = value;+ _storeWord(index * _cellSize + _cellBackground, value);}void setAttributes(int index, int value) {- _data[index * _cellSize + _cellAttributes] = value;+ _storeWord(index * _cellSize + _cellAttributes, value);}void setContent(int index, int value) {_textVersion++;- _data[index * _cellSize + _cellContent] = value;+ _storeWord(index * _cellSize + _cellContent, value);}void setCodePoint(int index, int char) {@@ -109,38 +139,24 @@ class BufferLine with IndexedItem {void setCell(int index, int char, int witdh, CursorStyle style) {_textVersion++;- final offset = index * _cellSize;- _data[offset + _cellForeground] = style.foreground;- _data[offset + _cellBackground] = style.background;- _data[offset + _cellAttributes] = style.attrs;- _data[offset + _cellContent] = char | (witdh << CellContent.widthShift);+ _store(index * _cellSize, style.foreground, style.background, style.attrs,+ char | (witdh << CellContent.widthShift));}void setCellData(int index, CellData cellData) {_textVersion++;- final offset = index * _cellSize;- _data[offset + _cellForeground] = cellData.foreground;- _data[offset + _cellBackground] = cellData.background;- _data[offset + _cellAttributes] = cellData.flags;- _data[offset + _cellContent] = cellData.content;+ _store(index * _cellSize, cellData.foreground, cellData.background,+ cellData.flags, cellData.content);}void eraseCell(int index, CursorStyle style) {_textVersion++;- final offset = index * _cellSize;- _data[offset + _cellForeground] = style.foreground;- _data[offset + _cellBackground] = style.background;- _data[offset + _cellAttributes] = style.attrs;- _data[offset + _cellContent] = 0;+ _store(index * _cellSize, style.foreground, style.background, style.attrs, 0);}void resetCell(int index) {_textVersion++;- final offset = index * _cellSize;- _data[offset + _cellForeground] = 0;- _data[offset + _cellBackground] = 0;- _data[offset + _cellAttributes] = 0;- _data[offset + _cellContent] = 0;+ _store(index * _cellSize, 0, 0, 0, 0);}/// Erase cells whose index satisfies [start] <= index < [end]. Erased cells@@ -170,6 +186,7 @@ class BufferLine with IndexedItem {style ??= CursorStyle.empty;+ if (count > 0) _paintVersion++;if (start + count < _length) {final moveStart = start * _cellSize;final moveEnd = (_length - count) * _cellSize;@@ -208,6 +225,7 @@ class BufferLine with IndexedItem {eraseCell(start - 1, style);}+ if (count > 0) _paintVersion++;if (start + count < _length) {final moveStart = start * _cellSize;final moveEnd = (_length - count) * _cellSize;@@ -258,6 +276,7 @@ class BufferLine with IndexedItem {}_textVersion++;+ _paintVersion++;_length = length;for (var i = 0; i < _anchors.length; i++) {@@ -300,6 +319,7 @@ class BufferLine with IndexedItem {/// line.void copyFrom(BufferLine src, int srcCol, int dstCol, int len) {_textVersion++;+ _paintVersion++;resize(dstCol + len);// data.setRange(diff --git a/desktop/third_party/xterm/lib/src/ui/line_picture_cache.dart b/desktop/third_party/xterm/lib/src/ui/line_picture_cache.dartnew file mode 100644index 000000000..209eca14a--- /dev/null+++ b/desktop/third_party/xterm/lib/src/ui/line_picture_cache.dart@@ -0,0 +1,76 @@+import 'dart:ui';++import 'package:xterm/src/core/buffer/line.dart';++/// Recorded drawings of buffer lines, reused for as long as a line's+/// [BufferLine.paintVersion] holds.+///+/// A frame used to draw every visible cell again, one paragraph per cell, even+/// when a single line had changed — and a blinking cursor repainted the whole+/// grid twice a second. Lines keep their identity while they scroll (see+/// `Buffer.scrollUp`/`index`), so a drawing keyed by the line object follows+/// it up the screen and only the lines that actually changed are recorded+/// again.+///+/// The cache holds only what the last frame drew: [endFrame] disposes every+/// drawing the frame did not use, so it never outgrows the viewport.+class LinePictureCache {+ final _entries = <BufferLine, _LinePicture>{};+ var _frame = 0;++ /// The number of lines with a drawing held.+ int get length => _entries.length;++ /// Starts a frame; every [lookup] or [store] until [endFrame] marks its line+ /// as still on screen.+ void beginFrame() => _frame++;++ /// The drawing of [line] if it is current and was recorded at [phase], or+ /// null when it must be recorded.+ Picture? lookup(BufferLine line, [Offset phase = Offset.zero]) {+ final entry = _entries[line];+ if (entry == null ||+ entry.version != line.paintVersion ||+ entry.phase != phase) {+ return null;+ }+ entry.frame = _frame;+ return entry.picture;+ }++ /// Holds [picture] as the drawing of [line] at its current version, recorded+ /// at [phase], replacing (and disposing) any older one.+ void store(BufferLine line, Picture picture, [Offset phase = Offset.zero]) {+ final old = _entries[line];+ if (old != null && !identical(old.picture, picture)) old.picture.dispose();+ _entries[line] = _LinePicture(picture, line.paintVersion, phase, _frame);+ }++ /// Disposes every drawing the current frame did not use: lines that scrolled+ /// out of view, were dropped from the buffer, or belong to the other buffer.+ void endFrame() {+ _entries.removeWhere((_, entry) {+ if (entry.frame == _frame) return false;+ entry.picture.dispose();+ return true;+ });+ }++ /// Disposes everything — the drawings no longer match what a line would draw+ /// (theme, font, text scale or pixel ratio changed), or nothing is drawn.+ void clear() {+ for (final entry in _entries.values) {+ entry.picture.dispose();+ }+ _entries.clear();+ }+}++class _LinePicture {+ _LinePicture(this.picture, this.version, this.phase, this.frame);++ final Picture picture;+ final int version;+ final Offset phase;+ int frame;+}diff --git a/desktop/third_party/xterm/lib/src/ui/painter.dart b/desktop/third_party/xterm/lib/src/ui/painter.dartindex 25cf2efd9..7adc94536 100644--- a/desktop/third_party/xterm/lib/src/ui/painter.dart+++ b/desktop/third_party/xterm/lib/src/ui/painter.dart@@ -1,7 +1,9 @@import 'dart:ui';import 'package:flutter/painting.dart';+import 'package:quiver/collection.dart';import 'package:xterm/src/ui/block_glyphs.dart';+import 'package:xterm/src/ui/line_picture_cache.dart';import 'package:xterm/src/ui/palette_builder.dart';import 'package:xterm/src/ui/paragraph_cache.dart';import 'package:xterm/xterm.dart';@@ -38,6 +40,11 @@ class TerminalPainter {/// [_textStyle] is changed, or when the system font changes.final _paragraphCache = ParagraphCache(10240);+ /// Recorded lines, reused while they are unchanged. Cleared with+ /// [_paragraphCache] and whenever anything else that shapes a drawing+ /// changes.+ final _lineCache = LinePictureCache();+TerminalStyle get textStyle => _textStyle;TerminalStyle _textStyle;set textStyle(TerminalStyle value) {@@ -45,6 +52,9 @@ class TerminalPainter {_textStyle = value;_cellSize = _measureCharSize();_paragraphCache.clear();+ _lineCache.clear();+ _runParagraphs.clear();+ _runAligned.clear();}TextScaler get textScaler => _textScaler;@@ -54,6 +64,9 @@ class TerminalPainter {_textScaler = value;_cellSize = _measureCharSize();_paragraphCache.clear();+ _lineCache.clear();+ _runParagraphs.clear();+ _runAligned.clear();}TerminalTheme get theme => _theme;@@ -63,6 +76,9 @@ class TerminalPainter {_theme = value;_colorPalette = PaletteBuilder(value).build();_paragraphCache.clear();+ _lineCache.clear();+ _runParagraphs.clear();+ _runAligned.clear();}/// Device pixels per logical pixel, used to snap block-glyph edges so that@@ -75,6 +91,7 @@ class TerminalPainter {set devicePixelRatio(double value) {if (value == _devicePixelRatio) return;_devicePixelRatio = value;+ _lineCache.clear();}Size _measureCharSize() {@@ -107,6 +124,9 @@ class TerminalPainter {void clearFontCache() {_cellSize = _measureCharSize();_paragraphCache.clear();+ _lineCache.clear();+ _runParagraphs.clear();+ _runAligned.clear();}/// Paints the cursor based on the current cursor type.@@ -161,28 +181,266 @@ class TerminalPainter {);}+ /// Starts a frame of [paintLineCached] calls.+ void beginFrame() => _lineCache.beginFrame();++ /// Ends a frame of [paintLineCached] calls, releasing the drawings of lines+ /// it did not paint.+ void endFrame() => _lineCache.endFrame();++ /// Releases every recorded line, for a renderer that stops drawing.+ void clearLineCache() => _lineCache.clear();++ /// The number of lines with a recorded drawing held.+ int get cachedLineCount => _lineCache.length;++ /// Paints [line] like [paintLine], replaying its recorded drawing when the+ /// line has not changed since it was recorded.+ ///+ /// Block glyphs snap their edges to device pixels where they are drawn, so a+ /// drawing is only valid at the fraction of a device pixel it was recorded+ /// at. The line is recorded at [offset]'s sub-pixel part (its phase) and+ /// replayed moved by the rest, a whole number of device pixels; a line that+ /// lands on another phase — only possible at a fractional pixel ratio — is+ /// recorded again.+ void paintLineCached(Canvas canvas, Offset offset, BufferLine line) {+ final phase = _devicePixelPhase(offset);+ var picture = _lineCache.lookup(line, phase);+ if (picture == null) {+ final recorder = PictureRecorder();+ paintLine(Canvas(recorder), phase, line);+ picture = recorder.endRecording();+ _lineCache.store(line, picture, phase);+ }+ canvas.save();+ canvas.translate(offset.dx - phase.dx, offset.dy - phase.dy);+ canvas.drawPicture(picture);+ canvas.restore();+ }++ /// The part of [offset] that is not a whole number of device pixels.+ Offset _devicePixelPhase(Offset offset) {+ double part(double logical) {+ final device = logical * _devicePixelRatio;+ return (device - device.floorToDouble()) / _devicePixelRatio;+ }++ return Offset(part(offset.dx), part(offset.dy));+ }+/// Paints [line] to [canvas] at [offset]. The x offset of [offset] is usually/// 0, and the y offset is the top of the line.+ ///+ /// Backgrounds first, then glyphs. Neighbouring cells that share a background+ /// colour are filled with one rectangle rather than one per cell — the same+ /// area [paintCellBackground] covers, including its one-pixel overlap to the+ /// right, in a fraction of the draw calls.void paintLine(Canvas canvas,Offset offset,BufferLine line,) {- final cellData = CellData.empty();+ final cellData = _lineCellData;final cellWidth = _cellSize.width;+ final length = line.length;++ Color? runColor;+ var runStart = 0;+ var runEnd = 0;+ void fillRun() {+ if (runColor == null) return;+ _backgroundPaint.color = runColor!;+ canvas.drawRect(+ Rect.fromLTRB(+ offset.dx + runStart * cellWidth,+ offset.dy,+ offset.dx + runEnd * cellWidth + 1,+ offset.dy + _cellSize.height,+ ),+ _backgroundPaint,+ );+ runColor = null;+ }++ for (var i = 0; i < length; i++) {+ line.getCellData(i, cellData);+ final span = cellData.content >> CellContent.widthShift == 2 ? 2 : 1;+ final color = cellBackgroundColor(cellData);+ if (color != runColor || i != runEnd) {+ fillRun();+ if (color != null) {+ runColor = color;+ runStart = i;+ }+ }+ runEnd = i + span;+ if (span == 2) i++;+ }+ fillRun();- for (var i = 0; i < line.length; i++) {+ var i = 0;+ while (i < length) {line.getCellData(i, cellData);+ final end = _asciiRunEnd(line, i, cellData);+ if (end - i >= 2) {+ _paintAsciiRun(canvas, offset.translate(i * cellWidth, 0), line, i, end,+ cellData);+ i = end;+ continue;+ }+ paintCellForeground(canvas, offset.translate(i * cellWidth, 0), cellData);+ i += cellData.content >> CellContent.widthShift == 2 ? 2 : 1;+ }+ }- final charWidth = cellData.content >> CellContent.widthShift;- final cellOffset = offset.translate(i * cellWidth, 0);+ /// How many ASCII runs have been painted as one paragraph — a count for+ /// tests to see where runs were cut. Debug builds only.+ int debugAsciiRunsPainted = 0;- paintCell(canvas, cellOffset, cellData);+ /// Laid-out runs of plain ASCII, keyed by their colours, flags and text.+ final _runParagraphs = LruMap<String, Paragraph>(maximumSize: 2048);- if (charWidth == 2) {- i++;- }+ /// Whether each weight/slant (bold | italic << 1) sets every printable ASCII+ /// character exactly one cell wide, so a run of them lands on the grid.+ final _runAligned = <int, bool>{};++ static bool _isAsciiRunCode(int content) {+ final code = content & CellContent.codepointMask;+ return code >= 0x20 &&+ code <= 0x7E &&+ content >> CellContent.widthShift == 1;+ }++ /// Where a run of plain ASCII that starts at [start] ends: the first cell that+ /// is not printable ASCII, or is styled differently. [start] itself (in+ /// [cellData]) not qualifying ends the run at once.+ int _asciiRunEnd(BufferLine line, int start, CellData cellData) {+ if (!_isAsciiRunCode(cellData.content)) return start;+ final flags = cellData.flags;+ if (!_runAlignedFor(flags)) return start;+ final foreground = cellData.foreground;+ final background = cellData.background;+ var end = start + 1;+ while (end < line.length &&+ _isAsciiRunCode(line.getContent(end)) &&+ line.getForeground(end) == foreground &&+ line.getBackground(end) == background &&+ line.getAttributes(end) == flags) {+ end++;+ }+ return end;+ }++ bool _runAlignedFor(int flags) {+ final bold = flags & CellFlags.bold != 0;+ final italic = flags & CellFlags.italic != 0;+ return _runAligned[(bold ? 1 : 0) | (italic ? 2 : 0)] ??=+ _measureRunAligned(bold, italic);+ }++ bool _measureRunAligned(bool bold, bool italic) {+ final text = String.fromCharCodes([for (var c = 0x20; c <= 0x7E; c++) c]);+ final style = _runTextStyle(null, bold: bold, italic: italic);+ final builder = ParagraphBuilder(style.getParagraphStyle())+ ..pushStyle(style.getTextStyle(textScaler: _textScaler))+ ..addText(text);+ final paragraph = builder.build()+ ..layout(const ParagraphConstraints(width: double.infinity));+ final advance = paragraph.maxIntrinsicWidth / text.length;+ paragraph.dispose();+ return (advance - _cellSize.width).abs() < 0.001;+ }++ /// The style of a glyph run: what [paintCellForeground] gives one cell, with+ /// ligatures, contextual alternates and kerning off — one cell at a time never+ /// had any of them, and each would move glyphs off the grid.+ TextStyle _runTextStyle(+ Color? color, {+ required bool bold,+ required bool italic,+ bool underline = false,+ }) {+ return _textStyle+ .toTextStyle(+ color: color,+ bold: bold,+ italic: italic,+ underline: underline,+ )+ .copyWith(fontFeatures: const [+ FontFeature.disable('liga'),+ FontFeature.disable('calt'),+ FontFeature.disable('kern'),+ ]);+ }++ /// Paints cells [start]..[end) of [line] — plain ASCII sharing one style, as+ /// found by [_asciiRunEnd] — as one paragraph instead of one per cell.+ void _paintAsciiRun(+ Canvas canvas,+ Offset offset,+ BufferLine line,+ int start,+ int end,+ CellData cellData,+ ) {+ final flags = cellData.flags;+ final underline = flags & CellFlags.underline != 0;+ final codes = <int>[];+ var visible = underline;+ for (var i = start; i < end; i++) {+ final code = line.getCodePoint(i);+ if (code != 0x20) visible = true;+ // The same workaround as [paintCellForeground]: Flutter underlines no+ // trailing space, but does a non-breaking one.+ codes.add(underline && code == 0x20 ? 0xA0 : code);+ }+ // Spaces with nothing under them draw nothing, one cell at a time or not.+ if (!visible) return;+ assert(() {+ debugAsciiRunsPainted++;+ return true;+ }());++ final text = String.fromCharCodes(codes);+ final key = '${cellData.foreground}|${cellData.background}|$flags|'+ '${_textScaler.hashCode}|$text';+ var paragraph = _runParagraphs[key];+ if (paragraph == null) {+ var color = flags & CellFlags.inverse == 0+ ? resolveForegroundColor(cellData.foreground)+ : resolveBackgroundColor(cellData.background);+ if (flags & CellFlags.faint != 0) color = color.withOpacity(0.5);+ final style = _runTextStyle(+ color,+ bold: flags & CellFlags.bold != 0,+ italic: flags & CellFlags.italic != 0,+ underline: underline,+ );+ final builder = ParagraphBuilder(style.getParagraphStyle())+ ..pushStyle(style.getTextStyle(textScaler: _textScaler))+ ..addText(text);+ paragraph = builder.build()+ ..layout(const ParagraphConstraints(width: double.infinity));+ _runParagraphs[key] = paragraph;+ }+ canvas.drawParagraph(paragraph, offset);+ }++ final _lineCellData = CellData.empty();+ final _backgroundPaint = Paint();++ /// The colour [paintCellBackground] fills [cellData] with, or null when it+ /// leaves the cell to the terminal's own background.+ @pragma('vm:prefer-inline')+ Color? cellBackgroundColor(CellData cellData) {+ if (cellData.flags & CellFlags.inverse != 0) {+ return resolveForegroundColor(cellData.foreground);+ }+ if (cellData.background & CellColor.typeMask == CellColor.normal) {+ return null;}+ return resolveBackgroundColor(cellData.background);}@pragma('vm:prefer-inline')diff --git a/desktop/third_party/xterm/lib/src/ui/render.dart b/desktop/third_party/xterm/lib/src/ui/render.dartindex 28e0d9d56..03553319d 100644--- a/desktop/third_party/xterm/lib/src/ui/render.dart+++ b/desktop/third_party/xterm/lib/src/ui/render.dart@@ -118,6 +118,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {if (!value) {_outputRepaintTimer?.cancel();_outputRepaintTimer = null;+ // A hidden tile draws nothing, so it holds no recorded lines either.+ _painter.clearLineCache();}if (attached) {if (value) {@@ -282,6 +284,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {void detach() {_outputRepaintTimer?.cancel();_outputRepaintTimer = null;+ _painter.clearLineCache();super.detach();_offset.removeListener(_onScroll);_terminal.removeListener(_onTerminalChange);@@ -577,13 +580,17 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {final effectFirstLine = firstLine.clamp(0, lines.length - 1);final effectLastLine = lastLine.clamp(0, lines.length - 1);+ // Unchanged lines replay their recorded drawing; only lines written since+ // the last frame are drawn cell by cell (see LinePictureCache).+ _painter.beginFrame();for (var i = effectFirstLine; i <= effectLastLine; i++) {- _painter.paintLine(+ _painter.paintLineCached(canvas,offset.translate(0, (i * charHeight + _lineOffset).truncateToDouble()),lines[i],);}+ _painter.endFrame();if (_terminal.buffer.absoluteCursorY >= effectFirstLine &&_terminal.buffer.absoluteCursorY <= effectLastLine) {