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): native-like fling and sliding remote scroll
tonyb2b8d30a45f3
diff --git a/mobile/lib/terminal/remote_scroll_physics.dart b/mobile/lib/terminal/remote_scroll_physics.dartindex cab12db76..b3b16055d 100644--- a/mobile/lib/terminal/remote_scroll_physics.dart+++ b/mobile/lib/terminal/remote_scroll_physics.dart@@ -1,34 +1,30 @@-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.+/// `altBufferScrollPhysics`). Drag and fling are the platform's own, so a flick carries as far and+/// slows the way it does in any list on the phone; only the fling's slow tail is cut.///-/// ⚠️ **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.+/// ⚠️ **The tail, not the fling, is what read as lag.** The platform eases its last few pixels out+/// over a second or more. Here each line is a redraw the program sends back, so that ease arrives as+/// a line, a pause, a line — the screen still ticking well after it looked stopped. A fling ends+/// once it is slower than [stopVelocity].///-/// 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.+/// ⚠️ **A fling once ran seconds behind the finger** (measured on Claude Code, 2026-10-02: 150–450+/// wheels, the screen moving 2–5 s after the finger lifted), and was cut to a quarter-second coast+/// for it — which stopped a fast flick dead. What ran behind was the queue: a wheel per line went+/// out faster than the program redrew, each waiting on the redraws before it. The scroll now sends+/// only as fast as the program answers (`TerminalView.altBufferScrollPaced`), so a long fling costs+/// a few dozen redraws, not one per line, and stops when the platform's does.////// 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.+/// defers to the platform entirely, overscroll and all.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;+ /// Slower than this, in logical pixels a second, a fling is over: about ten lines a second, below+ /// which the lines come one at a time.+ static const stopVelocity = 200.0;@overrideRemoteScrollPhysics applyTo(ScrollPhysics? ancestor) =>@@ -39,17 +35,33 @@ class RemoteScrollPhysics extends ScrollPhysics {ScrollMetrics position,double velocity,) {- if (position.minScrollExtent.isFinite ||+ final platform = super.createBallisticSimulation(position, velocity);+ if (platform == null ||+ position.minScrollExtent.isFinite ||position.maxScrollExtent.isFinite) {- return super.createBallisticSimulation(position, velocity);+ return platform;}- 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,- );+ if (velocity.abs() < stopVelocity) return null;+ return _EndsWhenSlow(platform, stopVelocity);}}++/// [_inner] — the platform's fling — until its speed falls below [_stopVelocity]. Its speed only+/// ever falls, so the fling ends where it is then, with no jump.+class _EndsWhenSlow extends Simulation {+ _EndsWhenSlow(this._inner, this._stopVelocity)+ : super(tolerance: _inner.tolerance);++ final Simulation _inner;+ final double _stopVelocity;++ @override+ double x(double time) => _inner.x(time);++ @override+ double dx(double time) => _inner.dx(time);++ @override+ bool isDone(double time) =>+ _inner.isDone(time) || _inner.dx(time).abs() < _stopVelocity;+}diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dartindex 05756b75d..07b3aa3c1 100644--- a/mobile/lib/widgets/terminal_panel.dart+++ b/mobile/lib/widgets/terminal_panel.dart@@ -1286,6 +1286,8 @@ class _TerminalPanelState extends State<TerminalPanel>? (up) => session.sendScrollCommand(up, 1): null,altBufferScrollPhysics: const RemoteScrollPhysics(),+ altBufferScrollPaced: true,+ altBufferScrollAnimated: true,),),),diff --git a/mobile/third_party/xterm/README.autonomous.md b/mobile/third_party/xterm/README.autonomous.mdindex 0ec5dccfd..29081d106 100644--- a/mobile/third_party/xterm/README.autonomous.md+++ b/mobile/third_party/xterm/README.autonomous.md@@ -253,6 +253,37 @@ it if one is dropped.`lib/src/ui/infinite_scroll_view.dart`). `TerminalView.altBufferScrollPhysics`reaches the `Scrollable` that turns a drag into wheel events, layered overthe 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`).+ never meets an end, and its slow tail arrives as a line at a time; the+ phone keeps the platform's fling and ends it once it is slower than about+ ten lines a second (`mobile/lib/terminal/remote_scroll_physics.dart`).Null keeps the platform's physics, as upstream.++19. **The alternate buffer's scroll waits for the program**+ (`lib/src/terminal_view.dart`, `lib/src/ui/scroll_handler.dart`). With+ `TerminalView.altBufferScrollPaced`, the wheel events of a scroll go out in+ batches, at most two of them unanswered by a write from the program; lines+ scrolled meanwhile join the next batch, at most a screen of them, and a+ turn back drops what still waits. A batch with no answer in 120 ms counts+ as answered — a program at the end of its history redraws nothing. A remote+ program redraws at the far end of a link: a wheel event per line, sent as+ fast as a fling scrolls, queued behind the redraws before it and moved its+ screen long after the fling had stopped. False sends each line as it is+ scrolled, as upstream.++20. **A full-screen program's scroll slides into place**+ (`lib/src/ui/remote_scroll_animator.dart`, `lib/src/ui/scroll_shift.dart`,+ `lib/src/ui/render.dart`, `lib/src/ui/line_picture_cache.dart`,+ `lib/src/ui/painter.dart`, `lib/src/ui/scroll_handler.dart`,+ `lib/src/terminal_view.dart`). On the alternate screen a scroll is the+ program's redraw, landing a line or more on from the last at uneven moments,+ so the text jumped. With `TerminalView.altBufferScrollAnimated`, a redraw+ within 400 ms of a wheel event is compared with the screen before it, one+ signature per row (`detectScrollShift`): when at least three rows, and most+ of those that could show it, agree on one shift and no other comes close,+ the rows that moved are drawn that far back — where they were — and eased to+ their place (e^-1 per 40 ms), clipped to the rows that changed so the fixed+ rows stay put. The rows that left are drawn from their last recording, taken+ out of the line cache (`LinePictureCache.take`) as they slide out. Purely+ visual: emulator, hit-testing and selection see the new screen at once. A+ change that is not a recognisable scroll ends any slide on the spot, as the+ screen behaved before. False draws each redraw as it lands, as upstream.diff --git a/mobile/third_party/xterm/lib/src/terminal_view.dart b/mobile/third_party/xterm/lib/src/terminal_view.dartindex 2a7370580..bc2b792ed 100644--- a/mobile/third_party/xterm/lib/src/terminal_view.dart+++ b/mobile/third_party/xterm/lib/src/terminal_view.dart@@ -57,6 +57,9 @@ class TerminalView extends StatefulWidget {this.simulateScroll = true,this.onAltBufferScroll,this.altBufferScrollPhysics,+ this.altBufferScrollPaced = false,+ this.altBufferScrollAnimated = false,+ this.onAltBufferScrollShift,});/// The underlying terminal that this widget renders.@@ -185,6 +188,26 @@ class TerminalView extends StatefulWidget {/// platform's own. Null keeps the platform's.final ScrollPhysics? altBufferScrollPhysics;+ /// AUTONOMOUS PATCH: the alternate buffer's scroll sends its wheel events+ /// only as fast as the program answers them — at most two batches without a+ /// write back — and lines scrolled meanwhile go together in the next batch.+ /// A remote program redraws at the far end of a link, and wheel events sent+ /// faster than that queue up, moving its screen long after the finger+ /// stopped. False sends each line as it is scrolled, as upstream.+ final bool altBufferScrollPaced;++ /// AUTONOMOUS PATCH: a full-screen program's redraw that answers the wheel+ /// slides into place over a few frames, rather than jumping there a line or+ /// more at a time — see `RemoteScrollAnimator`. Purely visual: the emulator+ /// holds the new screen at once. False draws each redraw as it lands, as+ /// upstream.+ final bool altBufferScrollAnimated;++ /// AUTONOMOUS PATCH: with [altBufferScrollAnimated], told of each redraw+ /// that answered the wheel — the rows it slid, or 0 when it could not be read+ /// as a scroll and jumped. For measuring; nothing depends on it.+ final void Function(int rows)? onAltBufferScrollShift;+@overrideState<TerminalView> createState() => TerminalViewState();}@@ -211,6 +234,13 @@ class TerminalViewState extends State<TerminalView> {RenderTerminal get renderTerminal =>_viewportKey.currentContext!.findRenderObject() as RenderTerminal;+ /// AUTONOMOUS PATCH: [lines] wheel lines just went to a full-screen program —+ /// see [TerminalView.altBufferScrollAnimated].+ void _expectAltBufferScroll(int lines) {+ final render = _viewportKey.currentContext?.findRenderObject();+ if (render is RenderTerminal) render.expectRemoteScroll(lines);+ }+@overridevoid initState() {_focusNode = widget.focusNode ?? FocusNode();@@ -301,6 +331,8 @@ class TerminalViewState extends State<TerminalView> {onEditableRect: _onEditableRect,composingText: _composingText,composingBacktrackCells: _composingBacktrackCells,+ animateRemoteScroll: widget.altBufferScrollAnimated,+ onRemoteScrollShift: widget.onAltBufferScrollShift,);},);@@ -310,6 +342,9 @@ class TerminalViewState extends State<TerminalView> {simulateScroll: widget.simulateScroll,onAltBufferScroll: widget.onAltBufferScroll,physics: widget.altBufferScrollPhysics,+ paced: widget.altBufferScrollPaced,+ onWheelsSent:+ widget.altBufferScrollAnimated ? _expectAltBufferScroll : null,getCellOffset: (offset) => renderTerminal.getCellOffset(offset),getLineHeight: () => renderTerminal.lineHeight,child: child,@@ -698,6 +733,8 @@ class _TerminalView extends LeafRenderObjectWidget {this.onEditableRect,this.composingText,this.composingBacktrackCells = 0,+ this.animateRemoteScroll = false,+ this.onRemoteScrollShift,});final Terminal terminal;@@ -732,6 +769,10 @@ class _TerminalView extends LeafRenderObjectWidget {final int composingBacktrackCells;+ final bool animateRemoteScroll;++ final void Function(int rows)? onRemoteScrollShift;+@overrideRenderTerminal createRenderObject(BuildContext context) {return RenderTerminal(@@ -753,6 +794,8 @@ class _TerminalView extends LeafRenderObjectWidget {composingText: composingText,composingBacktrackCells: composingBacktrackCells,devicePixelRatio: MediaQuery.maybeDevicePixelRatioOf(context) ?? 1.0,+ animateRemoteScroll: animateRemoteScroll,+ onRemoteScrollShift: onRemoteScrollShift,);}@@ -776,6 +819,8 @@ class _TerminalView extends LeafRenderObjectWidget {..onEditableRect = onEditableRect..composingText = composingText..composingBacktrackCells = composingBacktrackCells- ..devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context) ?? 1.0;+ ..devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context) ?? 1.0+ ..animateRemoteScroll = animateRemoteScroll+ ..onRemoteScrollShift = onRemoteScrollShift;}}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.dartindex e6b6423bc..cbffd0877 100644--- a/mobile/third_party/xterm/lib/src/ui/line_picture_cache.dart+++ b/mobile/third_party/xterm/lib/src/ui/line_picture_cache.dart@@ -48,6 +48,20 @@ class LinePictureCache {canvas.restore();}+ /// Hands over [line]'s recording if it still shows [version], and forgets it:+ /// the caller owns the picture from here, and disposes it. Null when there is+ /// none, or it shows another version.+ ///+ /// What a slide draws the rows that left the screen with+ /// (`RemoteScrollAnimator`): by the time it knows they left, the line has+ /// been written over, and only this recording still shows what it was.+ Picture? take(BufferLine line, int version) {+ final entry = _pictures[line];+ if (entry == null || entry.version != version) return null;+ _pictures.remove(line);+ return entry.picture;+ }+/// Drops every recording — the font, the scale or the colours changed, or the/// lines belong to an emulator that is gone.void clear() {diff --git a/mobile/third_party/xterm/lib/src/ui/painter.dart b/mobile/third_party/xterm/lib/src/ui/painter.dartindex aad581208..5489c14ff 100644--- a/mobile/third_party/xterm/lib/src/ui/painter.dart+++ b/mobile/third_party/xterm/lib/src/ui/painter.dart@@ -171,6 +171,11 @@ class TerminalPainter {void paintLineCached(Canvas canvas, Offset offset, BufferLine line) =>_linePictures.draw(canvas, offset, line);+ /// AUTONOMOUS PATCH: [line]'s last recording, handed over to the caller if it+ /// still shows [version] — see [LinePictureCache.take].+ Picture? takeLinePicture(BufferLine line, int version) =>+ _linePictures.take(line, version);+/// Paints [line] to [canvas] at [offset]. The x offset of [offset] is usually/// 0, and the y offset is the top of the line.///diff --git a/mobile/third_party/xterm/lib/src/ui/remote_scroll_animator.dart b/mobile/third_party/xterm/lib/src/ui/remote_scroll_animator.dartnew file mode 100644index 000000000..c9979619e--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/remote_scroll_animator.dart@@ -0,0 +1,340 @@+import 'dart:math' as math;+import 'dart:ui';++import 'package:flutter/scheduler.dart';+import 'package:xterm/src/core/buffer/line.dart';+import 'package:xterm/src/core/cell.dart';+import 'package:xterm/src/ui/scroll_shift.dart';+import 'package:xterm/src/utils/circular_buffer.dart';++/// Hands over [line]'s recorded drawing if it still shows [version], or null —+/// `TerminalPainter.takeLinePicture`. The caller owns, and disposes, what it gets.+typedef TakeLinePicture = Picture? Function(BufferLine line, int version);++/// AUTONOMOUS PATCH: slides a full-screen program's content to where its redraw+/// put it, instead of letting the screen jump there — `RenderTerminal`'s side of+/// `TerminalView.altBufferScrollAnimated`.+///+/// ⚠️ **On the alternate screen a scroll is the program's redraw.** The phone+/// sends wheel events and the program answers with a new screen, a few lines on+/// from the last: the text jumps a whole line or more at a time, at whatever+/// moments the replies land. When a redraw arrives within [_armedFor] of a wheel+/// event, it is compared with the screen before it ([detectScrollShift]). Found+/// moved by `n` rows, the moved rows are drawn `n` rows back — exactly where+/// they were — and eased to their place over a few frames. The rows that left+/// are drawn from their last recording ([ghosts]) as they slide out.+///+/// Only a visual offset: the emulator, hit-testing and selection all see the+/// new screen at once. A change that is not a recognisable scroll — output, a+/// redraw of something else — ends any slide on the spot, which is how the+/// screen behaved before.+class RemoteScrollAnimator {+ RemoteScrollAnimator({+ required this.onFrame,+ required this.takePicture,+ this.onShift,+ });++ /// The slide moved: draw again.+ final VoidCallback onFrame;++ final TakeLinePicture takePicture;++ /// Told of each redraw that answered a wheel: the rows it slid, or 0 when it+ /// could not be read as a scroll and the screen jumped.+ void Function(int rows)? onShift;++ /// A redraw this long after the last wheel event is not that scroll's answer.+ static const _armedFor = Duration(milliseconds: 400);++ /// How fast a slide eases in: it keeps `e^-1` of its distance after this+ /// long, and is all but there after three times it.+ static const _easeSeconds = 0.040;++ /// Closer than this, in logical pixels, a slide is there.+ static const _stillBelow = 0.5;++ final _clock = Stopwatch()..start();+ int _armedUntilMs = -1;+ bool _up = false;+ bool _down = false;++ /// The screen as last laid out — what was drawn, and what a redraw is+ /// compared with. Kept only while armed or sliding.+ List<BufferLine>? _lines;+ List<int>? _versions;+ List<int>? _signatures;++ int _top = 0;+ int _bottom = -1;+ double _offset = 0;+ double _lineHeight = 0;++ /// Rows that slid out of the region, by the row they would occupy now —+ /// outside [top]..[bottom] — each drawn from its last recording.+ final _ghosts = <int, Picture>{};++ int? _frameCallbackId;+ Duration? _lastTick;++ bool get _armed => _clock.elapsedMilliseconds < _armedUntilMs;++ /// Whether rows [top]..[bottom] are drawn [offset] pixels from their place.+ bool get isSliding => _offset != 0;++ int get top => _top;++ int get bottom => _bottom;++ double get offset => _offset;++ Iterable<MapEntry<int, Picture>> get ghosts => _ghosts.entries;++ /// [lines] wheel lines were just sent, negative for up. The first [rowCount]+ /// rows of [screen], each [lineHeight] tall, are what is on screen now.+ void expect(+ int lines,+ IndexAwareCircularBuffer<BufferLine> screen,+ int rowCount,+ double lineHeight,+ ) {+ if (lines == 0 || screen.length < rowCount) return;+ if (!_armed) {+ _up = false;+ _down = false;+ }+ if (lines < 0) {+ _up = true;+ } else {+ _down = true;+ }+ _armedUntilMs = _clock.elapsedMilliseconds + _armedFor.inMilliseconds;+ if (_signatures == null) _remember(screen, rowCount, lineHeight);+ }++ /// The screen was laid out again: [screen]'s first [rowCount] rows, each+ /// [lineHeight] tall, are what the next frame draws.+ void update(+ IndexAwareCircularBuffer<BufferLine> screen,+ int rowCount,+ double lineHeight,+ ) {+ if (!_armed && !isSliding) {+ _forgetScreen();+ return;+ }+ if (screen.length < rowCount) {+ reset();+ return;+ }+ final before = _signatures;+ if (before == null ||+ before.length != rowCount ||+ lineHeight != _lineHeight) {+ // A different grid: nothing to compare with.+ finish();+ _remember(screen, rowCount, lineHeight);+ return;+ }+ if (_unchanged(screen, rowCount)) return;++ final lines = List<BufferLine>.generate(rowCount, (row) => screen[row]);+ final versions = List<int>.generate(rowCount, (row) => lines[row].paintVersion);+ final signatures = List<int>.filled(rowCount, 0);+ final blank = List<bool>.filled(rowCount, false);+ for (var row = 0; row < rowCount; row++) {+ signatures[row] = _signature(lines[row]);+ blank[row] = _isBlank(lines[row]);+ }++ if (_armed) {+ final shift = detectScrollShift(+ before: before,+ after: signatures,+ blank: blank,+ up: _up,+ down: _down,+ );+ if (shift != null && _slide(shift, lineHeight)) {+ onShift?.call(shift.rows);+ } else {+ finish();+ onShift?.call(0);+ }+ } else {+ // Changed after the scroll was over: output, not a scroll. Jump.+ finish();+ }++ _lines = lines;+ _versions = versions;+ _signatures = signatures;+ }++ /// Ends any slide where it stands: everything at its place.+ void finish() {+ final id = _frameCallbackId;+ if (id != null) {+ SchedulerBinding.instance.cancelFrameCallbackWithId(id);+ _frameCallbackId = null;+ }+ _lastTick = null;+ _offset = 0;+ _disposeGhosts();+ }++ /// Back to how it was made: not armed, nothing remembered, nothing sliding.+ void reset() {+ finish();+ _forgetScreen();+ _armedUntilMs = -1;+ _up = false;+ _down = false;+ }++ void dispose() => reset();++ bool _slide(ScrollShift shift, double lineHeight) {+ final lines = _lines;+ final versions = _versions;+ if (lines == null || versions == null) return false;+ final carried = isSliding ? _offset : 0.0;+ final offset = carried + shift.rows * lineHeight;+ // Farther than the region is tall, there is nothing on screen to slide.+ if (offset.abs() >= (shift.bottom - shift.top + 1) * lineHeight) {+ return false;+ }+ if (offset == 0) {+ // This shift undid what was still sliding: everything is in place.+ finish();+ return true;+ }++ if (carried == 0) {+ _disposeGhosts();+ } else if (_ghosts.isNotEmpty) {+ // Row `r` before is row `r - rows` now.+ final moved = {+ for (final ghost in _ghosts.entries)+ ghost.key - shift.rows: ghost.value,+ };+ _ghosts+ ..clear()+ ..addAll(moved);+ }+ // The rows that left the region slide out from where they were.+ for (var row = shift.top; row <= shift.bottom; row++) {+ final at = row - shift.rows;+ if (at >= shift.top && at <= shift.bottom) continue;+ final picture = takePicture(lines[row], versions[row]);+ if (picture == null) continue;+ _ghosts.remove(at)?.dispose();+ _ghosts[at] = picture;+ }++ _top = shift.top;+ _bottom = shift.bottom;+ _offset = offset;+ _pruneGhosts();+ _scheduleTick();+ return true;+ }++ void _scheduleTick() {+ if (_frameCallbackId != null) return;+ _frameCallbackId =+ SchedulerBinding.instance.scheduleFrameCallback(_tick);+ }++ void _tick(Duration timeStamp) {+ _frameCallbackId = null;+ if (!isSliding) return;+ final last = _lastTick;+ _lastTick = timeStamp;+ final seconds = last == null+ ? 1 / 60+ : math.max(0, (timeStamp - last).inMicroseconds) / 1e6;+ _offset *= math.exp(-seconds / _easeSeconds);+ if (_offset.abs() < _stillBelow) {+ finish();+ } else {+ _pruneGhosts();+ _scheduleTick();+ }+ onFrame();+ }++ /// Drops the ghosts the slide can no longer bring into the region: it only+ /// ever closes in on zero, so a ghost out of reach now stays out of it.+ void _pruneGhosts() {+ if (_ghosts.isEmpty) return;+ final reach = _lineHeight > 0 ? (_offset.abs() / _lineHeight).ceil() : 0;+ _ghosts.removeWhere((at, picture) {+ final inReach = _offset < 0+ ? at > _bottom && at <= _bottom + reach+ : at < _top && at >= _top - reach;+ if (!inReach) picture.dispose();+ return !inReach;+ });+ }++ void _disposeGhosts() {+ for (final picture in _ghosts.values) {+ picture.dispose();+ }+ _ghosts.clear();+ }++ void _remember(+ IndexAwareCircularBuffer<BufferLine> screen,+ int rowCount,+ double lineHeight,+ ) {+ final lines = List<BufferLine>.generate(rowCount, (row) => screen[row]);+ _lineHeight = lineHeight;+ _lines = lines;+ _versions = [for (final line in lines) line.paintVersion];+ _signatures = [for (final line in lines) _signature(line)];+ }++ void _forgetScreen() {+ _lines = null;+ _versions = null;+ _signatures = null;+ }++ bool _unchanged(IndexAwareCircularBuffer<BufferLine> screen, int rowCount) {+ final lines = _lines!;+ final versions = _versions!;+ for (var row = 0; row < rowCount; row++) {+ final line = screen[row];+ if (!identical(line, lines[row]) ||+ line.paintVersion != versions[row]) {+ return false;+ }+ }+ return true;+ }++ /// Everything the row draws — characters, colours, attributes — as one number.+ static int _signature(BufferLine line) {+ final data = line.data;+ final end = line.length * 4;+ var hash = line.length;+ for (var i = 0; i < end; i++) {+ hash = 0x1fffffff & (hash * 31 + data[i]);+ }+ return hash;+ }++ /// Nothing but spaces: such a row matches any other, so it proves no shift.+ static bool _isBlank(BufferLine line) {+ final data = line.data;+ final end = line.length * 4;+ for (var i = 3; i < end; i += 4) {+ final codePoint = data[i] & CellContent.codepointMask;+ if (codePoint != 0 && codePoint != 0x20) return false;+ }+ return true;+ }+}diff --git a/mobile/third_party/xterm/lib/src/ui/render.dart b/mobile/third_party/xterm/lib/src/ui/render.dartindex 7e90c3bee..0d8894d67 100644--- a/mobile/third_party/xterm/lib/src/ui/render.dart+++ b/mobile/third_party/xterm/lib/src/ui/render.dart@@ -1,4 +1,4 @@-import 'dart:math' show max;+import 'dart:math' show max, min;import 'package:flutter/rendering.dart';import 'package:flutter/scheduler.dart';import 'package:flutter/widgets.dart';@@ -11,6 +11,7 @@ import 'package:xterm/src/terminal.dart';import 'package:xterm/src/ui/controller.dart';import 'package:xterm/src/ui/cursor_type.dart';import 'package:xterm/src/ui/painter.dart';+import 'package:xterm/src/ui/remote_scroll_animator.dart';import 'package:xterm/src/ui/selection_mode.dart';import 'package:xterm/src/ui/terminal_size.dart';import 'package:xterm/src/ui/terminal_text_style.dart';@@ -37,8 +38,12 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {String? composingText,int composingBacktrackCells = 0,double devicePixelRatio = 1.0,+ bool animateRemoteScroll = false,+ void Function(int rows)? onRemoteScrollShift,}) : _terminal = terminal,_devicePixelRatio = devicePixelRatio,+ _animateRemoteScroll = animateRemoteScroll,+ _onRemoteScrollShift = onRemoteScrollShift,_controller = controller,_offset = offset,_padding = padding,@@ -67,6 +72,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {_reportedViewportSize = null;// The recorded lines are the old emulator's: none of them is drawn again._painter.clearLinePictures();+ _remoteScroll?.reset();if (attached && _renderingEnabled) _terminal.addListener(_onTerminalChange);_resizeTerminalIfNeeded();markNeedsLayout();@@ -116,6 +122,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {set renderingEnabled(bool value) {if (value == _renderingEnabled) return;_renderingEnabled = value;+ _remoteScroll?.reset();if (attached) {if (value) {_terminal.addListener(_onTerminalChange);@@ -131,18 +138,21 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {set textStyle(TerminalStyle value) {if (value == _painter.textStyle) return;_painter.textStyle = value;+ _remoteScroll?.reset();markNeedsLayout();}set textScaler(TextScaler value) {if (value == _painter.textScaler) return;_painter.textScaler = value;+ _remoteScroll?.reset();markNeedsLayout();}set theme(TerminalTheme value) {if (value == _painter.theme) return;_painter.theme = value;+ _remoteScroll?.reset();markNeedsPaint();}@@ -199,6 +209,72 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {markNeedsPaint();}+ /// AUTONOMOUS PATCH: whether a full-screen program's scroll slides into place+ /// rather than jumping — `TerminalView.altBufferScrollAnimated`.+ bool _animateRemoteScroll;+ set animateRemoteScroll(bool value) {+ if (value == _animateRemoteScroll) return;+ _animateRemoteScroll = value;+ if (!value) {+ _remoteScroll?.dispose();+ _remoteScroll = null;+ markNeedsPaint();+ }+ }++ void Function(int rows)? _onRemoteScrollShift;+ set onRemoteScrollShift(void Function(int rows)? value) {+ _onRemoteScrollShift = value;+ _remoteScroll?.onShift = value;+ }++ /// Made the first time a wheel event goes out with [_animateRemoteScroll] on.+ RemoteScrollAnimator? _remoteScroll;++ /// AUTONOMOUS PATCH: [lines] wheel lines just went to the program, negative+ /// for up. Its next redraw may be that scroll's answer, and then slides into+ /// place instead of jumping — see [RemoteScrollAnimator].+ void expectRemoteScroll(int lines) {+ if (!_animateRemoteScroll ||+ !_renderingEnabled ||+ !attached ||+ !_isWholeAltScreen) {+ return;+ }+ final animator = _remoteScroll ??= RemoteScrollAnimator(+ onFrame: markNeedsPaint,+ takePicture: _painter.takeLinePicture,+ onShift: _onRemoteScrollShift,+ );+ animator.expect(+ lines,+ _terminal.buffer.lines,+ _terminal.viewHeight,+ _painter.cellSize.height,+ );+ }++ /// On the alternate screen, with no history: buffer line `i` is screen row+ /// `i`, which is what a slide's rows are counted in.+ bool get _isWholeAltScreen =>+ _terminal.isUsingAltBuffer &&+ _terminal.buffer.lines.length == _terminal.viewHeight;++ /// The screen was laid out again: a slide starts, carries on or ends here.+ void _updateRemoteScroll() {+ final animator = _remoteScroll;+ if (animator == null) return;+ if (!_isWholeAltScreen) {+ animator.reset();+ return;+ }+ animator.update(+ _terminal.buffer.lines,+ _terminal.viewHeight,+ _painter.cellSize.height,+ );+ }+TerminalSize? _viewportSize;TerminalSize? _reportedViewportSize;@@ -261,6 +337,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {_terminal.removeListener(_onTerminalChange);_controller.removeListener(_onControllerUpdate);_focusNode.removeListener(_onFocusChange);+ _remoteScroll?.reset();}@override@@ -276,6 +353,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {@overridevoid dispose() {+ _remoteScroll?.dispose();+ _remoteScroll = null;_painter.clearLinePictures();super.dispose();}@@ -298,6 +377,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {_updateScrollOffset();if (followTail) _stickToBottom = true;_laidOutMaxScrollExtent = _maxScrollExtent;+ _updateRemoteScroll();_scheduleEditableRect();}@@ -557,7 +637,12 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {final effectFirstLine = firstLine.clamp(0, lines.length - 1);final effectLastLine = lastLine.clamp(0, lines.length - 1);+ // AUTONOMOUS PATCH: a full-screen program's scroll, still sliding into+ // place — its rows are drawn by [_paintSlide], the rest as ever.+ final slide = _remoteScroll?.isSliding == true ? _remoteScroll : null;+for (var i = effectFirstLine; i <= effectLastLine; i++) {+ if (slide != null && i >= slide.top && i <= slide.bottom) continue;_painter.paintLineCached(canvas,offset.translate(0, _snapLineTop(i * charHeight + _lineOffset)),@@ -565,16 +650,27 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {);}- if (_terminal.buffer.absoluteCursorY >= effectFirstLine &&- _terminal.buffer.absoluteCursorY <= effectLastLine) {+ if (slide != null) {+ _paintSlide(canvas, offset, slide, effectFirstLine, effectLastLine);+ }++ final cursorY = _terminal.buffer.absoluteCursorY;+ if (cursorY >= effectFirstLine && cursorY <= effectLastLine) {+ // A cursor inside the sliding rows moves with them.+ final cursorAt = slide != null &&+ cursorY >= slide.top &&+ cursorY <= slide.bottom+ ? offset + cursorOffset.translate(0, slide.offset)+ : offset + cursorOffset;+if (_isComposingText) {- _paintComposingText(canvas, offset + cursorOffset);+ _paintComposingText(canvas, cursorAt);}if (_shouldShowCursor) {_painter.paintCursor(canvas,- offset + cursorOffset,+ cursorAt,cursorType: _cursorType,hasFocus: _focusNode.hasFocus,);@@ -602,6 +698,49 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {canvas.restore();}+ /// AUTONOMOUS PATCH: the rows of a scroll still sliding into place — each+ /// drawn [RemoteScrollAnimator.offset] from where it belongs, with the rows+ /// that left the screen sliding out after them, all clipped to the rows the+ /// scroll moved so the program's fixed rows above and below stay put.+ void _paintSlide(+ Canvas canvas,+ Offset offset,+ RemoteScrollAnimator slide,+ int firstLine,+ int lastLine,+ ) {+ final lines = _terminal.buffer.lines;+ final lineHeight = _painter.cellSize.height;+ final shift = slide.offset;+ final top = offset.dy + _snapLineTop(slide.top * lineHeight + _lineOffset);+ final bottom =+ offset.dy + _snapLineTop((slide.bottom + 1) * lineHeight + _lineOffset);++ canvas.save();+ canvas.clipRect(+ Rect.fromLTRB(offset.dx, top, offset.dx + size.width, bottom),+ );+ final from = max(slide.top, firstLine);+ final to = min(slide.bottom, lastLine);+ for (var i = from; i <= to; i++) {+ _painter.paintLineCached(+ canvas,+ offset.translate(0, _snapLineTop(i * lineHeight + _lineOffset + shift)),+ lines[i],+ );+ }+ for (final ghost in slide.ghosts) {+ canvas.save();+ canvas.translate(+ offset.dx,+ offset.dy + _snapLineTop(ghost.key * lineHeight + _lineOffset + shift),+ );+ canvas.drawPicture(ghost.value);+ canvas.restore();+ }+ 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 threediff --git a/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dartindex f52de2b12..892d4b1b8 100644--- a/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart+++ b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart@@ -1,3 +1,6 @@+import 'dart:async';+import 'dart:math' show max;+import 'package:flutter/widgets.dart';import 'package:xterm/core.dart';import 'package:xterm/src/ui/infinite_scroll_view.dart';@@ -15,6 +18,8 @@ class TerminalScrollGestureHandler extends StatefulWidget {this.simulateScroll = true,this.onAltBufferScroll,this.physics,+ this.paced = false,+ this.onWheelsSent,required this.child,});@@ -43,6 +48,15 @@ class TerminalScrollGestureHandler extends StatefulWidget {/// `TerminalView.altBufferScrollPhysics`.final ScrollPhysics? physics;+ /// AUTONOMOUS PATCH: wheel events go out as fast as the program redraws for+ /// them, not as fast as the finger moves — see+ /// `TerminalView.altBufferScrollPaced`.+ final bool paced;++ /// AUTONOMOUS PATCH: told of each batch of wheel lines as it goes out,+ /// negative for up — see `TerminalView.altBufferScrollAnimated`.+ final void Function(int lines)? onWheelsSent;+final Widget child;@override@@ -64,6 +78,23 @@ class _TerminalScrollGestureHandlerState/// Used to calculate the cell offset of the terminal mouse event.var lastPointerPosition = Offset.zero;+ /// AUTONOMOUS PATCH ([TerminalScrollGestureHandler.paced]): lines scrolled+ /// and not yet sent, negative for up.+ var _unsentLines = 0;++ /// Batches of wheel events sent that no write from the program has answered.+ var _batchesInFlight = 0;++ /// Lets the next batch go when no answer comes: a program already at the top+ /// of its history has nothing to redraw, and a scroll that waited for it+ /// would never move again.+ Timer? _answerWait;++ /// Two, so the next batch is on its way while the program redraws the last.+ static const _maxBatchesInFlight = 2;++ static const _answerWaitLimit = Duration(milliseconds: 120);+@overridevoid initState() {widget.terminal.addListener(_onTerminalUpdated);@@ -74,6 +105,7 @@ class _TerminalScrollGestureHandlerState@overridevoid dispose() {widget.terminal.removeListener(_onTerminalUpdated);+ _resetPacing();super.dispose();}@@ -83,6 +115,9 @@ class _TerminalScrollGestureHandlerStateoldWidget.terminal.removeListener(_onTerminalUpdated);widget.terminal.addListener(_onTerminalUpdated);isAltBuffer = widget.terminal.isUsingAltBuffer;+ _resetPacing();+ } else if (!widget.paced) {+ _resetPacing();}super.didUpdateWidget(oldWidget);}@@ -90,7 +125,20 @@ class _TerminalScrollGestureHandlerStatevoid _onTerminalUpdated() {if (isAltBuffer != widget.terminal.isUsingAltBuffer) {isAltBuffer = widget.terminal.isUsingAltBuffer;+ _resetPacing();setState(() {});+ return;+ }+ // AUTONOMOUS PATCH: the program wrote — on the alternate buffer, its redraw+ // for the wheel events in flight — so another batch may go. Any write+ // counts: one that answers nothing only lets the next batch go sooner.+ if (_batchesInFlight > 0) {+ _batchesInFlight--;+ if (_batchesInFlight == 0) {+ _answerWait?.cancel();+ _answerWait = null;+ }+ _sendUnsentLines();}}@@ -124,13 +172,60 @@ class _TerminalScrollGestureHandlerStatefinal delta = currentLineOffset - lastLineOffset;- for (var i = 0; i < delta.abs(); i++) {- _sendScrollEvent(delta < 0);+ if (widget.paced) {+ _queueLines(delta);+ } else {+ if (delta != 0) widget.onWheelsSent?.call(delta);+ for (var i = 0; i < delta.abs(); i++) {+ _sendScrollEvent(delta < 0);+ }}lastLineOffset = currentLineOffset;}+ /// AUTONOMOUS PATCH ([TerminalScrollGestureHandler.paced]): [delta] more+ /// lines to scroll — sent now if the program has kept up, else in the next+ /// batch, together with the lines scrolled while it caught up.+ void _queueLines(int delta) {+ if (delta == 0) return;+ // Turned back: what still waits would carry the screen away from the finger.+ if (_unsentLines != 0 && (_unsentLines < 0) != (delta < 0)) {+ _unsentLines = 0;+ }+ // At most a screen waits. On a slow link the rest of a fast fling is+ // dropped, rather than played out long after the fling has stopped.+ final screen = max(1, widget.terminal.viewHeight);+ _unsentLines = (_unsentLines + delta).clamp(-screen, screen);+ _sendUnsentLines();+ }++ void _sendUnsentLines() {+ if (_unsentLines == 0 || _batchesInFlight >= _maxBatchesInFlight) return;+ final lines = _unsentLines;+ _unsentLines = 0;+ _batchesInFlight++;+ _answerWait?.cancel();+ _answerWait = Timer(_answerWaitLimit, _onAnswerWaitOver);+ widget.onWheelsSent?.call(lines);+ for (var i = 0; i < lines.abs(); i++) {+ _sendScrollEvent(lines < 0);+ }+ }++ void _onAnswerWaitOver() {+ _answerWait = null;+ _batchesInFlight = 0;+ _sendUnsentLines();+ }++ void _resetPacing() {+ _answerWait?.cancel();+ _answerWait = null;+ _unsentLines = 0;+ _batchesInFlight = 0;+ }+@overrideWidget build(BuildContext context) {if (!isAltBuffer) {diff --git a/mobile/third_party/xterm/lib/src/ui/scroll_shift.dart b/mobile/third_party/xterm/lib/src/ui/scroll_shift.dartnew file mode 100644index 000000000..a19fb2b1f--- /dev/null+++ b/mobile/third_party/xterm/lib/src/ui/scroll_shift.dart@@ -0,0 +1,114 @@+import 'dart:math' show max, min;++/// AUTONOMOUS PATCH: how far a full-screen program's redraw moved its content —+/// what `RemoteScrollAnimator` slides instead of letting the screen jump.+///+/// Row `i` of the new screen shows what row `i + rows` showed before, for the+/// rows from [top] to [bottom] — the scrolled lines; the rows outside them, the+/// program's own fixed rows, stay where they are.+class ScrollShift {+ const ScrollShift(this.top, this.bottom, this.rows);++ final int top;+ final int bottom;++ /// Negative when the content moved down — a scroll up, towards older lines.+ final int rows;++ @override+ String toString() => 'ScrollShift($top..$bottom by $rows)';+}++/// Rows that must agree on one shift before it is believed.+const _minRowsAgreeing = 3;++/// Compares two screens, one signature per row, and finds the shift that turned+/// [before] into [after] — or null when there is none to be sure of.+///+/// [blank] marks the rows of [after] with nothing on them: they agree with+/// every other blank row, so they are no evidence of anything. [up] and [down]+/// say which way the wheel went; a shift the other way is not this scroll.+///+/// ⚠️ **Null is the safe answer.** A program redraws for many reasons, and a+/// slide drawn for a change that was not a scroll moves the wrong text. A shift+/// is taken only when at least three rows, and most of the rows that could show+/// it, agree on it, and no other shift comes close.+ScrollShift? detectScrollShift({+ required List<int> before,+ required List<int> after,+ required List<bool> blank,+ required bool up,+ required bool down,+}) {+ final rowCount = after.length;+ if (before.length != rowCount || blank.length != rowCount) return null;+ if (!up && !down) return null;++ // The rows that changed. Above and below them — a header, the prompt — the+ // screen stood still.+ var top = 0;+ while (top < rowCount && before[top] == after[top]) {+ top++;+ }+ if (top == rowCount) return null;+ var bottom = rowCount - 1;+ while (before[bottom] == after[bottom]) {+ bottom--;+ }+ final span = bottom - top + 1;+ if (span < _minRowsAgreeing) return null;++ var best = 0;+ var bestAgreeing = 0;+ var bestCandidates = 0;+ var runnerUpAgreeing = 0;+ for (var rows = -(span - 1); rows <= span - 1; rows++) {+ if (rows == 0 || (rows < 0 && !up) || (rows > 0 && !down)) continue;+ // The rows whose old content, `rows` away, is still inside the region.+ final from = max(top, top - rows);+ final to = min(bottom, bottom - rows);+ var agreeing = 0;+ var candidates = 0;+ for (var i = from; i <= to; i++) {+ if (blank[i] || before[i] == after[i]) continue;+ candidates++;+ if (after[i] == before[i + rows]) agreeing++;+ }+ if (agreeing > bestAgreeing) {+ runnerUpAgreeing = bestAgreeing;+ best = rows;+ bestAgreeing = agreeing;+ bestCandidates = candidates;+ } else if (agreeing > runnerUpAgreeing) {+ runnerUpAgreeing = agreeing;+ }+ }++ if (bestAgreeing < _minRowsAgreeing) return null;+ // Most of the rows that could show it, show it.+ if (bestAgreeing * 10 < bestCandidates * 6) return null;+ // And nothing else is nearly as good: repeated rows — rules, borders, a+ // column of equal lines — agree with more than one shift.+ if (runnerUpAgreeing * 2 >= bestAgreeing) return null;++ // The rows that moved, and next to them the rows that came in or went out+ // with them — up to a row with something on it that stood still. Without+ // that stop, a status line that changed below the prompt would stretch the+ // region over the prompt, and slide it with the scrolled lines.+ var first = -1;+ var last = -1;+ for (var i = max(top, top - best); i <= min(bottom, bottom - best); i++) {+ if (!blank[i] && before[i] != after[i] && after[i] == before[i + best]) {+ if (first < 0) first = i;+ last = i;+ }+ }+ bool stoodStill(int row) => !blank[row] && before[row] == after[row];+ while (first > top && !stoodStill(first - 1)) {+ first--;+ }+ while (last < bottom && !stoodStill(last + 1)) {+ last++;+ }+ return ScrollShift(first, last, best);+}