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.

25.6 KB
Raw Blame
import 'dart:async';
import 'dart:math' show max;
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/cell.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/prompt_placeholder.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/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,
    Duration? outputRepaintInterval,
    required TerminalStyle textStyle,
    required TextScaler textScaler,
    required TerminalTheme theme,
    bool fillsBackground = true,
    required FocusNode focusNode,
    required TerminalCursorType cursorType,
    required bool alwaysShowCursor,
    EditableRectCallback? onEditableRect,
    String? composingText,
    int composingBacktrackCells = 0,
  })  : _terminal = terminal,
        _controller = controller,
        _offset = offset,
        _padding = padding,
        _autoResize = autoResize,
        _resizeBuffer = resizeBuffer,
        _renderingEnabled = renderingEnabled,
        _outputRepaintInterval = outputRepaintInterval,
        _focusNode = focusNode,
        _cursorType = cursorType,
        _alwaysShowCursor = alwaysShowCursor,
        _onEditableRect = onEditableRect,
        _composingText = composingText,
        _composingBacktrackCells = composingBacktrackCells,
        _fillsBackground = fillsBackground,
        _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;
    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;
    if (!value) {
      _outputRepaintTimer?.cancel();
      _outputRepaintTimer = null;
      // A hidden tile draws nothing, so it holds no recorded lines either.
      _painter.clearLineCache();
    }
    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();
  }

  Duration? _outputRepaintInterval;
  Timer? _outputRepaintTimer;

  set outputRepaintInterval(Duration? value) {
    if (value == _outputRepaintInterval) return;
    _outputRepaintInterval = value;
    _outputRepaintTimer?.cancel();
    _outputRepaintTimer = null;
    // A focused tile resumes immediately even if its former background timer
    // was waiting; there may be no later output chunk to wake it up.
    if (value == null && attached && _renderingEnabled) markNeedsLayout();
  }

  set textStyle(TerminalStyle value) {
    if (value == _painter.textStyle) return;
    _painter.textStyle = value;
    markNeedsLayout();
  }

  set textScaler(TextScaler value) {
    if (value == _painter.textScaler) return;
    _painter.textScaler = value;
    markNeedsLayout();
  }

  set theme(TerminalTheme value) {
    if (value == _painter.theme) return;
    _painter.theme = value;
    markNeedsPaint();
  }

  /// Whether each frame opens with a solid fill in the theme's background.
  /// False while [TerminalView.backgroundOpacity] is below 1: the view's own
  /// translucent fill sits underneath, and a solid one here would hide what
  /// shows through it. This render object is a repaint boundary, so its layer
  /// is re-recorded from empty on every paint either way.
  bool _fillsBackground;
  set fillsBackground(bool value) {
    if (value == _fillsBackground) return;
    _fillsBackground = value;
    markNeedsPaint();
  }

  set devicePixelRatio(double value) {
    if (value == _painter.devicePixelRatio) return;
    _painter.devicePixelRatio = value;
    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();
  }

  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() {
    final interval = _outputRepaintInterval;
    if (interval != null && interval > Duration.zero) {
      if (_outputRepaintTimer?.isActive ?? false) return;
      _outputRepaintTimer = Timer(interval, () {
        _outputRepaintTimer = null;
        if (!attached || !_renderingEnabled) return;
        markNeedsLayout();
        _scheduleEditableRect();
      });
      return;
    }
    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() {
    _outputRepaintTimer?.cancel();
    _outputRepaintTimer = null;
    _painter.clearLineCache();
    super.detach();
    _offset.removeListener(_onScroll);
    _terminal.removeListener(_onTerminalChange);
    _controller.removeListener(_onControllerUpdate);
    _focusNode.removeListener(_onFocusChange);
  }

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

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

  @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;
    _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;
  }

  /// The colour a cell's foreground word paints in under the current theme.
  Color resolveForegroundColor(int cellColor) {
    return _painter.resolveForegroundColor(cellColor);
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    _paint(context, offset);
    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);
    if (_fillsBackground) {
      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);

    // Unchanged lines replay their recorded drawing; only lines written since
    // the last frame are drawn cell by cell (see LinePictureCache).
    _painter.beginFrame();
    for (var i = effectFirstLine; i <= effectLastLine; i++) {
      _painter.paintLineCached(
        canvas,
        offset.translate(0, (i * charHeight + _lineOffset).truncateToDouble()),
        lines[i],
      );
    }
    _painter.endFrame();

    if (_terminal.buffer.absoluteCursorY >= effectFirstLine &&
        _terminal.buffer.absoluteCursorY <= effectLastLine) {
      final caret = _isComposingText
          ? _paintComposingText(canvas, offset + cursorOffset)
          : offset + cursorOffset;

      if (_shouldShowCursor) {
        _painter.paintCursor(
          canvas,
          caret,
          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();
  }

  /// Paints the text that is currently being composed in IME to [canvas] at
  /// [offset], usually the cursor position, and returns where the caret
  /// belongs: after it, as in any text field. Left at the cursor, the block
  /// covered the preview's first character — a lone Telex `a`, still
  /// composing until the next key, looked like nothing had been typed.
  Offset _paintComposingText(Canvas canvas, Offset offset) {
    final composingText = _composingText;
    if (composingText == null) {
      return offset;
    }

    var startColumn = _terminal.buffer.cursorX - _composingBacktrackCells;
    var startLine = _terminal.buffer.absoluteCursorY;
    while (startColumn < 0 && startLine > 0) {
      startColumn += _terminal.viewWidth;
      startLine--;
    }
    final lastColumn = _terminal.viewWidth - 1;
    final firstColumn = startColumn.clamp(0, lastColumn);
    final renderOrigin = offset - cursorOffset;
    Offset cellOffset(int column) =>
        renderOrigin +
        Offset(
          column * _painter.cellSize.width,
          startLine * _painter.cellSize.height + _lineOffset,
        );
    final composingOffset = cellOffset(firstColumn);
    final caret = cellOffset(
      (firstColumn + runesCells(composingText.runes)).clamp(0, lastColumn),
    );

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

    _coverPromptPlaceholder(canvas, renderOrigin);
    textPainter.paint(canvas, composingOffset);
    textPainter.dispose();
    return caret;
  }

  /// Hides a prompt's dim placeholder behind an input-method preview, as the
  /// program will once the typed text echoes (see [promptPlaceholderEnd]).
  void _coverPromptPlaceholder(Canvas canvas, Offset renderOrigin) {
    final buffer = _terminal.buffer;
    final lineIndex = buffer.absoluteCursorY;
    final line = buffer.lines[lineIndex];
    final end = promptPlaceholderEnd(line, buffer.cursorX);
    final cell = CellData.empty();
    final top = lineIndex * _painter.cellSize.height + _lineOffset;
    for (var column = buffer.cursorX; column < end; column++) {
      line.getCellData(column, cell);
      _painter.paintCellCover(
        canvas,
        renderOrigin + Offset(column * _painter.cellSize.width, top),
        cell,
      );
    }
  }

  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);
  }
}