import 'dart:ui'; import 'package:flutter/painting.dart'; import 'package:xterm/src/core/buffer/graphemes.dart'; import 'package:xterm/src/ui/cell_glyphs.dart'; import 'package:xterm/src/ui/palette_builder.dart'; import 'package:xterm/src/ui/paragraph_cache.dart'; import 'package:xterm/src/ui/text_runs.dart'; import 'package:xterm/xterm.dart'; /// Encapsulates the logic for painting various terminal elements. class TerminalPainter { TerminalPainter({ required TerminalTheme theme, required TerminalStyle textStyle, required TextScaler textScaler, }) : _textStyle = textStyle, _theme = theme, _textScaler = textScaler; /// A lookup table from terminal colors to Flutter colors. late var _colorPalette = PaletteBuilder(_theme).build(); /// Size of each character in the terminal. late var _cellSize = _measureCharSize(); /// The cached for cells in the terminal. Should be cleared when the same /// cell no longer produces the same visual output. For example, when /// [_textStyle] is changed, or when the system font changes. final _paragraphCache = ParagraphCache(10240); /// Paragraphs for runs of same-styled cells ([paintLine]). final _runCache = TextRunCache(4096); /// Changes whenever the same cells would paint differently (style, text /// scale, theme or fonts), so pictures of painted lines can be dropped. int get generation => _generation; var _generation = 0; void _invalidate() { _paragraphCache.clear(); _runCache.clear(); for (final picture in _glyphPictures.values) { picture.dispose(); } _glyphPictures.clear(); _generation++; } /// Recorded box drawing, block and Powerline glyphs by code point, colour, /// columns and the cell's sub-pixel position (which decides how lines snap /// to pixels), so each is built once rather than per cell. final _glyphPictures = <(int, int, int, int), Picture>{}; void _paintGlyph( Canvas canvas, Offset offset, int codePoint, int columns, Color color, ) { final left = offset.dx.floorToDouble(); final top = offset.dy.floorToDouble(); // The fraction of a pixel the cell starts at, in 64ths. final dx = ((offset.dx - left) * 64).round(); final dy = ((offset.dy - top) * 64).round(); final key = (codePoint, color.toARGB32(), columns, dx << 8 | dy); var picture = _glyphPictures[key]; if (picture == null) { if (_glyphPictures.length >= 1024) _invalidateGlyphs(); final recorder = PictureRecorder(); paintCellGlyph( Canvas(recorder), Offset(dx / 64, dy / 64) & Size(_cellSize.width * columns, _cellSize.height), codePoint, color, ); picture = recorder.endRecording(); _glyphPictures[key] = picture; } canvas.save(); canvas.translate(left, top); canvas.drawPicture(picture); canvas.restore(); } void _invalidateGlyphs() { for (final picture in _glyphPictures.values) { picture.dispose(); } _glyphPictures.clear(); } TerminalStyle get textStyle => _textStyle; TerminalStyle _textStyle; set textStyle(TerminalStyle value) { if (value == _textStyle) return; _textStyle = value; _cellSize = _measureCharSize(); _invalidate(); } TextScaler get textScaler => _textScaler; TextScaler _textScaler = TextScaler.linear(1.0); set textScaler(TextScaler value) { if (value == _textScaler) return; _textScaler = value; _cellSize = _measureCharSize(); _invalidate(); } TerminalTheme get theme => _theme; TerminalTheme _theme; set theme(TerminalTheme value) { if (value == _theme) return; _theme = value; _colorPalette = PaletteBuilder(value).build(); _invalidate(); } Size _measureCharSize() { const test = 'mmmmmmmmmm'; final textStyle = _textStyle.toTextStyle(); final builder = ParagraphBuilder(textStyle.getParagraphStyle()); builder.pushStyle( textStyle.getTextStyle(textScaler: _textScaler), ); builder.addText(test); final paragraph = builder.build(); paragraph.layout(ParagraphConstraints(width: double.infinity)); // Whole-pixel rows: every row starts on a pixel, so backgrounds and box // drawing meet the next row without a seam. The width stays the font's // advance, which text runs rely on. final result = Size( paragraph.maxIntrinsicWidth / test.length, paragraph.height.ceilToDouble(), ); paragraph.dispose(); return result; } /// The size of each character in the terminal. Size get cellSize => _cellSize; /// When the set of font available to the system changes, call this method to /// clear cached state related to font rendering. void clearFontCache() { _cellSize = _measureCharSize(); _invalidate(); } /// Paints the cursor based on the current cursor type. /// /// [cell] is the cell under the cursor: a focused block cursor draws its /// character again in the background colour, so the character stays /// readable, and a cursor over a wide character spans both columns. void paintCursor( Canvas canvas, Offset offset, { required TerminalCursorType cursorType, bool hasFocus = true, CellData? cell, }) { final wide = cell != null && cell.content >> CellContent.widthShift == 2; final size = wide ? Size(_cellSize.width * 2, _cellSize.height) : _cellSize; final thickness = cursorThickness; final paint = Paint()..color = _theme.cursor; if (!hasFocus) { paint ..style = PaintingStyle.stroke ..strokeWidth = 1; canvas.drawRect((offset & size).deflate(0.5), paint); return; } switch (cursorType) { case TerminalCursorType.block: canvas.drawRect(offset & size, paint); if (cell != null) { paintCellForeground(canvas, offset, _underCursor(cell)); } return; case TerminalCursorType.underline: canvas.drawRect( Rect.fromLTWH( offset.dx, offset.dy + size.height - thickness, size.width, thickness, ), paint, ); return; case TerminalCursorType.verticalBar: canvas.drawRect( Rect.fromLTWH(offset.dx, offset.dy, thickness, size.height), paint, ); return; } } /// The width of an underline or bar cursor: a tenth of the line height, /// at least one pixel. double get cursorThickness => (_cellSize.height / 10).roundToDouble().clamp(1.0, double.infinity); /// [cell] as drawn on top of a block cursor: in the background colour, /// without inverse. CellData _underCursor(CellData cell) { final background = _theme.background.toARGB32() & CellColor.valueMask; return CellData( foreground: CellColor.rgb | background, background: 0, flags: cell.flags & ~CellFlags.inverse, content: cell.content, ); } @pragma('vm:prefer-inline') void paintHighlight(Canvas canvas, Offset offset, int length, Color color) { final endOffset = offset.translate(length * _cellSize.width, _cellSize.height); final paint = Paint() ..color = color ..strokeWidth = 1; canvas.drawRect( Rect.fromPoints(offset, endOffset), paint, ); } /// Paints [line] to [canvas] at [offset] (the top left of its first cell): /// every background, merged into runs of one colour, then the text. A /// line's plain text is one paragraph with a span per style ([RowText]); /// box drawing, block and Powerline characters are geometry /// ([paintCellGlyph]); anything else is drawn in its own cell. /// /// With [paragraphs] false (a line just written, which may scroll away /// before it is drawn again; see `RowPictureCache`), or with less plain /// text than [minRowTextInk], the text is drawn cell by cell from the /// per-character cache instead: laying out a new paragraph costs more /// than drawing a few cached glyphs once, and less on every later frame. void paintLine( Canvas canvas, Offset offset, BufferLine line, { bool paragraphs = true, }) { _paintBackgrounds(canvas, offset, line); final cellData = CellData.empty(); final cellWidth = _cellSize.width; final row = _rowText..clear(); final length = line.length; // Plain text into the row's paragraph (or straight to the canvas when // the line is not laid out); everything else drawn now. for (var i = 0; i < length; i++) { line.getCellData(i, cellData); final content = cellData.content; final cellFlags = cellData.flags; final width = content >> CellContent.widthShift; final cluster = content & CellContent.clusterFlag != 0; final code = content & CellContent.codepointMask; final hidden = cellFlags & CellFlags.invisible != 0; final decorated = cellFlags & _decorations != 0; if (!cluster && (code == 0 || hidden || (code == 0x20 && !decorated))) { if (paragraphs) row.skip(1, _plainStyle); continue; } if (paragraphs && !cluster && width == 1 && (code == 0x20 || isRunCharacter(code))) { final color = _foregroundColor(cellData).toARGB32(); final flags = cellFlags & _textFlags; final key = color ^ (flags * 0x9E3779B1); TextStyle Function()? style; if (!row.continues(key)) { final styled = CellData( foreground: cellData.foreground, background: cellData.background, flags: cellFlags, content: 0, ); style = () => _cellTextStyle(styled); } row.add( // Flutter draws no decoration under a plain space at the end of a // span; it does under a no-break space. code == 0x20 ? 0xA0 : code, key, style, decorated: decorated, ); continue; } paintCellForeground(canvas, offset.translate(i * cellWidth, 0), cellData); if (paragraphs) row.skip(width == 2 ? 2 : 1, _plainStyle); if (width == 2) i++; } if (row.ink == 0) return; if (row.ink >= minRowTextInk) { final paragraph = row.layout(_runCache, _textScaler, cellWidth); if (paragraph != null) { canvas.drawParagraph(paragraph, offset); return; } } // Cell by cell: few characters, or a font whose glyphs are off the grid. for (var i = 0; i < length; i++) { line.getCellData(i, cellData); final content = cellData.content; if (content & CellContent.clusterFlag != 0) continue; final code = content & CellContent.codepointMask; if (content >> CellContent.widthShift != 1 || !isRunCharacter(code)) { if (code != 0x20 || cellData.flags & _decorations == 0) continue; } paintCellForeground(canvas, offset.translate(i * cellWidth, 0), cellData); } } /// The least characters with ink a line needs to be drawn as one /// paragraph rather than cell by cell (see [paintLine]). static const minRowTextInk = 4; final _rowText = RowText(); TextStyle _plainStyle() => _textStyle.toTextStyle(); static const _decorations = CellFlags.underline | CellFlags.strikethrough | CellFlags.overline; /// The flags that change how text is drawn, besides its colour. static const _textFlags = CellFlags.bold | CellFlags.italic | CellFlags.underline | CellAttr.underlineStyleMask | CellFlags.strikethrough | CellFlags.overline; /// Paints the backgrounds of [line]'s cells, one rectangle per run of a /// colour, with edges on whole pixels so neighbouring runs meet exactly. void _paintBackgrounds(Canvas canvas, Offset offset, BufferLine line) { final cellWidth = _cellSize.width; final cellData = CellData.empty(); Color? runColor; var runStart = 0; void flush(int end) { final color = runColor; if (color == null) return; final left = (offset.dx + runStart * cellWidth).roundToDouble(); final right = (offset.dx + end * cellWidth).roundToDouble(); canvas.drawRect( Rect.fromLTRB(left, offset.dy, right, offset.dy + _cellSize.height), Paint()..color = color, ); } for (var i = 0; i < line.length; i++) { line.getCellData(i, cellData); final color = _backgroundColor(cellData); if (color != runColor) { flush(i); runColor = color; runStart = i; } } flush(line.length); } /// The colour a cell's background is painted in; null for the theme's /// background, which is not painted. Color? _backgroundColor(CellData cellData) { if (cellData.flags & CellFlags.inverse != 0) { return resolveForegroundColor(cellData.foreground); } if (cellData.background & CellColor.typeMask == CellColor.normal) { return null; } return resolveBackgroundColor(cellData.background); } /// The colour a cell's text is drawn in, inverse and faint applied. Color _foregroundColor(CellData cellData) { final color = cellData.flags & CellFlags.inverse == 0 ? resolveForegroundColor(cellData.foreground) : resolveBackgroundColor(cellData.background); if (cellData.flags & CellFlags.faint == 0) return color; return color.withValues(alpha: color.a * 0.5); } TextStyle _cellTextStyle(CellData cellData) { final cellFlags = cellData.flags; final underline = cellFlags & CellFlags.underline != 0; return _textStyle.toTextStyle( color: _foregroundColor(cellData), bold: cellFlags & CellFlags.bold != 0, italic: cellFlags & CellFlags.italic != 0, underline: underline, strikethrough: cellFlags & CellFlags.strikethrough != 0, overline: cellFlags & CellFlags.overline != 0, decorationStyle: underline ? _underlineStyle(cellFlags) : null, ); } @pragma('vm:prefer-inline') void paintCell(Canvas canvas, Offset offset, CellData cellData) { paintCellBackground(canvas, offset, cellData); paintCellForeground(canvas, offset, cellData); } /// Paints the character in the cell represented by [cellData] to [canvas] /// at [offset]: its whole grapheme cluster, centred in the cell's columns /// when the glyph is narrower, or the geometry of a box drawing, block or /// Powerline character. void paintCellForeground(Canvas canvas, Offset offset, CellData cellData) { final content = cellData.content; final cluster = content & CellContent.clusterFlag != 0; final charCode = content & CellContent.codepointMask; if (charCode == 0 && !cluster) return; // SGR 8 (conceal): the cell keeps its background, the text is hidden. if (cellData.flags & CellFlags.invisible != 0) return; final columns = content >> CellContent.widthShift == 2 ? 2 : 1; if (!cluster && isCellGlyph(charCode)) { _paintGlyph( canvas, offset, charCode, columns, _foregroundColor(cellData)); return; } final cacheKey = cellData.getHash() ^ _textScaler.hashCode; var paragraph = _paragraphCache.getLayoutFromCache(cacheKey); if (paragraph == null) { var text = cellContentText(content); if (cellData.flags & _decorations != 0 && text == ' ') { // Flutter draws no decoration under a lone space; it does under a // no-break space. text = String.fromCharCode(0xA0); } paragraph = _paragraphCache.performAndCacheLayout( text, _cellTextStyle(cellData), _textScaler, cacheKey, ); } final room = _cellSize.width * columns; final glyph = paragraph.maxIntrinsicWidth; if (glyph <= room + 0.5) { // Narrower (a fallback font's emoji or CJK): centred in its columns. final dx = glyph < room - 0.5 ? (room - glyph) / 2 : 0.0; canvas.drawParagraph(paragraph, offset.translate(dx, 0)); return; } // Wider (a symbol or icon from a fallback font with a full-em advance): // scaled down to its columns and centred in the row, so it neither // covers the next cell nor shifts the grid. final scale = room / glyph; final dy = (_cellSize.height - paragraph.height * scale) / 2; canvas.save(); canvas.translate(offset.dx, offset.dy + dy); canvas.scale(scale); canvas.drawParagraph(paragraph, Offset.zero); canvas.restore(); } /// The line style of the underline in [flags] (SGR 4:1-4:5, 21). static TextDecorationStyle _underlineStyle(int flags) { final style = (flags & CellAttr.underlineStyleMask) >> CellAttr.underlineStyleShift; return switch (style) { 2 => TextDecorationStyle.double, 3 => TextDecorationStyle.wavy, 4 => TextDecorationStyle.dotted, 5 => TextDecorationStyle.dashed, _ => TextDecorationStyle.solid, }; } /// Paints the background of a cell represented by [cellData] to [canvas] at /// [offset]. @pragma('vm:prefer-inline') void paintCellBackground(Canvas canvas, Offset offset, CellData cellData) { final color = _backgroundColor(cellData); if (color == null) return; final doubleWidth = cellData.content >> CellContent.widthShift == 2; final widthScale = doubleWidth ? 2 : 1; final size = Size(_cellSize.width * widthScale + 1, _cellSize.height); canvas.drawRect(offset & size, Paint()..color = color); } /// Get the effective foreground color for a cell from information encoded in /// [cellColor]. @pragma('vm:prefer-inline') Color resolveForegroundColor(int cellColor) { final colorType = cellColor & CellColor.typeMask; final colorValue = cellColor & CellColor.valueMask; switch (colorType) { case CellColor.normal: return _theme.foreground; case CellColor.named: case CellColor.palette: return _colorPalette[colorValue]; case CellColor.rgb: default: return Color(colorValue | 0xFF000000); } } /// Get the effective background color for a cell from information encoded in /// [cellColor]. @pragma('vm:prefer-inline') Color resolveBackgroundColor(int cellColor) { final colorType = cellColor & CellColor.typeMask; final colorValue = cellColor & CellColor.valueMask; switch (colorType) { case CellColor.normal: return _theme.background; case CellColor.named: case CellColor.palette: return _colorPalette[colorValue]; case CellColor.rgb: default: return Color(colorValue | 0xFF000000); } } }