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.

37.4 KB
Raw Blame
import 'dart:math' show max, min;
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/buffer/range.dart';
import 'package:xterm/src/core/buffer/segment.dart';
import 'package:xterm/src/core/mouse/button.dart';
import 'package:xterm/src/core/mouse/button_state.dart';
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/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';
import 'package:xterm/src/ui/terminal_theme.dart';
import 'package:xterm/src/utils/input_trace.dart';
import 'package:xterm/src/utils/unicode_v11.dart';

typedef EditableRectCallback = void Function(Rect rect, Rect caretRect);

class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
  RenderTerminal({
    required Terminal terminal,
    required TerminalController controller,
    required ViewportOffset offset,
    required EdgeInsets padding,
    required bool autoResize,
    bool resizeBuffer = true,
    bool renderingEnabled = true,
    required TerminalStyle textStyle,
    required TextScaler textScaler,
    required TerminalTheme theme,
    required FocusNode focusNode,
    required TerminalCursorType cursorType,
    required bool alwaysShowCursor,
    EditableRectCallback? onEditableRect,
    String? composingText,
    int composingBacktrackCells = 0,
    double devicePixelRatio = 1.0,
    bool animateRemoteScroll = false,
    void Function(int rows)? onRemoteScrollShift,
    bool mirrorRemoteScroll = false,
    bool mirrorPageKeys = false,
    RemoteScrollLink? remoteScrollLink,
    RemoteScrollMemory? remoteScrollMemory,
  })  : _terminal = terminal,
        _mirrorRemoteScroll = mirrorRemoteScroll,
        _mirrorPageKeys = mirrorPageKeys,
        _remoteScrollMemory = remoteScrollMemory,
        _remoteScrollLink = remoteScrollLink,
        _devicePixelRatio = devicePixelRatio,
        _animateRemoteScroll = animateRemoteScroll,
        _onRemoteScrollShift = onRemoteScrollShift,
        _controller = controller,
        _offset = offset,
        _padding = padding,
        _autoResize = autoResize,
        _resizeBuffer = resizeBuffer,
        _renderingEnabled = renderingEnabled,
        _focusNode = focusNode,
        _cursorType = cursorType,
        _alwaysShowCursor = alwaysShowCursor,
        _onEditableRect = onEditableRect,
        _composingText = composingText,
        _composingBacktrackCells = composingBacktrackCells,
        _painter = TerminalPainter(
          theme: theme,
          textStyle: textStyle,
          textScaler: textScaler,
        );

  Terminal _terminal;
  set terminal(Terminal terminal) {
    if (_terminal == terminal) return;
    if (attached && _renderingEnabled) {
      _terminal.removeListener(_onTerminalChange);
    }
    _terminal = terminal;
    _reportedViewportSize = null;
    _predictedText = '';
    _predictedCells = 0;
    // 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();
  }

  TerminalController _controller;
  set controller(TerminalController controller) {
    if (_controller == controller) return;
    if (attached) _controller.removeListener(_onControllerUpdate);
    _controller = controller;
    if (attached) _controller.addListener(_onControllerUpdate);
    markNeedsLayout();
  }

  ViewportOffset _offset;
  set offset(ViewportOffset value) {
    if (value == _offset) return;
    if (attached) _offset.removeListener(_onScroll);
    _offset = value;
    if (attached) _offset.addListener(_onScroll);
    markNeedsLayout();
  }

  EdgeInsets _padding;
  set padding(EdgeInsets value) {
    if (value == _padding) return;
    _padding = value;
    markNeedsLayout();
  }

  bool _autoResize;
  set autoResize(bool value) {
    if (value == _autoResize) return;
    _autoResize = value;
    markNeedsLayout();
  }

  bool _resizeBuffer;
  set resizeBuffer(bool value) {
    if (value == _resizeBuffer) return;
    _resizeBuffer = value;
    _reportedViewportSize = null;
    markNeedsLayout();
  }

  bool _renderingEnabled;
  set renderingEnabled(bool value) {
    if (value == _renderingEnabled) return;
    _renderingEnabled = value;
    _remoteScroll?.reset();
    _mirror?.reset();
    if (attached) {
      if (value) {
        _terminal.addListener(_onTerminalChange);
      } else {
        _terminal.removeListener(_onTerminalChange);
      }
    }
    // Catch up from the live buffer once, preserving follow-tail or the user's
    // scroll offset. Hidden output never queues a renderer layout or paint.
    if (value) markNeedsLayout();
  }

  set textStyle(TerminalStyle value) {
    if (value == _painter.textStyle) return;
    _painter.textStyle = value;
    _remoteScroll?.reset();
    _mirror?.reset();
    markNeedsLayout();
  }

  set textScaler(TextScaler value) {
    if (value == _painter.textScaler) return;
    _painter.textScaler = value;
    _remoteScroll?.reset();
    _mirror?.reset();
    markNeedsLayout();
  }

  set theme(TerminalTheme value) {
    if (value == _painter.theme) return;
    _painter.theme = value;
    _remoteScroll?.reset();
    _mirror?.reset();
    markNeedsPaint();
  }

  FocusNode _focusNode;
  set focusNode(FocusNode value) {
    if (value == _focusNode) return;
    if (attached) _focusNode.removeListener(_onFocusChange);
    _focusNode = value;
    if (attached) _focusNode.addListener(_onFocusChange);
    markNeedsPaint();
  }

  TerminalCursorType _cursorType;
  set cursorType(TerminalCursorType value) {
    if (value == _cursorType) return;
    _cursorType = value;
    markNeedsPaint();
  }

  bool _alwaysShowCursor;
  set alwaysShowCursor(bool value) {
    if (value == _alwaysShowCursor) return;
    _alwaysShowCursor = value;
    markNeedsPaint();
  }

  EditableRectCallback? _onEditableRect;
  set onEditableRect(EditableRectCallback? value) {
    if (value == _onEditableRect) return;
    _onEditableRect = value;
    markNeedsLayout();
  }

  String? _composingText;
  set composingText(String? value) {
    if (value == _composingText) return;
    _composingText = value;
    markNeedsPaint();
  }

  int _composingBacktrackCells;
  set composingBacktrackCells(int value) {
    if (value == _composingBacktrackCells) return;
    _composingBacktrackCells = value;
    markNeedsPaint();
  }

  /// AUTONOMOUS PATCH: what is typed and not yet echoed, drawn faint at the
  /// cursor — `TerminalView.predictsEcho`. Set by the view directly rather than
  /// through a rebuild: it changes with every key and every echo.
  String _predictedText = '';
  int _predictedCells = 0;
  set predictedText(String value) {
    if (value == _predictedText) return;
    _predictedText = value;
    var cells = 0;
    for (final rune in value.runes) {
      final width = unicodeV11.wcwidth(rune);
      if (width > 0) cells += width;
    }
    _predictedCells = cells;
    markNeedsPaint();
  }

  /// AUTONOMOUS PATCH: the screen's pixels per logical pixel — the grid each
  /// line's top is placed on, see [_snapLineTop].
  double _devicePixelRatio;
  set devicePixelRatio(double value) {
    if (value == _devicePixelRatio) return;
    _devicePixelRatio = value;
    markNeedsPaint();
  }

  /// 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 (_mirrorRemoteScroll ||
        !_animateRemoteScroll ||
        !_renderingEnabled ||
        !attached ||
        !_isWholeAltScreen) {
      return;
    }
    final animator = _remoteScroll ??= RemoteScrollAnimator(
      onFrame: _paintSlideFrame,
      takePicture: _painter.takeLinePicture,
      onShift: _onRemoteScrollShift,
    );
    animator.expect(
      lines,
      _terminal.buffer.lines,
      _terminal.viewHeight,
      _painter.cellSize.height,
    );
  }

  /// 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;

  /// AUTONOMOUS PATCH: whether the mirror may scroll the program a page at a
  /// time with its Page Up and Page Down keys — `TerminalView.altBufferScrollPageKeys`.
  bool _mirrorPageKeys;
  set mirrorPageKeys(bool value) => _mirrorPageKeys = value;

  /// AUTONOMOUS PATCH: what the mirror knew of this program's rows, kept by the
  /// embedder across emulators and views — `TerminalView.altBufferScrollMemory`.
  RemoteScrollMemory? _remoteScrollMemory;
  set remoteScrollMemory(RemoteScrollMemory? value) {
    if (identical(value, _remoteScrollMemory)) return;
    _remoteScrollMemory = value;
    _mirror?.memory = value;
  }

  RemoteScrollMirror? _mirror;

  /// The mirror drawing a full-screen program's scroll, if one was made — for a
  /// benchmark to compare where it draws the rows with where the finger is.
  @visibleForTesting
  RemoteScrollMirror? get debugRemoteScrollMirror => _mirror;

  /// The screen for the mirror to fetch ahead from, when it can be read whole.
  RemoteScreen? _mirrorScreen() {
    if (!_canMirror || _terminal.synchronizedOutputHeld) return null;
    return (
      lines: _terminal.buffer.lines,
      rowCount: _terminal.viewHeight,
      lineHeight: _painter.cellSize.height,
    );
  }

  RemoteScrollMirror get _mirrorNow => _mirror ??= _newMirror();

  RemoteScrollMirror _newMirror() => RemoteScrollMirror(
        onFrame: markNeedsPaint,
        requestLines: (lines) => _remoteScrollLink?.send(lines),
        requestsIdle: () => _remoteScrollLink?.idle ?? true,
        cancelRequests: () => _remoteScrollLink?.cancel() ?? 0,
        pageKeysEnabled: () => _mirrorPageKeys,
        requestPage: (direction, count) =>
            _mirrorPageKeys &&
            (_remoteScrollLink?.sendPage(direction, count: count) ?? false),
        readScreen: _mirrorScreen,
      )..memory = _remoteScrollMemory;

  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,
      screenWhole: !_terminal.synchronizedOutputHeld,
    );
  }

  /// 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,
      screenWhole: !_terminal.synchronizedOutputHeld,
    );
    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.
  ///
  /// ⚠️ **Not while the terminal holds a frame** ([Terminal.synchronizedOutputHeld]):
  /// its buffer is part old, part new, and the slide repaints every frame, so it
  /// drew exactly the torn screen the hold keeps from the listeners. The frame's
  /// end lays the terminal out and paints it anyway; the slide only loses the
  /// frames in between, a few milliseconds of them.
  void _paintSlideFrame() {
    if (_terminal.synchronizedOutputHeld) return;
    markNeedsPaint();
  }

  /// 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() {
    // A program whose page keys scroll it gets its mirror before the first
    // scroll: it fetches ahead from the start, its scrolling rows remembered
    // or read off its prompt box (`RemoteScrollMirror._seedScrollingRows`).
    if (_mirror == null &&
        _mirrorRemoteScroll &&
        _mirrorPageKeys &&
        _canMirror) {
      _mirrorNow;
    }
    final mirror = _mirror;
    if (mirror != null) {
      if (!_isWholeAltScreen) {
        mirror.reset();
      } else if (!_terminal.synchronizedOutputHeld) {
        // ⚠️ Never a frame still arriving: part old, part new, it was matched
        // and written into the mirror's document as one, and rows came out of
        // order (reported on a phone, 2026-10-06). Its end lays the screen out
        // again, whole.
        mirror.frame(
          _terminal.buffer.lines,
          _terminal.viewHeight,
          _painter.cellSize.height,
        );
      }
    }
    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;

  final TerminalPainter _painter;

  var _stickToBottom = true;
  double _laidOutMaxScrollExtent = 0;
  bool _editableRectPending = false;

  void _onScroll() {
    // Output may already have extended the buffer since the last layout. The
    // scroll position still describes that layout, so comparing it to the live
    // buffer would mistake a jump to the tail for scrolling up into history.
    _stickToBottom = _scrollOffset >= _laidOutMaxScrollExtent - 0.5;
    if (!_renderingEnabled) return;
    markNeedsLayout();
    _scheduleEditableRect();
  }

  /// Resolve the tail against the buffer and viewport of the next layout,
  /// rather than jumping to a ScrollPosition extent from the previous frame.
  void scrollToBottom() {
    final needsLayout = !_stickToBottom ||
        !hasSize ||
        (_maxScrollExtent - _scrollOffset).abs() > 0.5;
    _stickToBottom = true;
    if (_renderingEnabled && needsLayout) markNeedsLayout();
  }

  void _onFocusChange() {
    markNeedsPaint();
    _scheduleEditableRect();
  }

  void _onTerminalChange() {
    markNeedsLayout();
    _scheduleEditableRect();
  }

  void _onControllerUpdate() {
    if (_renderingEnabled) markNeedsLayout();
  }

  @override
  final isRepaintBoundary = true;

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    _offset.addListener(_onScroll);
    if (_renderingEnabled) _terminal.addListener(_onTerminalChange);
    _controller.addListener(_onControllerUpdate);
    _focusNode.addListener(_onFocusChange);
  }

  @override
  void detach() {
    super.detach();
    _offset.removeListener(_onScroll);
    _terminal.removeListener(_onTerminalChange);
    _controller.removeListener(_onControllerUpdate);
    _focusNode.removeListener(_onFocusChange);
    _remoteScroll?.reset();
    _mirror?.reset();
  }

  @override
  bool hitTestSelf(Offset position) {
    return true;
  }

  @override
  void systemFontsDidChange() {
    _painter.clearFontCache();
    super.systemFontsDidChange();
  }

  @override
  void dispose() {
    _remoteScroll?.dispose();
    _remoteScroll = null;
    _mirror?.dispose();
    _mirror = null;
    _painter.clearLinePictures();
    super.dispose();
  }

  @override
  void performLayout() {
    size = constraints.biggest;
    if (!_renderingEnabled) return;

    final followTail = _stickToBottom;
    _updateViewportSize();

    if (followTail) {
      // Correct before publishing the dimensions. A terminal redraw may empty
      // its history for one frame; publishing that short extent while pixels
      // still points into the old history starts a macOS bounce to the top.
      // That animation would keep scrolling even as the next output refills it.
      _offset.correctBy(_maxScrollExtent - _scrollOffset);
    }
    _updateScrollOffset();
    if (followTail) _stickToBottom = true;
    _laidOutMaxScrollExtent = _maxScrollExtent;
    _updateRemoteScroll();
    _scheduleEditableRect();
  }

  /// Total height of the terminal in pixels. Includes scrollback buffer.
  double get _terminalHeight =>
      _terminal.buffer.lines.length * _painter.cellSize.height;

  /// The distance from the top of the terminal to the top of the viewport.
  // double get _scrollOffset => _offset.pixels;
  double get _scrollOffset {
    // return _offset.pixels ~/ _painter.cellSize.height * _painter.cellSize.height;
    return _offset.pixels;
  }

  /// The height of a terminal line in pixels. This includes the line spacing.
  /// Height of the entire terminal is expected to be a multiple of this value.
  double get lineHeight => _painter.cellSize.height;

  /// Get the top-left corner of the cell at [cellOffset] in pixels.
  Offset getOffset(CellOffset cellOffset) {
    final row = cellOffset.y;
    final col = cellOffset.x;
    final x = col * _painter.cellSize.width;
    final y = row * _painter.cellSize.height;
    return Offset(x + _padding.left, y + _padding.top - _scrollOffset);
  }

  /// Get the [CellOffset] of the cell that [offset] is in.
  CellOffset getCellOffset(Offset offset) {
    final x = offset.dx - _padding.left;
    final y = offset.dy - _padding.top + _scrollOffset;
    final row = y ~/ _painter.cellSize.height;
    final col = x ~/ _painter.cellSize.width;
    return CellOffset(
      col.clamp(0, _terminal.viewWidth - 1),
      row.clamp(0, _terminal.buffer.lines.length - 1),
    );
  }

  /// Selects entire words in the terminal that contains [from] and [to].
  void selectWord(Offset from, [Offset? to]) {
    final fromOffset = getCellOffset(from);
    final fromBoundary = _terminal.buffer.getWordBoundary(fromOffset);
    if (fromBoundary == null) return;
    if (to == null) {
      _controller.setSelection(
        _terminal.buffer.createAnchorFromOffset(fromBoundary.begin),
        _terminal.buffer.createAnchorFromOffset(fromBoundary.end),
        mode: SelectionMode.line,
      );
    } else {
      final toOffset = getCellOffset(to);
      final toBoundary = _terminal.buffer.getWordBoundary(toOffset);
      if (toBoundary == null) return;
      final range = fromBoundary.merge(toBoundary);
      _controller.setSelection(
        _terminal.buffer.createAnchorFromOffset(range.begin),
        _terminal.buffer.createAnchorFromOffset(range.end),
        mode: SelectionMode.line,
      );
    }
  }

  /// Selects characters in the terminal that starts from [from] to [to]. At
  /// least one cell is selected even if [from] and [to] are same.
  void selectCharacters(Offset from, [Offset? to]) {
    final fromPosition = getCellOffset(from);
    if (to == null) {
      _controller.setSelection(
        _terminal.buffer.createAnchorFromOffset(fromPosition),
        _terminal.buffer.createAnchorFromOffset(fromPosition),
      );
    } else {
      var toPosition = getCellOffset(to);
      if (toPosition.x >= fromPosition.x) {
        toPosition = CellOffset(toPosition.x + 1, toPosition.y);
      }
      _controller.setSelection(
        _terminal.buffer.createAnchorFromOffset(fromPosition),
        _terminal.buffer.createAnchorFromOffset(toPosition),
      );
    }
  }

  /// Send a mouse event at [offset] with [button] being currently in [buttonState].
  bool mouseEvent(
    TerminalMouseButton button,
    TerminalMouseButtonState buttonState,
    Offset offset,
  ) {
    final position = getCellOffset(offset);
    return _terminal.mouseInput(button, buttonState, position);
  }

  /// Layout can change the scroll offset and ancestors can move this view.
  /// Report the final caret once per frame, including when a retained view
  /// returns without fresh output. Unfocused terminals have no native caret.
  void _scheduleEditableRect() {
    if (_editableRectPending ||
        !attached ||
        !_renderingEnabled ||
        !_focusNode.hasFocus ||
        _onEditableRect == null) {
      return;
    }
    _editableRectPending = true;
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _editableRectPending = false;
      if (!attached || !_renderingEnabled || !_focusNode.hasFocus || !hasSize) {
        return;
      }
      _notifyEditableRect();
    });
  }

  void _notifyEditableRect() {
    final cursor = localToGlobal(cursorOffset);

    final rect = Rect.fromLTRB(
      cursor.dx,
      cursor.dy,
      size.width,
      cursor.dy + _painter.cellSize.height,
    );

    final caretRect = cursor & _painter.cellSize;

    _onEditableRect?.call(rect, caretRect);
  }

  /// Update the viewport size in cells based on the current widget size in
  /// pixels.
  void _updateViewportSize() {
    if (size <= _painter.cellSize) {
      return;
    }

    final viewportSize = TerminalSize(
      size.width ~/ _painter.cellSize.width,
      _viewportHeight ~/ _painter.cellSize.height,
    );

    if (_viewportSize != viewportSize) {
      _viewportSize = viewportSize;
    }
    // A retained view may have received a replacement screen while hidden,
    // even when its own pixel dimensions did not change.
    _resizeTerminalIfNeeded();
  }

  /// Notify the underlying terminal that the viewport size has changed.
  void _resizeTerminalIfNeeded() {
    if (_renderingEnabled &&
        _autoResize &&
        !_resizeBuffer &&
        _viewportSize != null &&
        _reportedViewportSize != _viewportSize) {
      _reportedViewportSize = _viewportSize;
      // Shrinking a captured TUI locally can discard its latest rows when
      // its cursor is parked near the top. Keep the authoritative remote
      // cells while requesting a new grid; the next keyframe replaces them.
      _terminal.onResize?.call(
        _viewportSize!.width,
        _viewportSize!.height,
        _painter.cellSize.width.round(),
        _painter.cellSize.height.round(),
      );
      return;
    }
    if (_renderingEnabled &&
        _autoResize &&
        _resizeBuffer &&
        _viewportSize != null &&
        (_terminal.viewWidth != _viewportSize!.width ||
            _terminal.viewHeight != _viewportSize!.height)) {
      _terminal.resize(
        _viewportSize!.width,
        _viewportSize!.height,
        _painter.cellSize.width.round(),
        _painter.cellSize.height.round(),
      );
    }
  }

  /// Update the scroll offset based on the current terminal state. This should
  /// be called in [performLayout] after the viewport size has been updated.
  void _updateScrollOffset() {
    _offset.applyViewportDimension(_viewportHeight);
    _offset.applyContentDimensions(0, _maxScrollExtent);
  }

  bool get _isComposingText {
    return _composingText != null && _composingText!.isNotEmpty;
  }

  bool get _shouldShowCursor {
    return _terminal.cursorVisibleMode || _alwaysShowCursor || _isComposingText;
  }

  double get _viewportHeight {
    return size.height - _padding.vertical;
  }

  double get _maxScrollExtent {
    return max(_terminalHeight - _viewportHeight, 0.0);
  }

  double get _lineOffset {
    return -_scrollOffset + _padding.top;
  }

  /// The offset of the cursor from the top left corner of this render object.
  Offset get cursorOffset {
    return Offset(
      _terminal.buffer.cursorX * _painter.cellSize.width,
      _terminal.buffer.absoluteCursorY * _painter.cellSize.height + _lineOffset,
    );
  }

  Size get cellSize {
    return _painter.cellSize;
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    if (xtermInputTrace == null) {
      _paint(context, offset);
    } else {
      final recordedBefore = _painter.linesRecorded;
      final watch = Stopwatch()..start();
      _paint(context, offset);
      final micros = watch.elapsedMicroseconds;
      final redrawn = _painter.linesRecorded - recordedBefore;
      if (redrawn > 0 || micros > 4000) {
        inputTrace(
          () => 'paint ${(micros / 1000).toStringAsFixed(1)}ms'
              ' redrawn=$redrawn cursor=${_terminal.buffer.cursorX},'
              '${_terminal.buffer.absoluteCursorY}',
        );
      }
    }
    context.setWillChangeHint();
  }

  void _paint(PaintingContext context, Offset offset) {
    final canvas = context.canvas;

    // A terminal cell with the default background deliberately does not paint
    // its own fill (see TerminalPainter.paintCellBackground). That is fine
    // only when another paint pass has already cleared this layer. During an
    // incremental terminal/IME repaint it has not: old composition underlines,
    // cursors and glyphs survive until a full widget rebuild. Own the entire
    // render region here so every frame starts from the current app/terminal
    // background, then clip all terminal drawing to that region.
    final paintBounds = offset & size;
    canvas.save();
    canvas.clipRect(paintBounds);
    canvas.drawRect(
      paintBounds,
      Paint()..color = _painter.theme.background,
    );

    final lines = _terminal.buffer.lines;
    final charHeight = _painter.cellSize.height;

    final firstLineOffset = _scrollOffset - _padding.top;
    final lastLineOffset = _scrollOffset + size.height + _padding.bottom;

    final firstLine = firstLineOffset ~/ charHeight;
    final lastLine = lastLineOffset ~/ charHeight;

    final effectFirstLine = firstLine.clamp(0, lines.length - 1);
    final effectLastLine = lastLine.clamp(0, lines.length - 1);

    // 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 (movingTop != null && i >= movingTop && i <= movingBottom!) continue;
      _painter.paintLineCached(
        canvas,
        offset.translate(0, _snapLineTop(i * charHeight + _lineOffset)),
        // The program's own rows as they were, while the mirror fetches ahead.
        mirror?.heldRow(i) ?? lines[i],
      );
    }

    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 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) {
        _paintComposingText(canvas, cursorAt);
      } else if (predicting) {
        _paintPredictedText(canvas, cursorAt);
      }

      if (_shouldShowCursor) {
        _painter.paintCursor(
          canvas,
          // Past what is drawn ahead of the echo, where the echo will leave it.
          predicting
              ? cursorAt.translate(
                  _predictedCells * _painter.cellSize.width,
                  0,
                )
              : cursorAt,
          cursorType: _cursorType,
          hasFocus: _focusNode.hasFocus,
        );
      }
    }

    _paintHighlights(
      canvas,
      offset,
      _controller.highlights,
      effectFirstLine,
      effectLastLine,
    );

    if (_controller.selection != null) {
      _paintSelection(
        canvas,
        offset,
        _controller.selection!,
        effectFirstLine,
        effectLastLine,
      );
    }

    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
  /// 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 three
  /// device pixels: a slow scroll moved the text in visible three-pixel steps,
  /// holding still for frames in between, while the finger moved smoothly. On
  /// the device grid it moves a pixel at a time and stays as crisp.
  double _snapLineTop(double y) {
    final ratio = _devicePixelRatio;
    if (ratio <= 0) return y.truncateToDouble();
    return (y * ratio).roundToDouble() / ratio;
  }

  /// Paints the text that is currently being composed in IME to [canvas] at
  /// [offset]. [offset] is usually the cursor position.
  void _paintComposingText(Canvas canvas, Offset offset) {
    final composingText = _composingText;
    if (composingText == null) {
      return;
    }

    var startColumn = _terminal.buffer.cursorX - _composingBacktrackCells;
    var startLine = _terminal.buffer.absoluteCursorY;
    while (startColumn < 0 && startLine > 0) {
      startColumn += _terminal.viewWidth;
      startLine--;
    }
    final renderOrigin = offset - cursorOffset;
    final composingOffset = renderOrigin +
        Offset(
          startColumn.clamp(0, _terminal.viewWidth - 1).toDouble() *
              _painter.cellSize.width,
          startLine * _painter.cellSize.height + _lineOffset,
        );

    final style = _painter.textStyle.toTextStyle(
      color: _painter.resolveForegroundColor(_terminal.cursor.foreground),
      backgroundColor: _painter.theme.background,
      // Native macOS input can mark an entire uncommitted terminal buffer,
      // even with Telex disabled. Underlining that buffer makes ordinary input
      // look like a rendering artifact and does not match Terminal.app.
      underline: false,
    );

    // Do not use ParagraphBuilder with an empty placeholder for the leading
    // terminal cells. On macOS that run can retain the platform marked-text
    // decoration (a grey underline), despite the TextStyle above explicitly
    // selecting TextDecoration.none. Paint only the pre-edit run at its cell
    // position so an IME remains visible without styling ordinary terminal
    // input as marked/underlined text.
    final textPainter = TextPainter(
      text: TextSpan(
        text: composingText,
        style: style.copyWith(
          decoration: TextDecoration.none,
          decorationColor: const Color(0x00000000),
        ),
      ),
      textDirection: TextDirection.ltr,
      textScaler: _painter.textScaler,
    )..layout(
        maxWidth: (size.width - composingOffset.dx).clamp(0.0, size.width));

    textPainter.paint(canvas, composingOffset);
    textPainter.dispose();
  }

  /// AUTONOMOUS PATCH: [_predictedText] at [offset], the cursor — in the
  /// cursor's colour, faint, over the cells it will be echoed into.
  void _paintPredictedText(Canvas canvas, Offset offset) {
    final color = _painter.resolveForegroundColor(_terminal.cursor.foreground);
    final style = _painter.textStyle.toTextStyle(
      color: color.withAlpha((color.a * 255 * 0.55).round()),
      backgroundColor: _painter.theme.background,
      underline: false,
    );
    final textPainter = TextPainter(
      text: TextSpan(
        text: _predictedText,
        style: style.copyWith(
          decoration: TextDecoration.none,
          decorationColor: const Color(0x00000000),
        ),
      ),
      textDirection: TextDirection.ltr,
      textScaler: _painter.textScaler,
    )..layout(maxWidth: (size.width - offset.dx).clamp(0.0, size.width));
    textPainter.paint(canvas, offset);
    textPainter.dispose();
  }

  void _paintSelection(
    Canvas canvas,
    Offset offset,
    BufferRange selection,
    int firstLine,
    int lastLine,
  ) {
    for (final segment in selection.toSegments()) {
      if (segment.line >= _terminal.buffer.lines.length) {
        break;
      }

      if (segment.line < firstLine) {
        continue;
      }

      if (segment.line > lastLine) {
        break;
      }

      _paintSegment(canvas, offset, segment, _painter.theme.selection);
    }
  }

  void _paintHighlights(
    Canvas canvas,
    Offset offset,
    List<TerminalHighlight> highlights,
    int firstLine,
    int lastLine,
  ) {
    for (var highlight in _controller.highlights) {
      final range = highlight.range?.normalized;

      if (range == null ||
          range.begin.y > lastLine ||
          range.end.y < firstLine) {
        continue;
      }

      for (var segment in range.toSegments()) {
        if (segment.line < firstLine) {
          continue;
        }

        if (segment.line > lastLine) {
          break;
        }

        _paintSegment(canvas, offset, segment, highlight.color);
      }
    }
  }

  // The render box's own paint offset (e.g. from an ancestor Padding) must be added here just like
  // paintLine/paintCursor already do — this was missing, so a selection/highlight rect was drawn in
  // the wrong place whenever this box's offset was non-zero, leaving trailing selected characters
  // rendered outside the highlighted box instead of inside it.
  @pragma('vm:prefer-inline')
  void _paintSegment(
    Canvas canvas,
    Offset offset,
    BufferSegment segment,
    Color color,
  ) {
    final start = segment.start ?? 0;
    final end = segment.end ?? _terminal.viewWidth;

    final startOffset = offset.translate(
      start * _painter.cellSize.width,
      segment.line * _painter.cellSize.height + _lineOffset,
    );

    _painter.paintHighlight(canvas, startOffset, end - start, color);
  }
}