Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
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/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/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';
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,
}) : _terminal = terminal,
_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;
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 (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;
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();
}
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() {
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);
}
@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;
}
@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);
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);
for (var i = effectFirstLine; i <= effectLastLine; i++) {
_painter.paintLine(
canvas,
offset.translate(0, (i * charHeight + _lineOffset).truncateToDouble()),
lines[i],
);
}
if (_terminal.buffer.absoluteCursorY >= effectFirstLine &&
_terminal.buffer.absoluteCursorY <= effectLastLine) {
if (_isComposingText) {
_paintComposingText(canvas, offset + cursorOffset);
}
if (_shouldShowCursor) {
_painter.paintCursor(
canvas,
offset + cursorOffset,
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]. [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();
}
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);
}
}
56ae2e47fThis file is pinned to the selected release. Download the original to open it in your design tool.