Skip to content

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.

feat(mobile): finger-driven scroll mirror, hide stray cursor

tony441903082dc3
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 20f6b33fb..cd7a74efe 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -398,6 +398,24 @@ class TerminalSession extends ChangeNotifier {
int _generation = 0;
bool _remoteCursorVisible = true;
bool _cursorBlinkPhaseVisible = true;
+
+ /// Whether the cursor is hidden until the program draws again, because where the screen has it
+ /// is not where the program put it.
+ ///
+ /// ⚠️ **A pane made shorter loses the rows under its cursor.** tmux shrinks a pane by deleting
+ /// rows from the bottom up to the cursor before it pushes any into the history (`screen_resize_y`),
+ /// and it never asks whether they were empty. A shell's are; Claude Code's classic screen parks
+ /// the cursor on its prompt with four rows of its own under it (a border, two status lines, a
+ /// blank). The keyboard coming up shrinks the pane and those rows go. When Claude Code's redraw
+ /// for the resize follows the keyframe, it puts the cursor back on the prompt within milliseconds
+ /// — but when it did not (seen 2026-10-06), the cursor stayed at the bottom row, under the status
+ /// lines and against the key bar, until the first key typed made Claude Code draw again. So the
+ /// cursor is not shown until the program's next output, whichever of the two that is.
+ bool _cursorAwaitsProgram = false;
+
+ /// The pane height whose shrinking cut rows drawn under the cursor ([_noteCutUnderCursor]), spent
+ /// on the keyframe that answers it.
+ int? _cutUnderCursorFrom;
List<int> _utf8Tail = const [];
final List<int> _inputBytes = [];
Timer? _heartbeat;
@@ -528,6 +546,8 @@ class TerminalSession extends ChangeNotifier {
_utf8Tail = const [];
_remoteCursorVisible = true;
_cursorBlinkPhaseVisible = true;
+ _cursorAwaitsProgram = false;
+ _cutUnderCursorFrom = null;
_resyncRequested = false;
_resyncAttempts = 0;
_openSentAt = null;
@@ -1174,15 +1194,46 @@ class TerminalSession extends ChangeNotifier {
terminal.setCursorVisibleMode(_remoteCursorVisible);
terminal.write(text);
_remoteCursorVisible = terminal.cursorVisibleMode;
+ if (_cursorAwaitsProgram) {
+ _cursorAwaitsProgram = false;
+ if (kTypingTrace) typingEvent('cursor: shown — the program drew again');
+ }
_applyCursorVisibility();
}
void _applyCursorVisibility() {
terminal.setCursorVisibleMode(
- _remoteCursorVisible && _cursorBlinkPhaseVisible,
+ _remoteCursorVisible && _cursorBlinkPhaseVisible && !_cursorAwaitsProgram,
);
}
+ /// Notes whether making the pane [nextRows] high cuts rows drawn under the cursor, for the
+ /// keyframe that answers it ([_cutUnderCursorFrom]). Read only while the emulator still has the
+ /// pane's height — the emulator's own shrink deletes the same rows tmux will. Only ever set here,
+ /// never cleared: a later step of the same shrink reads an emulator that has lost them already.
+ void _noteCutUnderCursor(int nextRows) {
+ if (nextRows < rows &&
+ terminal.viewHeight == rows &&
+ !_showingKeptScreen &&
+ !terminal.isUsingAltBuffer &&
+ _drawnUnderCursor()) {
+ _cutUnderCursorFrom = rows;
+ }
+ }
+
+ /// Whether a row under the cursor has anything drawn on it — what tmux deletes first when the
+ /// pane is made shorter. See [_cursorAwaitsProgram].
+ bool _drawnUnderCursor() {
+ final buffer = terminal.buffer;
+ final top = buffer.scrollBack;
+ for (var y = buffer.cursorY + 1; y < terminal.viewHeight; y++) {
+ final index = top + y;
+ if (index < 0 || index >= buffer.lines.length) break;
+ if (buffer.lines[index].getText().trim().isNotEmpty) return true;
+ }
+ return false;
+ }
+
bool _writeBytes(List<int> bytes) {
// Most packets end on a scalar boundary. Decode their existing byte view
// directly; only a split UTF-8 scalar needs a joined buffer.
@@ -1232,6 +1283,21 @@ class TerminalSession extends ChangeNotifier {
// the stream on owns what is shown now, and this screen is dropped.
return;
}
+ final cutFrom = _cutUnderCursorFrom;
+ if (cutFrom != null && _clampRows(nextRows) < cutFrom) {
+ // The answer to the shrink that cut rows under the cursor. A keyframe at the old size, sent
+ // before the resize landed, leaves it for the one that is.
+ _cutUnderCursorFrom = null;
+ if (!replacement.isUsingAltBuffer && !_cursorAwaitsProgram) {
+ _cursorAwaitsProgram = true;
+ if (kTypingTrace) {
+ typingEvent(
+ 'cursor: hidden — the pane shrank from $cutFrom rows through rows'
+ ' drawn under it, so it waits for the program to draw again',
+ );
+ }
+ }
+ }
_bindTerminal(replacement);
terminal = replacement;
_showingKeptScreen = false;
@@ -1240,6 +1306,8 @@ class TerminalSession extends ChangeNotifier {
_utf8Tail = decoded.tail;
_remoteCursorVisible = terminal.cursorVisibleMode;
_cursorBlinkPhaseVisible = true;
+ // A keyframe is the program's screen, not a redraw by it: a cursor held stays held through it.
+ _applyCursorVisibility();
_expectedSeq = frame.seq + 1;
_staleInARow = 0;
_lastRenderedSeq = frame.seq;
@@ -1800,6 +1868,8 @@ class TerminalSession extends ChangeNotifier {
static const _resizeCoalesceWindow = Duration(milliseconds: 50);
void resize(int width, int height) {
+ // [Terminal.resize] asks here before it shrinks itself, so this still reads the pane's height.
+ _noteCutUnderCursor(_clampRows(height));
_pendingCols = _clampCols(width);
_pendingRows = _clampRows(height);
final last = _lastResizeFlushAt;
@@ -1828,8 +1898,15 @@ class TerminalSession extends ChangeNotifier {
final nextRows = _pendingRows!;
_pendingCols = null;
_pendingRows = null;
+ final cutFrom = _cutUnderCursorFrom;
+ if (cutFrom != null && nextRows >= cutFrom) {
+ // The shrink was taken back before it was asked for — the keyboard went down again.
+ _cutUnderCursorFrom = null;
+ }
if (nextCols == cols && nextRows == rows) return;
if (_resizeStillComing(nextCols, nextRows)) return;
+ // A keyframe's own resize to the measured size comes straight here, not through [resize].
+ _noteCutUnderCursor(nextRows);
cols = nextCols;
rows = nextRows;
_lastResizeFlushAt = DateTime.now();
diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dart
index e8623c6a0..45462383a 100644
--- a/mobile/lib/widgets/terminal_panel.dart
+++ b/mobile/lib/widgets/terminal_panel.dart
@@ -1694,6 +1694,10 @@ class _TerminalPanelState extends State<TerminalPanel>
altBufferScrollPhysics: const RemoteScrollPhysics(),
altBufferScrollPaced: true,
altBufferScrollAnimated: true,
+ // The finger moves the screen; the program only fills
+ // it in — `RemoteScrollMirror`. The slide above is
+ // what is left when it is off.
+ altBufferScrollMirror: true,
// How many redraws slid and how many jumped — the
// scroll's smoothness, for the trace.
onAltBufferScrollShift: kTypingTrace
diff --git a/mobile/third_party/xterm/lib/src/terminal_view.dart b/mobile/third_party/xterm/lib/src/terminal_view.dart
index 2f212f49e..a40156940 100644
--- a/mobile/third_party/xterm/lib/src/terminal_view.dart
+++ b/mobile/third_party/xterm/lib/src/terminal_view.dart
@@ -65,6 +65,7 @@ class TerminalView extends StatefulWidget {
this.altBufferScrollPaced = false,
this.altBufferScrollAnimated = false,
this.onAltBufferScrollShift,
+ this.altBufferScrollMirror = false,
this.keepsInputAcrossTerminals = false,
this.predictsEcho = false,
});
@@ -220,6 +221,14 @@ class TerminalView extends StatefulWidget {
/// as a scroll and jumped. For measuring; nothing depends on it.
final void Function(int rows)? onAltBufferScrollShift;
+ /// AUTONOMOUS PATCH: a full-screen program's scroll is moved by the finger on
+ /// the phone and only filled in by the program — the scrolling rows drawn from
+ /// rows already seen, the program kept a few rows ahead, and brought back to
+ /// the row on screen when the scroll is over. See `RemoteScrollMirror`. Takes
+ /// the place of [altBufferScrollAnimated]'s slide. False leaves the screen to
+ /// follow the program's redraws.
+ final bool altBufferScrollMirror;
+
/// AUTONOMOUS PATCH: the keyboard's buffer — and what it is composing — is
/// kept when [terminal] is replaced, for an embedder that replaces it only
/// with the next screen of the SAME stream (a keyframe), and gives another
@@ -297,6 +306,23 @@ class TerminalViewState extends State<TerminalView> {
if (render is RenderTerminal) render.expectRemoteScroll(lines);
}
+ /// AUTONOMOUS PATCH: what [TerminalView.altBufferScrollMirror] asks the
+ /// program to scroll through — the scroll handler's own pacing.
+ final _remoteScrollLink = RemoteScrollLink();
+
+ RenderTerminal? get _renderOrNull {
+ final render = _viewportKey.currentContext?.findRenderObject();
+ return render is RenderTerminal ? render : null;
+ }
+
+ void _mirrorScrollStart(double pixels) =>
+ _renderOrNull?.mirrorScrollStart(pixels);
+
+ bool _mirrorScrollTo(double pixels) =>
+ _renderOrNull?.mirrorScrollTo(pixels) ?? false;
+
+ void _mirrorScrollEnd() => _renderOrNull?.mirrorScrollEnd();
+
@override
void initState() {
_focusNode = widget.focusNode ?? FocusNode();
@@ -399,6 +425,8 @@ class TerminalViewState extends State<TerminalView> {
composingBacktrackCells: _composingBacktrackCells,
animateRemoteScroll: widget.altBufferScrollAnimated,
onRemoteScrollShift: widget.onAltBufferScrollShift,
+ mirrorRemoteScroll: widget.altBufferScrollMirror,
+ remoteScrollLink: _remoteScrollLink,
);
},
);
@@ -411,6 +439,10 @@ class TerminalViewState extends State<TerminalView> {
paced: widget.altBufferScrollPaced,
onWheelsSent:
widget.altBufferScrollAnimated ? _expectAltBufferScroll : null,
+ link: widget.altBufferScrollMirror ? _remoteScrollLink : null,
+ onScrollPosition: widget.altBufferScrollMirror ? _mirrorScrollTo : null,
+ onScrollStart: widget.altBufferScrollMirror ? _mirrorScrollStart : null,
+ onScrollEnd: widget.altBufferScrollMirror ? _mirrorScrollEnd : null,
getCellOffset: (offset) => renderTerminal.getCellOffset(offset),
getLineHeight: () => renderTerminal.lineHeight,
child: child,
@@ -964,6 +996,8 @@ class _TerminalView extends LeafRenderObjectWidget {
this.composingBacktrackCells = 0,
this.animateRemoteScroll = false,
this.onRemoteScrollShift,
+ this.mirrorRemoteScroll = false,
+ this.remoteScrollLink,
});
final Terminal terminal;
@@ -1002,6 +1036,10 @@ class _TerminalView extends LeafRenderObjectWidget {
final void Function(int rows)? onRemoteScrollShift;
+ final bool mirrorRemoteScroll;
+
+ final RemoteScrollLink? remoteScrollLink;
+
@override
RenderTerminal createRenderObject(BuildContext context) {
return RenderTerminal(
@@ -1025,6 +1063,8 @@ class _TerminalView extends LeafRenderObjectWidget {
devicePixelRatio: MediaQuery.maybeDevicePixelRatioOf(context) ?? 1.0,
animateRemoteScroll: animateRemoteScroll,
onRemoteScrollShift: onRemoteScrollShift,
+ mirrorRemoteScroll: mirrorRemoteScroll,
+ remoteScrollLink: remoteScrollLink,
);
}
@@ -1050,6 +1090,8 @@ class _TerminalView extends LeafRenderObjectWidget {
..composingBacktrackCells = composingBacktrackCells
..devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context) ?? 1.0
..animateRemoteScroll = animateRemoteScroll
- ..onRemoteScrollShift = onRemoteScrollShift;
+ ..onRemoteScrollShift = onRemoteScrollShift
+ ..mirrorRemoteScroll = mirrorRemoteScroll
+ ..remoteScrollLink = remoteScrollLink;
}
}
diff --git a/mobile/third_party/xterm/lib/src/ui/remote_scroll_mirror.dart b/mobile/third_party/xterm/lib/src/ui/remote_scroll_mirror.dart
new file mode 100644
index 000000000..88d348888
--- /dev/null
+++ b/mobile/third_party/xterm/lib/src/ui/remote_scroll_mirror.dart
@@ -0,0 +1,772 @@
+import 'dart:async';
+import 'dart:math' as math;
+
+import 'package:flutter/scheduler.dart';
+import 'package:xterm/src/core/buffer/line.dart';
+import 'package:xterm/src/core/cell.dart';
+import 'package:xterm/src/utils/circular_buffer.dart';
+import 'package:xterm/src/utils/input_trace.dart';
+
+/// AUTONOMOUS PATCH: a full-screen program's scroll, moved by the finger here
+/// and filled in by the program — `TerminalView.altBufferScrollMirror`.
+///
+/// ⚠️ **On the alternate screen the phone has no history to scroll.** The
+/// program (Claude Code's fullscreen renderer) holds it, and every step of a
+/// scroll is a wheel event out and a redraw back: drawn as it lands, the screen
+/// moves 50–150ms behind the finger, in steps as uneven as the link (measured
+/// on a phone, 2026-10-05). No easing of those steps feels like a native list.
+///
+/// So while a scroll runs, the rows that scroll — the program's own header and
+/// prompt rows stay as they are — are drawn from a document of rows kept here,
+/// at exactly where the finger puts them, every frame. The program is asked to
+/// scroll a few rows AHEAD of the finger ([_lead]), so the rows about to come
+/// into view are usually here before they are needed; each whole frame it draws
+/// is matched against the document ([_align]) and written into it. When the
+/// scroll is over the program is brought back to the row on screen, and drawing
+/// goes back to the live screen.
+///
+/// Coordinates: document row `d` is one row of the program's content. Screen
+/// row `i` of the program shows document row [_remote] + i; screen row `s` of
+/// the PHONE shows document row [display] + s, a fraction while the finger is
+/// between rows. [offset] is the distance between the two, in pixels.
+class RemoteScrollMirror {
+ RemoteScrollMirror({
+ required this.onFrame,
+ required this.requestLines,
+ required this.requestsIdle,
+ });
+
+ /// Something drawn from here moved: paint again.
+ final VoidCallback onFrame;
+
+ /// Ask the program to scroll [lines] rows — positive is down, towards newer
+ /// rows — through the scroll's pacing.
+ final void Function(int lines) requestLines;
+
+ /// Whether every row asked for has gone out and been answered.
+ final bool Function() requestsIdle;
+
+ /// How many rows the program is kept ahead of the finger, at most.
+ static const _lead = 10;
+
+ /// A match is believed only with at least this many rows agreeing on it…
+ static const _minAgree = 4;
+
+ /// …and at least this share of the rows that could show it.
+ static const _minAgreeShare = 0.35;
+
+ /// Rows kept either side of the program's screen.
+ static const _keepRows = 300;
+
+ /// How fast the screen catches up with the finger after being held at the
+ /// edge of what is known, in radians a second (a critically damped spring).
+ static const _omega = 40.0;
+
+ /// The longest the program gets to come back to the row on screen.
+ static const _settleLimit = Duration(milliseconds: 1500);
+
+ /// Ask again when the program has not moved for this long and nothing is out.
+ static const _resyncAfter = Duration(milliseconds: 120);
+
+ final _clock = Stopwatch()..start();
+
+ // The grid the document is in; any change and it is dropped.
+ int _rowCount = 0;
+ int _columns = 0;
+ double _lineHeight = 0;
+
+ /// The rows that scroll, as screen rows; null until a scroll has shown them.
+ int? _top;
+ int? _bottom;
+
+ /// What the program's screen showed last, one entry per screen row: what a
+ /// new frame is compared with.
+ List<_Row>? _lastFrame;
+
+ final _document = <int, _DocRow>{};
+ int _documentMin = 0;
+ int _documentMax = -1;
+
+ /// The document row of the program's screen row 0.
+ int _remote = 0;
+
+ /// The document row the program has been asked to show at its row 0.
+ int _requested = 0;
+ int _requestedAtMs = 0;
+ int _frameAtMs = 0;
+
+ bool _scrolling = false;
+ bool _active = false;
+ bool _settling = false;
+ Timer? _settleTimer;
+
+ double _anchorPixels = 0;
+ double _anchorRow = 0;
+ double _lastPixels = 0;
+
+ /// Where the finger puts document row 0 — fractional.
+ double _target = 0;
+ double _lastTarget = 0;
+ int _direction = 0;
+
+ /// How fast the finger — or the fling — was moving, in rows a second.
+ double _fingerVelocity = 0;
+ int _lastMoveMs = 0;
+
+ double _display = 0;
+ double _velocity = 0;
+ bool _chasing = false;
+ int? _tick;
+ Duration? _lastTick;
+
+ // Trace only.
+ int _framesAligned = 0;
+ int _framesLost = 0;
+ int _clampedUpdates = 0;
+ int _startedAtMs = 0;
+
+ /// Whether the rows that scroll are being drawn from here.
+ bool get isActive => _active;
+
+ int get top => _top ?? 0;
+
+ int get bottom => _bottom ?? -1;
+
+ /// The document row shown at the phone's screen row 0.
+ double get display => _display;
+
+ /// How far the program's rows are drawn from where the program has them —
+ /// what a cursor inside the scrolling rows moves by.
+ double get offset => (_remote - _display) * _lineHeight;
+
+ /// Document row [row], as last seen; null when it never has been.
+ BufferLine? rowAt(int row) => _document[row]?.line;
+
+ int get _nowMs => _clock.elapsedMilliseconds;
+
+ /// A scroll began with the scrollable at [pixels]; [screen]'s first
+ /// [rowCount] rows are what the program shows now.
+ void begin(
+ double pixels,
+ IndexAwareCircularBuffer<BufferLine> screen,
+ int rowCount,
+ double lineHeight,
+ ) {
+ if (_scrolling) return;
+ if (!_sameGrid(screen, rowCount, lineHeight)) {
+ _forget();
+ _takeGrid(screen, rowCount, lineHeight);
+ }
+ _scrolling = true;
+ _settling = false;
+ _settleTimer?.cancel();
+ _settleTimer = null;
+ _startedAtMs = _nowMs;
+ _framesAligned = 0;
+ _framesLost = 0;
+ _clampedUpdates = 0;
+ _resyncs = 0;
+ // The document may be from the last scroll; the screen may have moved
+ // since, under output. This frame says where it is now, or that it is gone.
+ _frame(screen, rowCount);
+ _anchorPixels = pixels;
+ _lastPixels = pixels;
+ _anchorRow = _active ? _display : _remote.toDouble();
+ _target = _anchorRow;
+ _lastTarget = _target;
+ // A scroll that catches the last one still settling keeps its books: rows
+ // asked for are still on their way.
+ if (!_active) _requested = _remote;
+ _direction = 0;
+ _fingerVelocity = 0;
+ _lastMoveMs = _nowMs;
+ if (!_active) _display = _remote.toDouble();
+ _activateIfReady();
+ inputTrace(
+ () => 'mirror: begin · ${_document.length} rows known'
+ ' (${_documentMin - _remote}..${_documentMax - _remote} from the screen)'
+ ' · scrolling rows ${_top ?? '?'}..${_bottom ?? '?'}',
+ );
+ }
+
+ /// The scrollable is at [pixels]: the finger, or a fling, moved.
+ void scrollTo(
+ double pixels,
+ IndexAwareCircularBuffer<BufferLine> screen,
+ int rowCount,
+ double lineHeight,
+ ) {
+ if (!_scrolling) begin(pixels, screen, rowCount, lineHeight);
+ if (!_scrolling || _lineHeight <= 0) return;
+ _lastPixels = pixels;
+ _lastTarget = _target;
+ _target = _anchorRow + (pixels - _anchorPixels) / _lineHeight;
+ final moved = _target - _lastTarget;
+ if (moved.abs() > 1e-6) _direction = moved > 0 ? 1 : -1;
+ final now = _nowMs;
+ final elapsed = now - _lastMoveMs;
+ if (elapsed >= 4) {
+ _fingerVelocity = moved * 1000 / elapsed;
+ _lastMoveMs = now;
+ }
+ _follow();
+ _requestRemote();
+ if (_active) onFrame();
+ }
+
+ /// The scroll is over: the finger is up and any fling has run out.
+ void end() {
+ if (!_scrolling) return;
+ _scrolling = false;
+ _direction = 0;
+ if (!_active) {
+ // Never shown from here: the program was only ever followed.
+ inputTrace(() => 'mirror: end · never shown from the document');
+ return;
+ }
+ _settling = true;
+ _target = _target.roundToDouble();
+ _settleTimer?.cancel();
+ _settleTimer = Timer(_settleLimit, _settleTimedOut);
+ // ⚠️ Glided to the whole row, never set there: the last step of a fling is
+ // often bigger than what is left to the row, and following exactly would
+ // jump it. Starting at the finger's own speed, so the scroll does not stop
+ // dead before it eases in.
+ if (!_chasing) {
+ _chasing = true;
+ _velocity = _fingerVelocity.clamp(-40.0, 40.0);
+ }
+ _requestRemote();
+ _scheduleTick();
+ }
+
+ /// A whole frame from the program: [screen]'s first [rowCount] rows.
+ void frame(
+ IndexAwareCircularBuffer<BufferLine> screen,
+ int rowCount,
+ double lineHeight,
+ ) {
+ if (!_scrolling && !_active) return;
+ if (!_sameGrid(screen, rowCount, lineHeight)) {
+ inputTrace(() => 'mirror: the grid changed — back to the live screen');
+ reset();
+ return;
+ }
+ _frame(screen, rowCount);
+ _activateIfReady();
+ if (!_active) {
+ // Still learning which rows scroll: the program follows the finger.
+ _requestRemote();
+ return;
+ }
+ _follow();
+ _requestRemote();
+ _checkSettled();
+ onFrame();
+ }
+
+ /// Everything dropped: the document, the scroll, the drawing from here.
+ void reset() {
+ final wasActive = _active;
+ _scrolling = false;
+ _settling = false;
+ _settleTimer?.cancel();
+ _settleTimer = null;
+ _cancelTick();
+ _active = false;
+ _chasing = false;
+ _velocity = 0;
+ _forget();
+ if (wasActive) onFrame();
+ }
+
+ void dispose() {
+ _settleTimer?.cancel();
+ _settleTimer = null;
+ _cancelTick();
+ _document.clear();
+ _lastFrame = null;
+ }
+
+ /* The document */
+
+ bool _sameGrid(
+ IndexAwareCircularBuffer<BufferLine> screen,
+ int rowCount,
+ double lineHeight,
+ ) =>
+ rowCount == _rowCount &&
+ lineHeight == _lineHeight &&
+ screen.length >= rowCount &&
+ rowCount > 0 &&
+ screen[0].length == _columns;
+
+ void _takeGrid(
+ IndexAwareCircularBuffer<BufferLine> screen,
+ int rowCount,
+ double lineHeight,
+ ) {
+ _rowCount = rowCount;
+ _lineHeight = lineHeight;
+ _columns = rowCount > 0 && screen.length > 0 ? screen[0].length : 0;
+ }
+
+ void _forget() {
+ _document.clear();
+ _documentMin = 0;
+ _documentMax = -1;
+ _lastFrame = null;
+ _top = null;
+ _bottom = null;
+ _remote = 0;
+ _requested = 0;
+ _rowCount = 0;
+ _columns = 0;
+ _lineHeight = 0;
+ }
+
+ /// Matches the screen against what is known, moves [_remote] by what it
+ /// finds, and writes the scrolling rows into the document.
+ void _frame(IndexAwareCircularBuffer<BufferLine> screen, int rowCount) {
+ if (screen.length < rowCount) return;
+ _frameAtMs = _nowMs;
+ final rows = [
+ for (var i = 0; i < rowCount; i++) _Row.of(screen[i]),
+ ];
+ final last = _lastFrame;
+ _lastFrame = rows;
+ if (last == null || last.length != rowCount) return;
+
+ // The rows that differ from the last frame where they stand.
+ final changed = <int>[
+ for (var i = 0; i < rowCount; i++)
+ if (!rows[i].blank && rows[i].signature != last[i].signature) i,
+ ];
+ final top = _top;
+ final bottom = _bottom;
+ final changedScrolling = top == null || bottom == null
+ ? changed.length
+ : changed.where((i) => i >= top && i <= bottom).length;
+ if (changedScrolling < 3) {
+ // Nothing that scrolls moved: a spinner, a prompt row, a cursor.
+ _store(screen);
+ return;
+ }
+
+ final shift = _align(rows, last, changed);
+ if (shift == null) {
+ _framesLost++;
+ _lost();
+ _store(screen);
+ return;
+ }
+ _framesAligned++;
+ _remote += shift.rows;
+ _widenScrollingRows(shift, rows, last);
+ _store(screen);
+ }
+
+ /// The shift that turned what is known into [rows] — [rows] screen row `i`
+ /// shows document row `_remote + shift + i` — or null when nothing is sure.
+ _Shift? _align(List<_Row> rows, List<_Row> last, List<int> changed) {
+ // The document, once there is one. Before it — the scrolling rows not yet
+ // known — the last frame stands in, every row of it; after, the last
+ // frame's own rows are in the document, and its fixed rows (a header, the
+ // prompt) are not content to match against.
+ final useLast = _top == null || _bottom == null;
+ int? known(int row) {
+ final kept = _document[row];
+ if (kept != null) return kept.signature;
+ if (!useLast) return null;
+ final i = row - _remote;
+ if (i >= 0 && i < last.length) return last[i].signature;
+ return null;
+ }
+
+ final expected = _requested - _remote;
+ final reach = _rowCount + 2 * _lead;
+ final scores = <({int rows, int agree, int share})>[];
+ for (var k = -reach; k <= reach; k++) {
+ if (k == 0) continue;
+ var agree = 0;
+ var comparable = 0;
+ for (final i in changed) {
+ final signature = known(_remote + k + i);
+ if (signature == null) continue;
+ comparable++;
+ if (signature == rows[i].signature) agree++;
+ }
+ if (agree >= _minAgree && agree >= comparable * _minAgreeShare) {
+ scores.add((rows: k, agree: agree, share: comparable));
+ }
+ }
+ if (scores.isEmpty) return null;
+ scores.sort((a, b) => b.agree.compareTo(a.agree));
+ final best = scores.first;
+ var chosen = best;
+ if (scores.length > 1 && scores[1].agree * 2 >= best.agree) {
+ // Repeated rows agree with more than one shift: the one nearest to what
+ // was asked for is the program's answer.
+ final close = scores.where((s) => s.agree * 10 >= best.agree * 8);
+ chosen = close.reduce(
+ (a, b) =>
+ (a.rows - expected).abs() <= (b.rows - expected).abs() ? a : b,
+ );
+ final rivals = scores.where(
+ (s) =>
+ s != chosen &&
+ (s.rows - expected).abs() == (chosen.rows - expected).abs() &&
+ s.agree * 10 >= best.agree * 8,
+ );
+ if (rivals.isNotEmpty) return null;
+ }
+ // The rows that moved with it: what bounds the scrolling rows.
+ var first = -1;
+ var lastRow = -1;
+ for (final i in changed) {
+ if (known(_remote + chosen.rows + i) == rows[i].signature) {
+ if (first < 0) first = i;
+ lastRow = i;
+ }
+ }
+ return _Shift(chosen.rows, first, lastRow);
+ }
+
+ /// The scrolling rows: those the shift moved, and next to them the rows that
+ /// came in with it — up to a row that stood still.
+ void _widenScrollingRows(_Shift shift, List<_Row> rows, List<_Row> last) {
+ bool stoodStill(int i) =>
+ !rows[i].blank && rows[i].signature == last[i].signature;
+ var top = shift.first;
+ var bottom = shift.last;
+ if (top < 0) return;
+ // Rows come in on the side the content moves away from.
+ for (var n = 0; n < shift.rows.abs() && top > 0; n++) {
+ if (shift.rows > 0 || stoodStill(top - 1)) break;
+ top--;
+ }
+ for (var n = 0; n < shift.rows.abs() && bottom < _rowCount - 1; n++) {
+ if (shift.rows < 0 || stoodStill(bottom + 1)) break;
+ bottom++;
+ }
+ final known = _top != null && _bottom != null;
+ var newTop = known ? math.min(_top!, top) : top;
+ var newBottom = known ? math.max(_bottom!, bottom) : bottom;
+ // A row at the edge that stood still while everything else moved is the
+ // program's own — a status line — and not part of what scrolls.
+ while (newTop < newBottom && stoodStill(newTop) && newTop < shift.first) {
+ newTop++;
+ }
+ while (
+ newBottom > newTop && stoodStill(newBottom) && newBottom > shift.last) {
+ newBottom--;
+ }
+ if (newTop != _top || newBottom != _bottom) {
+ inputTrace(() => 'mirror: scrolling rows $newTop..$newBottom');
+ }
+ _top = newTop;
+ _bottom = newBottom;
+ }
+
+ /// The program's scrolling rows into the document, at [_remote].
+ void _store(IndexAwareCircularBuffer<BufferLine> screen) {
+ final top = _top;
+ final bottom = _bottom;
+ if (top == null || bottom == null) return;
+ for (var i = top; i <= bottom; i++) {
+ final row = _remote + i;
+ final line = screen[i];
+ final kept = _document[row];
+ if (kept != null && kept.sameCells(line)) continue;
+ _document[row] = _DocRow.copyOf(line);
+ }
+ final first = _remote + top;
+ final last = _remote + bottom;
+ if (_documentMax < _documentMin) {
+ _documentMin = first;
+ _documentMax = last;
+ } else {
+ _documentMin = math.min(_documentMin, first);
+ _documentMax = math.max(_documentMax, last);
+ }
+ // Only what a scroll could come back to.
+ if (_documentMax - _documentMin > 2 * _keepRows + _rowCount) {
+ final low = _remote - _keepRows;
+ final high = _remote + _rowCount + _keepRows;
+ _document.removeWhere((row, _) => row < low || row > high);
+ _documentMin = math.max(_documentMin, low);
+ _documentMax = math.min(_documentMax, high);
+ }
+ }
+
+ /// The frame could not be placed: the program drew something else. What is
+ /// known is no longer worth anything; start again from this screen.
+ void _lost() {
+ inputTrace(() => 'mirror: frame not placed — starting again from it');
+ _document.clear();
+ _documentMin = 0;
+ _documentMax = -1;
+ final wasActive = _active;
+ _active = false;
+ _chasing = false;
+ _velocity = 0;
+ _remote = 0;
+ _requested = 0;
+ _display = 0;
+ if (_scrolling) {
+ // The finger carries on from this screen.
+ _anchorPixels = _lastPixels;
+ _anchorRow = 0;
+ _target = 0;
+ _lastTarget = 0;
+ } else {
+ _settling = false;
+ _settleTimer?.cancel();
+ _settleTimer = null;
+ }
+ if (wasActive) onFrame();
+ }
+
+ void _activateIfReady() {
+ if (_active || !_scrolling) return;
+ if (_top == null || _bottom == null || _lastFrame == null) return;
+ // From the live screen: what is drawn does not move on the switch.
+ _active = true;
+ _display = _remote.toDouble();
+ _velocity = 0;
+ _chasing = true;
+ _scheduleTick();
+ inputTrace(
+ () => 'mirror: drawing from the document · rows $_top..$_bottom'
+ ' · ${_nowMs - _startedAtMs}ms after the scroll began',
+ );
+ }
+
+ /* The screen */
+
+ /// Where the screen may be: everything it shows must be known.
+ double _clamp(double row) {
+ final top = _top ?? 0;
+ final bottom = _bottom ?? -1;
+ if (_documentMax < _documentMin) return _remote.toDouble();
+ final low = (_documentMin - top).toDouble();
+ final high = (_documentMax - bottom).toDouble();
+ if (high < low) return _remote.toDouble();
+ return row.clamp(low, high);
+ }
+
+ /// The screen to where the finger is — exactly, unless it is catching up.
+ void _follow() {
+ if (!_active) return;
+ final goal = _clamp(_target);
+ if (goal != _target) _clampedUpdates++;
+ if (!_chasing) {
+ final stride = (_target - _lastTarget).abs() + 1e-6;
+ if ((goal - _display).abs() <= stride) {
+ _display = goal;
+ return;
+ }
+ _chasing = true;
+ _velocity = 0;
+ }
+ _scheduleTick();
+ }
+
+ void _scheduleTick() {
+ if (_tick != null) return;
+ _tick = SchedulerBinding.instance.scheduleFrameCallback(_onTick);
+ }
+
+ void _cancelTick() {
+ final id = _tick;
+ if (id != null) SchedulerBinding.instance.cancelFrameCallbackWithId(id);
+ _tick = null;
+ _lastTick = null;
+ }
+
+ void _onTick(Duration timeStamp) {
+ _tick = null;
+ if (!_active) {
+ _lastTick = null;
+ return;
+ }
+ final last = _lastTick;
+ _lastTick = timeStamp;
+ final seconds = last == null
+ ? 1 / 60
+ : math.max(0, (timeStamp - last).inMicroseconds) / 1e6;
+ if (_chasing) {
+ // A critically damped spring towards the goal, solved exactly.
+ final goal = _clamp(_target);
+ final x = _display - goal;
+ final decay = math.exp(-_omega * seconds);
+ final u = _velocity + _omega * x;
+ final next = (x + u * seconds) * decay;
+ _velocity = (_velocity - _omega * u * seconds) * decay;
+ // Never beyond what is known, however the speed it started with carries
+ // it: a row past the document would be drawn as nothing.
+ final at = _clamp(goal + next);
+ if (at != goal + next) _velocity = 0;
+ _display = at;
+ if ((at - goal).abs() < 0.01 && _velocity.abs() < 0.5) {
+ _display = goal;
+ _velocity = 0;
+ _chasing = false;
+ }
+ onFrame();
+ }
+ _resyncIfStalled();
+ _checkSettled();
+ if (_active && (_chasing || _settling)) _scheduleTick();
+ }
+
+ /* The program */
+
+ /// The program asked to scroll to where the finger is, and a little ahead.
+ void _requestRemote() {
+ final lead = _scrolling && _active
+ ? math.min(_lead, ((_bottom ?? 0) - (_top ?? 0)) ~/ 3) * _direction
+ : 0;
+ // Settling, the row the screen is coming to rest on — not where it is
+ // on the way there.
+ final goal = (_settling ? _clamp(_target).round() : _target.round()) + lead;
+ final lines = goal - _requested;
+ if (lines == 0) return;
+ _requested = goal;
+ _requestedAtMs = _nowMs;
+ requestLines(lines);
+ }
+
+ /// Rows asked for and never answered — the program was at an end, or the
+ /// pacing let them go — leave the books wrong: start them again from where
+ /// the program is.
+ void _resyncIfStalled() {
+ if (_requested == _remote) return;
+ final now = _nowMs;
+ if (now - _frameAtMs < _resyncAfter.inMilliseconds) return;
+ if (now - _requestedAtMs < _resyncAfter.inMilliseconds) return;
+ if (!requestsIdle()) return;
+ if (_resyncs < _maxResyncs) {
+ _resyncs++;
+ _requested = _remote;
+ _requestRemote();
+ return;
+ }
+ if (!_settling) return;
+ // The program will not come to the row on screen — it scrolls in steps of
+ // its own, or it is at an end — so the screen goes to the program's row: a
+ // glide of a row or two, rather than a jump when the settle runs out.
+ inputTrace(
+ () => 'mirror: settling on the program\'s row $_remote'
+ ' (asked for ${_clamp(_target).round()})',
+ );
+ _requested = _remote;
+ _target = _remote.toDouble();
+ if (!_chasing) {
+ _chasing = true;
+ _velocity = 0;
+ }
+ _scheduleTick();
+ }
+
+ /// Asked again this many times at most in one scroll: a program at the top
+ /// of its history answers nothing, however often it is asked.
+ static const _maxResyncs = 3;
+ int _resyncs = 0;
+
+ void _checkSettled() {
+ if (!_active || !_settling || _chasing) return;
+ if (_display != _remote.toDouble()) return;
+ final took = _nowMs - _startedAtMs;
+ inputTrace(
+ () => 'mirror: done in ${took}ms · frames placed $_framesAligned,'
+ ' lost $_framesLost · held at the edge $_clampedUpdates times',
+ );
+ _settling = false;
+ _settleTimer?.cancel();
+ _settleTimer = null;
+ _active = false;
+ _cancelTick();
+ onFrame();
+ }
+
+ void _settleTimedOut() {
+ _settleTimer = null;
+ if (!_active || !_settling) return;
+ inputTrace(
+ () => 'mirror: the program did not come back to row'
+ ' ${_display.round()} (it is at $_remote) — showing where it is',
+ );
+ _settling = false;
+ _active = false;
+ _chasing = false;
+ _velocity = 0;
+ _display = _remote.toDouble();
+ _cancelTick();
+ onFrame();
+ }
+}
+
+/// One screen row, for matching: what it says, and whether it says anything.
+class _Row {
+ const _Row(this.signature, this.blank);
+
+ factory _Row.of(BufferLine line) {
+ final data = line.data;
+ final cells = line.length;
+ var hash = cells;
+ var blank = true;
+ for (var i = 0; i < cells; i++) {
+ var codePoint = data[i * 4 + 3] & CellContent.codepointMask;
+ if (codePoint == 0) codePoint = 0x20;
+ if (codePoint != 0x20) blank = false;
+ hash = 0x1fffffff & (hash * 31 + codePoint);
+ }
+ return _Row(hash, blank);
+ }
+
+ /// The characters the row shows — not their colours, which Claude Code
+ /// changes on a row as it scrolls (see `RemoteScrollAnimator._signature`).
+ final int signature;
+
+ final bool blank;
+}
+
+/// One row of the document: a copy of the line as it was drawn, kept while the
+/// program's screen moves on and writes over the original.
+class _DocRow {
+ _DocRow(this.line, this.signature);
+
+ factory _DocRow.copyOf(BufferLine source) {
+ final line = BufferLine(source.length)
+ ..copyFrom(source, 0, 0, source.length);
+ return _DocRow(line, _Row.of(line).signature);
+ }
+
+ final BufferLine line;
+ final int signature;
+
+ /// Whether [other] draws exactly this — every cell, colours included — so the
+ /// copy, and its recorded drawing, can stay.
+ bool sameCells(BufferLine other) {
+ if (other.length != line.length) return false;
+ final a = line.data;
+ final b = other.data;
+ final end = line.length * 4;
+ if (a.length < end || b.length < end) return false;
+ for (var i = 0; i < end; i++) {
+ if (a[i] != b[i]) return false;
+ }
+ return true;
+ }
+}
+
+/// [rows]: the program's screen row `i` now shows what document row
+/// `_remote + rows + i` held; [first]..[last]: the rows that agreed.
+class _Shift {
+ const _Shift(this.rows, this.first, this.last);
+
+ final int rows;
+ final int first;
+ final int last;
+}
diff --git a/mobile/third_party/xterm/lib/src/ui/render.dart b/mobile/third_party/xterm/lib/src/ui/render.dart
index 8d36065de..cab48de89 100644
--- a/mobile/third_party/xterm/lib/src/ui/render.dart
+++ b/mobile/third_party/xterm/lib/src/ui/render.dart
@@ -12,6 +12,8 @@ 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/remote_scroll_mirror.dart';
+import 'package:xterm/src/ui/scroll_handler.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';
@@ -42,7 +44,11 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
double devicePixelRatio = 1.0,
bool animateRemoteScroll = false,
void Function(int rows)? onRemoteScrollShift,
+ bool mirrorRemoteScroll = false,
+ RemoteScrollLink? remoteScrollLink,
}) : _terminal = terminal,
+ _mirrorRemoteScroll = mirrorRemoteScroll,
+ _remoteScrollLink = remoteScrollLink,
_devicePixelRatio = devicePixelRatio,
_animateRemoteScroll = animateRemoteScroll,
_onRemoteScrollShift = onRemoteScrollShift,
@@ -77,6 +83,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
// The recorded lines are the old emulator's: none of them is drawn again.
_painter.clearLinePictures();
_remoteScroll?.reset();
+ _mirror?.reset();
if (attached && _renderingEnabled) _terminal.addListener(_onTerminalChange);
_resizeTerminalIfNeeded();
markNeedsLayout();
@@ -127,6 +134,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
if (value == _renderingEnabled) return;
_renderingEnabled = value;
_remoteScroll?.reset();
+ _mirror?.reset();
if (attached) {
if (value) {
_terminal.addListener(_onTerminalChange);
@@ -143,6 +151,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
if (value == _painter.textStyle) return;
_painter.textStyle = value;
_remoteScroll?.reset();
+ _mirror?.reset();
markNeedsLayout();
}
@@ -150,6 +159,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
if (value == _painter.textScaler) return;
_painter.textScaler = value;
_remoteScroll?.reset();
+ _mirror?.reset();
markNeedsLayout();
}
@@ -157,6 +167,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
if (value == _painter.theme) return;
_painter.theme = value;
_remoteScroll?.reset();
+ _mirror?.reset();
markNeedsPaint();
}
@@ -256,7 +267,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
/// 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 ||
+ if (_mirrorRemoteScroll ||
+ !_animateRemoteScroll ||
!_renderingEnabled ||
!attached ||
!_isWholeAltScreen) {
@@ -275,6 +287,69 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
);
}
+ /// AUTONOMOUS PATCH: whether a full-screen program's scroll is moved by the
+ /// finger here and filled in by the program — `TerminalView.altBufferScrollMirror`,
+ /// see [RemoteScrollMirror]. In its place, [expectRemoteScroll]'s slide.
+ bool _mirrorRemoteScroll;
+ set mirrorRemoteScroll(bool value) {
+ if (value == _mirrorRemoteScroll) return;
+ _mirrorRemoteScroll = value;
+ _mirror?.dispose();
+ _mirror = null;
+ markNeedsPaint();
+ }
+
+ /// Where the mirror asks the program to scroll — the scroll handler's pacing.
+ RemoteScrollLink? _remoteScrollLink;
+ set remoteScrollLink(RemoteScrollLink? value) => _remoteScrollLink = value;
+
+ RemoteScrollMirror? _mirror;
+
+ RemoteScrollMirror get _mirrorNow => _mirror ??= RemoteScrollMirror(
+ onFrame: markNeedsPaint,
+ requestLines: (lines) => _remoteScrollLink?.send(lines),
+ requestsIdle: () => _remoteScrollLink?.idle ?? true,
+ );
+
+ bool get _canMirror =>
+ _mirrorRemoteScroll &&
+ _renderingEnabled &&
+ attached &&
+ hasSize &&
+ _painter.cellSize.height > 0 &&
+ _isWholeAltScreen;
+
+ /// AUTONOMOUS PATCH: a scroll began on the alternate screen, the scrollable at
+ /// [pixels].
+ void mirrorScrollStart(double pixels) {
+ if (!_canMirror) return;
+ _mirrorNow.begin(
+ pixels,
+ _terminal.buffer.lines,
+ _terminal.viewHeight,
+ _painter.cellSize.height,
+ );
+ }
+
+ /// AUTONOMOUS PATCH: the scrollable is at [pixels]. False when it cannot be
+ /// mirrored now — then the scroll goes out as plain wheel events.
+ bool mirrorScrollTo(double pixels) {
+ if (!_canMirror) {
+ _mirror?.reset();
+ return false;
+ }
+ _mirrorNow.scrollTo(
+ pixels,
+ _terminal.buffer.lines,
+ _terminal.viewHeight,
+ _painter.cellSize.height,
+ );
+ return true;
+ }
+
+ /// AUTONOMOUS PATCH: the scroll is over — the finger up, any fling run out.
+ void mirrorScrollEnd() => _mirror?.end();
+
/// AUTONOMOUS PATCH: a frame of the slide — drawn, unless a redraw is still
/// arriving.
///
@@ -296,6 +371,18 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
/// The screen was laid out again: a slide starts, carries on or ends here.
void _updateRemoteScroll() {
+ final mirror = _mirror;
+ if (mirror != null) {
+ if (!_isWholeAltScreen) {
+ mirror.reset();
+ } else {
+ mirror.frame(
+ _terminal.buffer.lines,
+ _terminal.viewHeight,
+ _painter.cellSize.height,
+ );
+ }
+ }
final animator = _remoteScroll;
if (animator == null) return;
if (!_isWholeAltScreen) {
@@ -372,6 +459,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
_controller.removeListener(_onControllerUpdate);
_focusNode.removeListener(_onFocusChange);
_remoteScroll?.reset();
+ _mirror?.reset();
}
@override
@@ -389,6 +477,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
void dispose() {
_remoteScroll?.dispose();
_remoteScroll = null;
+ _mirror?.dispose();
+ _mirror = null;
_painter.clearLinePictures();
super.dispose();
}
@@ -686,12 +776,20 @@ 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;
+ // AUTONOMOUS PATCH: a full-screen program's scroll, its scrolling rows drawn
+ // where the finger has them ([_paintMirror]) or still sliding into place
+ // ([_paintSlide]) — the rest as ever.
+ final mirror =
+ _mirror?.isActive == true && _isWholeAltScreen ? _mirror : null;
+ final slide = mirror == null && _remoteScroll?.isSliding == true
+ ? _remoteScroll
+ : null;
+ final movingTop = mirror?.top ?? slide?.top;
+ final movingBottom = mirror?.bottom ?? slide?.bottom;
+ final movedBy = mirror?.offset ?? slide?.offset ?? 0.0;
for (var i = effectFirstLine; i <= effectLastLine; i++) {
- if (slide != null && i >= slide.top && i <= slide.bottom) continue;
+ if (movingTop != null && i >= movingTop && i <= movingBottom!) continue;
_painter.paintLineCached(
canvas,
offset.translate(0, _snapLineTop(i * charHeight + _lineOffset)),
@@ -699,18 +797,19 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
);
}
- if (slide != null) {
+ if (mirror != null) {
+ _paintMirror(canvas, offset, mirror);
+ } else 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;
+ // A cursor inside the moving rows moves with them.
+ final cursorAt =
+ movingTop != null && cursorY >= movingTop && cursorY <= movingBottom!
+ ? offset + cursorOffset.translate(0, movedBy)
+ : offset + cursorOffset;
final predicting = !_isComposingText && _predictedText.isNotEmpty;
if (_isComposingText) {
@@ -756,6 +855,37 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
canvas.restore();
}
+ /// AUTONOMOUS PATCH: the scrolling rows as the finger has them — each document
+ /// row of [RemoteScrollMirror] at its place relative to [RemoteScrollMirror.display],
+ /// clipped to the rows that scroll so the program's fixed rows stay put. A row
+ /// never seen is left as background.
+ void _paintMirror(Canvas canvas, Offset offset, RemoteScrollMirror mirror) {
+ final lineHeight = _painter.cellSize.height;
+ final top = offset.dy + _snapLineTop(mirror.top * lineHeight + _lineOffset);
+ final bottom = offset.dy +
+ _snapLineTop((mirror.bottom + 1) * lineHeight + _lineOffset);
+ canvas.save();
+ canvas.clipRect(
+ Rect.fromLTRB(offset.dx, top, offset.dx + size.width, bottom),
+ );
+ final display = mirror.display;
+ final first = (display + mirror.top).floor();
+ final last = (display + mirror.bottom).ceil();
+ for (var row = first; row <= last; row++) {
+ final line = mirror.rowAt(row);
+ if (line == null) continue;
+ _painter.paintLineCached(
+ canvas,
+ offset.translate(
+ 0,
+ _snapLineTop((row - display) * lineHeight + _lineOffset),
+ ),
+ line,
+ );
+ }
+ 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
diff --git a/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart
index 892d4b1b8..d876b3801 100644
--- a/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart
+++ b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart
@@ -5,6 +5,35 @@ import 'package:flutter/widgets.dart';
import 'package:xterm/core.dart';
import 'package:xterm/src/ui/infinite_scroll_view.dart';
+/// AUTONOMOUS PATCH: how something other than the finger asks a full-screen
+/// program to scroll — `RemoteScrollMirror` keeping the program ahead of the
+/// finger — through the same pacing the finger's wheel events go through.
+class RemoteScrollLink {
+ void Function(int lines)? _send;
+ bool Function()? _idle;
+ Object? _owner;
+
+ /// Scroll the program [lines] rows, positive towards newer ones. Dropped when
+ /// no scroll handler is listening: the program is not on its alternate screen.
+ void send(int lines) => _send?.call(lines);
+
+ /// Whether every row asked for has gone out and been answered.
+ bool get idle => _idle?.call() ?? true;
+
+ void _attach(Object owner, void Function(int) send, bool Function() idle) {
+ _owner = owner;
+ _send = send;
+ _idle = idle;
+ }
+
+ void _detach(Object owner) {
+ if (!identical(_owner, owner)) return;
+ _owner = null;
+ _send = null;
+ _idle = null;
+ }
+}
+
/// Handles scrolling gestures in the alternate screen buffer. In alternate
/// screen buffer, the terminal don't have a scrollback buffer, instead, the
/// scroll gestures are converted to escape sequences based on the current
@@ -20,6 +49,10 @@ class TerminalScrollGestureHandler extends StatefulWidget {
this.physics,
this.paced = false,
this.onWheelsSent,
+ this.link,
+ this.onScrollPosition,
+ this.onScrollStart,
+ this.onScrollEnd,
required this.child,
});
@@ -57,6 +90,21 @@ class TerminalScrollGestureHandler extends StatefulWidget {
/// negative for up — see `TerminalView.altBufferScrollAnimated`.
final void Function(int lines)? onWheelsSent;
+ /// AUTONOMOUS PATCH: where something else sends its wheel lines in — see
+ /// [RemoteScrollLink].
+ final RemoteScrollLink? link;
+
+ /// AUTONOMOUS PATCH: offered the scroll's position first — true takes it, and
+ /// then it is not turned into wheel events here: `TerminalView.altBufferScrollMirror`,
+ /// where the mirror decides what the program is asked for (through [link]).
+ /// False — it cannot take it now — and the scroll goes out as wheels as ever.
+ final bool Function(double pixels)? onScrollPosition;
+
+ /// AUTONOMOUS PATCH: a scroll began, at the scrollable's [pixels]; and one
+ /// ended — the finger up and any fling run out.
+ final void Function(double pixels)? onScrollStart;
+ final VoidCallback? onScrollEnd;
+
final Widget child;
@override
@@ -99,16 +147,20 @@ class _TerminalScrollGestureHandlerState
void initState() {
widget.terminal.addListener(_onTerminalUpdated);
isAltBuffer = widget.terminal.isUsingAltBuffer;
+ widget.link?._attach(this, _queueLines, _pacingIdle);
super.initState();
}
@override
void dispose() {
widget.terminal.removeListener(_onTerminalUpdated);
+ widget.link?._detach(this);
_resetPacing();
super.dispose();
}
+ bool _pacingIdle() => _unsentLines == 0 && _batchesInFlight == 0;
+
@override
void didUpdateWidget(covariant TerminalScrollGestureHandler oldWidget) {
if (oldWidget.terminal != widget.terminal) {
@@ -119,6 +171,10 @@ class _TerminalScrollGestureHandlerState
} else if (!widget.paced) {
_resetPacing();
}
+ if (!identical(oldWidget.link, widget.link)) {
+ oldWidget.link?._detach(this);
+ widget.link?._attach(this, _queueLines, _pacingIdle);
+ }
super.didUpdateWidget(oldWidget);
}
@@ -170,6 +226,14 @@ class _TerminalScrollGestureHandlerState
void _onScroll(double offset) {
final currentLineOffset = offset ~/ widget.getLineHeight();
+ // AUTONOMOUS PATCH: the mirror moves the screen and asks the program for
+ // rows itself. Kept in step, so a switch back never sends the whole gap.
+ final onScrollPosition = widget.onScrollPosition;
+ if (onScrollPosition != null && onScrollPosition(offset)) {
+ lastLineOffset = currentLineOffset;
+ return;
+ }
+
final delta = currentLineOffset - lastLineOffset;
if (widget.paced) {
@@ -239,10 +303,24 @@ class _TerminalScrollGestureHandlerState
onPointerDown: (event) {
lastPointerPosition = event.position;
},
- child: InfiniteScrollView(
- onScroll: _onScroll,
- physics: widget.physics,
- child: widget.child,
+ child: NotificationListener<ScrollNotification>(
+ // AUTONOMOUS PATCH: where a scroll begins and ends — for
+ // [TerminalScrollGestureHandler.onScrollStart] and `onScrollEnd`. Only
+ // this scrollable's own, and passed on for the page to see as well.
+ onNotification: (notification) {
+ if (notification.depth != 0) return false;
+ if (notification is ScrollStartNotification) {
+ widget.onScrollStart?.call(notification.metrics.pixels);
+ } else if (notification is ScrollEndNotification) {
+ widget.onScrollEnd?.call();
+ }
+ return false;
+ },
+ child: InfiniteScrollView(
+ onScroll: _onScroll,
+ physics: widget.physics,
+ child: widget.child,
+ ),
),
);
}