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
feat(mobile): smoother terminal scroll
tony6191163aa8d4
diff --git a/mobile/lib/terminal/keyframe_write.dart b/mobile/lib/terminal/keyframe_write.dartnew file mode 100644index 000000000..5c2ca11e8--- /dev/null+++ b/mobile/lib/terminal/keyframe_write.dart@@ -0,0 +1,42 @@+import 'package:xterm/xterm.dart';++/// How much of a keyframe is parsed before the frame is handed back — see+/// [writeKeyframeInSlices]. A keyframe no longer than this is written in one go, at once.+const keyframeSliceChars = 16 * 1024;++/// Writes a keyframe's [text] into its [replacement] emulator, [keyframeSliceChars] at a time,+/// handing the frame back between slices. False when [stillWanted] says the stream moved on+/// meanwhile, and the rest is not written.+///+/// ⚠️ **One write froze the screen for the length of the parse.** A keyframe is the whole screen+/// and 500 lines of history (`SNAPSHOT_HISTORY_LINES` in the CLI's `tmuxStream.ts`) — tens of+/// kilobytes of styled cells, every row padded to its full width — and one arrives on every open,+/// every resize (so every keyboard raised or lowered) and every resync. Parsed in one go it held the+/// UI thread for as long as the parse took: a scroll or a swipe in progress stopped dead, then+/// jumped. Sliced, the frames keep coming while it parses.+///+/// Nothing half-parsed is ever shown: the emulator on screen is untouched until the caller swaps+/// [replacement] in, and output that arrives meanwhile waits its turn behind it on the session's+/// render queue (`TerminalSession.handleBinary`).+///+/// A slice never ends between the halves of a surrogate pair — the parser reads each write as its+/// own run of code points. A slice that ends inside an escape sequence is fine: the parser holds+/// the unfinished sequence for the next write, as it does for any packet.+Future<bool> writeKeyframeInSlices(+ Terminal replacement,+ String text, {+ required bool Function() stillWanted,+}) async {+ var start = 0;+ while (text.length - start > keyframeSliceChars) {+ var end = start + keyframeSliceChars;+ final last = text.codeUnitAt(end - 1);+ if (last >= 0xD800 && last <= 0xDBFF) end--;+ replacement.write(text.substring(start, end));+ start = end;+ await Future<void>.delayed(Duration.zero);+ if (!stillWanted()) return false;+ }+ replacement.write(start == 0 ? text : text.substring(start));+ return true;+}diff --git a/mobile/lib/terminal/remote_scroll_physics.dart b/mobile/lib/terminal/remote_scroll_physics.dartnew file mode 100644index 000000000..cab12db76--- /dev/null+++ b/mobile/lib/terminal/remote_scroll_physics.dart@@ -0,0 +1,55 @@+import 'dart:math' as math;++import 'package:flutter/physics.dart';+import 'package:flutter/widgets.dart';++/// The scroll physics of a full-screen program's scroll — the alternate screen, where the phone has+/// no history of its own and a scroll is wheel events sent to the machine (`TerminalView`'s+/// `altBufferScrollPhysics`). A drag is the platform's own; a fling is short.+///+/// ⚠️ **A fling here coasted for seconds, sending the program a wheel for every line it passed.**+/// That scrollable has no ends — its extents are infinite — so a platform fling never meets a+/// boundary and runs until friction alone stops it. Measured on Claude Code (2026-10-02): a flick of a tenth of a second coasted 2–5 s and sent 150–450 wheels, 97% of+/// them after the finger had lifted; the program, a few hundred milliseconds behind, kept redrawing+/// a screen that jumped for seconds after the person had stopped.+///+/// Here the fling decays at [decayPerSecond] from a speed held to [maxVelocity]: at most+/// `maxVelocity / decayPerSecond` pixels, nearly all of it in the first quarter second. While the+/// finger is down nothing changes — each line dragged is still one wheel.+///+/// Only where the extents are infinite. Anywhere else — reused on a scrollable with ends — it+/// defers to the platform, so a bounded scroll keeps its own fling and its overscroll.+class RemoteScrollPhysics extends ScrollPhysics {+ const RemoteScrollPhysics({super.parent});++ /// How fast the fling's speed falls away: it keeps `e^-decayPerSecond` of its speed after a+ /// second, which at 10 is gone in effect within a quarter of one.+ static const decayPerSecond = 10.0;++ /// The fastest a fling starts, in logical pixels a second — with [decayPerSecond], a fling that+ /// carries at most 300 px: some twenty lines of wheels, however hard the flick.+ static const maxVelocity = 3000.0;++ @override+ RemoteScrollPhysics applyTo(ScrollPhysics? ancestor) =>+ RemoteScrollPhysics(parent: buildParent(ancestor));++ @override+ Simulation? createBallisticSimulation(+ ScrollMetrics position,+ double velocity,+ ) {+ if (position.minScrollExtent.isFinite ||+ position.maxScrollExtent.isFinite) {+ return super.createBallisticSimulation(position, velocity);+ }+ final tolerance = toleranceFor(position);+ if (velocity.abs() < tolerance.velocity) return null;+ return FrictionSimulation(+ math.exp(-decayPerSecond),+ position.pixels,+ velocity.clamp(-maxVelocity, maxVelocity).toDouble(),+ tolerance: tolerance,+ );+ }+}diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dartindex a863feed6..6b2e6446a 100644--- a/mobile/lib/terminal/terminal_session.dart+++ b/mobile/lib/terminal/terminal_session.dart@@ -8,6 +8,7 @@ import 'package:xterm/xterm.dart';import '../core/crash_log.dart';import 'control_chord.dart';+import 'keyframe_write.dart';import 'screen_snapshot.dart';import 'terminal_binary.dart';import 'terminal_input.dart';@@ -930,47 +931,7 @@ class TerminalSession extends ChangeNotifier {return;}if (frame.kind == TerminalBinaryKind.keyframe) {- final nextCols = frame.cols;- final nextRows = frame.rows;- if (nextCols == null || nextRows == null) {- await _requestResync('TERMINAL_KEYFRAME_INVALID');- return;- }- // Publish a complete screen atomically. A damaged snapshot must- // leave the retained screen available while resync recovers.- final decoded = decodeUtf8Chunk(_prepareKeyframeBytes(bytes));- final replacement = _newTerminal(bindCallbacks: false)- ..resize(_clampCols(nextCols), _clampRows(nextRows))- ..write(decoded.text);- _bindTerminal(replacement);- terminal = replacement;- _showingKeptScreen = false;- cols = _clampCols(nextCols);- rows = _clampRows(nextRows);- _utf8Tail = decoded.tail;- _remoteCursorVisible = terminal.cursorVisibleMode;- _cursorBlinkPhaseVisible = true;- _expectedSeq = frame.seq + 1;- _lastRenderedSeq = frame.seq;- _resyncRequested = false;- _resyncAttempts = 0;- _autoReopenAttempts = 0;- errorCode = null;- errorMessage = null;- takenOverBy = null;- _resyncTimer?.cancel();- _resyncTimer = null;- status = TerminalSessionStatus.controlling;- _markForAck(bytes.length);- notifyListeners();- final measured = _measuredViewport;- if (measured != null) {- _pendingCols = measured.cols;- _pendingRows = measured.rows;- }- if (_pendingCols != null && _pendingRows != null) {- unawaited(_flushResize());- }+ await _applyKeyframe(frame, bytes, generation);return;}if (frame.kind == TerminalBinaryKind.sync) {@@ -1118,6 +1079,66 @@ class TerminalSession extends ChangeNotifier {return true;}+ /// A keyframe: the stream's whole screen and its history, which replaces the emulator outright.+ /// Published whole and at once — see [writeKeyframeInSlices] for how a large one is parsed.+ Future<void> _applyKeyframe(+ TerminalBinaryFrame frame,+ Uint8List bytes,+ int generation,+ ) async {+ final nextCols = frame.cols;+ final nextRows = frame.rows;+ if (nextCols == null || nextRows == null) {+ await _requestResync('TERMINAL_KEYFRAME_INVALID');+ return;+ }+ // Publish a complete screen atomically. A damaged snapshot must+ // leave the retained screen available while resync recovers.+ final decoded = decodeUtf8Chunk(_prepareKeyframeBytes(bytes));+ final replacement = _newTerminal(bindCallbacks: false)+ ..resize(_clampCols(nextCols), _clampRows(nextRows));+ if (decoded.text.length <= keyframeSliceChars) {+ replacement.write(decoded.text);+ } else if (!await writeKeyframeInSlices(+ replacement,+ decoded.text,+ stillWanted: () => _isCurrent(generation) && frame.streamId == streamId,+ )) {+ // Closed, reopened or taken over while it parsed: whoever moved+ // the stream on owns what is shown now, and this screen is dropped.+ return;+ }+ _bindTerminal(replacement);+ terminal = replacement;+ _showingKeptScreen = false;+ cols = _clampCols(nextCols);+ rows = _clampRows(nextRows);+ _utf8Tail = decoded.tail;+ _remoteCursorVisible = terminal.cursorVisibleMode;+ _cursorBlinkPhaseVisible = true;+ _expectedSeq = frame.seq + 1;+ _lastRenderedSeq = frame.seq;+ _resyncRequested = false;+ _resyncAttempts = 0;+ _autoReopenAttempts = 0;+ errorCode = null;+ errorMessage = null;+ takenOverBy = null;+ _resyncTimer?.cancel();+ _resyncTimer = null;+ status = TerminalSessionStatus.controlling;+ _markForAck(bytes.length);+ notifyListeners();+ final measured = _measuredViewport;+ if (measured != null) {+ _pendingCols = measured.cols;+ _pendingRows = measured.rows;+ }+ if (_pendingCols != null && _pendingRows != null) {+ unawaited(_flushResize());+ }+ }+List<int> _prepareKeyframeBytes(Uint8List bytes) {if (engineId != 'grok') return bytes;diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dartindex 4ea7399f4..05756b75d 100644--- a/mobile/lib/widgets/terminal_panel.dart+++ b/mobile/lib/widgets/terminal_panel.dart@@ -17,6 +17,7 @@ import '../terminal/terminal_binary.dart';import '../terminal/terminal_font_store.dart';import '../terminal/terminal_link_opener.dart';import '../terminal/remote_media_download.dart';+import '../terminal/remote_scroll_physics.dart';import '../terminal/terminal_links.dart';import '../terminal/terminal_prompt_zone.dart';import '../phone/tty.dart';@@ -1284,6 +1285,7 @@ class _TerminalPanelState extends State<TerminalPanel>onAltBufferScroll: session.scrollViaTmuxCopyMode? (up) => session.sendScrollCommand(up, 1): null,+ altBufferScrollPhysics: const RemoteScrollPhysics(),),),),diff --git a/mobile/third_party/xterm/README.autonomous.md b/mobile/third_party/xterm/README.autonomous.mdindex 0c3ed58b7..0ec5dccfd 100644--- a/mobile/third_party/xterm/README.autonomous.md+++ b/mobile/third_party/xterm/README.autonomous.md@@ -229,3 +229,30 @@ it if one is dropped.without the keyboard seeing them; left holding the old words, the keyboardwould edit them again — Telex re-marks the word it believes is being typedand would rub out characters the prompt no longer holds.++17. **A scroll replays lines instead of drawing them** (`lib/src/ui/painter.dart`,+ `lib/src/ui/line_picture_cache.dart`, `lib/src/ui/glyph_run.dart`,+ `lib/src/ui/render.dart`, `lib/src/core/buffer/line.dart`). A scroll moves+ every line on screen each frame and changes none, yet every frame drew each+ one again cell by cell. `TerminalPainter.paintLineCached` records a line+ once into a `Picture` (`LinePictureCache`) and replays it while+ `BufferLine.paintVersion` — a new counter, bumped by every mutation of the+ line, colour included — is unchanged; at most 256 lines are kept, least+ recently drawn out first, and all of them go when the font, scale, theme or+ emulator changes. `paintLine` itself now fills a run of same-coloured cells+ with one rectangle, and draws a run of printable ASCII in one style as one+ paragraph (`GlyphRun`; ligatures, contextual alternates and kerning off, so+ each character stays on its cell); wide, non-ASCII and underlined cells+ keep a paragraph each.+ A line's top is snapped to the device's pixel grid rather than truncated to+ whole logical pixels, which moved a slow scroll in three-pixel steps on a+ 3× phone.++18. **The alternate buffer's scroll takes the embedder's physics**+ (`lib/src/terminal_view.dart`, `lib/src/ui/scroll_handler.dart`,+ `lib/src/ui/infinite_scroll_view.dart`). `TerminalView.altBufferScrollPhysics`+ reaches the `Scrollable` that turns a drag into wheel events, layered over+ the platform's physics. Its extents are infinite, so a platform fling there+ never meets an end and coasted for seconds, a wheel event per line; the+ phone passes a short fling (`mobile/lib/terminal/remote_scroll_physics.dart`).+ Null keeps the platform's physics, as upstream.diff --git a/mobile/third_party/xterm/lib/src/core/buffer/line.dart b/mobile/third_party/xterm/lib/src/core/buffer/line.dartindex 7ea477ad4..7b0b06082 100644--- a/mobile/third_party/xterm/lib/src/core/buffer/line.dart+++ b/mobile/third_party/xterm/lib/src/core/buffer/line.dart@@ -38,6 +38,18 @@ class BufferLine with IndexedItem {int get textVersion => _textVersion;int _textVersion = 0;+ /// AUTONOMOUS PATCH: what a painter's recording of this line is checked against+ /// (`TerminalPainter.paintLineCached`). Bumped by every change to what the line+ /// draws — text, colours, attributes, length — where [textVersion] skips colour.+ int get paintVersion => _paintVersion;+ int _paintVersion = 0;++ /// The text changed, and with it what the line draws.+ void _textChanged() {+ _textVersion++;+ _paintVersion++;+ }+final _anchors = <CellAnchor>[];List<CellAnchor> get anchors => _anchors;@@ -75,7 +87,7 @@ class BufferLine with IndexedItem {}CellData createCellData(int index) {- _textVersion++;+ _textChanged();final cellData = CellData.empty();final offset = index * _cellSize;_data[offset + _cellForeground] = cellData.foreground;@@ -86,19 +98,22 @@ class BufferLine with IndexedItem {}void setForeground(int index, int value) {+ _paintVersion++;_data[index * _cellSize + _cellForeground] = value;}void setBackground(int index, int value) {+ _paintVersion++;_data[index * _cellSize + _cellBackground] = value;}void setAttributes(int index, int value) {+ _paintVersion++;_data[index * _cellSize + _cellAttributes] = value;}void setContent(int index, int value) {- _textVersion++;+ _textChanged();_data[index * _cellSize + _cellContent] = value;}@@ -108,7 +123,7 @@ class BufferLine with IndexedItem {}void setCell(int index, int char, int witdh, CursorStyle style) {- _textVersion++;+ _textChanged();final offset = index * _cellSize;_data[offset + _cellForeground] = style.foreground;_data[offset + _cellBackground] = style.background;@@ -117,7 +132,7 @@ class BufferLine with IndexedItem {}void setCellData(int index, CellData cellData) {- _textVersion++;+ _textChanged();final offset = index * _cellSize;_data[offset + _cellForeground] = cellData.foreground;_data[offset + _cellBackground] = cellData.background;@@ -126,7 +141,7 @@ class BufferLine with IndexedItem {}void eraseCell(int index, CursorStyle style) {- _textVersion++;+ _textChanged();final offset = index * _cellSize;_data[offset + _cellForeground] = style.foreground;_data[offset + _cellBackground] = style.background;@@ -135,7 +150,7 @@ class BufferLine with IndexedItem {}void resetCell(int index) {- _textVersion++;+ _textChanged();final offset = index * _cellSize;_data[offset + _cellForeground] = 0;_data[offset + _cellBackground] = 0;@@ -169,6 +184,7 @@ class BufferLine with IndexedItem {assert(count >= 0 && start + count <= _length);style ??= CursorStyle.empty;+ _paintVersion++;if (start + count < _length) {final moveStart = start * _cellSize;@@ -203,6 +219,7 @@ class BufferLine with IndexedItem {/// Inserts [count] cells at [start]. New cells are initialized with [style].void insertCells(int start, int count, [CursorStyle? style]) {style ??= CursorStyle.empty;+ _paintVersion++;if (start > 0 && getWidth(start - 1) == 2) {eraseCell(start - 1, style);@@ -257,7 +274,7 @@ class BufferLine with IndexedItem {}}- _textVersion++;+ _textChanged();_length = length;for (var i = 0; i < _anchors.length; i++) {@@ -299,7 +316,7 @@ class BufferLine with IndexedItem {/// Copies [len] cells from [src] starting at [srcCol] to [dstCol] at this/// line.void copyFrom(BufferLine src, int srcCol, int dstCol, int len) {- _textVersion++;+ _textChanged();resize(dstCol + len);// data.setRange(diff --git a/mobile/third_party/xterm/lib/src/terminal_view.dart b/mobile/third_party/xterm/lib/src/terminal_view.dartindex 20b7125c0..2a7370580 100644--- a/mobile/third_party/xterm/lib/src/terminal_view.dart+++ b/mobile/third_party/xterm/lib/src/terminal_view.dart@@ -56,6 +56,7 @@ class TerminalView extends StatefulWidget {this.hardwareKeyboardOnly = false,this.simulateScroll = true,this.onAltBufferScroll,+ this.altBufferScrollPhysics,});/// The underlying terminal that this widget renders.@@ -179,6 +180,11 @@ class TerminalView extends StatefulWidget {/// backend-native way to scroll instead of the emulator's own mouse/key simulation.final void Function(bool up)? onAltBufferScroll;+ /// AUTONOMOUS PATCH: the physics of the alternate buffer's scroll — the one+ /// that turns a drag into wheel events for the program — layered over the+ /// platform's own. Null keeps the platform's.+ final ScrollPhysics? altBufferScrollPhysics;+@overrideState<TerminalView> createState() => TerminalViewState();}@@ -303,6 +309,7 @@ class TerminalViewState extends State<TerminalView> {terminal: widget.terminal,simulateScroll: widget.simulateScroll,onAltBufferScroll: widget.onAltBufferScroll,+ physics: widget.altBufferScrollPhysics,getCellOffset: (offset) => renderTerminal.getCellOffset(offset),getLineHeight: () => renderTerminal.lineHeight,child: child,@@ -745,6 +752,7 @@ class _TerminalView extends LeafRenderObjectWidget {onEditableRect: onEditableRect,composingText: composingText,composingBacktrackCells: composingBacktrackCells,+ devicePixelRatio: MediaQuery.maybeDevicePixelRatioOf(context) ?? 1.0,);}@@ -767,6 +775,7 @@ class _TerminalView extends LeafRenderObjectWidget {..alwaysShowCursor = alwaysShowCursor..onEditableRect = onEditableRect..composingText = composingText- ..composingBacktrackCells = composingBacktrackCells;+ ..composingBacktrackCells = composingBacktrackCells+ ..devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context) ?? 1.0;}}diff --git a/mobile/third_party/xterm/lib/src/ui/glyph_run.dart b/mobile/third_party/xterm/lib/src/ui/glyph_run.dartnew file mode 100644index 000000000..64a868a99--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/glyph_run.dart@@ -0,0 +1,88 @@+import 'package:xterm/src/core/buffer/cell_flags.dart';+import 'package:xterm/src/core/cell.dart';++/// AUTONOMOUS PATCH: a run of cells `TerminalPainter.paintLine` lays out and+/// draws as ONE paragraph — printable ASCII in one style, and the blanks+/// between — where every cell used to be a paragraph of its own.+///+/// ⚠️ **ASCII only, and that is what keeps a run on the grid.** In a monospace+/// face every ASCII glyph advances by exactly the width the cell is measured+/// from (`'m'`, `TerminalPainter._measureCharSize`), so the n-th character of a+/// run lands on the n-th cell. A character from a fallback font, an emoji or a+/// CJK glyph advances by its own width, and in a run would push the rest of the+/// line off the grid — so those are drawn a cell at a time, as before.+///+/// Blanks never end a run: a space has no ink whatever its colour (its fill is+/// the background pass's), so it rides along as a space. Underlined cells are+/// never part of one — an underline is ink, and a run's own would stop short of+/// a trailing space.+class GlyphRun {+ final _text = StringBuffer();++ /// The run's first cell; -1 while no run is open.+ int start = -1;++ /// One past the last cell with ink. Blanks after it are not drawn.+ int _inkEnd = -1;++ /// The first cell's content, and the style every character in the run shares.+ int content = 0;+ int foreground = 0;+ int background = 0;+ int flags = 0;++ bool get isOpen => start >= 0;++ /// Cells from the first character to the last, the blanks between included.+ int get length => _inkEnd - start;++ /// What is drawn: one character per cell, from the first to the last ink.+ String get text => _text.toString().substring(0, length);++ /// Whether [cell] can be in a run at all: printable ASCII or blank, and not+ /// underlined. Only such a cell is handed to [add] or [open].+ static bool takes(CellData cell) {+ if (cell.flags & CellFlags.underline != 0) return false;+ final code = cell.content & CellContent.codepointMask;+ return code == 0 || (code >= 0x20 && code < 0x7F);+ }++ /// Adds [cell], at [index], when it fits: a blank fits any run (and opens+ /// none), a character fits the open run when it shares its style. False when+ /// it does not — a character in another style, or no run open — and the+ /// caller draws what is open and [open]s a new run with it.+ bool add(int index, CellData cell) {+ final code = cell.content & CellContent.codepointMask;+ if (code == 0 || code == 0x20) {+ if (isOpen) _text.writeCharCode(0x20);+ return true;+ }+ if (!isOpen ||+ cell.foreground != foreground ||+ cell.background != background ||+ cell.flags != flags) {+ return false;+ }+ _text.writeCharCode(code);+ _inkEnd = index + 1;+ return true;+ }++ /// Starts a new run with the character [cell], at [index].+ void open(int index, CellData cell) {+ close();+ start = index;+ _inkEnd = index + 1;+ content = cell.content;+ foreground = cell.foreground;+ background = cell.background;+ flags = cell.flags;+ _text.writeCharCode(cell.content & CellContent.codepointMask);+ }++ void close() {+ _text.clear();+ start = -1;+ _inkEnd = -1;+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/infinite_scroll_view.dart b/mobile/third_party/xterm/lib/src/ui/infinite_scroll_view.dartindex 7561fcccd..1d755620e 100644--- a/mobile/third_party/xterm/lib/src/ui/infinite_scroll_view.dart+++ b/mobile/third_party/xterm/lib/src/ui/infinite_scroll_view.dart@@ -12,16 +12,22 @@ class InfiniteScrollView extends StatelessWidget {const InfiniteScrollView({super.key,required this.onScroll,+ this.physics,required this.child,});final ScrollCallback onScroll;+ /// AUTONOMOUS PATCH: layered over the platform's physics by the [Scrollable];+ /// null keeps the platform's.+ final ScrollPhysics? physics;+final Widget child;@overrideWidget build(BuildContext context) {return Scrollable(+ physics: physics,viewportBuilder: (context, position) {return _InfiniteScrollView(position: position,diff --git a/mobile/third_party/xterm/lib/src/ui/line_picture_cache.dart b/mobile/third_party/xterm/lib/src/ui/line_picture_cache.dartnew file mode 100644index 000000000..e6b6423bc--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/line_picture_cache.dart@@ -0,0 +1,67 @@+import 'dart:collection';+import 'dart:ui';++import 'package:xterm/src/core/buffer/line.dart';++/// Draws [line] with its top-left at [offset] — `TerminalPainter.paintLine`.+typedef LinePaint = void Function(+ Canvas canvas, Offset offset, BufferLine line);++/// AUTONOMOUS PATCH: each line's drawing, recorded once and replayed while the+/// line is unchanged ([BufferLine.paintVersion]).+///+/// ⚠️ **This is what makes a scroll cheap.** A scroll moves every line on+/// screen each frame and changes none of them, yet every frame drew each one+/// again cell by cell — a hash, a cache lookup and a `drawParagraph` for every+/// character on screen, some two thousand a frame on a phone. Now a frame+/// replays one picture per line, and only a line that changed is drawn again.+class LinePictureCache {+ LinePictureCache(this._paint, {this.capacity = 256});++ final LinePaint _paint;++ /// A few screens' worth: what a scroll back and forth passes over again. Each+ /// entry is a short display list, not pixels.+ final int capacity;++ /// Least recently drawn first.+ final _pictures = LinkedHashMap<BufferLine, _LinePicture>.identity();++ /// Draws [line] with its top-left at [offset]: its recording while that still+ /// shows the line, else a fresh one.+ void draw(Canvas canvas, Offset offset, BufferLine line) {+ var entry = _pictures.remove(line);+ if (entry == null || entry.version != line.paintVersion) {+ entry?.picture.dispose();+ final recorder = PictureRecorder();+ _paint(Canvas(recorder), Offset.zero, line);+ entry = _LinePicture(recorder.endRecording(), line.paintVersion);+ }+ // Re-inserted, so the map stays least recently drawn first.+ _pictures[line] = entry;+ if (_pictures.length > capacity) {+ _pictures.remove(_pictures.keys.first)!.picture.dispose();+ }+ canvas.save();+ canvas.translate(offset.dx, offset.dy);+ canvas.drawPicture(entry.picture);+ canvas.restore();+ }++ /// Drops every recording — the font, the scale or the colours changed, or the+ /// lines belong to an emulator that is gone.+ void clear() {+ for (final entry in _pictures.values) {+ entry.picture.dispose();+ }+ _pictures.clear();+ }+}++/// One line's recorded drawing, and the [BufferLine.paintVersion] it shows.+class _LinePicture {+ _LinePicture(this.picture, this.version);++ final Picture picture;+ final int version;+}diff --git a/mobile/third_party/xterm/lib/src/ui/painter.dart b/mobile/third_party/xterm/lib/src/ui/painter.dartindex f93550569..aad581208 100644--- a/mobile/third_party/xterm/lib/src/ui/painter.dart+++ b/mobile/third_party/xterm/lib/src/ui/painter.dart@@ -1,6 +1,8 @@import 'dart:ui';import 'package:flutter/painting.dart';+import 'package:xterm/src/ui/glyph_run.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';@@ -37,6 +39,14 @@ class TerminalPainter {/// [_textStyle] is changed, or when the system font changes.final _paragraphCache = ParagraphCache(10240);+ /// AUTONOMOUS PATCH: each line's drawing, replayed while the line is+ /// unchanged — see [paintLineCached].+ late final _linePictures = LinePictureCache(paintLine);++ /// Reused by every line drawn: painting is synchronous and never re-entrant.+ final _cell = CellData.empty();+ final _run = GlyphRun();+TerminalStyle get textStyle => _textStyle;TerminalStyle _textStyle;set textStyle(TerminalStyle value) {@@ -44,6 +54,7 @@ class TerminalPainter {_textStyle = value;_cellSize = _measureCharSize();_paragraphCache.clear();+ clearLinePictures();}TextScaler get textScaler => _textScaler;@@ -53,6 +64,7 @@ class TerminalPainter {_textScaler = value;_cellSize = _measureCharSize();_paragraphCache.clear();+ clearLinePictures();}TerminalTheme get theme => _theme;@@ -62,6 +74,7 @@ class TerminalPainter {_theme = value;_colorPalette = PaletteBuilder(value).build();_paragraphCache.clear();+ clearLinePictures();}Size _measureCharSize() {@@ -94,8 +107,13 @@ class TerminalPainter {void clearFontCache() {_cellSize = _measureCharSize();_paragraphCache.clear();+ clearLinePictures();}+ /// Drops every recorded line — the font, the scale or the colours changed, or+ /// the lines themselves belong to an emulator that is gone.+ void clearLinePictures() => _linePictures.clear();+/// Paints the cursor based on the current cursor type.void paintCursor(Canvas canvas,@@ -148,30 +166,152 @@ class TerminalPainter {);}+ /// AUTONOMOUS PATCH: [paintLine], replayed from the line's last recording while+ /// it has not changed since — see [LinePictureCache].+ void paintLineCached(Canvas canvas, Offset offset, BufferLine line) =>+ _linePictures.draw(canvas, offset, line);+/// Paints [line] to [canvas] at [offset]. The x offset of [offset] is usually/// 0, and the y offset is the top of the line.+ ///+ /// AUTONOMOUS PATCH: the fills first, then the characters — each in runs+ /// rather than a cell at a time. See [_paintBackground] and [_paintForeground].void paintLine(Canvas canvas,Offset offset,BufferLine line,) {- final cellData = CellData.empty();- final cellWidth = _cellSize.width;+ _paintBackground(canvas, offset, line);+ _paintForeground(canvas, offset, line);+ }- for (var i = 0; i < line.length; i++) {- line.getCellData(i, cellData);+ /// The line's fills: one rectangle per run of cells that share a colour,+ /// where it was one per cell — a highlighted prompt row is one, not eighty.+ void _paintBackground(Canvas canvas, Offset offset, BufferLine line) {+ final cell = _cell;+ Color? color;+ var start = 0;+ var index = 0;+ while (index < line.length) {+ line.getCellData(index, cell);+ final next = _backgroundColorOf(cell);+ if (next != color) {+ _fillCells(canvas, offset, start, index, color);+ color = next;+ start = index;+ }+ // A wide character's fill covers its second cell too, whatever that holds.+ index += cell.content >> CellContent.widthShift == 2 ? 2 : 1;+ }+ _fillCells(canvas, offset, start, index, color);+ }- final charWidth = cellData.content >> CellContent.widthShift;- final cellOffset = offset.translate(i * cellWidth, 0);+ /// Cells [start] to [end] filled with [color]; nothing for the default ground.+ void _fillCells(+ Canvas canvas,+ Offset offset,+ int start,+ int end,+ Color? color,+ ) {+ if (color == null || end <= start) return;+ canvas.drawRect(+ Rect.fromLTWH(+ offset.dx + start * _cellSize.width,+ offset.dy,+ // One pixel past the run, as each cell's own fill was: no hairline+ // between it and whatever is drawn next to it.+ (end - start) * _cellSize.width + 1,+ _cellSize.height,+ ),+ Paint()..color = color,+ );+ }- paintCell(canvas, cellOffset, cellData);+ /// The fill [cellData] calls for, or null for the default ground — which is+ /// left to the render object's own clear (see [paintCellBackground]).+ Color? _backgroundColorOf(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);+ }- if (charWidth == 2) {- i++;+ /// The line's characters: a run of printable ASCII in one style as ONE+ /// paragraph ([GlyphRun]), anything else — a wide or non-ASCII character, an+ /// underlined cell — a cell at a time, as before.+ void _paintForeground(Canvas canvas, Offset offset, BufferLine line) {+ final cell = _cell;+ final run = _run..close();+ for (var i = 0; i < line.length; i++) {+ line.getCellData(i, cell);+ if (GlyphRun.takes(cell)) {+ if (!run.add(i, cell)) {+ _paintRun(canvas, offset, run);+ run.open(i, cell);+ }+ continue;}+ _paintRun(canvas, offset, run);+ paintCellForeground(+ canvas, offset.translate(i * _cellSize.width, 0), cell);+ if (cell.content >> CellContent.widthShift == 2) i++;+ }+ _paintRun(canvas, offset, run);+ }++ /// Draws [run], when one is open, and closes it.+ void _paintRun(Canvas canvas, Offset offset, GlyphRun run) {+ if (!run.isOpen) return;+ final at = offset.translate(run.start * _cellSize.width, 0);+ if (run.length == 1) {+ // A lone character: the single-cell paragraph, cached across lines.+ paintCellForeground(+ canvas,+ at,+ CellData(+ foreground: run.foreground,+ background: run.background,+ flags: run.flags,+ content: run.content,+ ),+ );+ } else {+ final paragraph = _layoutRun(run);+ canvas.drawParagraph(paragraph, at);+ // The recording holds what it drew; the paragraph itself is not kept.+ paragraph.dispose();}+ run.close();}+ /// [run]'s characters laid out as one paragraph, in its style.+ Paragraph _layoutRun(GlyphRun run) {+ final style = _textStyle+ .toTextStyle(+ color: _foregroundColorOf(run.foreground, run.background, run.flags),+ bold: run.flags & CellFlags.bold != 0,+ italic: run.flags & CellFlags.italic != 0,+ )+ .copyWith(fontFeatures: _gridFeatures);+ final builder = ParagraphBuilder(style.getParagraphStyle());+ builder.pushStyle(style.getTextStyle(textScaler: _textScaler));+ builder.addText(run.text);+ return builder.build()+ ..layout(ParagraphConstraints(width: double.infinity));+ }++ /// No ligatures, contextual alternates or kerning in a run: each would move+ /// or merge glyphs that a terminal draws one per cell.+ static const _gridFeatures = [+ FontFeature.disable('liga'),+ FontFeature.disable('calt'),+ FontFeature.disable('kern'),+ ];+@pragma('vm:prefer-inline')void paintCell(Canvas canvas, Offset offset, CellData cellData) {paintCellBackground(canvas, offset, cellData);@@ -196,16 +336,12 @@ class TerminalPainter {if (paragraph == null) {final cellFlags = cellData.flags;- var color = cellFlags & CellFlags.inverse == 0- ? resolveForegroundColor(cellData.foreground)- : resolveBackgroundColor(cellData.background);-- if (cellData.flags & CellFlags.faint != 0) {- color = color.withOpacity(0.5);- }-final style = _textStyle.toTextStyle(- color: color,+ color: _foregroundColorOf(+ cellData.foreground,+ cellData.background,+ cellFlags,+ ),bold: cellFlags & CellFlags.bold != 0,italic: cellFlags & CellFlags.italic != 0,underline: cellFlags & CellFlags.underline != 0,@@ -255,6 +391,15 @@ class TerminalPainter {canvas.drawRect(offset & size, paint);}+ /// The colour a cell's character is drawn in: its foreground, or its+ /// background when inverse, at half strength when faint.+ Color _foregroundColorOf(int foreground, int background, int flags) {+ final color = flags & CellFlags.inverse == 0+ ? resolveForegroundColor(foreground)+ : resolveBackgroundColor(background);+ return flags & CellFlags.faint != 0 ? color.withOpacity(0.5) : color;+ }+/// Get the effective foreground color for a cell from information encoded in/// [cellColor].@pragma('vm:prefer-inline')diff --git a/mobile/third_party/xterm/lib/src/ui/render.dart b/mobile/third_party/xterm/lib/src/ui/render.dartindex b8da24cd9..7e90c3bee 100644--- a/mobile/third_party/xterm/lib/src/ui/render.dart+++ b/mobile/third_party/xterm/lib/src/ui/render.dart@@ -36,7 +36,9 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {EditableRectCallback? onEditableRect,String? composingText,int composingBacktrackCells = 0,+ double devicePixelRatio = 1.0,}) : _terminal = terminal,+ _devicePixelRatio = devicePixelRatio,_controller = controller,_offset = offset,_padding = padding,@@ -63,6 +65,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {}_terminal = terminal;_reportedViewportSize = null;+ // The recorded lines are the old emulator's: none of them is drawn again.+ _painter.clearLinePictures();if (attached && _renderingEnabled) _terminal.addListener(_onTerminalChange);_resizeTerminalIfNeeded();markNeedsLayout();@@ -186,6 +190,15 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {markNeedsPaint();}+ /// AUTONOMOUS PATCH: the screen's pixels per logical pixel — the grid each+ /// line's top is placed on, see [_snapLineTop].+ double _devicePixelRatio;+ set devicePixelRatio(double value) {+ if (value == _devicePixelRatio) return;+ _devicePixelRatio = value;+ markNeedsPaint();+ }+TerminalSize? _viewportSize;TerminalSize? _reportedViewportSize;@@ -261,6 +274,12 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {super.systemFontsDidChange();}+ @override+ void dispose() {+ _painter.clearLinePictures();+ super.dispose();+ }+@overridevoid performLayout() {size = constraints.biggest;@@ -539,9 +558,9 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {final effectLastLine = lastLine.clamp(0, lines.length - 1);for (var i = effectFirstLine; i <= effectLastLine; i++) {- _painter.paintLine(+ _painter.paintLineCached(canvas,- offset.translate(0, (i * charHeight + _lineOffset).truncateToDouble()),+ offset.translate(0, _snapLineTop(i * charHeight + _lineOffset)),lines[i],);}@@ -583,6 +602,18 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {canvas.restore();}+ /// AUTONOMOUS PATCH: a line's top, on the screen's own pixel grid.+ ///+ /// It was truncated to whole LOGICAL pixels, which on a 3× phone is three+ /// device pixels: a slow scroll moved the text in visible three-pixel steps,+ /// holding still for frames in between, while the finger moved smoothly. On+ /// the device grid it moves a pixel at a time and stays as crisp.+ double _snapLineTop(double y) {+ final ratio = _devicePixelRatio;+ if (ratio <= 0) return y.truncateToDouble();+ return (y * ratio).roundToDouble() / ratio;+ }+/// Paints the text that is currently being composed in IME to [canvas] at/// [offset]. [offset] is usually the cursor position.void _paintComposingText(Canvas canvas, Offset offset) {diff --git a/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dartindex ad6f0a565..f52de2b12 100644--- a/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart+++ b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart@@ -14,6 +14,7 @@ class TerminalScrollGestureHandler extends StatefulWidget {required this.getLineHeight,this.simulateScroll = true,this.onAltBufferScroll,+ this.physics,required this.child,});@@ -38,6 +39,10 @@ class TerminalScrollGestureHandler extends StatefulWidget {/// need the emulator's own mouse/key simulation at all.final void Function(bool up)? onAltBufferScroll;+ /// AUTONOMOUS PATCH: the scroll's physics, layered over the platform's — see+ /// `TerminalView.altBufferScrollPhysics`.+ final ScrollPhysics? physics;+final Widget child;@override@@ -141,6 +146,7 @@ class _TerminalScrollGestureHandlerState},child: InfiniteScrollView(onScroll: _onScroll,+ physics: widget.physics,child: widget.child,),);