diff --git a/app/fonts/README.md b/app/fonts/README.md index 8611d467..ec95efe4 100644 --- a/app/fonts/README.md +++ b/app/fonts/README.md @@ -7,6 +7,32 @@ from the Flutter SDK's DevTools assets. They give monospace text (artifact text previews, background task output) a real fixed-width face on every platform: Flutter web does not resolve the generic `monospace` family. +## Terminal symbols + +`symbols-nerd-font/SymbolsNerdFontMono-Subset.ttf` (568 KiB) is a subset of +Symbols Nerd Font Mono from Nerd Fonts 3.5.1 +(github.com/ryanoasis/nerd-fonts release v3.5.1, `NerdFontsSymbolsOnly.tar.xz`, +`SymbolsNerdFontMono-Regular.ttf`, 2.5 MiB). The terminal views list it first +among their fallback families, so Powerline and Nerd Font prompt glyphs draw +on every platform and offline (Flutter web's own fallback fetches Noto fonts +from Google's CDN, which has none of these). It is a plain asset registered +with a `FontLoader` the first time a terminal is drawn +(`lib/ui/text/terminal_symbols_font.dart`), not a startup download. + +Kept ranges (`pyftsubset --unicodes=...`, fontTools 4): Powerline and +Powerline Extra U+E0A0-E0D7, Seti-UI U+E5FA-E6B7, Font Awesome U+ED00-F2FF, +Font Logos U+F300-F381, Octicons U+F400-F533 with U+2665 and U+26A1, IEC power +symbols U+23FB-23FE and U+2B58. Left out for size: Devicons, Codicons, +Weather, Pomicons and Material Design (1.2 MiB alone). The box drawing, +block and Powerline separator characters are drawn by the emulator itself +and do not need the font. + +Licences: the font and the patcher are MIT (`symbols-nerd-font/LICENSE`, +(c) 2014 Ryan L McIntyre, registered with `LicenseRegistry`); the kept icon +sets are Powerline Extra, Seti-UI and Octicons MIT, Font Awesome 6 CC BY 4.0 +(icons, attribution: Fonticons, Inc.), Font Logos Unlicense. See the Nerd +Fonts README's icon set table. + ## Optional interface fonts Chosen per device in Settings > Font (`lib/ui/theme/app_font.dart`). They are diff --git a/app/fonts/symbols-nerd-font/LICENSE b/app/fonts/symbols-nerd-font/LICENSE new file mode 100644 index 00000000..06eb073d --- /dev/null +++ b/app/fonts/symbols-nerd-font/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ryan L McIntyre + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/fonts/symbols-nerd-font/SymbolsNerdFontMono-Subset.ttf b/app/fonts/symbols-nerd-font/SymbolsNerdFontMono-Subset.ttf new file mode 100644 index 00000000..c22fcb2d Binary files /dev/null and b/app/fonts/symbols-nerd-font/SymbolsNerdFontMono-Subset.ttf differ diff --git a/app/lib/features/chat/shell/chat_shell_terminal_theme.dart b/app/lib/features/chat/shell/chat_shell_terminal_theme.dart index 3c3a5a37..fbd0a893 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_theme.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_theme.dart @@ -1,9 +1,11 @@ +import 'dart:async'; import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:xterm/xterm.dart'; import '../../../ui/text/monospace.dart'; +import '../../../ui/text/terminal_symbols_font.dart'; import '../conversation/chat_card_styles.dart'; /// The terminal's colours from the host theme: the card's inset surface as @@ -54,12 +56,24 @@ TerminalTheme chatShellTerminalTheme(BuildContext context) { } /// The terminal's text: the host's monospace family at [fontSize] (the -/// terminal text size setting), else a little under the card body size. +/// terminal text size setting), else a little under the card body size, with +/// the bundled symbols font first among the fallbacks for Powerline and Nerd +/// Font icons (registered on first use). +/// +/// Line height 1.1: the emulator rounds a row up to whole pixels (about +/// 1.13 at the default size), close to other terminals' 1.0-1.2. Box +/// drawing, block and Powerline characters fill the whole row whatever the +/// height, so frames and bars join across rows. TerminalStyle chatShellTerminalStyle(BuildContext context, {double? fontSize}) { + unawaited(ensureTerminalSymbolsFont()); return TerminalStyle( fontFamily: appMonospaceFamily, + fontFamilyFallback: const [ + terminalSymbolsFamily, + ...kTerminalDefaultFontFamilyFallback, + ], fontSize: fontSize ?? chatShellTerminalDefaultFontSize(context), - height: 1.3, + height: 1.1, ); } @@ -78,7 +92,11 @@ Size chatShellTerminalCellSize(BuildContext context, TerminalStyle style) { ..addText('mmmmmmmmmm'); final paragraph = builder.build() ..layout(const ui.ParagraphConstraints(width: double.infinity)); - final size = Size(paragraph.maxIntrinsicWidth / 10, paragraph.height); + // Rows are whole pixels, as the emulator's painter rounds them. + final size = Size( + paragraph.maxIntrinsicWidth / 10, + paragraph.height.ceilToDouble(), + ); paragraph.dispose(); return size; } diff --git a/app/lib/ui/text/terminal_symbols_font.dart b/app/lib/ui/text/terminal_symbols_font.dart new file mode 100644 index 00000000..eb2c160d --- /dev/null +++ b/app/lib/ui/text/terminal_symbols_font.dart @@ -0,0 +1,32 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// The bundled icon font terminals fall back to for Powerline and Nerd Font +/// glyphs (fonts/README.md): a subset of Symbols Nerd Font Mono. +const String terminalSymbolsFamily = 'SymbolsNerdFontMono'; + +const String terminalSymbolsAsset = + 'fonts/symbols-nerd-font/SymbolsNerdFontMono-Subset.ttf'; + +const String terminalSymbolsLicenseAsset = 'fonts/symbols-nerd-font/LICENSE'; + +Future? _loading; + +/// Registers [terminalSymbolsFamily] the first time a terminal is drawn. It +/// is a plain asset, not a `fonts:` family, so the web build does not +/// download it at startup. Once registered the engine reports a font change +/// and terminal views draw again with it. A failed load is logged; the +/// glyphs then stay as the platform's fallback draws them. +Future ensureTerminalSymbolsFont() => _loading ??= _load(); + +Future _load() async { + try { + final loader = FontLoader(terminalSymbolsFamily) + ..addFont(rootBundle.load(terminalSymbolsAsset)); + await loader.load(); + } catch (error) { + debugPrint('Terminal symbols font did not load: $error'); + } +} diff --git a/app/lib/ui/theme/app_font_licenses.dart b/app/lib/ui/theme/app_font_licenses.dart index e7b5e631..96f4a168 100644 --- a/app/lib/ui/theme/app_font_licenses.dart +++ b/app/lib/ui/theme/app_font_licenses.dart @@ -1,11 +1,13 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; +import '../text/terminal_symbols_font.dart'; import 'app_font.dart'; bool _registered = false; -/// Adds each bundled interface font's SIL Open Font License to the +/// Adds each bundled interface font's SIL Open Font License, and the +/// terminal symbols font's MIT licence, to the /// [LicenseRegistry]. The texts are read from the bundle only when a licence /// page asks for them. void registerAppFontLicenses() { @@ -19,5 +21,8 @@ void registerAppFontLicenses() { font.label, ], await rootBundle.loadString(asset)); } + yield LicenseEntryWithLineBreaks([ + 'Symbols Nerd Font Mono', + ], await rootBundle.loadString(terminalSymbolsLicenseAsset)); }); } diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index 40a07baf..a511f932 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -327,6 +327,83 @@ origin flag is not saved (as in the app's emulator); scrolled-in rows are blank in the default colour (as in the app's emulator, not xterm's BCE). The server emulates at the PTY size; a client drawing at another size gets the snapshot at the PTY's. +## Unicode, glyphs and drawing (2026-11-26) + +All in the vendored emulator (`third_party/xterm`, README lists the patches) +plus the view's style (`chat_shell_terminal_theme.dart`). + +- **Widths** follow glibc `wcwidth` (what tmux, readline and ncurses lay + out with) on Unicode 16 tables generated by + `third_party/xterm/tool/gen_unicode_tables.py` from Python's + `unicodedata` and `emoji-data.txt`; every assigned code point was compared + with glibc 2.44 and the few differences (prepended concatenation marks, + Hangul fillers, U+3248-324F) are pinned to glibc. Combining marks and + format characters 0, East Asian Wide/Fullwidth (every default emoji) 2. +- **Graphemes**: a zero-width character (combining mark, variation + selector, ZWJ, tag, Hangul medial/final jamo) joins the cell before the + cursor; a pictograph after a ZWJ, a skin tone after a modifier base and a + second regional indicator join too. The cell keeps the cluster interned + (`CellContent.clusterFlag` + an index into one shared table, capped at + 65,536 clusters of at most 32 UTF-16 units), so cells stay four words and + reflow/scrolling copy them unchanged. The painter draws the whole cluster; + copy (`getText`) returns it whole. A zero-width character with nothing + before it on the line is dropped (it takes no column). A wide character + never starts in the last column (it wraps whole). +- **Choice where terminals disagree**: U+FE0F after a text-default emoji + (❤️, keycaps) and a flag make the cell two columns, as kitty, WezTerm, + foot, Ghostty and iTerm2 do. A flag is also 2 under wcwidth (1 + 1), but + wcwidth gives U+FE0F 0, so a program measuring with wcwidth counts ❤️ as + one column; a ZWJ family is one two-column cell here but 6 columns to + wcwidth (2 + 0 + 2 + 0 + 2). Inside tmux, which redraws with its own + widths, such emoji can still shift the rest of that line by a column. +- **Glyphs**: box drawing (U+2500-257F: light, heavy, double, dashed, + rounded, diagonal), block elements (U+2580-259F) and Powerline separators + (U+E0B0-E0BF) are geometry that fills the cell (`ui/cell_glyphs.dart`), + with half-pixel bleed across cell sides and inner edges on whole pixels, + so they join across cells and rows at any line height. Other Nerd Font + icons come from the bundled subset of Symbols Nerd Font Mono (568 KiB, + MIT; `fonts/README.md`), first in the terminal's fallback families and + registered on first use (`lib/ui/text/terminal_symbols_font.dart`). A + glyph wider than its columns (a full-em icon or symbol from a fallback + font) is scaled down to fit; a narrower one (emoji, CJK) is centred. +- **Line height** 1.1, rows rounded up to whole pixels (about 1.13 at the + default 13.3 px), was 1.3. Roboto Mono has no italic: italic stays + synthesised (a bundled italic was not added). +- **Drawing**: backgrounds are one rectangle per run of a colour with + whole-pixel edges. Each line is a picture reused until the line changes + (`BufferLine.version`) or the painter's style, theme or fonts change, so a + frame records only changed lines. A new line draws its text from the + per-character paragraph cache; a line drawn unchanged in two frames is + re-recorded "settled", its plain text laid out as one paragraph with a + span per style (glyphs advance one cell each; checked against the grid, + cell by cell otherwise), at most 8 lines per frame. Measured on CanvasKit, + laying out a paragraph per new line cost more than it saved while output + streams (every visible line is new each frame), so new lines never pay + for it. `TerminalStyle` and `TerminalTheme` compare by value, so a view + rebuild no longer clears every cache. + +Bench: `tool/perf/terminal_stream_bench.dart` (the app's style, theme and +sliced feed; profile web build) driven by `tool/perf/terminal_stream_bench.mjs` +in headless Chromium (CanvasKit, software raster, 1280x800, 8 MB per +workload, generated at up to 30 MB/s; the emulator's parsing is the +throughput limit). Medians of two interleaved runs on a shared, loaded +machine (frame ms; `screen` redraws all 48 rows with colours each chunk, +`progress` rewrites one status line under a static screen): + +| workload | before build p50/p90 | after | before raster p50/p90 | after | before MB/s | after | +| --- | --- | --- | --- | --- | --- | --- | +| `seq` | 1.0/1.5 | 1.5/2.3 | 7.6/8.7 | 7.7/8.8 | 1.05 | 1.01 | +| `yes` | 0.9/1.3 | 1.2/1.7 | 7.6/8.8 | 7.4/8.2 | 0.59 | 0.66 | +| unicode lines | 1.4/1.9 | 2.7/3.6 | 8.6/9.6 | 10.5/12.0 | 1.92 | 1.98 | +| coloured lines | 1.5/1.9 | 2.1/2.6 | 8.7/9.6 | 8.9/9.9 | 2.23 | 2.58 | +| `screen` | 4.1/4.8 | 3.4/4.0 | 13.0/14.6 | 11.4/14.0 | 2.77 | 3.82 | +| `progress` | 2.7/2.9 | 0.9/3.2 | 11.2/11.8 | 8.6/10.3 | 3.79 | 3.94 | + +Streaming plain lines is unchanged within noise (+0.5 ms build for the +pictures); full-screen redraws and mostly static screens are cheaper; the +unicode workload (six procedural glyphs per line, paths rasterised in +software) costs about 2 ms more raster. Runs on this machine vary by about +±20 % between repetitions. ## Login and lifetime (server) @@ -422,7 +499,14 @@ the snapshot at the PTY's. `lib/features/chat/shell/chat_shell_terminals.dart` (`ChatShellInputPipe` made public), `lib/features/chat/chat_screen_workspace.dart` (Ctrl+Tab yields to a shown terminal). Tests `test/features/terminal/`. Probe fixture - `tool/perf/terminal_fixture.dart` (`?terminals=1`, `?terminal=panel|float`). + `tool/perf/terminal_fixture.dart` (`?terminals=1`, `?terminal=panel|float`, + showcases `?terminalAttrs=1`, `?terminalUnicode=1`). +- Emulator Unicode and drawing: `third_party/xterm/lib/src/utils/unicode_{width,tables}.dart`, + `core/buffer/{graphemes,grapheme_join}.dart`, `ui/{cell_glyphs,text_runs,row_pictures,painter}.dart`, + `third_party/xterm/tool/gen_unicode_tables.py`; tests + `test/third_party_xterm/{grapheme,glyph_paint}_test.dart`. Symbols font + `fonts/symbols-nerd-font/`, `lib/ui/text/terminal_symbols_font.dart`. + Bench `tool/perf/terminal_stream_bench.{dart,mjs}`. ## Verification diff --git a/app/pubspec.yaml b/app/pubspec.yaml index ee4340c9..0ed37808 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -86,6 +86,9 @@ flutter: - fonts/ibm-plex-sans/ - fonts/source-sans-3/ - fonts/atkinson-hyperlegible-next/ + # Terminal icon fallback, registered when a terminal is first drawn + # (lib/ui/text/terminal_symbols_font.dart). + - fonts/symbols-nerd-font/ fonts: - family: RobotoMono diff --git a/app/test/third_party_xterm/glyph_paint_test.dart b/app/test/third_party_xterm/glyph_paint_test.dart new file mode 100644 index 00000000..ec56bfa4 --- /dev/null +++ b/app/test/third_party_xterm/glyph_paint_test.dart @@ -0,0 +1,311 @@ +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/src/ui/painter.dart'; +import 'package:xterm/src/ui/row_pictures.dart'; +import 'package:xterm/xterm.dart'; + +import 'paint_fixture.dart'; + +/// Box drawing, block and Powerline characters are geometry that fills the +/// cell, so they join across cells and rows; text runs land on the grid. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final painter = fixturePainter(); + final w = painter.cellSize.width.round(); + final h = painter.cellSize.height.round(); + + /// A line of [cols] cells written with [text] by a terminal. + BufferLine lineOf(String text, {int cols = 6}) { + final terminal = Terminal(maxLines: 100)..resize(cols, 5); + terminal.write(text); + return terminal.buffer.lines[0]; + } + + /// [lines] painted one under the other. + Future paintLines(List lines, {int cols = 6}) => + Pixels.paint(cols * w, lines.length * h, (canvas) { + for (var i = 0; i < lines.length; i++) { + painter.paintLine(canvas, Offset(0, i * h.toDouble()), lines[i]); + } + }); + + Rect cellRect(int x, int y) => Rect.fromLTWH( + x * w.toDouble(), + y * h.toDouble(), + w.toDouble(), + h.toDouble(), + ); + + test('cells are whole pixels high', () { + final odd = TerminalPainter( + theme: fixtureTheme, + textStyle: const TerminalStyle(fontSize: 13, height: 1.15), + textScaler: TextScaler.noScaling, + ); + final height = odd.cellSize.height; + expect(height, height.roundToDouble()); + }); + + test('a full block fills its cell exactly', () async { + final pixels = await paintLines([lineOf('\u2588')]); + expect(pixels.count(foregroundColor, cellRect(0, 0)), w * h); + expect(pixels.count(foregroundColor, cellRect(1, 0)), 0); + }); + + test('half and eighth blocks fill their part of the cell', () async { + final pixels = await paintLines([lineOf('\u2580\u2584\u258C\u2581')]); + expect(pixels.count(foregroundColor, cellRect(0, 0)), w * h ~/ 2); + expect(pixels.at(w ~/ 2, 0), foregroundColor); // upper half + expect(pixels.at(w + w ~/ 2, h - 1), foregroundColor); // lower half + expect(pixels.at(w + w ~/ 2, 0).a, 0); + expect(pixels.at(2 * w, h ~/ 2), foregroundColor); // left half + expect(pixels.at(3 * w - 1, h ~/ 2).a, 0); + // The lower eighth: whole pixel rows, about an eighth of the height. + final rows = [ + for (var y = 0; y < h; y++) + if (pixels.count( + foregroundColor, + Rect.fromLTWH(3.0 * w, y.toDouble(), w.toDouble(), 1), + ) == + w) + y, + ]; + expect(rows.length, closeTo(h / 8, 1)); + expect(rows.last, h - 1); + for (var y = 0; y < h; y++) { + if (!rows.contains(y)) expect(pixels.at(3 * w + w ~/ 2, y).a, 0); + } + }); + + test('a horizontal line runs unbroken across cells', () async { + final pixels = await paintLines([lineOf('\u2500\u2500\u2500')]); + final row = [ + for (var y = 0; y < h; y++) + if (pixels.at(1, y) == foregroundColor) y, + ]; + expect(row, isNotEmpty); + for (var x = 0; x < 3 * w; x++) { + expect(pixels.at(x, row.first), foregroundColor, reason: 'x=$x'); + } + }); + + test('a vertical line runs unbroken across rows', () async { + final pixels = await paintLines([lineOf('\u2502'), lineOf('\u2502')]); + final column = [ + for (var x = 0; x < w; x++) + if (pixels.at(x, 1) == foregroundColor) x, + ]; + expect(column, isNotEmpty); + for (var y = 0; y < 2 * h; y++) { + expect(pixels.at(column.first, y), foregroundColor, reason: 'y=$y'); + } + }); + + test('corners and tees join the lines they meet', () async { + // \u250C\u2500\u2510 over \u2502 \u2502: the corner's arms reach the cell edges. + final pixels = await paintLines([ + lineOf('\u250C\u2500\u2510'), + lineOf('\u2502 \u2502'), + ]); + final lineY = [ + for (var y = 0; y < h; y++) + if (pixels.at(w + 1, y) == foregroundColor) y, + ].first; + final lineX = [ + for (var x = 0; x < w; x++) + if (pixels.at(x, h + 1) == foregroundColor) x, + ].first; + // The corner's right arm reaches its right edge, the down arm its bottom. + expect(pixels.at(w - 1, lineY), foregroundColor); + expect(pixels.at(lineX, h - 1), foregroundColor); + // Nothing left of or above the corner's elbow. + expect(pixels.at(0, lineY).a, 0); + expect(pixels.at(lineX, 0).a, 0); + }); + + test('double lines draw two strokes', () async { + final pixels = await paintLines([lineOf('\u2550')]); + final rows = [ + for (var y = 0; y < h; y++) + if (pixels.at(w ~/ 2, y) == foregroundColor) y, + ]; + // Two separate strokes: a gap between the first and last painted rows. + expect(rows.length, lessThan(rows.last - rows.first + 1)); + for (var x = 0; x < w; x++) { + expect(pixels.at(x, rows.first), foregroundColor); + expect(pixels.at(x, rows.last), foregroundColor); + } + }); + + test('a Powerline arrow fills the cell height at its base', () async { + final pixels = await paintLines([lineOf('\uE0B0\uE0B2')]); + // Right-pointing: the whole left column; left-pointing: the right (the + // top and bottom pixels are the antialiased points of the triangle). + for (var y = 1; y < h - 1; y++) { + expect(pixels.at(0, y), foregroundColor, reason: 'y=$y'); + expect(pixels.at(2 * w - 1, y), foregroundColor, reason: 'y=$y'); + } + expect(pixels.at(0, 0).a, greaterThan(0.4)); + expect(pixels.at(0, h - 1).a, greaterThan(0.4)); + // The tip reaches the far side only in the middle. + expect(pixels.at(w - 1, h ~/ 2).a, greaterThan(0)); + expect(pixels.at(w - 1, 0).a, 0); + expect(pixels.at(w, 0).a, 0); + // About half the cell. + final filled = pixels.count(foregroundColor, cellRect(0, 0)); + expect(filled, closeTo(w * h / 2, w * h * 0.1)); + }); + + test('Powerline diagonals fill a triangle', () async { + final pixels = await paintLines([lineOf('\uE0B8\uE0BC')]); + expect(pixels.at(0, h - 1), foregroundColor); // lower left + expect(pixels.at(w - 2, 0).a, 0); + expect(pixels.at(w, 0), foregroundColor); // upper left + expect(pixels.at(2 * w - 1, h - 1).a, 0); + }); + + /// [line] drawn cell by cell with [TerminalPainter.paintCell]. + Future paintCells(BufferLine line, int cols) => + Pixels.paint(cols * w, h, (canvas) { + final cell = CellData.empty(); + for (var x = 0; x < cols; x++) { + line.getCellData(x, cell); + painter.paintCell(canvas, Offset(x * w.toDouble(), 0), cell); + } + }); + + Future expectSamePixels(Pixels a, Pixels b) async { + for (var y = 0; y < a.height; y++) { + for (var x = 0; x < a.width; x++) { + expect(a.at(x, y), b.at(x, y), reason: '($x, $y)'); + } + } + } + + test('a line of text paints exactly as cell by cell', () async { + // Long enough to be one paragraph, with spans of three styles. + const cols = 24; + final line = lineOf( + 'plain \x1b[31mred\x1b[0m and \x1b[1;34mbold\x1b[0m text!', + cols: cols, + ); + await expectSamePixels( + await paintLines([line], cols: cols), + await paintCells(line, cols), + ); + }); + + test('a short line is drawn cell by cell, the same', () async { + final line = lineOf('Ab c-d'); + await expectSamePixels(await paintLines([line]), await paintCells(line, 6)); + }); + + test('text after a wide character and an emoji stays on the grid', () async { + const cols = 24; + final line = lineOf('\u4E2D\u{1F600}x text after them', cols: cols); + final pixels = await paintLines([line], cols: cols); + // Each plain character's cell is inked, the spaces are not. + for (var x = 4; x < 4 + 'x text after them'.length; x++) { + final blank = ' x text after them'[x - 3] == ' '; + final ink = pixels.count(foregroundColor, cellRect(x, 0)); + expect(ink > 0, !blank, reason: 'cell $x'); + } + }); + + test('an underline does not run under undecorated blanks', () async { + const cols = 24; + final line = lineOf( + '\x1b[4munderline\x1b[24m \x1b[4mmore text\x1b[0m', + cols: cols, + ); + final pixels = await paintLines([line], cols: cols); + for (var x = 9; x < 12; x++) { + expect(pixels.count(foregroundColor, cellRect(x, 0)), 0, reason: 'x=$x'); + } + await expectSamePixels(pixels, await paintCells(line, cols)); + }); + + test('a styled run breaks where the colour changes', () async { + final pixels = await paintLines([lineOf('a\x1b[31mb\x1b[0mc')]); + expect(pixels.count(foregroundColor, cellRect(0, 0)), greaterThan(0)); + expect(pixels.count(foregroundColor, cellRect(1, 0)), 0); + expect(pixels.count(fixtureTheme.red, cellRect(1, 0)), greaterThan(0)); + expect(pixels.count(foregroundColor, cellRect(2, 0)), greaterThan(0)); + }); + + test('backgrounds merge into runs that meet without a gap', () async { + final pixels = await paintLines([lineOf('\x1b[44m \x1b[0m')]); + for (var x = 0; x < 3 * w; x++) { + expect(pixels.at(x, h ~/ 2), fixtureTheme.blue, reason: 'x=$x'); + } + expect(pixels.at(3 * w + 1, h ~/ 2).a, 0); + }); + + test('a grapheme cluster is drawn in its own cell', () async { + final pixels = await paintLines([lineOf('e\u0301\u{1F1F5}\u{1F1F9}x')]); + expect(pixels.count(foregroundColor, cellRect(0, 0)), greaterThan(0)); + expect(pixels.count(foregroundColor, cellRect(3, 0)), greaterThan(0)); + }); + + group('row pictures', () { + test('a line is recorded again only when it changes', () { + final cache = RowPictureCache(settleAfter: 100); + final line = lineOf('abc'); + var recorded = 0; + void paint(Canvas canvas, bool settled) => recorded++; + final first = cache.pictureOf(line, 0, paint); + expect(cache.pictureOf(line, 0, paint), same(first)); + expect(recorded, 1); + line.setCodePoint(0, 0x7A); + expect(cache.pictureOf(line, 0, paint), isNot(same(first))); + expect(recorded, 2); + // A new painter generation (theme, font) records every line again. + cache.pictureOf(line, 1, paint); + expect(recorded, 3); + cache.clear(); + }); + + test('a line drawn unchanged settles into laid out text, within the ' + 'frame budget', () { + final cache = RowPictureCache(settleAfter: 2, settlePerFrame: 1); + final lines = [lineOf('one'), lineOf('two')]; + final settledCalls = []; + void paint(Canvas canvas, bool settled) => settledCalls.add(settled); + for (var frame = 0; frame < 4; frame++) { + cache.beginFrame(); + for (final line in lines) { + cache.pictureOf(line, 0, paint); + } + } + // Recorded new (not settled), then each settled in its own frame. + expect(settledCalls, [false, false, true, true]); + expect(cache.isSettled(lines[0]), isTrue); + expect(cache.isSettled(lines[1]), isTrue); + // A change starts the line over. + lines[0].setCodePoint(0, 0x7A); + cache.beginFrame(); + cache.pictureOf(lines[0], 0, paint); + expect(settledCalls.last, isFalse); + expect(cache.isSettled(lines[0]), isFalse); + cache.clear(); + }); + + test('trim keeps the most recently used lines', () { + final cache = RowPictureCache(); + final lines = [for (var i = 0; i < 4; i++) lineOf('$i')]; + for (final line in lines) { + cache.pictureOf(line, 0, (_, _) {}); + } + cache.pictureOf(lines[0], 0, (_, _) {}); + cache.trim(2); + expect(cache.length, 2); + var recorded = 0; + cache.pictureOf(lines[0], 0, (_, _) => recorded++); + expect(recorded, 0); + cache.pictureOf(lines[1], 0, (_, _) => recorded++); + expect(recorded, 1); + cache.clear(); + }); + }); +} diff --git a/app/test/third_party_xterm/grapheme_test.dart b/app/test/third_party_xterm/grapheme_test.dart new file mode 100644 index 00000000..629282fd --- /dev/null +++ b/app/test/third_party_xterm/grapheme_test.dart @@ -0,0 +1,203 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/src/utils/unicode_width.dart'; +import 'package:xterm/xterm.dart'; + +import 'xterm_fixture.dart'; + +/// Widths and grapheme clusters: what each character sequence occupies and +/// where the cursor ends, byte for byte as a program writes it. +void main() { + int widthOf(CellData cell) => cell.content >> CellContent.widthShift; + + String grapheme(FixtureTerminal t, int x, int y) => + t.buffer.lines[t.buffer.scrollBack + y].getGrapheme(x); + + group('widths follow glibc wcwidth', () { + test('ASCII, Latin, CJK, emoji, combining, format characters', () { + expect(UnicodeWidth.width(0x41), 1); + expect(UnicodeWidth.width(0xE9), 1); // \u00E9 + expect(UnicodeWidth.width(0x4E2D), 2); // \u4E2D + expect(UnicodeWidth.width(0xFF21), 2); // fullwidth A + expect(UnicodeWidth.width(0x1F600), 2); // \u{1F600} + expect(UnicodeWidth.width(0x1FAE8), 2); // Unicode 15 shaking face + expect(UnicodeWidth.width(0x0301), 0); // combining acute + expect(UnicodeWidth.width(0x200D), 0); // ZWJ + expect(UnicodeWidth.width(0xFE0F), 0); // VS16 + expect(UnicodeWidth.width(0x1160), 0); // Hangul medial vowel filler + expect(UnicodeWidth.width(0x00AD), 1); // soft hyphen, as glibc + expect(UnicodeWidth.width(0x0600), 1); // prepended mark, as glibc + expect(UnicodeWidth.width(0x2764), 1); // \u2764 text default + expect(UnicodeWidth.width(0x1F1F5), 1); // regional indicator + expect(UnicodeWidth.width(0xE0B0), 1); // Powerline (private use) + expect(UnicodeWidth.width(0x2500), 1); // box drawing + }); + }); + + group('combining marks join the previous cell', () { + test('e + U+0301 is one cell, and the cursor moves one column', () { + final t = FixtureTerminal(); + t.feed('e\u0301|'); + expect(grapheme(t, 0, 0), 'e\u0301'); + expect(t.charAt(1, 0), '|'); + expect(t.buffer.cursorX, 2); + expect(t.row(0), 'e\u0301|'); + }); + + test('several marks stack on one base', () { + final t = FixtureTerminal(); + t.feed('a\u0300\u0316\u0317b'); + expect(grapheme(t, 0, 0), 'a\u0300\u0316\u0317'); + expect(t.charAt(1, 0), 'b'); + }); + + test('a mark with nothing before it on the line takes no column', () { + final t = FixtureTerminal(); + t.feed('\u0301x'); + expect(t.charAt(0, 0), 'x'); + expect(t.buffer.cursorX, 1); + }); + + test('a mark after a wide character joins it, not its second column', () { + final t = FixtureTerminal(); + t.feed('\u4E2D\u0301x'); + expect(grapheme(t, 0, 0), '\u4E2D\u0301'); + expect(widthOf(t.cell(0, 0)), 2); + expect(t.charAt(2, 0), 'x'); + }); + + test('a mark in the pending-wrap column joins the last cell', () { + final t = FixtureTerminal(width: 4); + t.feed('abcd\u0301'); + expect(grapheme(t, 3, 0), 'd\u0301'); + expect(t.row(1), ''); + t.feed('e'); + expect(t.row(1), 'e'); + }); + + test('Hangul conjoining jamo make one syllable cell', () { + final t = FixtureTerminal(); + t.feed('\u1100\u1161\u11A8|'); + expect(grapheme(t, 0, 0), '\u1100\u1161\u11A8'); + expect(t.charAt(2, 0), '|'); + }); + }); + + group('emoji sequences', () { + test('VS16 widens a text-default emoji to two columns', () { + final t = FixtureTerminal(); + t.feed('\u2764\uFE0F|'); + expect(grapheme(t, 0, 0), '\u2764\uFE0F'); + expect(widthOf(t.cell(0, 0)), 2); + expect(t.charAt(2, 0), '|'); + expect(t.buffer.cursorX, 3); + }); + + test('VS16 at the last column cannot widen and stays one column', () { + final t = FixtureTerminal(width: 4); + t.feed('abc\u2764\uFE0F'); + expect(grapheme(t, 3, 0), '\u2764\uFE0F'); + expect(widthOf(t.cell(3, 0)), 1); + }); + + test('VS15 keeps one column', () { + final t = FixtureTerminal(); + t.feed('\u2764\uFE0E|'); + expect(widthOf(t.cell(0, 0)), 1); + expect(t.charAt(1, 0), '|'); + }); + + test('a skin tone joins its base: two columns, not four', () { + final t = FixtureTerminal(); + t.feed('\u{1F44D}\u{1F3FD}|'); + expect(grapheme(t, 0, 0), '\u{1F44D}\u{1F3FD}'); + expect(widthOf(t.cell(0, 0)), 2); + expect(t.charAt(2, 0), '|'); + }); + + test('a ZWJ family is one two-column cell', () { + const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}'; + final t = FixtureTerminal(); + t.feed('$family|'); + expect(grapheme(t, 0, 0), family); + expect(widthOf(t.cell(0, 0)), 2); + expect(t.charAt(2, 0), '|'); + expect(t.row(0), '$family|'); + }); + + test('two regional indicators are one two-column flag', () { + final t = FixtureTerminal(); + t.feed('\u{1F1F5}\u{1F1F9}|'); + expect(grapheme(t, 0, 0), '\u{1F1F5}\u{1F1F9}'); + expect(widthOf(t.cell(0, 0)), 2); + expect(t.charAt(2, 0), '|'); + }); + + test('a third regional indicator starts the next flag', () { + final t = FixtureTerminal(); + t.feed('\u{1F1F5}\u{1F1F9}\u{1F1EC}\u{1F1E7}'); + expect(grapheme(t, 0, 0), '\u{1F1F5}\u{1F1F9}'); + expect(grapheme(t, 2, 0), '\u{1F1EC}\u{1F1E7}'); + expect(t.buffer.cursorX, 4); + }); + + test('a keycap is one cell', () { + final t = FixtureTerminal(); + t.feed('1\uFE0F\u20E3|'); + expect(grapheme(t, 0, 0), '1\uFE0F\u20E3'); + expect(t.charAt(2, 0), '|'); + }); + + test('a letter after ZWJ does not join: only pictographs do', () { + final t = FixtureTerminal(); + t.feed('a\u200Db'); + expect(grapheme(t, 0, 0), 'a\u200D'); + expect(t.charAt(1, 0), 'b'); + }); + }); + + group('wide characters', () { + test('a wide character in the last column wraps whole', () { + final t = FixtureTerminal(width: 5); + t.feed('abcd\u4E2D'); + expect(t.row(0), 'abcd'); + expect(t.row(1), '\u4E2D'); + expect(t.buffer.lines[t.buffer.scrollBack + 1].isWrapped, isTrue); + }); + + test('overwriting the second column of a wide character blanks it', () { + final t = FixtureTerminal(); + t.feed('\u4E2D\x1b[2Gx'); + expect(t.charAt(0, 0), ''); + expect(t.charAt(1, 0), 'x'); + }); + }); + + group('copy returns whole graphemes', () { + test('selected text keeps marks, sequences and flags', () { + const text = 'e\u0301 \u{1F44D}\u{1F3FD} \u{1F1F5}\u{1F1F9} \u4E2D'; + final t = FixtureTerminal(width: 30); + t.feed(text); + final range = BufferRangeLine( + CellOffset(0, t.buffer.scrollBack), + CellOffset(30, t.buffer.scrollBack), + ); + expect(t.buffer.getText(range).trimRight(), text); + }); + + test('a selection ending inside a wide cluster leaves it out', () { + final t = FixtureTerminal(); + t.feed('a\u{1F1F5}\u{1F1F9}b'); + final line = t.buffer.lines[t.buffer.scrollBack]; + expect(line.getText(0, 2), 'a'); + expect(line.getText(0, 3), 'a\u{1F1F5}\u{1F1F9}'); + }); + + test('clusters survive reflow', () { + final t = FixtureTerminal(width: 6); + t.feed('abcde\u0301f\u{1F1F5}\u{1F1F9}'); + t.terminal.resize(4, 5); + t.terminal.resize(10, 5); + expect(t.row(0), 'abcde\u0301f\u{1F1F5}\u{1F1F9}'); + }); + }); +} diff --git a/app/third_party/xterm/README.md b/app/third_party/xterm/README.md index 83e2e235..944a559d 100644 --- a/app/third_party/xterm/README.md +++ b/app/third_party/xterm/README.md @@ -40,3 +40,18 @@ Local patches (keep this list current): - `TerminalView.cursorBlinkVisible`: the host animates a blinking cursor; while false the render object skips the cursor (the painter is unchanged) - `RenderTerminal` is exported from `ui.dart` (cell geometry for hosts) +- Unicode: cell widths follow glibc `wcwidth` on Unicode 16 tables + (`utils/unicode_width.dart`, generated `utils/unicode_tables.dart` by + `tool/gen_unicode_tables.py`); grapheme clusters (combining marks, + variation selectors, emoji ZWJ sequences, skin tones, flags, Hangul jamo) + join the previous cell (`core/buffer/grapheme_join.dart`) and are stored + interned (`core/buffer/graphemes.dart`, `CellContent.clusterFlag`), drawn + whole and copied whole; U+FE0F and flags take two columns; a wide character + never starts in the last column +- rendering: box drawing, block elements and Powerline separators drawn as + geometry filling the cell (`ui/cell_glyphs.dart`); whole-pixel row height; + one paragraph per line for plain text with a span per style + (`ui/text_runs.dart`), backgrounds merged per colour; a picture per line + reused until the line changes (`ui/row_pictures.dart`, + `BufferLine.version`); glyphs wider than their cells scaled to fit; + `TerminalStyle` and `TerminalTheme` compare by value diff --git a/app/third_party/xterm/lib/src/core/buffer/buffer.dart b/app/third_party/xterm/lib/src/core/buffer/buffer.dart index b4658a3c..75cbe370 100644 --- a/app/third_party/xterm/lib/src/core/buffer/buffer.dart +++ b/app/third_party/xterm/lib/src/core/buffer/buffer.dart @@ -1,6 +1,7 @@ import 'dart:math' show max, min; import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/buffer/grapheme_join.dart'; import 'package:xterm/src/core/buffer/line.dart'; import 'package:xterm/src/core/buffer/range_line.dart'; import 'package:xterm/src/core/buffer/range.dart'; @@ -9,7 +10,7 @@ import 'package:xterm/src/core/cursor.dart'; import 'package:xterm/src/core/reflow.dart'; import 'package:xterm/src/core/state.dart'; import 'package:xterm/src/utils/circular_buffer.dart'; -import 'package:xterm/src/utils/unicode_v11.dart'; +import 'package:xterm/src/utils/unicode_width.dart'; class Buffer { final TerminalState terminal; @@ -115,11 +116,39 @@ class Buffer { /// Writes a single character to the _terminal. Escape sequences or special /// characters are not interpreted and directly added to the buffer. /// + /// A character that continues the grapheme cluster before the cursor + /// (a combining mark, variation selector, emoji ZWJ sequence, skin tone, + /// the second letter of a flag) joins that cell instead of taking its own + /// (`joinPreviousCell`); widths follow glibc's wcwidth ([UnicodeWidth]). + /// /// See also: [Terminal.writeChar] void writeChar(int codePoint) { codePoint = charset.translate(codePoint); + if (UnicodeWidth.isControl(codePoint)) return; + + final cellWidth = UnicodeWidth.width(codePoint); + final joined = joinPreviousCell( + currentLine, + _cursorX, + viewWidth, + codePoint, + cellWidth, + ); + if (joined != null) { + _cursorX += joined; + return; + } + + // A wide character never starts in the last column: that column stays + // blank and the character wraps whole, as in xterm. + if (cellWidth == 2 && + _cursorX == viewWidth - 1 && + viewWidth > 1 && + terminal.autoWrapMode) { + currentLine.eraseCell(_cursorX, terminal.cursor); + _cursorX = viewWidth; + } - final cellWidth = unicodeV11.wcwidth(codePoint); if (_cursorX >= terminal.viewWidth) { index(); setCursorX(0); @@ -129,14 +158,24 @@ class Buffer { } final line = currentLine; - line.setCell(_cursorX, codePoint, cellWidth, terminal.cursor); - - if (_cursorX < viewWidth) { - _cursorX++; + // Overwriting the second column of a wide character blanks its first. + if (_cursorX > 0 && line.getWidth(_cursorX - 1) == 2) { + line.eraseCell(_cursorX - 1, terminal.cursor); } - + final x = _cursorX; + if (cellWidth == 2 && x + 1 >= viewWidth) { + // No room for the second column (a one-column screen or no autowrap): + // the character is kept in one column. + line.setCell(x, codePoint, 1, terminal.cursor); + if (_cursorX < viewWidth) _cursorX++; + return; + } + line.setCell(x, codePoint, cellWidth, terminal.cursor); if (cellWidth == 2) { - writeChar(0); + line.setCell(x + 1, 0, 0, terminal.cursor); + _cursorX += 2; + } else if (_cursorX < viewWidth) { + _cursorX++; } } diff --git a/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart b/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart new file mode 100644 index 00000000..a3dcc303 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/grapheme_join.dart @@ -0,0 +1,89 @@ +import 'package:xterm/src/core/buffer/graphemes.dart'; +import 'package:xterm/src/core/buffer/line.dart'; +import 'package:xterm/src/core/cell.dart'; +import 'package:xterm/src/utils/unicode_width.dart'; + +const _zwj = 0x200D; +const _vs16 = 0xFE0F; + +/// Adds [codePoint] to the grapheme cluster of the cell before [cursorX] in +/// [line] when it continues that cluster: +/// +/// * a zero-width character (combining mark, variation selector, zero width +/// joiner, tag, Hangul medial vowel or final consonant) joins whatever the +/// cell holds; with nothing before it on the line it is dropped, as its +/// width says it takes no column; +/// * a pictograph after a zero width joiner joins the emoji sequence; +/// * a skin tone modifier joins the emoji base before it; +/// * a regional indicator joins a lone one before it, making a flag. +/// +/// The cluster keeps its base's width, except that U+FE0F after a +/// text-default emoji and a completed flag take two columns, as in modern +/// terminals (kitty, WezTerm, foot, Ghostty, iTerm2). glibc's wcwidth gives +/// a flag two columns too (1 + 1), but U+FE0F 0, so a program that measures +/// with wcwidth (tmux, readline) counts such an emoji as one column. A +/// cluster at the last column cannot widen and stays one column. +/// +/// Returns null when [codePoint] starts a new cell, otherwise the columns +/// the cursor moves on (1 when the cluster widened over the cursor's +/// column, else 0). +int? joinPreviousCell( + BufferLine line, + int cursorX, + int viewWidth, + int codePoint, + int width, +) { + if (cursorX <= 0) return width == 0 ? 0 : null; + var x = (cursorX > viewWidth ? viewWidth : cursorX) - 1; + // The second column of a wide character: its cluster is one to the left. + if (x > 0 && line.getContent(x) == 0 && line.getWidth(x - 1) == 2) x--; + final content = line.getContent(x); + final empty = + content & (CellContent.codepointMask | CellContent.clusterFlag) == 0; + if (empty) return width == 0 ? 0 : null; + + final text = cellContentText(content); + final single = content & CellContent.clusterFlag == 0; + final base = single ? content & CellContent.codepointMask : text.runes.first; + final last = single ? base : text.runes.last; + + var widen = false; + if (width == 0) { + widen = + codePoint == _vs16 && single && UnicodeWidth.isEmojiTextDefault(base); + } else if (last == _zwj && UnicodeWidth.isPictographic(codePoint)) { + // An emoji ZWJ sequence: one glyph in the base's columns. + } else if (UnicodeWidth.isEmojiModifier(codePoint) && + single && + UnicodeWidth.isEmojiModifierBase(base)) { + // A skin tone: one glyph in the base's columns. + } else if (UnicodeWidth.isRegionalIndicator(codePoint) && + single && + UnicodeWidth.isRegionalIndicator(base)) { + widen = true; + } else { + return null; + } + + final cluster = text + String.fromCharCode(codePoint); + if (cluster.length > GraphemeTable.maxLength) return 0; + final id = GraphemeTable.instance.intern(cluster); + if (id == null) return 0; + + var cellWidth = content >> CellContent.widthShift; + var advance = 0; + if (widen && cellWidth == 1 && x + 1 < viewWidth) { + cellWidth = 2; + line.setForeground(x + 1, line.getForeground(x)); + line.setBackground(x + 1, line.getBackground(x)); + line.setAttributes(x + 1, line.getAttributes(x)); + line.setContent(x + 1, 0); + if (cursorX == x + 1) advance = 1; + } + line.setContent( + x, + id | CellContent.clusterFlag | (cellWidth << CellContent.widthShift), + ); + return advance; +} diff --git a/app/third_party/xterm/lib/src/core/buffer/graphemes.dart b/app/third_party/xterm/lib/src/core/buffer/graphemes.dart new file mode 100644 index 00000000..6dfd27f4 --- /dev/null +++ b/app/third_party/xterm/lib/src/core/buffer/graphemes.dart @@ -0,0 +1,63 @@ +import 'package:xterm/src/core/cell.dart'; + +/// The grapheme clusters of more than one code point that cells hold (a base +/// with combining marks, an emoji with a variation selector, skin tone or +/// zero width joiner sequence, a flag), interned once and shared by every +/// buffer. +/// +/// A cell whose content has [CellContent.clusterFlag] keeps the cluster's +/// index here in its code point bits, so cells stay four words and copying, +/// reflowing or scrolling them needs nothing extra. Entries are never freed: +/// a terminal shows few distinct clusters, and the table stops growing at +/// [maxEntries] (later clusters keep only the code points they had). +class GraphemeTable { + GraphemeTable._(); + + static final instance = GraphemeTable._(); + + /// The most distinct clusters kept. + static const maxEntries = 1 << 16; + + /// The most UTF-16 units one cluster keeps; marks beyond it are dropped, + /// as other terminals do, so a run of combining marks cannot grow a cell + /// without bound. + static const maxLength = 32; + + final _strings = []; + final _ids = {}; + + int get length => _strings.length; + + /// The index of [cluster], adding it; null when the table is full. + int? intern(String cluster) { + final known = _ids[cluster]; + if (known != null) return known; + if (_strings.length >= maxEntries) return null; + final id = _strings.length; + _strings.add(cluster); + _ids[cluster] = id; + return id; + } + + String operator [](int id) => _strings[id]; +} + +/// The text of a cell's [content]: its cluster, its one code point, or '' +/// for an empty cell. +String cellContentText(int content) { + final value = content & CellContent.codepointMask; + if (content & CellContent.clusterFlag != 0) { + return GraphemeTable.instance[value]; + } + return value == 0 ? '' : String.fromCharCode(value); +} + +/// The first code point of a cell's [content] (its base character), 0 for an +/// empty cell. +int cellContentBase(int content) { + final value = content & CellContent.codepointMask; + if (content & CellContent.clusterFlag != 0) { + return GraphemeTable.instance[value].runes.first; + } + return value; +} diff --git a/app/third_party/xterm/lib/src/core/buffer/line.dart b/app/third_party/xterm/lib/src/core/buffer/line.dart index 6e72114d..20bdf679 100644 --- a/app/third_party/xterm/lib/src/core/buffer/line.dart +++ b/app/third_party/xterm/lib/src/core/buffer/line.dart @@ -2,10 +2,11 @@ import 'dart:math' show min; import 'dart:typed_data'; import 'package:xterm/src/core/buffer/cell_offset.dart'; +import 'package:xterm/src/core/buffer/graphemes.dart'; import 'package:xterm/src/core/cell.dart'; import 'package:xterm/src/core/cursor.dart'; import 'package:xterm/src/utils/circular_buffer.dart'; -import 'package:xterm/src/utils/unicode_v11.dart'; +import 'package:xterm/src/utils/unicode_width.dart'; const _cellSize = 4; @@ -33,6 +34,12 @@ class BufferLine with IndexedItem { int get length => _length; + int _version = 0; + + /// Changes whenever a cell of this line or its length changes, so a + /// painter can keep what it drew for an unchanged line. + int get version => _version; + final _anchors = []; List get anchors => _anchors; @@ -53,8 +60,19 @@ class BufferLine with IndexedItem { return _data[index * _cellSize + _cellContent]; } + /// The cell's character, or its base character when it holds a grapheme + /// cluster; 0 for an empty cell. int getCodePoint(int index) { - return _data[index * _cellSize + _cellContent] & CellContent.codepointMask; + final content = _data[index * _cellSize + _cellContent]; + if (content & CellContent.clusterFlag == 0) { + return content & CellContent.codepointMask; + } + return cellContentBase(content); + } + + /// The cell's whole grapheme cluster ('' for an empty cell). + String getGrapheme(int index) { + return cellContentText(_data[index * _cellSize + _cellContent]); } int getWidth(int index) { @@ -80,27 +98,32 @@ class BufferLine with IndexedItem { } void setForeground(int index, int value) { + _version++; _data[index * _cellSize + _cellForeground] = value; } void setBackground(int index, int value) { + _version++; _data[index * _cellSize + _cellBackground] = value; } void setAttributes(int index, int value) { + _version++; _data[index * _cellSize + _cellAttributes] = value; } void setContent(int index, int value) { + _version++; _data[index * _cellSize + _cellContent] = value; } void setCodePoint(int index, int char) { - final width = unicodeV11.wcwidth(char); + final width = UnicodeWidth.width(char); setContent(index, char | (width << CellContent.widthShift)); } void setCell(int index, int char, int witdh, CursorStyle style) { + _version++; final offset = index * _cellSize; _data[offset + _cellForeground] = style.foreground; _data[offset + _cellBackground] = style.background; @@ -109,6 +132,7 @@ class BufferLine with IndexedItem { } void setCellData(int index, CellData cellData) { + _version++; final offset = index * _cellSize; _data[offset + _cellForeground] = cellData.foreground; _data[offset + _cellBackground] = cellData.background; @@ -117,6 +141,7 @@ class BufferLine with IndexedItem { } void eraseCell(int index, CursorStyle style) { + _version++; final offset = index * _cellSize; _data[offset + _cellForeground] = style.foreground; _data[offset + _cellBackground] = style.background; @@ -125,6 +150,7 @@ class BufferLine with IndexedItem { } void resetCell(int index) { + _version++; final offset = index * _cellSize; _data[offset + _cellForeground] = 0; _data[offset + _cellBackground] = 0; @@ -154,6 +180,7 @@ class BufferLine with IndexedItem { /// Remove [count] cells starting at [start]. Cells that are empty after the /// removal are filled with [style]. void removeCells(int start, int count, [CursorStyle? style]) { + _version++; assert(start >= 0 && start < _length); assert(count >= 0 && start + count <= _length); @@ -191,6 +218,7 @@ class BufferLine with IndexedItem { /// Inserts [count] cells at [start]. New cells are initialized with [style]. void insertCells(int start, int count, [CursorStyle? style]) { + _version++; style ??= CursorStyle.empty; if (start > 0 && getWidth(start - 1) == 2) { @@ -235,6 +263,7 @@ class BufferLine with IndexedItem { if (length == _length) { return; } + _version++; if (length > _length) { final newBufferSize = _calcCapacity(length) * _cellSize; @@ -270,9 +299,10 @@ class BufferLine with IndexedItem { } for (var i = cols - 1; i >= 0; i--) { - var codePoint = getCodePoint(i); + final content = getContent(i); - if (codePoint != 0) { + if (content & (CellContent.codepointMask | CellContent.clusterFlag) != + 0) { // we are at the last cell in this line that has content. // the length of this line is the index of this cell + 1 // the only exception is that if that last cell is wider @@ -287,6 +317,7 @@ class BufferLine with IndexedItem { /// Copies [len] cells from [src] starting at [srcCol] to [dstCol] at this /// line. void copyFrom(BufferLine src, int srcCol, int dstCol, int len) { + _version++; resize(dstCol + len); // data.setRange( @@ -333,8 +364,13 @@ class BufferLine with IndexedItem { final builder = StringBuffer(); for (var i = from; i < to; i++) { - final codePoint = getCodePoint(i); - final width = getWidth(i); + final content = getContent(i); + final width = content >> CellContent.widthShift; + if (content & CellContent.clusterFlag != 0) { + if (i + width <= to) builder.write(cellContentText(content)); + continue; + } + final codePoint = content & CellContent.codepointMask; if (codePoint != 0 && i + width <= to) { builder.writeCharCode(codePoint); } diff --git a/app/third_party/xterm/lib/src/core/cell.dart b/app/third_party/xterm/lib/src/core/cell.dart index 700f0c3e..b28af8cd 100644 --- a/app/third_party/xterm/lib/src/core/cell.dart +++ b/app/third_party/xterm/lib/src/core/cell.dart @@ -70,8 +70,14 @@ abstract class CellColor { } abstract class CellContent { + /// The code point, or with [clusterFlag] the cell's grapheme cluster index + /// (`GraphemeTable`). static const codepointMask = 0x1fffff; + /// The cell holds a grapheme cluster of several code points (a base with + /// combining marks, an emoji sequence, a flag). + static const clusterFlag = 1 << 21; + static const widthShift = 22; // static const widthMask = 3 << widthShift; } diff --git a/app/third_party/xterm/lib/src/ui/cell_glyphs.dart b/app/third_party/xterm/lib/src/ui/cell_glyphs.dart new file mode 100644 index 00000000..2d056434 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/cell_glyphs.dart @@ -0,0 +1,455 @@ +import 'dart:math' as math; +import 'dart:ui'; + +/// Box drawing (U+2500-257F), block elements (U+2580-259F) and Powerline +/// separators (U+E0B0-E0BF) drawn as geometry that fills the cell exactly, +/// so frames, bars and prompt segments join across cells and rows whatever +/// the font has (or lacks) and whatever the line height. +bool isCellGlyph(int codePoint) => + (codePoint >= 0x2500 && codePoint <= 0x259F) || + (codePoint >= 0xE0B0 && codePoint <= 0xE0BF); + +/// Paints [codePoint] (see [isCellGlyph]) in [color] over [cell]. Edges on +/// the cell's sides overlap the neighbours by half a pixel so antialiased +/// fractional cell edges leave no seam. +void paintCellGlyph(Canvas canvas, Rect cell, int codePoint, Color color) { + final paint = Paint() + ..color = color + ..isAntiAlias = true; + if (codePoint < 0x2580) { + _BoxDrawing(canvas, cell, paint).draw(codePoint); + } else if (codePoint < 0x25A0) { + _paintBlock(canvas, cell, codePoint, paint); + } else { + _paintPowerline(canvas, cell, codePoint, paint); + } +} + +const _bleed = 0.5; + +/// Widens the sides of [rect] that lie on [cell]'s sides by [_bleed]. +Rect _bled(Rect rect, Rect cell) => Rect.fromLTRB( + rect.left <= cell.left ? rect.left - _bleed : rect.left, + rect.top, + rect.right >= cell.right ? rect.right + _bleed : rect.right, + rect.bottom, + ); + +/// The arms of U+2500-257F: up, right, down and left in two bits each +/// (0 none, 1 light, 2 heavy, 3 double); 0 for the dashed, arc and diagonal +/// characters, which are drawn on their own. Generated from the Unicode +/// character names. +const List _boxArms = [ + 0x44, 0x88, 0x11, 0x22, 0x00, 0x00, 0x00, 0x00, // + 0x00, 0x00, 0x00, 0x00, 0x14, 0x18, 0x24, 0x28, // + 0x50, 0x90, 0x60, 0xA0, 0x05, 0x09, 0x06, 0x0A, // + 0x41, 0x81, 0x42, 0x82, 0x15, 0x19, 0x16, 0x25, // + 0x26, 0x1A, 0x29, 0x2A, 0x51, 0x91, 0x52, 0x61, // + 0x62, 0x92, 0xA1, 0xA2, 0x54, 0x94, 0x58, 0x98, // + 0x64, 0xA4, 0x68, 0xA8, 0x45, 0x85, 0x49, 0x89, // + 0x46, 0x86, 0x4A, 0x8A, 0x55, 0x95, 0x59, 0x99, // + 0x56, 0x65, 0x66, 0x96, 0x5A, 0xA5, 0x69, 0x9A, // + 0xA9, 0xA6, 0x6A, 0xAA, 0x00, 0x00, 0x00, 0x00, // + 0xCC, 0x33, 0x1C, 0x34, 0x3C, 0xD0, 0x70, 0xF0, // + 0x0D, 0x07, 0x0F, 0xC1, 0x43, 0xC3, 0x1D, 0x37, // + 0x3F, 0xD1, 0x73, 0xF3, 0xDC, 0x74, 0xFC, 0xCD, // + 0x47, 0xCF, 0xDD, 0x77, 0xFF, 0x00, 0x00, 0x00, // + 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x04, 0x10, // + 0x80, 0x02, 0x08, 0x20, 0x48, 0x21, 0x84, 0x12, // +]; + +const _none = 0; +const _light = 1; +const _heavy = 2; +const _double = 3; + +class _BoxDrawing { + _BoxDrawing(this.canvas, this.cell, this.paint) + : light = math.max(1.0, (cell.width / 8).roundToDouble()), + cx = (cell.left + cell.width / 2).floorToDouble(), + cy = (cell.top + cell.height / 2).floorToDouble(); + + final Canvas canvas; + final Rect cell; + final Paint paint; + + /// A light line's thickness; heavy is twice it, a double line two light + /// lines a light line apart. + final double light; + + /// The pixel the lines' centres run through. + final double cx; + final double cy; + + double get heavy => light * 2; + + void draw(int codePoint) { + final arms = _boxArms[codePoint - 0x2500]; + if (arms != 0) { + _arms(arms & 3, arms >> 2 & 3, arms >> 4 & 3, arms >> 6 & 3); + return; + } + switch (codePoint) { + case 0x2504 || 0x2505: + _dashes(3, horizontal: true, weight: (codePoint & 1) + 1); + case 0x2506 || 0x2507: + _dashes(3, horizontal: false, weight: (codePoint & 1) + 1); + case 0x2508 || 0x2509: + _dashes(4, horizontal: true, weight: (codePoint & 1) + 1); + case 0x250A || 0x250B: + _dashes(4, horizontal: false, weight: (codePoint & 1) + 1); + case 0x254C || 0x254D: + _dashes(2, horizontal: true, weight: (codePoint & 1) + 1); + case 0x254E || 0x254F: + _dashes(2, horizontal: false, weight: (codePoint & 1) + 1); + case >= 0x256D && <= 0x2570: + _arc(codePoint); + case >= 0x2571 && <= 0x2573: + _diagonals(codePoint); + } + } + + double _thickness(int weight) => weight == _heavy ? heavy : light; + + /// A horizontal stroke centred on [y] from [x0] to [x1]. + void _hLine(double x0, double x1, double y, double thickness) { + final top = y - (thickness / 2).floorToDouble(); + canvas.drawRect( + _bled(Rect.fromLTRB(x0, top, x1, top + thickness), cell), + paint, + ); + } + + /// A vertical stroke centred on [x] from [y0] to [y1]. + void _vLine(double x, double y0, double y1, double thickness) { + final left = x - (thickness / 2).floorToDouble(); + canvas.drawRect(Rect.fromLTRB(left, y0, left + thickness, y1), paint); + } + + /// The top (left) edge of a [thickness] stroke centred on [centre]. + static double _low(double centre, double thickness) => + centre - (thickness / 2).floorToDouble(); + + void _arms(int up, int right, int down, int left) { + final gap = light; + final verticalDouble = up == _double || down == _double; + final horizontalDouble = left == _double || right == _double; + + /// One arm from the cell's edge towards the centre. [before] and [after] + /// are the arms across it (up and down for a horizontal arm), [opposite] + /// the arm on the other side of the centre. + void arm( + int weight, { + required bool horizontal, + required bool positive, + required int before, + required int after, + required int opposite, + }) { + if (weight == _none) return; + final centre = horizontal ? cx : cy; + final sign = positive ? 1.0 : -1.0; + final edge = horizontal + ? (positive ? cell.right : cell.left) + : (positive ? cell.bottom : cell.top); + // Where the arm stops: the far side of a [thickness] line centred on + // [target], seen from the cell edge the arm starts at. + double reach(double target, double thickness) => positive + ? _low(target, thickness) + : _low(target, thickness) + thickness; + void stroke(double end, double across, double thickness) { + final a = math.min(end, edge); + final b = math.max(end, edge); + if (horizontal) { + _hLine(a, b, across, thickness); + } else { + _vLine(across, a, b, thickness); + } + } + + final acrossDouble = horizontal ? verticalDouble : horizontalDouble; + final mid = horizontal ? cy : cx; + if (weight != _double) { + double end; + if (acrossDouble && opposite == _none) { + // Against a double line: stop at its near line when it runs + // through, else span both lines it hangs from. + final through = before != _none && after != _none; + end = reach(centre + sign * (through ? gap : -gap), light); + } else { + final across = math.max(before, after); + end = reach( + centre, + across == _none || across == _double + ? _thickness(weight) + : _thickness(across), + ); + } + stroke(end, mid, _thickness(weight)); + return; + } + for (final side in const [-1.0, 1.0]) { + final near = side < 0 ? before : after; + final far = side < 0 ? after : before; + double end; + if (near == _double) { + end = reach(centre + sign * gap, light); + } else if (far == _double) { + end = reach(centre - sign * gap, light); + } else if (near != _none || far != _none) { + end = reach(centre, _thickness(math.max(near, far))); + } else { + end = reach(centre, light); + } + stroke(end, mid + side * gap, light); + } + } + + arm(right, + horizontal: true, + positive: true, + before: up, + after: down, + opposite: left); + arm(left, + horizontal: true, + positive: false, + before: up, + after: down, + opposite: right); + arm(down, + horizontal: false, + positive: true, + before: left, + after: right, + opposite: up); + arm(up, + horizontal: false, + positive: false, + before: left, + after: right, + opposite: down); + } + + void _dashes(int count, {required bool horizontal, required int weight}) { + final thickness = _thickness(weight); + final length = horizontal ? cell.width : cell.height; + final step = length / count; + final gap = math.max(1.0, (step * 0.4).roundToDouble()); + for (var i = 0; i < count; i++) { + final start = i * step + gap / 2; + final end = (i + 1) * step - gap / 2; + if (horizontal) { + final top = cy - (thickness / 2).floorToDouble(); + canvas.drawRect( + Rect.fromLTRB( + cell.left + start, + top, + cell.left + end, + top + thickness, + ), + paint, + ); + } else { + final left = cx - (thickness / 2).floorToDouble(); + canvas.drawRect( + Rect.fromLTRB( + left, cell.top + start, left + thickness, cell.top + end), + paint, + ); + } + } + } + + /// ╭ ╮ ╯ ╰: a quarter circle joining the two arms' centre lines. + void _arc(int codePoint) { + final x = cx - (light / 2).floorToDouble() + light / 2; + final y = cy - (light / 2).floorToDouble() + light / 2; + final toRight = codePoint == 0x256D || codePoint == 0x2570; + final toDown = codePoint == 0x256D || codePoint == 0x256E; + final hEdge = toRight ? cell.right + _bleed : cell.left - _bleed; + final vEdge = toDown ? cell.bottom : cell.top; + final radius = math.min((hEdge - x).abs(), (vEdge - y).abs()); + final hx = toRight ? x + radius : x - radius; + final vy = toDown ? y + radius : y - radius; + final path = Path() + ..moveTo(hEdge, y) + ..lineTo(hx, y) + ..arcToPoint( + Offset(x, vy), + radius: Radius.circular(radius), + clockwise: codePoint == 0x256E || codePoint == 0x2570, + ) + ..lineTo(x, vEdge); + canvas.drawPath( + path, + Paint() + ..color = paint.color + ..style = PaintingStyle.stroke + ..strokeWidth = light, + ); + } + + void _diagonals(int codePoint) { + final stroke = Paint() + ..color = paint.color + ..style = PaintingStyle.stroke + ..strokeWidth = light; + canvas.save(); + canvas.clipRect(cell); + if (codePoint != 0x2572) { + canvas.drawLine(cell.topRight, cell.bottomLeft, stroke); + } + if (codePoint != 0x2571) { + canvas.drawLine(cell.topLeft, cell.bottomRight, stroke); + } + canvas.restore(); + } +} + +void _paintBlock(Canvas canvas, Rect cell, int codePoint, Paint paint) { + final l = cell.left; + final t = cell.top; + final w = cell.width; + final h = cell.height; + // Edges inside the cell fall on whole pixels, so partial blocks are crisp. + double x(double f) => + f == 0 || f == 1 ? l + w * f : (l + w * f).roundToDouble(); + double y(double f) => + f == 0 || f == 1 ? t + h * f : (t + h * f).roundToDouble(); + void fill(double x0, double y0, double x1, double y1) { + canvas.drawRect( + _bled(Rect.fromLTRB(x(x0), y(y0), x(x1), y(y1)), cell), + paint, + ); + } + + switch (codePoint) { + case 0x2580: + fill(0, 0, 1, 0.5); + case >= 0x2581 && <= 0x2588: + fill(0, 1 - (codePoint - 0x2580) / 8, 1, 1); + case >= 0x2589 && <= 0x258F: + fill(0, 0, (0x2590 - codePoint) / 8, 1); + case 0x2590: + fill(0.5, 0, 1, 1); + case >= 0x2591 && <= 0x2593: + final alpha = (codePoint - 0x2590) / 4; + canvas.drawRect( + _bled(cell, cell), + Paint()..color = paint.color.withValues(alpha: paint.color.a * alpha), + ); + case 0x2594: + fill(0, 0, 1, 1 / 8); + case 0x2595: + fill(7 / 8, 0, 1, 1); + default: + // Quadrants U+2596-259F: upper left, upper right, lower left, lower + // right in bits 0-3. + const quadrants = [4, 8, 1, 13, 9, 7, 11, 2, 6, 14]; + final bits = quadrants[codePoint - 0x2596]; + if (bits & 1 != 0) fill(0, 0, 0.5, 0.5); + if (bits & 2 != 0) fill(0.5, 0, 1, 0.5); + if (bits & 4 != 0) fill(0, 0.5, 0.5, 1); + if (bits & 8 != 0) fill(0.5, 0.5, 1, 1); + } +} + +void _paintPowerline(Canvas canvas, Rect cell, int codePoint, Paint paint) { + final l = cell.left - _bleed; + final r = cell.right + _bleed; + final t = cell.top; + final b = cell.bottom; + final m = cell.center.dy; + final stroke = Paint() + ..color = paint.color + ..style = PaintingStyle.stroke + ..strokeWidth = math.max(1.0, (cell.width / 8).roundToDouble()); + + Path polygon(List points) => Path()..addPolygon(points, true); + + switch (codePoint) { + case 0xE0B0: + canvas.drawPath( + polygon([Offset(l, t), Offset(r, m), Offset(l, b)]), paint); + case 0xE0B1: + canvas.save(); + canvas.clipRect(cell); + canvas.drawPath( + Path() + ..moveTo(cell.left, t) + ..lineTo(cell.right, m) + ..lineTo(cell.left, b), + stroke, + ); + canvas.restore(); + case 0xE0B2: + canvas.drawPath( + polygon([Offset(r, t), Offset(l, m), Offset(r, b)]), paint); + case 0xE0B3: + canvas.save(); + canvas.clipRect(cell); + canvas.drawPath( + Path() + ..moveTo(cell.right, t) + ..lineTo(cell.left, m) + ..lineTo(cell.right, b), + stroke, + ); + canvas.restore(); + case 0xE0B4 || 0xE0B5: + // A half disc bulging right. + final oval = Rect.fromLTRB(cell.left - cell.width, t, cell.right, b); + final path = Path()..addArc(oval, -math.pi / 2, math.pi); + if (codePoint == 0xE0B4) { + path + ..lineTo(l, b) + ..lineTo(l, t) + ..close(); + canvas.drawPath(path, paint); + } else { + canvas.save(); + canvas.clipRect(cell); + canvas.drawPath(path, stroke); + canvas.restore(); + } + case 0xE0B6 || 0xE0B7: + final oval = Rect.fromLTRB(cell.left, t, cell.right + cell.width, b); + final path = Path()..addArc(oval, math.pi / 2, math.pi); + if (codePoint == 0xE0B6) { + path + ..lineTo(r, t) + ..lineTo(r, b) + ..close(); + canvas.drawPath(path, paint); + } else { + canvas.save(); + canvas.clipRect(cell); + canvas.drawPath(path, stroke); + canvas.restore(); + } + case 0xE0B8: + canvas.drawPath( + polygon([Offset(l, t), Offset(l, b), Offset(r, b)]), paint); + case 0xE0BA: + canvas.drawPath( + polygon([Offset(r, t), Offset(r, b), Offset(l, b)]), paint); + case 0xE0BC: + canvas.drawPath( + polygon([Offset(l, t), Offset(r, t), Offset(l, b)]), paint); + case 0xE0BE: + canvas.drawPath( + polygon([Offset(l, t), Offset(r, t), Offset(r, b)]), paint); + case 0xE0B9 || 0xE0BF: + _clippedLine(canvas, cell, cell.topLeft, cell.bottomRight, stroke); + case 0xE0BB || 0xE0BD: + _clippedLine(canvas, cell, cell.topRight, cell.bottomLeft, stroke); + } +} + +void _clippedLine(Canvas canvas, Rect cell, Offset a, Offset b, Paint paint) { + canvas.save(); + canvas.clipRect(cell); + canvas.drawLine(a, b, paint); + canvas.restore(); +} diff --git a/app/third_party/xterm/lib/src/ui/painter.dart b/app/third_party/xterm/lib/src/ui/painter.dart index 876d0fe7..0aa5c7b3 100644 --- a/app/third_party/xterm/lib/src/ui/painter.dart +++ b/app/third_party/xterm/lib/src/ui/painter.dart @@ -1,8 +1,11 @@ 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. @@ -26,13 +29,76 @@ class TerminalPainter { /// [_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(); - _paragraphCache.clear(); + _invalidate(); } TextScaler get textScaler => _textScaler; @@ -41,7 +107,7 @@ class TerminalPainter { if (value == _textScaler) return; _textScaler = value; _cellSize = _measureCharSize(); - _paragraphCache.clear(); + _invalidate(); } TerminalTheme get theme => _theme; @@ -50,7 +116,7 @@ class TerminalPainter { if (value == _theme) return; _theme = value; _colorPalette = PaletteBuilder(value).build(); - _paragraphCache.clear(); + _invalidate(); } Size _measureCharSize() { @@ -66,9 +132,12 @@ class TerminalPainter { 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, + paragraph.height.ceilToDouble(), ); paragraph.dispose(); @@ -82,7 +151,7 @@ class TerminalPainter { /// clear cached state related to font rendering. void clearFontCache() { _cellSize = _measureCharSize(); - _paragraphCache.clear(); + _invalidate(); } /// Paints the cursor based on the current cursor type. @@ -169,28 +238,183 @@ class TerminalPainter { ); } - /// Paints [line] to [canvas] at [offset]. The x offset of [offset] is usually - /// 0, and the y offset is the top of the line. + /// 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, - ) { + 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 charWidth = cellData.content >> CellContent.widthShift; - final cellOffset = offset.translate(i * cellWidth, 0); - - paintCell(canvas, cellOffset, cellData); - - if (charWidth == 2) { - i++; + 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') @@ -199,63 +423,62 @@ class TerminalPainter { paintCellForeground(canvas, offset, cellData); } - /// Paints the character in the cell represented by [cellData] to [canvas] at - /// [offset]. - @pragma('vm:prefer-inline') + /// 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 charCode = cellData.content & CellContent.codepointMask; - if (charCode == 0) return; + 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) { - final cellFlags = cellData.flags; - - var color = cellFlags & CellFlags.inverse == 0 - ? resolveForegroundColor(cellData.foreground) - : resolveBackgroundColor(cellData.background); - - if (cellData.flags & CellFlags.faint != 0) { - color = color.withOpacity(0.5); + 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); } - - final underline = cellFlags & CellFlags.underline != 0; - const decorated = - CellFlags.underline | CellFlags.strikethrough | CellFlags.overline; - final style = _textStyle.toTextStyle( - color: color, - 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, - ); - - // Flutter does not draw a decoration on a space which is not between - // other regular characters. As only single characters are drawn, this - // will never produce an underline below a space in the terminal. As a - // workaround the regular space CodePoint 0x20 is replaced with - // the CodePoint 0xA0. This is a non breaking space and a decoration can - // be drawn on it. - var char = String.fromCharCode(charCode); - if (cellFlags & decorated != 0 && charCode == 0x20) { - char = String.fromCharCode(0xA0); - } - paragraph = _paragraphCache.performAndCacheLayout( - char, - style, + text, + _cellTextStyle(cellData), _textScaler, cacheKey, ); } - canvas.drawParagraph(paragraph, offset); + 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). @@ -275,22 +498,12 @@ class TerminalPainter { /// [offset]. @pragma('vm:prefer-inline') void paintCellBackground(Canvas canvas, Offset offset, CellData cellData) { - late Color color; - final colorType = cellData.background & CellColor.typeMask; - - if (cellData.flags & CellFlags.inverse != 0) { - color = resolveForegroundColor(cellData.foreground); - } else if (colorType == CellColor.normal) { - return; - } else { - color = resolveBackgroundColor(cellData.background); - } - - final paint = Paint()..color = color; + 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); + canvas.drawRect(offset & size, Paint()..color = color); } /// Get the effective foreground color for a cell from information encoded in diff --git a/app/third_party/xterm/lib/src/ui/render.dart b/app/third_party/xterm/lib/src/ui/render.dart index f448a175..96c20bb8 100644 --- a/app/third_party/xterm/lib/src/ui/render.dart +++ b/app/third_party/xterm/lib/src/ui/render.dart @@ -14,6 +14,7 @@ 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/row_pictures.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'; @@ -176,6 +177,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { final TerminalPainter _painter; + final _rows = RowPictureCache(); + var _stickToBottom = true; void _onScroll() { @@ -219,6 +222,13 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { _controller.removeListener(_onControllerUpdate); _focusNode.removeListener(_onFocusChange); _cursorBlinkVisible?.removeListener(markNeedsPaint); + _rows.clear(); + } + + @override + void dispose() { + _rows.clear(); + super.dispose(); } @override @@ -461,13 +471,29 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { final effectFirstLine = firstLine.clamp(0, lines.length - 1); final effectLastLine = lastLine.clamp(0, lines.length - 1); + // Each line is drawn from its picture, recorded again only when the + // line changed, and settled into laid out text once it stays the same + // (RowPictureCache). + final generation = _painter.generation; + _rows.beginFrame(); for (var i = effectFirstLine; i <= effectLastLine; i++) { - _painter.paintLine( - canvas, - offset.translate(0, (i * charHeight + _lineOffset).truncateToDouble()), - lines[i], + final line = lines[i]; + final picture = _rows.pictureOf( + line, + generation, + (canvas, settled) => + _painter.paintLine(canvas, Offset.zero, line, paragraphs: settled), ); + final top = offset.translate( + 0, + (i * charHeight + _lineOffset).truncateToDouble(), + ); + canvas.save(); + canvas.translate(top.dx, top.dy); + canvas.drawPicture(picture); + canvas.restore(); } + _rows.trim((effectLastLine - effectFirstLine + 1) * 2 + 8); if (_terminal.buffer.absoluteCursorY >= effectFirstLine && _terminal.buffer.absoluteCursorY <= effectLastLine) { diff --git a/app/third_party/xterm/lib/src/ui/row_pictures.dart b/app/third_party/xterm/lib/src/ui/row_pictures.dart new file mode 100644 index 00000000..78224112 --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/row_pictures.dart @@ -0,0 +1,102 @@ +import 'dart:collection'; +import 'dart:ui'; + +import 'package:xterm/src/core/buffer/line.dart'; + +/// Paints a line at the origin; [settled] lines may lay out their text as +/// paragraphs (`TerminalPainter.paintLine`). +typedef RowPainter = void Function(Canvas canvas, bool settled); + +/// Pictures of painted lines, kept while a line's cells and the painter's +/// output stay the same, so a frame redraws only lines that changed: a +/// scrolled line is drawn again from its picture, and a full-screen redraw +/// of the same text records nothing new. +/// +/// A line is first recorded cell by cell from cached glyphs, which costs +/// little to record. Once it has been drawn unchanged in [settleAfter] +/// frames it is recorded again as settled, laying its text out as +/// paragraphs, which cost more to lay out but less to draw on every later +/// frame. Output streaming past never settles, so it never pays for the +/// layout; at most [settlePerFrame] lines settle in one frame. +class RowPictureCache { + RowPictureCache({this.settleAfter = 2, this.settlePerFrame = 8}); + + final int settleAfter; + final int settlePerFrame; + + final _entries = LinkedHashMap.identity(); + var _generation = -1; + var _settleBudget = 0; + + int get length => _entries.length; + + /// Starts a frame: up to [settlePerFrame] lines may settle in it. + void beginFrame() { + _settleBudget = settlePerFrame; + } + + /// Whether [line]'s picture is settled. + bool isSettled(BufferLine line) => _entries[line]?.settled ?? false; + + /// The picture of [line] painted by [paint], reused while the line's + /// version and [generation] (the painter's) are unchanged. + Picture pictureOf(BufferLine line, int generation, RowPainter paint) { + if (generation != _generation) { + clear(); + _generation = generation; + } + final cached = _entries.remove(line); + if (cached != null && cached.version == line.version) { + // Most recently used last. + _entries[line] = cached; + if (cached.settled) return cached.picture; + cached.reuses++; + if (cached.reuses < settleAfter || _settleBudget <= 0) { + return cached.picture; + } + _settleBudget--; + cached.picture.dispose(); + final entry = _record(line, paint, settled: true); + _entries[line] = entry; + return entry.picture; + } + cached?.picture.dispose(); + final entry = _record(line, paint, settled: false); + _entries[line] = entry; + return entry.picture; + } + + _RowPicture _record( + BufferLine line, + RowPainter paint, { + required bool settled, + }) { + final recorder = PictureRecorder(); + paint(Canvas(recorder), settled); + return _RowPicture(line.version, recorder.endRecording(), settled); + } + + /// Drops the least recently used pictures beyond [keep]. + void trim(int keep) { + while (_entries.length > keep) { + final oldest = _entries.keys.first; + _entries.remove(oldest)!.picture.dispose(); + } + } + + void clear() { + for (final entry in _entries.values) { + entry.picture.dispose(); + } + _entries.clear(); + } +} + +class _RowPicture { + _RowPicture(this.version, this.picture, this.settled); + + final int version; + final Picture picture; + final bool settled; + var reuses = 0; +} diff --git a/app/third_party/xterm/lib/src/ui/terminal_text_style.dart b/app/third_party/xterm/lib/src/ui/terminal_text_style.dart index d97acd72..44a7d4c2 100644 --- a/app/third_party/xterm/lib/src/ui/terminal_text_style.dart +++ b/app/third_party/xterm/lib/src/ui/terminal_text_style.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart' show listEquals; import 'package:flutter/widgets.dart'; const _kDefaultFontSize = 13.0; @@ -6,7 +7,8 @@ const _kDefaultHeight = 1.2; const _kDefaultFontFamily = 'monospace'; -const _kDefaultFontFamilyFallback = [ +/// The fallback families a [TerminalStyle] uses unless given its own. +const kTerminalDefaultFontFamilyFallback = [ 'Menlo', 'Monaco', 'Consolas', @@ -28,7 +30,7 @@ class TerminalStyle { this.fontSize = _kDefaultFontSize, this.height = _kDefaultHeight, this.fontFamily = _kDefaultFontFamily, - this.fontFamilyFallback = _kDefaultFontFamilyFallback, + this.fontFamilyFallback = kTerminalDefaultFontFamilyFallback, }); factory TerminalStyle.fromTextStyle(TextStyle textStyle) { @@ -39,7 +41,7 @@ class TerminalStyle { textStyle.fontFamilyFallback?.first ?? _kDefaultFontFamily, fontFamilyFallback: - textStyle.fontFamilyFallback ?? _kDefaultFontFamilyFallback, + textStyle.fontFamilyFallback ?? kTerminalDefaultFontFamilyFallback, ); } @@ -92,4 +94,22 @@ class TerminalStyle { fontFamilyFallback: fontFamilyFallback ?? this.fontFamilyFallback, ); } + + // Equal styles keep the painter's caches: a host that builds its style + // anew each frame does not make every line draw again. + @override + bool operator ==(Object other) => + other is TerminalStyle && + other.fontSize == fontSize && + other.height == height && + other.fontFamily == fontFamily && + listEquals(other.fontFamilyFallback, fontFamilyFallback); + + @override + int get hashCode => Object.hash( + fontSize, + height, + fontFamily, + Object.hashAll(fontFamilyFallback), + ); } diff --git a/app/third_party/xterm/lib/src/ui/terminal_theme.dart b/app/third_party/xterm/lib/src/ui/terminal_theme.dart index 0b70e422..571d8074 100644 --- a/app/third_party/xterm/lib/src/ui/terminal_theme.dart +++ b/app/third_party/xterm/lib/src/ui/terminal_theme.dart @@ -54,4 +54,47 @@ class TerminalTheme { final Color searchHitBackground; final Color searchHitBackgroundCurrent; final Color searchHitForeground; + + List get _colors => [ + cursor, + selection, + foreground, + background, + black, + red, + green, + yellow, + blue, + magenta, + cyan, + white, + brightBlack, + brightRed, + brightGreen, + brightYellow, + brightBlue, + brightMagenta, + brightCyan, + brightWhite, + searchHitBackground, + searchHitBackgroundCurrent, + searchHitForeground, + ]; + + // Equal themes keep the painter's caches: a host that builds its theme + // anew each frame does not make every line draw again. + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + if (other is! TerminalTheme) return false; + final mine = _colors; + final theirs = other._colors; + for (var i = 0; i < mine.length; i++) { + if (mine[i] != theirs[i]) return false; + } + return true; + } + + @override + int get hashCode => Object.hashAll(_colors); } diff --git a/app/third_party/xterm/lib/src/ui/text_runs.dart b/app/third_party/xterm/lib/src/ui/text_runs.dart new file mode 100644 index 00000000..466157ea --- /dev/null +++ b/app/third_party/xterm/lib/src/ui/text_runs.dart @@ -0,0 +1,147 @@ +import 'dart:ui'; + +import 'package:flutter/painting.dart'; +import 'package:quiver/collection.dart'; + +/// The text of one line's plain cells (see [isRunCharacter]) as a single +/// paragraph with a style span per run of same-styled cells, so a line is +/// laid out and drawn once rather than cell by cell. Columns drawn some other +/// way (wide characters, clusters, symbols, empty cells) are spaces, which +/// keep the following text on the grid since every glyph of the terminal +/// font advances one cell. +class RowText { + final _text = StringBuffer(); + final _starts = []; + final _keys = []; + final _styles = []; + final _decorated = []; + var _length = 0; + var _ink = 0; + + /// Characters with ink added since [clear]. + int get ink => _ink; + + void clear() { + _text.clear(); + _starts.clear(); + _keys.clear(); + _styles.clear(); + _decorated.clear(); + _length = 0; + _ink = 0; + } + + /// Whether a character in the style [key] continues the current span. + bool continues(int key) => _keys.isNotEmpty && _keys.last == key; + + /// Adds one cell's character [code] in the style [key] identifies: + /// [style] builds it, and is needed only when it starts a span (see + /// [continues]); [decorated] when it draws lines. + void add( + int code, + int key, + TextStyle Function()? style, { + required bool decorated, + }) { + if (!continues(key)) { + _starts.add(_text.length); + _keys.add(key); + _styles.add(style!); + _decorated.add(decorated); + } + _text.writeCharCode(code); + _length = _text.length; + if (code != 0x20 && code != 0xA0) _ink++; + } + + /// Adds [columns] columns without ink. Inside a decorated span they get + /// a plain span, so the decoration does not run under them. + void skip(int columns, TextStyle Function() plain) { + if (_keys.isEmpty || _decorated.last) { + _starts.add(_text.length); + _keys.add(_plainKey); + _styles.add(plain); + _decorated.add(false); + } + for (var i = 0; i < columns; i++) { + _text.writeCharCode(0x20); + } + } + + static const _plainKey = -1; + + /// The laid out paragraph, from [cache] when the same text and spans were + /// laid out before; null when the font's glyphs do not fall on the grid + /// of [cellWidth] (a fallback font, a proportional family). + Paragraph? layout(TextRunCache cache, TextScaler scaler, double cellWidth) { + final text = _text.toString().substring(0, _length); + // Spans that start after the last character with ink are left out. + var spans = _starts.length; + while (spans > 0 && _starts[spans - 1] >= text.length) { + spans--; + } + final signature = StringBuffer(); + for (var i = 0; i < spans; i++) { + signature + ..write(_starts[i]) + ..write(':') + ..write(_keys[i]) + ..write(','); + } + return cache.laidOut((text, signature.toString()), () { + final builder = ParagraphBuilder(_styles.first().getParagraphStyle()); + for (var i = 0; i < spans; i++) { + final start = _starts[i]; + final end = i + 1 < spans ? _starts[i + 1] : text.length; + builder + ..pushStyle(_styles[i]().getTextStyle(textScaler: scaler)) + ..addText(text.substring(start, end)) + ..pop(); + } + return builder.build() + ..layout(const ParagraphConstraints(width: double.infinity)); + }, text.length * cellWidth); + } +} + +/// Laid out [RowText] paragraphs, most recently used kept, so lines that +/// repeat (a redrawn screen, `yes`) are laid out once. +class TextRunCache { + TextRunCache(int maximumSize) + : _cache = LruMap<(String, String), Paragraph?>( + maximumSize: maximumSize, + ); + + final LruMap<(String, String), Paragraph?> _cache; + + /// The paragraph [build] makes for [key], or null when it is not + /// [expectedWidth] wide (to half a pixel). + Paragraph? laidOut( + (String, String) key, + Paragraph Function() build, + double expectedWidth, + ) { + if (_cache.containsKey(key)) return _cache[key]; + final paragraph = build(); + final aligned = (paragraph.maxIntrinsicWidth - expectedWidth).abs() <= 0.5; + if (!aligned) paragraph.dispose(); + final result = aligned ? paragraph : null; + _cache[key] = result; + return result; + } + + void clear() { + _cache.clear(); + } + + int get length => _cache.length; +} + +/// Whether [codePoint] may be drawn in a line's [RowText]: printable ASCII +/// and Latin-1 to Latin Extended-B, which the bundled monospace family draws +/// itself, one cell each. Everything else (symbols, other scripts, emoji) is +/// drawn in its own cell, where a fallback font's different advance cannot +/// shift the cells after it. +bool isRunCharacter(int codePoint) => + (codePoint > 0x20 && codePoint < 0x7F) || + (codePoint >= 0xA0 && codePoint < 0x250 && codePoint != 0xAD); diff --git a/app/third_party/xterm/lib/src/utils/unicode_tables.dart b/app/third_party/xterm/lib/src/utils/unicode_tables.dart new file mode 100644 index 00000000..148a68cb --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/unicode_tables.dart @@ -0,0 +1,1472 @@ +// GENERATED by tool/gen_unicode_tables.py from Python unicodedata 16.0.0 and emoji-data.txt. +// Do not edit by hand. Each list holds inclusive [first, last] pairs. + +const String unicodeTablesVersion = '16.0.0'; + +/// Code points glibc wcwidth measures as 0 columns (they join the previous cell). +const List zeroWidthRanges = [ + 0x300, + 0x36F, + 0x483, + 0x489, + 0x591, + 0x5BD, + 0x5BF, + 0x5BF, + 0x5C1, + 0x5C2, + 0x5C4, + 0x5C5, + 0x5C7, + 0x5C7, + 0x610, + 0x61A, + 0x61C, + 0x61C, + 0x64B, + 0x65F, + 0x670, + 0x670, + 0x6D6, + 0x6DC, + 0x6DF, + 0x6E4, + 0x6E7, + 0x6E8, + 0x6EA, + 0x6ED, + 0x711, + 0x711, + 0x730, + 0x74A, + 0x7A6, + 0x7B0, + 0x7EB, + 0x7F3, + 0x7FD, + 0x7FD, + 0x816, + 0x819, + 0x81B, + 0x823, + 0x825, + 0x827, + 0x829, + 0x82D, + 0x859, + 0x85B, + 0x897, + 0x89F, + 0x8CA, + 0x8E1, + 0x8E3, + 0x902, + 0x93A, + 0x93A, + 0x93C, + 0x93C, + 0x941, + 0x948, + 0x94D, + 0x94D, + 0x951, + 0x957, + 0x962, + 0x963, + 0x981, + 0x981, + 0x9BC, + 0x9BC, + 0x9C1, + 0x9C4, + 0x9CD, + 0x9CD, + 0x9E2, + 0x9E3, + 0x9FE, + 0x9FE, + 0xA01, + 0xA02, + 0xA3C, + 0xA3C, + 0xA41, + 0xA42, + 0xA47, + 0xA48, + 0xA4B, + 0xA4D, + 0xA51, + 0xA51, + 0xA70, + 0xA71, + 0xA75, + 0xA75, + 0xA81, + 0xA82, + 0xABC, + 0xABC, + 0xAC1, + 0xAC5, + 0xAC7, + 0xAC8, + 0xACD, + 0xACD, + 0xAE2, + 0xAE3, + 0xAFA, + 0xAFF, + 0xB01, + 0xB01, + 0xB3C, + 0xB3C, + 0xB3F, + 0xB3F, + 0xB41, + 0xB44, + 0xB4D, + 0xB4D, + 0xB55, + 0xB56, + 0xB62, + 0xB63, + 0xB82, + 0xB82, + 0xBC0, + 0xBC0, + 0xBCD, + 0xBCD, + 0xC00, + 0xC00, + 0xC04, + 0xC04, + 0xC3C, + 0xC3C, + 0xC3E, + 0xC40, + 0xC46, + 0xC48, + 0xC4A, + 0xC4D, + 0xC55, + 0xC56, + 0xC62, + 0xC63, + 0xC81, + 0xC81, + 0xCBC, + 0xCBC, + 0xCBF, + 0xCBF, + 0xCC6, + 0xCC6, + 0xCCC, + 0xCCD, + 0xCE2, + 0xCE3, + 0xD00, + 0xD01, + 0xD3B, + 0xD3C, + 0xD41, + 0xD44, + 0xD4D, + 0xD4D, + 0xD62, + 0xD63, + 0xD81, + 0xD81, + 0xDCA, + 0xDCA, + 0xDD2, + 0xDD4, + 0xDD6, + 0xDD6, + 0xE31, + 0xE31, + 0xE34, + 0xE3A, + 0xE47, + 0xE4E, + 0xEB1, + 0xEB1, + 0xEB4, + 0xEBC, + 0xEC8, + 0xECE, + 0xF18, + 0xF19, + 0xF35, + 0xF35, + 0xF37, + 0xF37, + 0xF39, + 0xF39, + 0xF71, + 0xF7E, + 0xF80, + 0xF84, + 0xF86, + 0xF87, + 0xF8D, + 0xF97, + 0xF99, + 0xFBC, + 0xFC6, + 0xFC6, + 0x102D, + 0x1030, + 0x1032, + 0x1037, + 0x1039, + 0x103A, + 0x103D, + 0x103E, + 0x1058, + 0x1059, + 0x105E, + 0x1060, + 0x1071, + 0x1074, + 0x1082, + 0x1082, + 0x1085, + 0x1086, + 0x108D, + 0x108D, + 0x109D, + 0x109D, + 0x1160, + 0x11FF, + 0x135D, + 0x135F, + 0x1712, + 0x1714, + 0x1732, + 0x1733, + 0x1752, + 0x1753, + 0x1772, + 0x1773, + 0x17B4, + 0x17B5, + 0x17B7, + 0x17BD, + 0x17C6, + 0x17C6, + 0x17C9, + 0x17D3, + 0x17DD, + 0x17DD, + 0x180B, + 0x180F, + 0x1885, + 0x1886, + 0x18A9, + 0x18A9, + 0x1920, + 0x1922, + 0x1927, + 0x1928, + 0x1932, + 0x1932, + 0x1939, + 0x193B, + 0x1A17, + 0x1A18, + 0x1A1B, + 0x1A1B, + 0x1A56, + 0x1A56, + 0x1A58, + 0x1A5E, + 0x1A60, + 0x1A60, + 0x1A62, + 0x1A62, + 0x1A65, + 0x1A6C, + 0x1A73, + 0x1A7C, + 0x1A7F, + 0x1A7F, + 0x1AB0, + 0x1ACE, + 0x1B00, + 0x1B03, + 0x1B34, + 0x1B34, + 0x1B36, + 0x1B3A, + 0x1B3C, + 0x1B3C, + 0x1B42, + 0x1B42, + 0x1B6B, + 0x1B73, + 0x1B80, + 0x1B81, + 0x1BA2, + 0x1BA5, + 0x1BA8, + 0x1BA9, + 0x1BAB, + 0x1BAD, + 0x1BE6, + 0x1BE6, + 0x1BE8, + 0x1BE9, + 0x1BED, + 0x1BED, + 0x1BEF, + 0x1BF1, + 0x1C2C, + 0x1C33, + 0x1C36, + 0x1C37, + 0x1CD0, + 0x1CD2, + 0x1CD4, + 0x1CE0, + 0x1CE2, + 0x1CE8, + 0x1CED, + 0x1CED, + 0x1CF4, + 0x1CF4, + 0x1CF8, + 0x1CF9, + 0x1DC0, + 0x1DFF, + 0x200B, + 0x200F, + 0x202A, + 0x202E, + 0x2060, + 0x2064, + 0x2066, + 0x206F, + 0x20D0, + 0x20F0, + 0x2CEF, + 0x2CF1, + 0x2D7F, + 0x2D7F, + 0x2DE0, + 0x2DFF, + 0x302A, + 0x302D, + 0x3099, + 0x309A, + 0x3164, + 0x3164, + 0xA66F, + 0xA672, + 0xA674, + 0xA67D, + 0xA69E, + 0xA69F, + 0xA6F0, + 0xA6F1, + 0xA802, + 0xA802, + 0xA806, + 0xA806, + 0xA80B, + 0xA80B, + 0xA825, + 0xA826, + 0xA82C, + 0xA82C, + 0xA8C4, + 0xA8C5, + 0xA8E0, + 0xA8F1, + 0xA8FF, + 0xA8FF, + 0xA926, + 0xA92D, + 0xA947, + 0xA951, + 0xA980, + 0xA982, + 0xA9B3, + 0xA9B3, + 0xA9B6, + 0xA9B9, + 0xA9BC, + 0xA9BD, + 0xA9E5, + 0xA9E5, + 0xAA29, + 0xAA2E, + 0xAA31, + 0xAA32, + 0xAA35, + 0xAA36, + 0xAA43, + 0xAA43, + 0xAA4C, + 0xAA4C, + 0xAA7C, + 0xAA7C, + 0xAAB0, + 0xAAB0, + 0xAAB2, + 0xAAB4, + 0xAAB7, + 0xAAB8, + 0xAABE, + 0xAABF, + 0xAAC1, + 0xAAC1, + 0xAAEC, + 0xAAED, + 0xAAF6, + 0xAAF6, + 0xABE5, + 0xABE5, + 0xABE8, + 0xABE8, + 0xABED, + 0xABED, + 0xD7B0, + 0xD7FF, + 0xFB1E, + 0xFB1E, + 0xFE00, + 0xFE0F, + 0xFE20, + 0xFE2F, + 0xFEFF, + 0xFEFF, + 0xFFA0, + 0xFFA0, + 0x101FD, + 0x101FD, + 0x102E0, + 0x102E0, + 0x10376, + 0x1037A, + 0x10A01, + 0x10A03, + 0x10A05, + 0x10A06, + 0x10A0C, + 0x10A0F, + 0x10A38, + 0x10A3A, + 0x10A3F, + 0x10A3F, + 0x10AE5, + 0x10AE6, + 0x10D24, + 0x10D27, + 0x10D69, + 0x10D6D, + 0x10EAB, + 0x10EAC, + 0x10EFC, + 0x10EFF, + 0x10F46, + 0x10F50, + 0x10F82, + 0x10F85, + 0x11001, + 0x11001, + 0x11038, + 0x11046, + 0x11070, + 0x11070, + 0x11073, + 0x11074, + 0x1107F, + 0x11081, + 0x110B3, + 0x110B6, + 0x110B9, + 0x110BA, + 0x110C2, + 0x110C2, + 0x11100, + 0x11102, + 0x11127, + 0x1112B, + 0x1112D, + 0x11134, + 0x11173, + 0x11173, + 0x11180, + 0x11181, + 0x111B6, + 0x111BE, + 0x111C9, + 0x111CC, + 0x111CF, + 0x111CF, + 0x1122F, + 0x11231, + 0x11234, + 0x11234, + 0x11236, + 0x11237, + 0x1123E, + 0x1123E, + 0x11241, + 0x11241, + 0x112DF, + 0x112DF, + 0x112E3, + 0x112EA, + 0x11300, + 0x11301, + 0x1133B, + 0x1133C, + 0x11340, + 0x11340, + 0x11366, + 0x1136C, + 0x11370, + 0x11374, + 0x113BB, + 0x113C0, + 0x113CE, + 0x113CE, + 0x113D0, + 0x113D0, + 0x113D2, + 0x113D2, + 0x113E1, + 0x113E2, + 0x11438, + 0x1143F, + 0x11442, + 0x11444, + 0x11446, + 0x11446, + 0x1145E, + 0x1145E, + 0x114B3, + 0x114B8, + 0x114BA, + 0x114BA, + 0x114BF, + 0x114C0, + 0x114C2, + 0x114C3, + 0x115B2, + 0x115B5, + 0x115BC, + 0x115BD, + 0x115BF, + 0x115C0, + 0x115DC, + 0x115DD, + 0x11633, + 0x1163A, + 0x1163D, + 0x1163D, + 0x1163F, + 0x11640, + 0x116AB, + 0x116AB, + 0x116AD, + 0x116AD, + 0x116B0, + 0x116B5, + 0x116B7, + 0x116B7, + 0x1171D, + 0x1171D, + 0x1171F, + 0x1171F, + 0x11722, + 0x11725, + 0x11727, + 0x1172B, + 0x1182F, + 0x11837, + 0x11839, + 0x1183A, + 0x1193B, + 0x1193C, + 0x1193E, + 0x1193E, + 0x11943, + 0x11943, + 0x119D4, + 0x119D7, + 0x119DA, + 0x119DB, + 0x119E0, + 0x119E0, + 0x11A01, + 0x11A0A, + 0x11A33, + 0x11A38, + 0x11A3B, + 0x11A3E, + 0x11A47, + 0x11A47, + 0x11A51, + 0x11A56, + 0x11A59, + 0x11A5B, + 0x11A8A, + 0x11A96, + 0x11A98, + 0x11A99, + 0x11C30, + 0x11C36, + 0x11C38, + 0x11C3D, + 0x11C3F, + 0x11C3F, + 0x11C92, + 0x11CA7, + 0x11CAA, + 0x11CB0, + 0x11CB2, + 0x11CB3, + 0x11CB5, + 0x11CB6, + 0x11D31, + 0x11D36, + 0x11D3A, + 0x11D3A, + 0x11D3C, + 0x11D3D, + 0x11D3F, + 0x11D45, + 0x11D47, + 0x11D47, + 0x11D90, + 0x11D91, + 0x11D95, + 0x11D95, + 0x11D97, + 0x11D97, + 0x11EF3, + 0x11EF4, + 0x11F00, + 0x11F01, + 0x11F36, + 0x11F3A, + 0x11F40, + 0x11F40, + 0x11F42, + 0x11F42, + 0x11F5A, + 0x11F5A, + 0x13440, + 0x13440, + 0x13447, + 0x13455, + 0x1611E, + 0x16129, + 0x1612D, + 0x1612F, + 0x16AF0, + 0x16AF4, + 0x16B30, + 0x16B36, + 0x16F4F, + 0x16F4F, + 0x16F8F, + 0x16F92, + 0x16FE4, + 0x16FE4, + 0x1BC9D, + 0x1BC9E, + 0x1BCA0, + 0x1BCA3, + 0x1CF00, + 0x1CF2D, + 0x1CF30, + 0x1CF46, + 0x1D167, + 0x1D169, + 0x1D173, + 0x1D182, + 0x1D185, + 0x1D18B, + 0x1D1AA, + 0x1D1AD, + 0x1D242, + 0x1D244, + 0x1DA00, + 0x1DA36, + 0x1DA3B, + 0x1DA6C, + 0x1DA75, + 0x1DA75, + 0x1DA84, + 0x1DA84, + 0x1DA9B, + 0x1DA9F, + 0x1DAA1, + 0x1DAAF, + 0x1E000, + 0x1E006, + 0x1E008, + 0x1E018, + 0x1E01B, + 0x1E021, + 0x1E023, + 0x1E024, + 0x1E026, + 0x1E02A, + 0x1E08F, + 0x1E08F, + 0x1E130, + 0x1E136, + 0x1E2AE, + 0x1E2AE, + 0x1E2EC, + 0x1E2EF, + 0x1E4EC, + 0x1E4EF, + 0x1E5EE, + 0x1E5EF, + 0x1E8D0, + 0x1E8D6, + 0x1E944, + 0x1E94A, + 0xE0001, + 0xE0001, + 0xE0020, + 0xE007F, + 0xE0100, + 0xE01EF, +]; + +/// East Asian Width W or F: two columns. +const List wideRanges = [ + 0x1100, + 0x115F, + 0x231A, + 0x231B, + 0x2329, + 0x232A, + 0x23E9, + 0x23EC, + 0x23F0, + 0x23F0, + 0x23F3, + 0x23F3, + 0x25FD, + 0x25FE, + 0x2614, + 0x2615, + 0x2630, + 0x2637, + 0x2648, + 0x2653, + 0x267F, + 0x267F, + 0x268A, + 0x268F, + 0x2693, + 0x2693, + 0x26A1, + 0x26A1, + 0x26AA, + 0x26AB, + 0x26BD, + 0x26BE, + 0x26C4, + 0x26C5, + 0x26CE, + 0x26CE, + 0x26D4, + 0x26D4, + 0x26EA, + 0x26EA, + 0x26F2, + 0x26F3, + 0x26F5, + 0x26F5, + 0x26FA, + 0x26FA, + 0x26FD, + 0x26FD, + 0x2705, + 0x2705, + 0x270A, + 0x270B, + 0x2728, + 0x2728, + 0x274C, + 0x274C, + 0x274E, + 0x274E, + 0x2753, + 0x2755, + 0x2757, + 0x2757, + 0x2795, + 0x2797, + 0x27B0, + 0x27B0, + 0x27BF, + 0x27BF, + 0x2B1B, + 0x2B1C, + 0x2B50, + 0x2B50, + 0x2B55, + 0x2B55, + 0x2E80, + 0x2E99, + 0x2E9B, + 0x2EF3, + 0x2F00, + 0x2FD5, + 0x2FF0, + 0x303E, + 0x3041, + 0x3096, + 0x3099, + 0x30FF, + 0x3105, + 0x312F, + 0x3131, + 0x318E, + 0x3190, + 0x31E5, + 0x31EF, + 0x321E, + 0x3220, + 0xA48C, + 0xA490, + 0xA4C6, + 0xA960, + 0xA97C, + 0xAC00, + 0xD7A3, + 0xF900, + 0xFAFF, + 0xFE10, + 0xFE19, + 0xFE30, + 0xFE52, + 0xFE54, + 0xFE66, + 0xFE68, + 0xFE6B, + 0xFF01, + 0xFF60, + 0xFFE0, + 0xFFE6, + 0x16FE0, + 0x16FE4, + 0x16FF0, + 0x16FF1, + 0x17000, + 0x187F7, + 0x18800, + 0x18CD5, + 0x18CFF, + 0x18D08, + 0x1AFF0, + 0x1AFF3, + 0x1AFF5, + 0x1AFFB, + 0x1AFFD, + 0x1AFFE, + 0x1B000, + 0x1B122, + 0x1B132, + 0x1B132, + 0x1B150, + 0x1B152, + 0x1B155, + 0x1B155, + 0x1B164, + 0x1B167, + 0x1B170, + 0x1B2FB, + 0x1D300, + 0x1D356, + 0x1D360, + 0x1D376, + 0x1F004, + 0x1F004, + 0x1F0CF, + 0x1F0CF, + 0x1F18E, + 0x1F18E, + 0x1F191, + 0x1F19A, + 0x1F200, + 0x1F202, + 0x1F210, + 0x1F23B, + 0x1F240, + 0x1F248, + 0x1F250, + 0x1F251, + 0x1F260, + 0x1F265, + 0x1F300, + 0x1F320, + 0x1F32D, + 0x1F335, + 0x1F337, + 0x1F37C, + 0x1F37E, + 0x1F393, + 0x1F3A0, + 0x1F3CA, + 0x1F3CF, + 0x1F3D3, + 0x1F3E0, + 0x1F3F0, + 0x1F3F4, + 0x1F3F4, + 0x1F3F8, + 0x1F43E, + 0x1F440, + 0x1F440, + 0x1F442, + 0x1F4FC, + 0x1F4FF, + 0x1F53D, + 0x1F54B, + 0x1F54E, + 0x1F550, + 0x1F567, + 0x1F57A, + 0x1F57A, + 0x1F595, + 0x1F596, + 0x1F5A4, + 0x1F5A4, + 0x1F5FB, + 0x1F64F, + 0x1F680, + 0x1F6C5, + 0x1F6CC, + 0x1F6CC, + 0x1F6D0, + 0x1F6D2, + 0x1F6D5, + 0x1F6D7, + 0x1F6DC, + 0x1F6DF, + 0x1F6EB, + 0x1F6EC, + 0x1F6F4, + 0x1F6FC, + 0x1F7E0, + 0x1F7EB, + 0x1F7F0, + 0x1F7F0, + 0x1F90C, + 0x1F93A, + 0x1F93C, + 0x1F945, + 0x1F947, + 0x1F9FF, + 0x1FA70, + 0x1FA7C, + 0x1FA80, + 0x1FA89, + 0x1FA8F, + 0x1FAC6, + 0x1FACE, + 0x1FADC, + 0x1FADF, + 0x1FAE9, + 0x1FAF0, + 0x1FAF8, + 0x20000, + 0x2FFFD, + 0x30000, + 0x3FFFD, +]; + +/// Extended_Pictographic: what a ZWJ joins into one emoji. +const List extendedPictographicRanges = [ + 0xA9, + 0xA9, + 0xAE, + 0xAE, + 0x203C, + 0x203C, + 0x2049, + 0x2049, + 0x2122, + 0x2122, + 0x2139, + 0x2139, + 0x2194, + 0x2199, + 0x21A9, + 0x21AA, + 0x231A, + 0x231B, + 0x2328, + 0x2328, + 0x2388, + 0x2388, + 0x23CF, + 0x23CF, + 0x23E9, + 0x23F3, + 0x23F8, + 0x23FA, + 0x24C2, + 0x24C2, + 0x25AA, + 0x25AB, + 0x25B6, + 0x25B6, + 0x25C0, + 0x25C0, + 0x25FB, + 0x25FE, + 0x2600, + 0x2605, + 0x2607, + 0x2612, + 0x2614, + 0x2685, + 0x2690, + 0x2705, + 0x2708, + 0x2712, + 0x2714, + 0x2714, + 0x2716, + 0x2716, + 0x271D, + 0x271D, + 0x2721, + 0x2721, + 0x2728, + 0x2728, + 0x2733, + 0x2734, + 0x2744, + 0x2744, + 0x2747, + 0x2747, + 0x274C, + 0x274C, + 0x274E, + 0x274E, + 0x2753, + 0x2755, + 0x2757, + 0x2757, + 0x2763, + 0x2767, + 0x2795, + 0x2797, + 0x27A1, + 0x27A1, + 0x27B0, + 0x27B0, + 0x27BF, + 0x27BF, + 0x2934, + 0x2935, + 0x2B05, + 0x2B07, + 0x2B1B, + 0x2B1C, + 0x2B50, + 0x2B50, + 0x2B55, + 0x2B55, + 0x3030, + 0x3030, + 0x303D, + 0x303D, + 0x3297, + 0x3297, + 0x3299, + 0x3299, + 0x1F000, + 0x1F0FF, + 0x1F10D, + 0x1F10F, + 0x1F12F, + 0x1F12F, + 0x1F16C, + 0x1F171, + 0x1F17E, + 0x1F17F, + 0x1F18E, + 0x1F18E, + 0x1F191, + 0x1F19A, + 0x1F1AD, + 0x1F1E5, + 0x1F201, + 0x1F20F, + 0x1F21A, + 0x1F21A, + 0x1F22F, + 0x1F22F, + 0x1F232, + 0x1F23A, + 0x1F23C, + 0x1F23F, + 0x1F249, + 0x1F3FA, + 0x1F400, + 0x1F53D, + 0x1F546, + 0x1F64F, + 0x1F680, + 0x1F6FF, + 0x1F774, + 0x1F77F, + 0x1F7D5, + 0x1F7FF, + 0x1F80C, + 0x1F80F, + 0x1F848, + 0x1F84F, + 0x1F85A, + 0x1F85F, + 0x1F888, + 0x1F88F, + 0x1F8AE, + 0x1F8FF, + 0x1F90C, + 0x1F93A, + 0x1F93C, + 0x1F945, + 0x1F947, + 0x1FAFF, + 0x1FC00, + 0x1FFFD, +]; + +/// Emoji shown as text by default (Emoji and not Emoji_Presentation): U+FE0F after one asks for the two-column emoji form. +const List emojiTextDefaultRanges = [ + 0x23, + 0x23, + 0x2A, + 0x2A, + 0x30, + 0x39, + 0xA9, + 0xA9, + 0xAE, + 0xAE, + 0x203C, + 0x203C, + 0x2049, + 0x2049, + 0x2122, + 0x2122, + 0x2139, + 0x2139, + 0x2194, + 0x2199, + 0x21A9, + 0x21AA, + 0x2328, + 0x2328, + 0x23CF, + 0x23CF, + 0x23ED, + 0x23EF, + 0x23F1, + 0x23F2, + 0x23F8, + 0x23FA, + 0x24C2, + 0x24C2, + 0x25AA, + 0x25AB, + 0x25B6, + 0x25B6, + 0x25C0, + 0x25C0, + 0x25FB, + 0x25FC, + 0x2600, + 0x2604, + 0x260E, + 0x260E, + 0x2611, + 0x2611, + 0x2618, + 0x2618, + 0x261D, + 0x261D, + 0x2620, + 0x2620, + 0x2622, + 0x2623, + 0x2626, + 0x2626, + 0x262A, + 0x262A, + 0x262E, + 0x262F, + 0x2638, + 0x263A, + 0x2640, + 0x2640, + 0x2642, + 0x2642, + 0x265F, + 0x2660, + 0x2663, + 0x2663, + 0x2665, + 0x2666, + 0x2668, + 0x2668, + 0x267B, + 0x267B, + 0x267E, + 0x267E, + 0x2692, + 0x2692, + 0x2694, + 0x2697, + 0x2699, + 0x2699, + 0x269B, + 0x269C, + 0x26A0, + 0x26A0, + 0x26A7, + 0x26A7, + 0x26B0, + 0x26B1, + 0x26C8, + 0x26C8, + 0x26CF, + 0x26CF, + 0x26D1, + 0x26D1, + 0x26D3, + 0x26D3, + 0x26E9, + 0x26E9, + 0x26F0, + 0x26F1, + 0x26F4, + 0x26F4, + 0x26F7, + 0x26F9, + 0x2702, + 0x2702, + 0x2708, + 0x2709, + 0x270C, + 0x270D, + 0x270F, + 0x270F, + 0x2712, + 0x2712, + 0x2714, + 0x2714, + 0x2716, + 0x2716, + 0x271D, + 0x271D, + 0x2721, + 0x2721, + 0x2733, + 0x2734, + 0x2744, + 0x2744, + 0x2747, + 0x2747, + 0x2763, + 0x2764, + 0x27A1, + 0x27A1, + 0x2934, + 0x2935, + 0x2B05, + 0x2B07, + 0x3030, + 0x3030, + 0x303D, + 0x303D, + 0x3297, + 0x3297, + 0x3299, + 0x3299, + 0x1F170, + 0x1F171, + 0x1F17E, + 0x1F17F, + 0x1F202, + 0x1F202, + 0x1F237, + 0x1F237, + 0x1F321, + 0x1F321, + 0x1F324, + 0x1F32C, + 0x1F336, + 0x1F336, + 0x1F37D, + 0x1F37D, + 0x1F396, + 0x1F397, + 0x1F399, + 0x1F39B, + 0x1F39E, + 0x1F39F, + 0x1F3CB, + 0x1F3CE, + 0x1F3D4, + 0x1F3DF, + 0x1F3F3, + 0x1F3F3, + 0x1F3F5, + 0x1F3F5, + 0x1F3F7, + 0x1F3F7, + 0x1F43F, + 0x1F43F, + 0x1F441, + 0x1F441, + 0x1F4FD, + 0x1F4FD, + 0x1F549, + 0x1F54A, + 0x1F56F, + 0x1F570, + 0x1F573, + 0x1F579, + 0x1F587, + 0x1F587, + 0x1F58A, + 0x1F58D, + 0x1F590, + 0x1F590, + 0x1F5A5, + 0x1F5A5, + 0x1F5A8, + 0x1F5A8, + 0x1F5B1, + 0x1F5B2, + 0x1F5BC, + 0x1F5BC, + 0x1F5C2, + 0x1F5C4, + 0x1F5D1, + 0x1F5D3, + 0x1F5DC, + 0x1F5DE, + 0x1F5E1, + 0x1F5E1, + 0x1F5E3, + 0x1F5E3, + 0x1F5E8, + 0x1F5E8, + 0x1F5EF, + 0x1F5EF, + 0x1F5F3, + 0x1F5F3, + 0x1F5FA, + 0x1F5FA, + 0x1F6CB, + 0x1F6CB, + 0x1F6CD, + 0x1F6CF, + 0x1F6E0, + 0x1F6E5, + 0x1F6E9, + 0x1F6E9, + 0x1F6F0, + 0x1F6F0, + 0x1F6F3, + 0x1F6F3, +]; + +/// Emoji_Modifier_Base: a skin tone modifier after one joins it. +const List emojiModifierBaseRanges = [ + 0x261D, + 0x261D, + 0x26F9, + 0x26F9, + 0x270A, + 0x270D, + 0x1F385, + 0x1F385, + 0x1F3C2, + 0x1F3C4, + 0x1F3C7, + 0x1F3C7, + 0x1F3CA, + 0x1F3CC, + 0x1F442, + 0x1F443, + 0x1F446, + 0x1F450, + 0x1F466, + 0x1F478, + 0x1F47C, + 0x1F47C, + 0x1F481, + 0x1F483, + 0x1F485, + 0x1F487, + 0x1F48F, + 0x1F48F, + 0x1F491, + 0x1F491, + 0x1F4AA, + 0x1F4AA, + 0x1F574, + 0x1F575, + 0x1F57A, + 0x1F57A, + 0x1F590, + 0x1F590, + 0x1F595, + 0x1F596, + 0x1F645, + 0x1F647, + 0x1F64B, + 0x1F64F, + 0x1F6A3, + 0x1F6A3, + 0x1F6B4, + 0x1F6B6, + 0x1F6C0, + 0x1F6C0, + 0x1F6CC, + 0x1F6CC, + 0x1F90C, + 0x1F90C, + 0x1F90F, + 0x1F90F, + 0x1F918, + 0x1F91F, + 0x1F926, + 0x1F926, + 0x1F930, + 0x1F939, + 0x1F93C, + 0x1F93E, + 0x1F977, + 0x1F977, + 0x1F9B5, + 0x1F9B6, + 0x1F9B8, + 0x1F9B9, + 0x1F9BB, + 0x1F9BB, + 0x1F9CD, + 0x1F9CF, + 0x1F9D1, + 0x1F9DD, + 0x1FAC3, + 0x1FAC5, + 0x1FAF0, + 0x1FAF8, +]; diff --git a/app/third_party/xterm/lib/src/utils/unicode_width.dart b/app/third_party/xterm/lib/src/utils/unicode_width.dart new file mode 100644 index 00000000..c0101334 --- /dev/null +++ b/app/third_party/xterm/lib/src/utils/unicode_width.dart @@ -0,0 +1,104 @@ +import 'dart:typed_data'; + +import 'package:xterm/src/utils/unicode_tables.dart'; + +/// Cell widths and the grapheme properties the buffer needs, from the +/// generated [unicodeTablesVersion] tables (tool/gen_unicode_tables.py). +/// +/// Widths follow glibc's `wcwidth`, which tmux, ncurses, readline and most +/// programs use to lay out their output, so the emulator's columns agree with +/// theirs: combining marks and format characters 0, East Asian Wide and +/// Fullwidth (every default-emoji character included) 2, the rest 1. +abstract final class UnicodeWidth { + static const _zero = 1; + static const _wide = 2; + static const _pictographic = 4; + static const _textDefault = 8; + static const _modifierBase = 16; + + static final Uint8List _bmp = _buildBmp(); + + /// Columns [codePoint] takes alone: 0, 1 or 2. Controls are 0. + static int width(int codePoint) { + if (codePoint < 0x20) return 0; + if (codePoint < 0x7F) return 1; + if (codePoint < 0xA0) return 0; + final props = _props(codePoint); + if (props & _zero != 0) return 0; + if (props & _wide != 0) return 2; + return 1; + } + + /// Whether [codePoint] is a C0 or C1 control or DEL, which never prints. + static bool isControl(int codePoint) => + codePoint < 0x20 || (codePoint >= 0x7F && codePoint < 0xA0); + + /// Extended_Pictographic: what a zero width joiner joins into one emoji. + static bool isPictographic(int codePoint) => + _props(codePoint) & _pictographic != 0; + + /// An emoji shown as one-column text by default, which U+FE0F turns into + /// its two-column emoji form. + static bool isEmojiTextDefault(int codePoint) => + _props(codePoint) & _textDefault != 0; + + /// Emoji_Modifier_Base: a skin tone modifier after it joins it. + static bool isEmojiModifierBase(int codePoint) => + _props(codePoint) & _modifierBase != 0; + + /// A skin tone modifier (U+1F3FB-1F3FF). + static bool isEmojiModifier(int codePoint) => + codePoint >= 0x1F3FB && codePoint <= 0x1F3FF; + + /// A regional indicator letter; two of them make a flag. + static bool isRegionalIndicator(int codePoint) => + codePoint >= 0x1F1E6 && codePoint <= 0x1F1FF; + + static int _props(int codePoint) { + if (codePoint < 0x10000) return _bmp[codePoint]; + var props = 0; + if (_within(zeroWidthRanges, codePoint)) props |= _zero; + if (_within(wideRanges, codePoint)) props |= _wide; + if (_within(extendedPictographicRanges, codePoint)) props |= _pictographic; + if (_within(emojiTextDefaultRanges, codePoint)) props |= _textDefault; + if (_within(emojiModifierBaseRanges, codePoint)) props |= _modifierBase; + return props; + } + + static Uint8List _buildBmp() { + final table = Uint8List(0x10000); + void mark(List ranges, int bit) { + for (var i = 0; i < ranges.length; i += 2) { + if (ranges[i] >= 0x10000) break; + final last = ranges[i + 1] < 0x10000 ? ranges[i + 1] : 0xFFFF; + for (var cp = ranges[i]; cp <= last; cp++) { + table[cp] |= bit; + } + } + } + + mark(zeroWidthRanges, _zero); + mark(wideRanges, _wide); + mark(extendedPictographicRanges, _pictographic); + mark(emojiTextDefaultRanges, _textDefault); + mark(emojiModifierBaseRanges, _modifierBase); + return table; + } + + /// Binary search of inclusive [first, last] pairs. + static bool _within(List ranges, int codePoint) { + var low = 0; + var high = ranges.length ~/ 2 - 1; + while (low <= high) { + final mid = (low + high) >> 1; + if (codePoint < ranges[mid * 2]) { + high = mid - 1; + } else if (codePoint > ranges[mid * 2 + 1]) { + low = mid + 1; + } else { + return true; + } + } + return false; + } +} diff --git a/app/third_party/xterm/tool/gen_unicode_tables.py b/app/third_party/xterm/tool/gen_unicode_tables.py new file mode 100644 index 00000000..92c10737 --- /dev/null +++ b/app/third_party/xterm/tool/gen_unicode_tables.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Generates lib/src/utils/unicode_tables.dart (cell widths and grapheme +properties for the emulator). + + python3 -I tool/gen_unicode_tables.py > lib/src/utils/unicode_tables.dart + +Widths follow glibc's wcwidth (what tmux, ncurses and the shell measure with): + 0 general categories Mn, Me and Cf (except U+00AD SOFT HYPHEN and the + prepended concatenation marks, 1), the Hangul fillers, Hangul + Jamo medial vowels and final consonants (U+1160-11FF, U+D7B0-D7FF) and + U+200B; + 2 East Asian Width W or F (which includes every Emoji_Presentation + character); + 1 everything else that prints. +The Unicode version is the running Python's `unicodedata` (16.0 with Python +3.13+); `emoji-data.txt` must be the same version +(https://www.unicode.org/Public//ucd/emoji/emoji-data.txt). +""" + +import sys +import unicodedata + +MAX = 0x110000 + + +def ranges(predicate): + out = [] + start = None + for cp in range(MAX): + hit = predicate(cp) + if hit and start is None: + start = cp + elif not hit and start is not None: + out.append((start, cp - 1)) + start = None + if start is not None: + out.append((start, MAX - 1)) + return out + + +# Where glibc 2.44 differs from the category rules below (checked by +# comparing every assigned code point with its wcwidth in en_US.UTF-8). +GLIBC_ONE = {0x00AD, *range(0x0600, 0x0606), 0x06DD, 0x070F, 0x0890, 0x0891, + 0x08E2, 0xFFF9, 0xFFFA, 0xFFFB, 0x110BD, 0x110CD, + *range(0x13430, 0x13440)} +GLIBC_ZERO = {0x3164, 0xFFA0} +GLIBC_TWO = set(range(0x3248, 0x3250)) + + +def zero_width(cp): + if cp in GLIBC_ONE: + return False + if cp in GLIBC_ZERO: + return True + if 0x1160 <= cp <= 0x11FF or 0xD7B0 <= cp <= 0xD7FF or cp == 0x200B: + return True + return unicodedata.category(chr(cp)) in ('Mn', 'Me', 'Cf') + + +def wide(cp): + if cp in GLIBC_TWO: + return True + return unicodedata.east_asian_width(chr(cp)) in ('W', 'F') + + +def emoji_property(path, name): + hits = set() + with open(path, encoding='utf-8') as data: + for line in data: + line = line.split('#', 1)[0].strip() + if not line: + continue + span, prop = [part.strip() for part in line.split(';')] + if prop != name: + continue + if '..' in span: + first, last = span.split('..') + else: + first = last = span + hits.update(range(int(first, 16), int(last, 16) + 1)) + return hits + + +def emit(name, doc, spans): + print(f'/// {doc}') + print(f'const List {name} = [') + for first, last in spans: + print(f' 0x{first:X}, 0x{last:X},') + print('];') + print() + + +def main(): + emoji_data = sys.argv[1] + emoji = emoji_property(emoji_data, 'Emoji') + presentation = emoji_property(emoji_data, 'Emoji_Presentation') + pictographic = emoji_property(emoji_data, 'Extended_Pictographic') + modifier_base = emoji_property(emoji_data, 'Emoji_Modifier_Base') + print('// GENERATED by tool/gen_unicode_tables.py from Python ' + f'unicodedata {unicodedata.unidata_version} and emoji-data.txt.') + print('// Do not edit by hand. Each list holds inclusive [first, last] pairs.') + print() + print(f"const String unicodeTablesVersion = '{unicodedata.unidata_version}';") + print() + emit('zeroWidthRanges', + 'Code points glibc wcwidth measures as 0 columns (they join the ' + 'previous cell).', + ranges(zero_width)) + emit('wideRanges', 'East Asian Width W or F: two columns.', ranges(wide)) + emit('extendedPictographicRanges', + 'Extended_Pictographic: what a ZWJ joins into one emoji.', + ranges(lambda cp: cp in pictographic)) + emit('emojiTextDefaultRanges', + 'Emoji shown as text by default (Emoji and not Emoji_Presentation): ' + 'U+FE0F after one asks for the two-column emoji form.', + ranges(lambda cp: cp in emoji and cp not in presentation)) + emit('emojiModifierBaseRanges', + 'Emoji_Modifier_Base: a skin tone modifier after one joins it.', + ranges(lambda cp: cp in modifier_base)) + + +if __name__ == '__main__': + main() diff --git a/app/tool/perf/terminal_fixture.dart b/app/tool/perf/terminal_fixture.dart index 3431937c..b3ad0cf9 100644 --- a/app/tool/perf/terminal_fixture.dart +++ b/app/tool/perf/terminal_fixture.dart @@ -33,6 +33,34 @@ const String _attributeShowcase = '\x1b]11;#000000\x07after strings\r\n' 'abc\x1b[2D'; +/// `?terminalUnicode=1`: widths, grapheme clusters, box drawing, blocks, +/// Powerline and Nerd Font glyphs, printed after the build terminal's +/// prompt. Each cluster takes the columns its width says (combining marks +/// none, emoji and CJK two), so the first three lines' `|` fall in columns +/// 6, 11 and 12. +const String _unicodeShowcase = + 'printf unicode\r\n' + 'e\u0301 n\u0303 a\u0300\u0316 |\r\n' + '\u4E2D\u6587 \u{1F600} \u{1F44D}\u{1F3FD} |\r\n' + '\u{1F468}\u200D\u{1F469}\u200D\u{1F467} \u{1F1F5}\u{1F1F9} ' + '\u2764\uFE0F 1\uFE0F\u20E3 |\r\n' + '\u250C\u2500\u252C\u2500\u2510 \u250F\u2501\u2533\u2501\u2513 ' + '\u2554\u2550\u2566\u2550\u2557 \u256D\u2500\u2500\u2500\u256E ' + '\u2588\u2589\u258A\u258B\u258C\u258D\u258E\u258F ' + '\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588\r\n' + '\u251C\u2500\u253C\u2500\u2524 \u2523\u2501\u254B\u2501\u252B ' + '\u2560\u2550\u256C\u2550\u2563 \u2502 \u2502 ' + '\u2591\u2591\u2592\u2592\u2593\u2593\u2588\u2588 ' + '\u2596\u2597\u2598\u2599\u259A\u259B\u259C\u259D\u259E\u259F\r\n' + '\u2514\u2500\u2534\u2500\u2518 \u2517\u2501\u253B\u2501\u251B ' + '\u255A\u2550\u2569\u2550\u255D \u2570\u2500\u2500\u2500\u256F ' + '\u2504\u2504 \u2506 \u254C\u254C \u2571\u2572\u2573\r\n' + '\x1b[30;44m \uE0A0 main \x1b[34;42m\uE0B0\x1b[30m ~/src \x1b[32;49m\uE0B0' + '\x1b[0m \x1b[35m\uE0B6\x1b[30;45mok\x1b[35;49m\uE0B4\x1b[0m ' + '\x1b[33m\uE0B2\x1b[30;43m 12:00 \x1b[33;49m\uE0BC\x1b[0m ' + '\uE0B1 \uE0B3 |\r\n' + 'icons: \uF418 \uF09B \uF303 \uE615 \u23FB |\r\n'; + void configureTerminalFixture(Map params) { _enabled = params['terminals'] == '1'; if (!_enabled) return; @@ -65,6 +93,9 @@ void configureTerminalFixture(Map params) { if (params['terminalAttrs'] == '1') { _output['term_build'] = _output['term_build']! + _attributeShowcase; } + if (params['terminalUnicode'] == '1') { + _output['term_build'] = _output['term_build']! + _unicodeShowcase; + } final mode = switch (params['terminal']) { 'panel' => TerminalMode.panel, 'float' => TerminalMode.float, diff --git a/app/tool/perf/terminal_stream_bench.dart b/app/tool/perf/terminal_stream_bench.dart new file mode 100644 index 00000000..3470c65b --- /dev/null +++ b/app/tool/perf/terminal_stream_bench.dart @@ -0,0 +1,215 @@ +// Terminal rendering bench: the app's emulator view (theme, text style and +// the sliced output feed the terminals use) streaming generated output at a +// fixed rate, with Flutter frame timings and rAF intervals recorded. +// +// Build (from app/): +// flutter build web --profile --target tool/perf/terminal_stream_bench.dart \ +// --output build/terminal-bench +// Run with tool/perf/terminal_stream_bench.mjs, or open the page with +// `?workload=seq|yes|unicode|colors|screen|progress&mb=30&rate=30` (the window size sets the grid). +// When the stream ends `window.__benchResult` holds a JSON summary: +// frames, build/raster/total quantiles (ms), rAF interval quantiles (ms), +// MB written, seconds and MB/s. +import 'dart:async'; +import 'dart:convert'; +import 'dart:js_interop'; +import 'dart:ui'; + +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_feed.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_theme.dart'; +import 'package:xterm/xterm.dart'; + +@JS('__benchResult') +external set _benchResult(JSString value); + +void main() { + final params = Uri.base.queryParameters; + runApp(_Bench(params)); +} + +class _Bench extends StatefulWidget { + const _Bench(this.params); + + final Map params; + + @override + State<_Bench> createState() => _BenchState(); +} + +class _BenchState extends State<_Bench> { + late final Terminal _terminal = Terminal(maxLines: 10000); + late final ChatShellTerminalFeed _feed = ChatShellTerminalFeed( + (text, _) => _terminal.write(text), + ); + final List _timings = []; + final List _intervals = []; + Duration? _lastFrame; + Timer? _producer; + final Stopwatch _clock = Stopwatch(); + int _written = 0; + int _counter = 0; + bool _done = false; + + String get _workload => widget.params['workload'] ?? 'seq'; + double get _megabytes => double.tryParse(widget.params['mb'] ?? '') ?? 30; + double get _rate => double.tryParse(widget.params['rate'] ?? '') ?? 30; + + @override + void initState() { + super.initState(); + SchedulerBinding.instance.addTimingsCallback(_onTimings); + SchedulerBinding.instance.addPersistentFrameCallback(_onFrame); + // Let the first frames settle before streaming. + Timer(const Duration(milliseconds: 1500), _start); + } + + void _onTimings(List timings) { + if (_clock.isRunning) _timings.addAll(timings); + } + + void _onFrame(Duration stamp) { + if (_clock.isRunning && _lastFrame != null) { + _intervals.add((stamp - _lastFrame!).inMicroseconds / 1000); + } + _lastFrame = stamp; + } + + void _start() { + _clock.start(); + const tick = Duration(milliseconds: 4); + final perTick = (_rate * 1e6 * tick.inMicroseconds / 1e6).round(); + _producer = Timer.periodic(tick, (_) { + if (_written >= _megabytes * 1e6) { + _producer?.cancel(); + _feed.then(_finish); + return; + } + final chunk = _chunk(perTick); + _written += chunk.length; + _feed.add(chunk, _written); + }); + } + + String _chunk(int size) { + final out = StringBuffer(); + while (out.length < size) { + _counter++; + switch (_workload) { + case 'yes': + out.write('y\r\n'); + case 'unicode': + out.write( + '$_counter e\u0301 \u00F1 \u4E2D\u6587 \u{1F600} \u{1F44D}\u{1F3FD} \u{1F1F5}\u{1F1F9} \u2502 \u256D\u2500\u256E \u2593\u2592\u2591 \u{E0B0} done\r\n', + ); + case 'colors': + final c = 31 + _counter % 7; + out.write( + '\x1b[${c}m$_counter\x1b[0m \x1b[1mbold\x1b[0m ' + 'plain text line with some words\r\n', + ); + case 'screen': + // A full-screen program redrawing every row (top, an editor). + out.write('\x1b[H'); + for (var row = 0; row < 48; row++) { + final c = 31 + (row + _counter) % 7; + out.write( + '\x1b[${c}m${(_counter + row).toString().padLeft(8)}' + '\x1b[0m \x1b[7m cpu ${row % 100}% \x1b[0m ' + '${'process name and arguments ' * 4}\x1b[K\r\n', + ); + } + case 'progress': + // A screen of text, then one status line rewritten in place (a + // progress bar, a build counter): one row changes per frame. + if (_counter == 1) { + for (var row = 0; row < 47; row++) { + out.write( + '\x1b[3${row % 7 + 1}mline $row\x1b[0m ' + '${'static output that does not change ' * 3}\r\n', + ); + } + } + final done = _counter % 50; + out.write( + '\r\x1b[1m[${'#' * done}${'.' * (50 - done)}]\x1b[0m ' + '$_counter files', + ); + default: + out.write('$_counter\r\n'); + } + } + return out.toString(); + } + + void _finish() { + if (_done) return; + _done = true; + // A last frame flushes the engine's batched timings. + SchedulerBinding.instance.scheduleFrame(); + Timer(const Duration(milliseconds: 600), () { + _clock.stop(); + final seconds = _clock.elapsedMicroseconds / 1e6; + List ms(Duration Function(FrameTiming t) pick) => [ + for (final t in _timings) pick(t).inMicroseconds / 1000, + ]; + final result = { + 'workload': _workload, + 'frames': _timings.length, + 'build': _quantiles(ms((t) => t.buildDuration)), + 'raster': _quantiles(ms((t) => t.rasterDuration)), + 'total': _quantiles(ms((t) => t.totalSpan)), + 'interval': _quantiles(_intervals), + 'mb': _written / 1e6, + 'seconds': seconds, + 'mbPerSecond': _written / 1e6 / seconds, + }; + _benchResult = jsonEncode(result).toJS; + // ignore: avoid_print + print('BENCH_RESULT ${jsonEncode(result)}'); + }); + } + + static Map _quantiles(List values) { + if (values.isEmpty) return const {}; + final sorted = [...values]..sort(); + double at(double q) => + sorted[(q * (sorted.length - 1)).round().clamp(0, sorted.length - 1)]; + double round(double v) => (v * 100).roundToDouble() / 100; + return { + 'p50': round(at(0.5)), + 'p90': round(at(0.9)), + 'p99': round(at(0.99)), + 'max': round(sorted.last), + 'mean': round(sorted.reduce((a, b) => a + b) / sorted.length), + }; + } + + @override + void dispose() { + _producer?.cancel(); + _feed.dispose(); + SchedulerBinding.instance.removeTimingsCallback(_onTimings); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + theme: ThemeData(brightness: Brightness.dark), + home: Builder( + builder: (context) => Scaffold( + body: TerminalView( + _terminal, + theme: chatShellTerminalTheme(context), + textStyle: chatShellTerminalStyle(context), + padding: const EdgeInsets.all(8), + readOnly: true, + ), + ), + ), + ); + } +} diff --git a/app/tool/perf/terminal_stream_bench.mjs b/app/tool/perf/terminal_stream_bench.mjs new file mode 100644 index 00000000..b92adbf4 --- /dev/null +++ b/app/tool/perf/terminal_stream_bench.mjs @@ -0,0 +1,74 @@ +#!/usr/bin/env node +// Streams generated output through the terminal bench build +// (tool/perf/terminal_stream_bench.dart) in headless Chrome and prints one +// JSON line per workload: Flutter frame build/raster quantiles, rAF +// intervals measured in the page, and the throughput reached. +// +// node tool/perf/terminal_stream_bench.mjs --build build/terminal-bench \ +// [--workloads seq,yes,unicode,colors,screen,progress] [--mb 30] [--rate 30] [--size 1280x800] +import { parseArgs } from 'node:util'; +import { setTimeout as delay } from 'node:timers/promises'; +import { openBrowser } from '../capture/browser.mjs'; +import { serveBuild } from '../capture/serve.mjs'; + +const { values: options } = parseArgs({ + options: { + build: { type: 'string' }, + workloads: { type: 'string', default: 'seq,yes,unicode,colors,screen,progress' }, + mb: { type: 'string', default: '30' }, + rate: { type: 'string', default: '30' }, + size: { type: 'string', default: '1280x800' }, + timeout: { type: 'string', default: '120000' }, + params: { type: 'string', default: '' }, + }, +}); +if (!options.build) throw new Error('--build required'); +const [width, height] = options.size.split('x').map(Number); + +const quantiles = (values) => { + const sorted = [...values].sort((a, b) => a - b); + const at = (q) => sorted[Math.round(q * (sorted.length - 1))] ?? 0; + const r = (v) => Math.round(v * 100) / 100; + return { p50: r(at(0.5)), p90: r(at(0.9)), p99: r(at(0.99)), max: r(sorted.at(-1) ?? 0) }; +}; + +const server = await serveBuild(options.build); +const browser = await openBrowser(); +const evaluate = async (expression) => { + const r = await browser.send('Runtime.evaluate', { expression, returnByValue: true }); + return r.result.value; +}; +try { + await browser.send('Page.enable'); + await browser.send('Runtime.enable'); + for (const workload of options.workloads.split(',')) { + const url = new URL('/', server.origin); + url.searchParams.set('workload', workload); + url.searchParams.set('mb', options.mb); + url.searchParams.set('rate', options.rate); + for (const [k, v] of new URLSearchParams(options.params)) url.searchParams.set(k, v); + await browser.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false }); + await browser.send('Page.navigate', { url: url.href }); + await delay(300); + await evaluate(`(() => { + window.__raf = []; + let last = performance.now(); + const tick = (t) => { window.__raf.push(t - last); last = t; if (!window.__benchResult) requestAnimationFrame(tick); }; + requestAnimationFrame(tick); + return true; + })()`); + const deadline = Date.now() + Number(options.timeout); + let result = null; + while (!result && Date.now() < deadline) { + await delay(500); + result = await evaluate('window.__benchResult ?? null'); + } + if (!result) throw new Error(`${workload}: no result before the timeout`); + const raf = await evaluate('window.__raf'); + // Skip the start-up frames before streaming starts. + console.log(JSON.stringify({ ...JSON.parse(result), pageRaf: quantiles(raf.slice(50)) })); + } +} finally { + await browser.close?.(); + await server.close?.(); +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index c44c1da8..326bb3e3 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -888,7 +888,9 @@ class _FixtureSink implements WebSocketSink { /// `?hits=N`, `?chats=N` and `?graph=1` add bench data /// (tool/perf/perf_fixture.dart); /// `?terminals=1` lists two machine terminals, and `?terminal=panel` or -/// `?terminal=float` opens them at launch (tool/perf/terminal_fixture.dart); +/// `?terminal=float` opens them at launch, with `?terminalAttrs=1` and +/// `?terminalUnicode=1` adding emulator showcases +/// (tool/perf/terminal_fixture.dart); /// `?windows=N` opens N floating probe windows whose content opens every /// kind of popup and a pushed page (tool/capture/window_probe.dart); /// `?speech=fake` reads replies aloud with a scripted engine, one word per