Merge branch 'main' into worktree-agent-a3f5466412d4c7d5d

This commit is contained in:
2026-11-26 01:58:57 +00:00
91 changed files with 10011 additions and 320 deletions
+26
View File
@@ -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
+21
View File
@@ -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.
@@ -27,6 +27,7 @@ class ChatShellRun {
this.outputEnd = 0,
this.outputBytes = 0,
this.gap = false,
this.snapshot = false,
this.terminal = false,
this.cols = 0,
this.rows = 0,
@@ -59,6 +60,11 @@ class ChatShellRun {
/// stretch of what the command wrote.
final bool gap;
/// True when [output] starts with the server's redraw of the terminal's
/// state at [outputStart] (screens, scrollback, cursor and modes) instead
/// of raw output: nothing earlier is missing from what it shows.
final bool snapshot;
/// True when the command runs in a pseudo-terminal of [cols] x [rows]:
/// [output] is then the raw terminal stream and it accepts typed input
/// while it runs. Older runs (and servers without terminals) are plain.
@@ -78,7 +84,7 @@ class ChatShellRun {
final bool purged;
/// Whether earlier output is not shown here.
bool get truncated => outputStart > 0 || gap;
bool get truncated => !snapshot && (outputStart > 0 || gap);
ChatShellRunState get state => switch (status) {
'running' => ChatShellRunState.running,
@@ -144,6 +150,7 @@ class ChatShellRun {
? next.outputBytes
: outputBytes,
gap: gap,
snapshot: snapshot,
terminal: next.terminal || terminal,
cols: next.cols == 0 ? cols : next.cols,
rows: next.rows == 0 ? rows : next.rows,
@@ -180,6 +187,7 @@ class ChatShellRun {
outputEnd: end,
outputBytes: end > outputBytes ? end : outputBytes,
gap: gap || dropped || (!contiguous && offset > 0),
snapshot: snapshot && contiguous && !dropped,
terminal: terminal,
cols: cols,
rows: rows,
@@ -0,0 +1,97 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
/// What one terminal view does locally, for its keys and its context menu:
/// copy, paste, select, clear the scrollback and scroll it.
class ChatShellTerminalActions {
ChatShellTerminalActions({
required this.terminal,
required this.controller,
required this.scroll,
required this.view,
});
final Terminal terminal;
final TerminalController controller;
final ScrollController scroll;
final GlobalKey<TerminalViewState> view;
/// Copies the selected text and clears the selection; false with none.
bool copySelection() {
final selection = controller.selection;
if (selection == null) return false;
final text = terminal.buffer.getText(selection);
if (text.isEmpty) return false;
Clipboard.setData(ClipboardData(text: text));
controller.clearSelection();
return true;
}
/// Pastes the clipboard into the process (bracketed when it asked).
Future<void> paste() async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text;
if (text == null || text.isEmpty) return;
terminal.paste(text);
controller.clearSelection();
scrollToBottom();
}
/// Selects everything the buffer holds, scrollback included.
void selectAll() {
final buffer = terminal.buffer;
controller.setSelection(
buffer.createAnchor(0, 0),
buffer.createAnchor(terminal.viewWidth, buffer.height - 1),
mode: SelectionMode.line,
);
}
/// Drops the scrollback above the screen (this view's copy only: the
/// server keeps the output, and a reload draws it again).
void clearScrollback() {
controller.clearSelection();
terminal.mainBuffer.clearScrollback();
terminal.notifyListeners();
}
double get _lineHeight => view.currentState?.renderTerminal.lineHeight ?? 0;
/// Scrolls the scrollback one screen up ([pages] < 0) or down, keeping a
/// line of context.
void scrollPages(int pages) {
if (!scroll.hasClients) return;
final position = scroll.position;
final step = position.viewportDimension - _lineHeight;
_jump(position.pixels + pages * (step > 0 ? step : _lineHeight));
}
void scrollToTop() {
if (scroll.hasClients) _jump(0);
}
void scrollToBottom() {
if (scroll.hasClients) _jump(scroll.position.maxScrollExtent);
}
/// Scrolls buffer row [y] into view, centred, unless it already shows.
void reveal(int y) {
final line = _lineHeight;
if (!scroll.hasClients || line <= 0) return;
final position = scroll.position;
final top = y * line;
final shown =
top >= position.pixels &&
top + line <= position.pixels + position.viewportDimension;
if (shown) return;
_jump(top - (position.viewportDimension - line) / 2);
}
void _jump(double pixels) {
final position = scroll.position;
position.jumpTo(
pixels.clamp(position.minScrollExtent, position.maxScrollExtent),
);
}
}
@@ -0,0 +1,94 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/// How long the visual bell's border takes to fade.
const Duration chatShellBellFlash = Duration(milliseconds: 300);
/// The visual bell: each time [bells] counts up (and [enabled] says so) a
/// border in the accent colour flashes round [child] and fades. Under
/// reduced motion it shows at full strength for the same time and goes,
/// without the fade.
class ChatShellBellFlash extends StatefulWidget {
const ChatShellBellFlash({
super.key,
required this.bells,
required this.enabled,
required this.child,
});
final ValueListenable<int> bells;
final bool enabled;
final Widget child;
@override
State<ChatShellBellFlash> createState() => _ChatShellBellFlashState();
}
class _ChatShellBellFlashState extends State<ChatShellBellFlash>
with SingleTickerProviderStateMixin {
late final AnimationController _flash = AnimationController(
vsync: this,
duration: chatShellBellFlash,
value: 0,
);
@override
void initState() {
super.initState();
widget.bells.addListener(_rang);
}
@override
void didUpdateWidget(ChatShellBellFlash old) {
super.didUpdateWidget(old);
if (old.bells != widget.bells) {
old.bells.removeListener(_rang);
widget.bells.addListener(_rang);
}
}
@override
void dispose() {
widget.bells.removeListener(_rang);
_flash.dispose();
super.dispose();
}
void _rang() {
if (widget.enabled && mounted) _flash.reverse(from: 1);
}
@override
Widget build(BuildContext context) {
final color = Theme.of(context).colorScheme.primary;
// Reduced motion: the border holds at full strength, then goes.
final steady = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
return Stack(
fit: StackFit.passthrough,
children: [
widget.child,
Positioned.fill(
child: IgnorePointer(
child: AnimatedBuilder(
animation: _flash,
builder: (context, _) => _flash.value == 0
? const SizedBox.shrink()
: DecoratedBox(
key: const ValueKey('terminal-bell-flash'),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: color.withValues(
alpha: steady ? 1 : _flash.value,
),
width: 2,
),
),
),
),
),
),
],
);
}
}
@@ -0,0 +1,93 @@
import 'package:flutter/material.dart';
import '../ui/transcript/chat_link_browser_menu.dart';
/// What the terminal's right-click menu offers.
enum ChatShellTerminalMenuItem { copy, paste, selectAll, clear, find }
/// Shows the terminal's context menu at [position] (global): Copy (with a
/// selection), Paste (into a live terminal), Select all, Clear scrollback
/// and Find…. Resolves with the chosen item, or null when dismissed.
Future<ChatShellTerminalMenuItem?> showChatShellTerminalMenu(
BuildContext context, {
required Offset position,
required bool canCopy,
required bool canPaste,
}) {
final overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
final local = overlay.globalToLocal(position);
PopupMenuItem<ChatShellTerminalMenuItem> item(
ChatShellTerminalMenuItem value,
String label,
IconData icon, {
bool enabled = true,
}) => PopupMenuItem(
key: ValueKey('terminal-menu-${value.name}'),
value: value,
enabled: enabled,
child: ListTile(
leading: Icon(icon),
title: Text(label),
contentPadding: EdgeInsets.zero,
dense: true,
),
);
return showMenu<ChatShellTerminalMenuItem>(
context: context,
position: RelativeRect.fromRect(
local & const Size(1, 1),
Offset.zero & overlay.size,
),
items: [
item(
ChatShellTerminalMenuItem.copy,
'Copy',
Icons.content_copy,
enabled: canCopy,
),
if (canPaste)
item(ChatShellTerminalMenuItem.paste, 'Paste', Icons.content_paste),
item(ChatShellTerminalMenuItem.selectAll, 'Select all', Icons.select_all),
const PopupMenuDivider(),
item(
ChatShellTerminalMenuItem.clear,
'Clear scrollback',
Icons.clear_all,
),
item(ChatShellTerminalMenuItem.find, 'Find…', Icons.search),
],
);
}
/// While the mouse is over [child] the browser's own context menu is
/// suppressed (on the web), so a right-click shows only the terminal's.
class ChatShellNoBrowserMenu extends StatefulWidget {
const ChatShellNoBrowserMenu({super.key, required this.child});
final Widget child;
@override
State<ChatShellNoBrowserMenu> createState() => _ChatShellNoBrowserMenuState();
}
class _ChatShellNoBrowserMenuState extends State<ChatShellNoBrowserMenu> {
bool _inside = false;
void _set(bool inside) {
if (inside == _inside) return;
_inside = inside;
suppressBrowserMenuOverLink(inside);
}
@override
void dispose() {
_set(false);
super.dispose();
}
@override
Widget build(BuildContext context) => MouseRegion(
onEnter: (_) => _set(true),
onExit: (_) => _set(false),
child: widget.child,
);
}
@@ -0,0 +1,58 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
/// How long a blinking cursor stays shown, then hidden (xterm's 600 ms is
/// close; most terminals use about half a second).
const Duration chatShellCursorBlinkPhase = Duration(milliseconds: 530);
/// The blink of a cursor the program asked to blink (DECSCUSR 1, 3 or 5).
/// It runs on a [Ticker] only while [update] says to blink: the terminal
/// is focused, the shape blinks and motion is not reduced. Otherwise the
/// cursor is steady ([visible] stays true), so an unfocused terminal or a
/// test schedules nothing. Typing or output shows it again at once
/// ([restart]), as terminals do.
class ChatShellCursorBlink {
ChatShellCursorBlink(TickerProvider vsync) {
_ticker = vsync.createTicker(_tick);
}
late final Ticker _ticker;
Duration _now = Duration.zero;
Duration _since = Duration.zero;
/// Whether the cursor is drawn in the current phase.
final ValueNotifier<bool> visible = ValueNotifier(true);
bool get blinking => _ticker.isActive;
void update({required bool blink}) {
if (blink == _ticker.isActive) return;
if (blink) {
_now = Duration.zero;
_since = Duration.zero;
_ticker.start();
} else {
_ticker.stop();
}
visible.value = true;
}
/// Shows the cursor and starts the phase again.
void restart() {
_since = _now;
visible.value = true;
}
void _tick(Duration elapsed) {
_now = elapsed;
final phase =
(elapsed - _since).inMicroseconds ~/
chatShellCursorBlinkPhase.inMicroseconds;
visible.value = phase.isEven;
}
void dispose() {
_ticker.dispose();
visible.dispose();
}
}
@@ -0,0 +1,63 @@
import 'package:flutter/foundation.dart';
import 'package:xterm/core.dart';
/// The emulator of one run or machine terminal, keeping [maxLines] lines
/// (Settings → Appearance → Terminal → Scrollback). It answers a cursor
/// position query (DSR 6) with the one-based row and column the protocol
/// specifies; xterm.dart 4.0.0 itself answers zero-based.
///
/// A live terminal does not reflow on resize: xterm.dart 4.0.0's reflow
/// leaves the cursor on a row other than its line's, so the shell's redraw
/// lands on old output. Without it a resize behaves as xterm's: narrowing
/// cuts rows at the new width, fewer rows scroll the top into scrollback
/// (keeping the cursor's row at the bottom), more rows bring it back.
/// Finished output, which nothing writes to any more, reflows to fit.
class ChatShellTerminal extends Terminal {
ChatShellTerminal({required super.maxLines}) : super(platform: _platform());
/// The package's own Alt handler (a fallback after the app's) leaves
/// Option alone only when it knows it is on a Mac.
static TerminalTargetPlatform _platform() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS
? TerminalTargetPlatform.macos
: TerminalTargetPlatform.unknown;
@override
void sendCursorPosition() {
onOutput?.call('\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}R');
}
@override
void resize(
int newWidth,
int newHeight, [
int? pixelWidth,
int? pixelHeight,
]) {
final width = newWidth;
final oldWidth = viewWidth;
if (!reflowEnabled && width >= 1 && width < oldWidth) {
// A cut row keeps its cells past the new width, which a later widening
// would show again beside what was written since: they are erased.
for (final buffer in [mainBuffer, altBuffer]) {
buffer.lines.forEach((line) {
if (line.length > width) {
line.eraseRange(width, line.length, CursorStyle.empty);
}
});
}
}
super.resize(newWidth, newHeight, pixelWidth, pixelHeight);
if (!reflowEnabled) return;
// Rewrapping keeps every blank row below the cursor, and the extra rows
// push the top of finished output into scrollback: they are dropped.
final lines = buffer.lines;
while (buffer.height > viewHeight &&
buffer.height - 1 > buffer.absoluteCursorY &&
lines[buffer.height - 1].getText().trim().isEmpty) {
lines.pop();
buffer.setCursor(buffer.cursorX, buffer.cursorY + 1);
}
}
}
@@ -0,0 +1,87 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:xterm/core.dart';
/// What a terminal's program asks of the app beyond drawing: the bell
/// (BEL), setting the clipboard (OSC 52) and reporting its working folder
/// (OSC 7). Old output drawn again (a replay) asks for nothing: [quiet] is
/// true then, so a reload neither rings nor overwrites the clipboard.
class ChatShellTerminalEvents {
ChatShellTerminalEvents(this.terminal, {required this.quiet}) {
terminal
..onBell = _bell
..onClipboardSet = _clipboard
..onWorkingDirectoryChange = _directory;
}
final Terminal terminal;
final bool Function() quiet;
/// Counts the bells rung by live output.
final ValueNotifier<int> bells = ValueNotifier(0);
/// The folder the program last reported (OSC 7), as a path; null before.
final ValueNotifier<String?> workingDirectory = ValueNotifier(null);
/// How many views draw this terminal now: a bell while none does dots the
/// terminal's tab.
final ValueNotifier<int> viewers = ValueNotifier(0);
final List<void Function(String text)> _toasts = [];
bool _disposed = false;
/// A view shows "Copied from terminal" with [toast] while it is the most
/// recently attached one; [detach] undoes both.
void attach(void Function(String text) toast) {
_toasts.add(toast);
viewers.value++;
}
/// A view may outlive the session by a frame (the tab closed first).
void detach(void Function(String text) toast) {
_toasts.remove(toast);
if (!_disposed) viewers.value--;
}
void _bell() {
if (!quiet()) bells.value++;
}
/// Only setting is supported (the emulator never reads the clipboard for
/// the program). An empty text clears nothing.
void _clipboard(String text, String selection) {
if (quiet() || text.isEmpty) return;
Clipboard.setData(ClipboardData(text: text));
if (_toasts.isNotEmpty) _toasts.last(text);
}
void _directory(String uri) {
final path = chatShellWorkingDirectoryPath(uri);
if (path != null) workingDirectory.value = path;
}
void dispose() {
_disposed = true;
terminal
..onBell = null
..onClipboardSet = null
..onWorkingDirectoryChange = null;
bells.dispose();
workingDirectory.dispose();
viewers.dispose();
}
}
/// The path of an OSC 7 `file://host/path` report (percent-decoded), or
/// null when it is not a file URI with a path.
String? chatShellWorkingDirectoryPath(String uri) {
final parsed = Uri.tryParse(uri.trim());
if (parsed == null || parsed.scheme != 'file') return null;
final String path;
try {
path = Uri.decodeComponent(parsed.path);
} on ArgumentError {
return null;
}
return path.isEmpty ? null : path;
}
@@ -0,0 +1,145 @@
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart';
import 'chat_shell_terminal_search.dart';
/// Find in one terminal's scrollback: the query, whether case matters, the
/// matches (highlighted on the emulator through its [controller]) and the
/// current one. Output arriving meanwhile marks the matches stale; the next
/// step or query searches again.
class ChatShellTerminalFind extends ChangeNotifier {
ChatShellTerminalFind({
required this.terminal,
required this.controller,
required this.hit,
required this.current,
}) {
terminal.addListener(_terminalChanged);
}
final Terminal terminal;
final TerminalController controller;
/// The highlight colours of a match and of the current one.
Color hit;
Color current;
String _query = '';
bool _caseSensitive = false;
List<ChatShellSearchMatch> _matches = const [];
final List<TerminalHighlight> _highlights = [];
int _index = -1;
bool _stale = false;
String get query => _query;
bool get caseSensitive => _caseSensitive;
int get count => _matches.length;
/// Whether there are more matches than [count] reports.
bool get capped => _matches.length >= chatShellSearchLimit;
/// The current match's position among [count] (0-based), -1 with none.
int get index => _index;
/// The current match, as the buffer is now.
ChatShellSearchMatch? get selected {
if (_index < 0 || _index >= _highlights.length) return null;
final range = _highlights[_index].range;
return range == null ? null : ChatShellSearchMatch(range.begin, range.end);
}
set query(String value) {
if (value == _query) return;
_query = value;
_search(keep: false);
}
void toggleCase() {
_caseSensitive = !_caseSensitive;
_search(keep: false);
}
/// Moves to the next match ([step] 1) or the previous one (-1), wrapping;
/// a stale search runs again first.
void step(int step) {
if (_stale) _search(keep: true);
if (_matches.isEmpty) return;
_setIndex((_index + step) % _matches.length);
}
/// Searches the buffer as it is now. With [keep] the current match stays
/// the one at (or just after) where it was; otherwise it is the last match
/// at or above the bottom of the scrollback, as terminals search upwards.
void _search({required bool keep}) {
final before = keep ? selected?.begin : null;
_stale = false;
_matches = chatShellTerminalSearch(
terminal.buffer,
_query,
caseSensitive: _caseSensitive,
);
_clearHighlights();
final buffer = terminal.buffer;
for (final match in _matches) {
_highlights.add(
controller.highlight(
p1: buffer.createAnchorFromOffset(match.begin),
p2: buffer.createAnchorFromOffset(match.end),
color: hit,
),
);
}
var index = _matches.isEmpty ? -1 : _matches.length - 1;
if (before != null) {
final after = _matches.indexWhere((m) => m.begin.isAfterOrSame(before));
if (after >= 0) index = after;
}
_index = -1;
_setIndex(index);
}
void _setIndex(int index) {
final buffer = terminal.buffer;
void paint(int at, Color color) {
if (at < 0 || at >= _highlights.length) return;
final old = _highlights[at];
final range = old.range;
_dispose(old);
if (range == null) return;
_highlights[at] = controller.highlight(
p1: buffer.createAnchorFromOffset(range.begin),
p2: buffer.createAnchorFromOffset(range.end),
color: color,
);
}
if (_index != index) paint(_index, hit);
_index = index;
paint(_index, current);
notifyListeners();
}
void _terminalChanged() {
if (_query.isEmpty || _stale) return;
_stale = true;
}
void _clearHighlights() {
_highlights.forEach(_dispose);
_highlights.clear();
}
static void _dispose(TerminalHighlight highlight) {
if (highlight.disposed) return;
highlight.p1.dispose();
highlight.p2.dispose();
highlight.dispose();
}
@override
void dispose() {
terminal.removeListener(_terminalChanged);
_clearHighlights();
super.dispose();
}
}
@@ -0,0 +1,147 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'chat_shell_terminal_find.dart';
/// The terminal's find bar: the query field (Enter finds the next match,
/// Shift+Enter the previous, Esc closes), the match count, Match case and
/// the previous/next and close buttons. [onStep] moves to a match and
/// scrolls it into view; [onClose] closes the bar and refocuses the
/// terminal.
class ChatShellTerminalFindBar extends StatefulWidget {
const ChatShellTerminalFindBar({
super.key,
required this.find,
required this.focus,
required this.onStep,
required this.onClose,
});
final ChatShellTerminalFind find;
final FocusNode focus;
final ValueChanged<int> onStep;
final VoidCallback onClose;
@override
State<ChatShellTerminalFindBar> createState() =>
_ChatShellTerminalFindBarState();
}
class _ChatShellTerminalFindBarState extends State<ChatShellTerminalFindBar> {
late final TextEditingController _text = TextEditingController(
text: widget.find.query,
);
@override
void dispose() {
_text.dispose();
super.dispose();
}
KeyEventResult _key(FocusNode node, KeyEvent event) {
if (event is KeyUpEvent) return KeyEventResult.ignored;
if (event.logicalKey == LogicalKeyboardKey.escape) {
widget.onClose();
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.enter ||
event.logicalKey == LogicalKeyboardKey.numpadEnter) {
widget.onStep(HardwareKeyboard.instance.isShiftPressed ? -1 : 1);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
String _count(ChatShellTerminalFind find) {
if (find.query.isEmpty) return '';
if (find.count == 0) return 'No results';
final total = find.capped ? '${find.count}+' : '${find.count}';
return '${find.index + 1} of $total';
}
@override
Widget build(BuildContext context) {
final find = widget.find;
final scheme = Theme.of(context).colorScheme;
// The buttons count as part of the field, so clicking one keeps the
// keyboard in it (Enter steps on from there).
return TextFieldTapRegion(
child: Material(
elevation: 3,
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
child: ListenableBuilder(
listenable: find,
builder: (context, _) => Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 240),
child: Focus(
onKeyEvent: _key,
skipTraversal: true,
child: TextField(
key: const ValueKey('terminal-find-field'),
controller: _text,
focusNode: widget.focus,
autofocus: true,
decoration: const InputDecoration(
hintText: 'Find',
border: InputBorder.none,
isDense: true,
),
onChanged: (value) {
find.query = value;
widget.onStep(0);
},
),
),
),
),
Semantics(
liveRegion: true,
child: Text(
_count(find),
key: const ValueKey('terminal-find-count'),
style: Theme.of(context).textTheme.bodySmall,
),
),
IconButton(
key: const ValueKey('terminal-find-case'),
tooltip: 'Match case',
isSelected: find.caseSensitive,
onPressed: () {
find.toggleCase();
widget.onStep(0);
},
icon: const Text('Aa'),
),
IconButton(
key: const ValueKey('terminal-find-previous'),
tooltip: 'Previous match',
onPressed: find.count == 0 ? null : () => widget.onStep(-1),
icon: const Icon(Icons.keyboard_arrow_up),
),
IconButton(
key: const ValueKey('terminal-find-next'),
tooltip: 'Next match',
onPressed: find.count == 0 ? null : () => widget.onStep(1),
icon: const Icon(Icons.keyboard_arrow_down),
),
IconButton(
key: const ValueKey('terminal-find-close'),
tooltip: 'Close find',
onPressed: widget.onClose,
icon: const Icon(Icons.close),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,88 @@
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart';
import 'chat_shell_terminal_actions.dart';
import 'chat_shell_terminal_find.dart';
import 'chat_shell_terminal_find_bar.dart';
import 'chat_shell_terminal_session.dart';
/// A terminal view's find in the scrollback: opening the bar (or focusing
/// it), stepping between matches and scrolling each into view, and closing
/// it back to the terminal.
mixin ChatShellTerminalFindHost<T extends StatefulWidget> on State<T> {
ChatShellTerminalSession get session;
TerminalController get controller;
FocusNode get focus;
ChatShellTerminalActions get actions;
final FocusNode _findFocus = FocusNode(debugLabel: 'terminal-find');
ChatShellTerminalFind? _find;
void disposeFind() {
_find?.dispose();
_findFocus.dispose();
}
/// Opens the find bar, or focuses its field when it is open.
void openFind() {
if (_find != null) {
_findFocus.requestFocus();
return;
}
final scheme = Theme.of(context).colorScheme;
setState(() {
_find = ChatShellTerminalFind(
terminal: session.terminal,
controller: controller,
hit: scheme.tertiary.withValues(alpha: 0.3),
current: scheme.tertiary.withValues(alpha: 0.6),
);
});
// The field's autofocus would not take the keyboard from the terminal,
// which holds it in the same scope.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _find != null) _findFocus.requestFocus();
});
}
void _closeFind() {
final find = _find;
if (find == null) return;
setState(() => _find = null);
find.dispose();
focus.requestFocus();
}
void _stepFind(int step) {
final find = _find;
if (find == null) return;
if (step != 0) find.step(step);
final match = find.selected;
if (match != null) actions.reveal(match.begin.y);
}
/// [child] with the find bar over its top end while it is open.
Widget overlayFindBar(Widget child) {
final find = _find;
return Stack(
children: [
child,
if (find != null)
PositionedDirectional(
top: 8,
start: 8,
end: 8,
child: Align(
alignment: AlignmentDirectional.topEnd,
child: ChatShellTerminalFindBar(
find: find,
focus: _findFocus,
onStep: _stepFind,
onClose: _closeFind,
),
),
),
],
);
}
}
@@ -0,0 +1,150 @@
import 'package:flutter/material.dart';
import 'package:xterm/xterm.dart';
import 'chat_shell_terminal_links.dart';
/// The link under the mouse in one terminal view, found at each move (and
/// again when output or scrolling moves the text under a still pointer):
/// the view shows a pointer cursor and [ChatShellLinkUnderline] underlines
/// it.
class ChatShellLinkHover extends ChangeNotifier {
ChatShellLinkHover(this.terminal, this.view);
final Terminal terminal;
final GlobalKey<TerminalViewState> view;
Offset? _pointer;
ChatShellTerminalLink? _link;
ChatShellTerminalLink? get link => _link;
/// The mouse moved to [global] over the terminal.
void hover(Offset global) {
_pointer = global;
refresh();
}
/// The mouse left the terminal.
void exit() {
_pointer = null;
_set(null);
}
/// Finds the link under the pointer again.
void refresh() {
final pointer = _pointer;
final render = _render;
if (pointer == null || render == null) return _set(null);
final local = render.globalToLocal(pointer);
if (!(Offset.zero & render.size).contains(local)) return _set(null);
_set(chatShellTerminalLinkAt(terminal, render.getCellOffset(local)));
}
RenderTerminal? get _render {
final state = view.currentState;
if (state == null || !state.mounted) return null;
final render = state.renderTerminal;
return render.attached && render.hasSize ? render : null;
}
void _set(ChatShellTerminalLink? link) {
if (link == _link) return;
_link = link;
notifyListeners();
}
/// The rows the hovered link covers, in the coordinates of [box].
List<Rect> rects(RenderBox box) {
final link = _link;
final render = _render;
if (link == null || render == null) return const [];
final cell = render.cellSize;
final width = terminal.viewWidth;
return [
for (var y = link.begin.y; y <= link.end.y; y++)
_rect(
render,
box,
CellOffset(y == link.begin.y ? link.begin.x : 0, y),
(y == link.end.y ? link.end.x : width) -
(y == link.begin.y ? link.begin.x : 0),
cell,
),
];
}
static Rect _rect(
RenderTerminal render,
RenderBox box,
CellOffset at,
int cells,
Size cell,
) {
final origin = box.globalToLocal(
render.localToGlobal(render.getOffset(at)),
);
return origin & Size(cells * cell.width, cell.height);
}
}
/// Underlines the hovered link over the terminal it wraps.
class ChatShellLinkUnderline extends StatefulWidget {
const ChatShellLinkUnderline({
super.key,
required this.hover,
required this.repaint,
required this.child,
});
final ChatShellLinkHover hover;
/// Scrolling, which moves the link.
final Listenable repaint;
final Widget child;
@override
State<ChatShellLinkUnderline> createState() => _ChatShellLinkUnderlineState();
}
class _ChatShellLinkUnderlineState extends State<ChatShellLinkUnderline> {
final GlobalKey _box = GlobalKey();
@override
Widget build(BuildContext context) => CustomPaint(
key: _box,
foregroundPainter: _Underline(
widget.hover,
Listenable.merge([widget.hover, widget.repaint]),
Theme.of(context).colorScheme.primary,
() => _box.currentContext?.findRenderObject() as RenderBox?,
),
child: widget.child,
);
}
class _Underline extends CustomPainter {
_Underline(this.hover, Listenable repaint, this.color, this.box)
: super(repaint: repaint);
final ChatShellLinkHover hover;
final Color color;
final RenderBox? Function() box;
@override
void paint(Canvas canvas, Size size) {
final box = this.box();
if (hover.link == null || box == null || !box.attached) return;
final paint = Paint()
..color = color
..strokeWidth = 1;
for (final rect in hover.rects(box)) {
final y = rect.bottom - 1.5;
if (y < 0 || y > size.height) continue;
canvas.drawLine(Offset(rect.left, y), Offset(rect.right, y), paint);
}
}
@override
bool shouldRepaint(_Underline old) =>
old.hover != hover || old.color != color;
}
@@ -2,10 +2,95 @@ import 'package:xterm/core.dart';
final RegExp _link = RegExp(r'''https?://[^\s<>"'`]+''');
/// A web link drawn in a terminal: where it goes and the cells it covers,
/// from [begin] to [end] (exclusive), which may span wrapped rows.
class ChatShellTerminalLink {
const ChatShellTerminalLink(this.uri, this.begin, this.end);
final Uri uri;
final CellOffset begin;
final CellOffset end;
@override
bool operator ==(Object other) =>
other is ChatShellTerminalLink &&
other.uri == uri &&
other.begin == begin &&
other.end == end;
@override
int get hashCode => Object.hash(uri, begin, end);
}
/// The web link drawn at [offset] in [buffer], if any: the operator taps the
/// login URL an auth command printed. A link the terminal wrapped across
/// rows is joined first. Only http and https links are offered.
Uri? chatShellLinkAt(Buffer buffer, CellOffset offset) {
Uri? chatShellLinkAt(Buffer buffer, CellOffset offset) =>
chatShellTextLinkAt(buffer, offset)?.uri;
/// The link at [offset] in [terminal]'s buffer: an OSC 8 hyperlink on the
/// cell first (the program's own link, whatever its text), else a web
/// address printed there. Only http and https links are offered.
ChatShellTerminalLink? chatShellTerminalLinkAt(
Terminal terminal,
CellOffset offset,
) {
final buffer = terminal.buffer;
if (offset.y < 0 || offset.y >= buffer.height) return null;
final target = terminal.hyperlinkAt(buffer.lines[offset.y], offset.x);
if (target != null) {
final uri = _web(target);
if (uri == null) return null;
return _hyperlinkExtent(terminal, offset, target, uri);
}
return chatShellTextLinkAt(buffer, offset);
}
Uri? _web(String text) {
final uri = Uri.tryParse(text);
if (uri == null || uri.host.isEmpty) return null;
return uri.scheme == 'http' || uri.scheme == 'https' ? uri : null;
}
/// The run of cells around [offset] carrying the same OSC 8 [target],
/// following wrapped rows.
ChatShellTerminalLink _hyperlinkExtent(
Terminal terminal,
CellOffset offset,
String target,
Uri uri,
) {
final lines = terminal.buffer.lines;
bool same(int x, int y) => terminal.hyperlinkAt(lines[y], x) == target;
var (bx, by) = (offset.x, offset.y);
while (true) {
if (bx > 0 && same(bx - 1, by)) {
bx--;
} else if (bx == 0 && by > 0 && lines[by].isWrapped) {
final width = lines[by - 1].length;
if (width == 0 || !same(width - 1, by - 1)) break;
(bx, by) = (width - 1, by - 1);
} else {
break;
}
}
var (ex, ey) = (offset.x, offset.y);
while (true) {
if (ex + 1 < lines[ey].length && same(ex + 1, ey)) {
ex++;
} else if (ex + 1 >= lines[ey].length &&
ey + 1 < lines.length &&
lines[ey + 1].isWrapped &&
same(0, ey + 1)) {
(ex, ey) = (0, ey + 1);
} else {
break;
}
}
return ChatShellTerminalLink(uri, CellOffset(bx, by), CellOffset(ex + 1, ey));
}
/// The web address printed at [offset] in [buffer], with its cells.
ChatShellTerminalLink? chatShellTextLinkAt(Buffer buffer, CellOffset offset) {
if (offset.y < 0 || offset.y >= buffer.height) return null;
var first = offset.y;
while (first > 0 && buffer.lines[first].isWrapped) {
@@ -16,6 +101,7 @@ Uri? chatShellLinkAt(Buffer buffer, CellOffset offset) {
last++;
}
final text = StringBuffer();
final cells = <CellOffset>[];
var tapped = 0;
for (var y = first; y <= last; y++) {
final line = buffer.lines[y];
@@ -24,6 +110,7 @@ Uri? chatShellLinkAt(Buffer buffer, CellOffset offset) {
final code = line.getCodePoint(x);
// One character per cell keeps cell and string positions aligned.
text.write(code == 0 || code > 0xFFFF ? ' ' : String.fromCharCode(code));
cells.add(CellOffset(x, y));
}
}
for (final match in _link.allMatches(text.toString())) {
@@ -32,7 +119,12 @@ Uri? chatShellLinkAt(Buffer buffer, CellOffset offset) {
if (tapped >= match.start + trimmed.length) return null;
final uri = Uri.tryParse(trimmed);
if (uri == null || uri.host.isEmpty) return null;
return uri;
final end = cells[match.start + trimmed.length - 1];
return ChatShellTerminalLink(
uri,
cells[match.start],
CellOffset(end.x + 1, end.y),
);
}
return null;
}
@@ -0,0 +1,97 @@
import 'package:xterm/core.dart';
/// The most matches a search reports; more show as "1000+".
const int chatShellSearchLimit = 1000;
/// One match of a scrollback search: from [begin] to [end] (exclusive), in
/// buffer cells (row 0 is the oldest scrollback line).
class ChatShellSearchMatch {
const ChatShellSearchMatch(this.begin, this.end);
final CellOffset begin;
final CellOffset end;
@override
bool operator ==(Object other) =>
other is ChatShellSearchMatch && other.begin == begin && other.end == end;
@override
int get hashCode => Object.hash(begin, end);
@override
String toString() => 'Match($begin, $end)';
}
/// Every place [query] occurs in [buffer], oldest first, at most [limit]. A
/// line the terminal wrapped across rows is searched as one, so a match may
/// span rows. Without [caseSensitive] letters match either case.
List<ChatShellSearchMatch> chatShellTerminalSearch(
Buffer buffer,
String query, {
bool caseSensitive = false,
int limit = chatShellSearchLimit,
}) {
final matches = <ChatShellSearchMatch>[];
if (query.isEmpty) return matches;
final needle = caseSensitive ? query : _fold(query);
final lines = buffer.lines;
var y = 0;
while (y < buffer.height && matches.length < limit) {
final text = StringBuffer();
final cells = <int>[];
var last = y;
while (last + 1 < buffer.height && lines[last + 1].isWrapped) {
last++;
}
for (var row = y; row <= last; row++) {
_appendRow(lines[row], row, text, cells, caseSensitive);
}
final haystack = text.toString();
var from = 0;
while (matches.length < limit) {
final at = haystack.indexOf(needle, from);
if (at < 0) break;
final endAt = at + needle.length - 1;
final first = _cell(cells[at]);
final lastCell = _cell(cells[endAt]);
final width = lines[lastCell.y].getWidth(lastCell.x) == 2 ? 2 : 1;
matches.add(
ChatShellSearchMatch(first, CellOffset(lastCell.x + width, lastCell.y)),
);
from = at + needle.length;
}
y = last + 1;
}
return matches;
}
/// A cell packed as `y * 0x10000 + x` (rows are at most 500 cells wide;
/// arithmetic, not shifts, so the web's 32-bit bit operations never wrap).
CellOffset _cell(int packed) => CellOffset(packed % 0x10000, packed ~/ 0x10000);
/// Appends row [y]'s characters to [text], recording each UTF-16 unit's
/// packed cell in [cells]. A wide character's second cell adds nothing; an
/// empty cell is a space.
void _appendRow(
BufferLine line,
int y,
StringBuffer text,
List<int> cells,
bool caseSensitive,
) {
for (var x = 0; x < line.length; x++) {
final code = line.getCodePoint(x);
if (code == 0 && x > 0 && line.getWidth(x - 1) == 2) continue;
var char = code == 0 ? ' ' : String.fromCharCode(code);
if (!caseSensitive) {
final folded = _fold(char);
// Folding that changes the length would misalign cells.
if (folded.length == char.length) char = folded;
}
text.write(char);
for (var i = 0; i < char.length; i++) {
cells.add(y * 0x10000 + x);
}
}
}
String _fold(String text) => text.toLowerCase();
@@ -0,0 +1,63 @@
import 'package:xterm/xterm.dart';
/// Clears a selection that no longer shows what was selected: the screen
/// was cleared, the selected rows were rewritten or dropped out of the
/// scrollback, or the program switched screens. Scrollback rows never
/// change once written, so only the selected rows on the screen when it
/// was made are watched, which keeps a large selection cheap to check.
class ChatShellSelectionGuard {
ChatShellSelectionGuard(this.terminal, this.controller) {
controller.addListener(_selected);
terminal.addListener(_changed);
}
final Terminal terminal;
final TerminalController controller;
/// The watched rows and their text when selected.
final List<(BufferLine, String)> _rows = [];
Buffer? _buffer;
bool _had = false;
bool _clearing = false;
void _selected() {
if (_clearing) return;
_rows.clear();
final selection = controller.selection?.normalized;
_had = selection != null;
if (selection == null) return;
final buffer = _buffer = terminal.buffer;
final screenTop = buffer.height - terminal.viewHeight;
final first = selection.begin.y < screenTop ? screenTop : selection.begin.y;
final last = selection.end.y.clamp(0, buffer.height - 1);
for (var y = first; y <= last; y++) {
final line = buffer.lines[y];
_rows.add((line, line.getText()));
}
}
void _changed() {
if (!_had) return;
if (controller.selection == null ||
!identical(terminal.buffer, _buffer) ||
_rows.any((row) => !row.$1.attached || row.$1.getText() != row.$2)) {
_clear();
}
}
void _clear() {
_had = false;
_rows.clear();
_clearing = true;
try {
controller.clearSelection();
} finally {
_clearing = false;
}
}
void dispose() {
controller.removeListener(_selected);
terminal.removeListener(_changed);
}
}
@@ -1,13 +1,14 @@
import 'package:flutter/foundation.dart';
import 'package:xterm/core.dart';
import '../../terminal/terminal_layout.dart';
import 'chat_shell_run.dart';
import 'chat_shell_terminal_emulator.dart';
import 'chat_shell_terminal_events.dart';
import 'chat_shell_terminal_feed.dart';
import 'chat_shell_terminal_key_input.dart';
/// Lines of scrollback one card's terminal keeps.
const int chatShellTerminalScrollback = 5000;
/// Lines a terminal keeps unless the setting says otherwise.
const int chatShellTerminalScrollback = terminalScrollbackDefault;
/// The terminal emulator state of one run: the xterm [terminal] fed with the
/// run's output in order, and the bridge from what the operator types (or
@@ -29,9 +30,19 @@ class ChatShellTerminalSession {
this.onReply,
this.onActivate,
bool Function()? optionAsMeta,
}) : optionAsMeta =
optionAsMeta ?? (() => TerminalLayout.instance.optionAsMeta),
terminal = _ChatShellTerminal() {
TerminalLayout? layout,
}) : layout = layout ?? TerminalLayout.instance,
optionAsMeta =
optionAsMeta ??
(() => (layout ?? TerminalLayout.instance).optionAsMeta),
terminal = ChatShellTerminal(
maxLines: (layout ?? TerminalLayout.instance).scrollback,
) {
events = ChatShellTerminalEvents(
terminal,
quiet: () => _replaying || !_live,
);
this.layout.addListener(_layoutChanged);
terminal.inputHandler = CascadeInputHandler([
ChatShellInputHandler(optionAsMeta: this.optionAsMeta),
defaultInputHandler,
@@ -49,6 +60,12 @@ class ChatShellTerminalSession {
final Terminal terminal;
/// The terminal preferences (text size, scrollback, bell) views follow.
final TerminalLayout layout;
/// The bell, clipboard and folder the program reports.
late final ChatShellTerminalEvents events;
/// Whether a Mac's Option key is Meta (Settings → Appearance → Terminal).
final bool Function() optionAsMeta;
@@ -96,8 +113,12 @@ class ChatShellTerminalSession {
}
/// Draws [run]'s held output from scratch: on open, after a gap and after
/// a readback replaced the card's copy. Answers the emulator gives to old
/// queries in that output are not sent: the process asked them long ago.
/// a readback replaced the card's copy. A machine terminal's read from
/// before the server's tail is the server's snapshot
/// ([ChatShellRun.snapshot]), which resets the emulator and restores the
/// screens, scrollback, cursor and modes; it is drawn the same way.
/// Answers the emulator gives to old queries in that output are not sent:
/// the process asked them long ago.
/// A large output is drawn in slices across turns of the event loop
/// (ChatShellTerminalFeed), so it never stalls the UI.
void replay(ChatShellRun run) {
@@ -109,6 +130,9 @@ class ChatShellTerminalSession {
terminal.useMainBuffer();
terminal.buffer.clear();
terminal.buffer.setCursor(0, 0);
// A full reset (RIS): modes a program set in the output drawn before
// (mouse reporting, bracketed paste, the alternate screen) end too.
terminal.write('\x1bc');
terminal.setCursorVisibleMode(true);
terminal.write('\x1b[0m');
if (run.truncated) {
@@ -146,7 +170,14 @@ class ChatShellTerminalSession {
}
/// Stops drawing what still waits (the emulator is going away).
void dispose() => _feed.dispose();
void dispose() {
layout.removeListener(_layoutChanged);
events.dispose();
_feed.dispose();
}
/// A changed scrollback length applies to this running terminal too.
void _layoutChanged() => terminal.maxLines = layout.scrollback;
/// Writes one slice. What the emulator sends while drawing live output
/// answers that output (onReply); during a replay it is not sent at all.
@@ -199,58 +230,3 @@ class ChatShellTerminalSession {
static String _drawable(ChatShellRun run, String text) =>
run.terminal ? text : text.replaceAll('\n', '\r\n');
}
/// The emulator with the scrollback the cards keep. It answers a cursor
/// position query (DSR 6) with the one-based row and column the protocol
/// specifies; xterm.dart 4.0.0 itself answers zero-based.
///
/// A live terminal does not reflow on resize: xterm.dart 4.0.0's reflow
/// leaves the cursor on a row other than its line's, so the shell's redraw
/// lands on old output. Without it a resize behaves as xterm's: narrowing
/// cuts rows at the new width, fewer rows scroll the top into scrollback
/// (keeping the cursor's row at the bottom), more rows bring it back.
/// Finished output, which nothing writes to any more, reflows to fit.
class _ChatShellTerminal extends Terminal {
_ChatShellTerminal()
: super(maxLines: chatShellTerminalScrollback, platform: _platform());
/// The package's own Alt handler (a fallback after the app's) leaves
/// Option alone only when it knows it is on a Mac.
static TerminalTargetPlatform _platform() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS
? TerminalTargetPlatform.macos
: TerminalTargetPlatform.unknown;
@override
void sendCursorPosition() {
onOutput?.call('\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}R');
}
@override
void resize(int width, int height, [int? pixelWidth, int? pixelHeight]) {
final oldWidth = viewWidth;
if (!reflowEnabled && width >= 1 && width < oldWidth) {
// A cut row keeps its cells past the new width, which a later widening
// would show again beside what was written since: they are erased.
for (final buffer in [mainBuffer, altBuffer]) {
buffer.lines.forEach((line) {
if (line.length > width) {
line.eraseRange(width, line.length, CursorStyle.empty);
}
});
}
}
super.resize(width, height, pixelWidth, pixelHeight);
if (!reflowEnabled) return;
// Rewrapping keeps every blank row below the cursor, and the extra rows
// push the top of finished output into scrollback: they are dropped.
final lines = buffer.lines;
while (buffer.height > viewHeight &&
buffer.height - 1 > buffer.absoluteCursorY &&
lines[buffer.height - 1].getText().trim().isEmpty) {
lines.pop();
buffer.setCursor(buffer.cursorX, buffer.cursorY + 1);
}
}
}
@@ -0,0 +1,110 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
bool _apple() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
/// The terminal's own key shortcuts. Cmd-C, Cmd-V and Cmd-A on Apple
/// platforms; elsewhere Ctrl-V (and the terminal convention Ctrl-Shift-V)
/// paste and Ctrl-Shift-C or Ctrl-Insert copies, so every other Ctrl key,
/// Ctrl-A included, reaches the process. Ctrl-C copies too while text is
/// selected (see [chatShellCopyKey]); a browser keeps Ctrl-Shift-C for its
/// developer tools, so there it is the key that works.
Map<ShortcutActivator, Intent> chatShellTerminalShortcuts() {
const paste = PasteTextIntent(SelectionChangedCause.keyboard);
if (_apple()) {
return const {
SingleActivator(LogicalKeyboardKey.keyC, meta: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.keyV, meta: true): paste,
SingleActivator(LogicalKeyboardKey.keyA, meta: true): SelectAllTextIntent(
SelectionChangedCause.keyboard,
),
};
}
return const {
SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.insert, control: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.keyV, control: true): paste,
SingleActivator(LogicalKeyboardKey.keyV, control: true, shift: true): paste,
};
}
/// Whether [event] is Ctrl-C outside Apple platforms: with text selected in
/// the terminal it copies the selection instead of interrupting the process,
/// as terminals in browsers and on Windows do. Without a selection Ctrl-C
/// stays the process's.
bool chatShellCopyKey(KeyEvent event, HardwareKeyboard keyboard) {
return !_apple() &&
event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.keyC &&
keyboard.isControlPressed &&
!keyboard.isShiftPressed &&
!keyboard.isAltPressed &&
!keyboard.isMetaPressed;
}
/// A key the terminal view answers itself instead of sending it to the
/// process.
enum ChatShellLocalKey {
find,
zoomIn,
zoomOut,
zoomReset,
pageUp,
pageDown,
top,
bottom,
}
/// The view's own key for [event], if it is one: find in the scrollback
/// (Cmd+F on Apple platforms, Ctrl+Shift+F elsewhere, where Ctrl+F is the
/// shell's forward-char), text size (Cmd or Ctrl with =/+, - and 0), and
/// with [mainBuffer] Shift+PgUp/PgDn/Home/End scrolling the scrollback. A
/// full-screen program (the alternate screen) keeps the Shift keys.
ChatShellLocalKey? chatShellLocalKey(
KeyEvent event,
HardwareKeyboard keyboard, {
required bool mainBuffer,
}) {
if (event is KeyUpEvent) return null;
final key = event.logicalKey;
final apple = _apple();
final ctrl = keyboard.isControlPressed;
final meta = keyboard.isMetaPressed;
final alt = keyboard.isAltPressed;
final shift = keyboard.isShiftPressed;
// Exactly the platform's command modifier (Shift aside).
final command = !alt && (apple ? meta && !ctrl : ctrl && !meta);
if (key == LogicalKeyboardKey.keyF && command && shift != apple) {
return event is KeyDownEvent ? ChatShellLocalKey.find : null;
}
if (command) {
if (key == LogicalKeyboardKey.equal ||
key == LogicalKeyboardKey.add ||
key == LogicalKeyboardKey.numpadAdd) {
return ChatShellLocalKey.zoomIn;
}
if (shift) return null;
if (key == LogicalKeyboardKey.minus ||
key == LogicalKeyboardKey.numpadSubtract) {
return ChatShellLocalKey.zoomOut;
}
if (key == LogicalKeyboardKey.digit0 || key == LogicalKeyboardKey.numpad0) {
return event is KeyDownEvent ? ChatShellLocalKey.zoomReset : null;
}
return null;
}
if (!mainBuffer || !shift || ctrl || meta || alt) return null;
return switch (key) {
LogicalKeyboardKey.pageUp => ChatShellLocalKey.pageUp,
LogicalKeyboardKey.pageDown => ChatShellLocalKey.pageDown,
LogicalKeyboardKey.home => ChatShellLocalKey.top,
LogicalKeyboardKey.end => ChatShellLocalKey.bottom,
_ => null,
};
}
@@ -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
@@ -53,16 +55,34 @@ TerminalTheme chatShellTerminalTheme(BuildContext context) {
);
}
/// The terminal's text: the host's monospace family at the card body size.
TerminalStyle chatShellTerminalStyle(BuildContext context) {
final body = chatCardBodyStyle(context) ?? const TextStyle();
/// The terminal's text: the host's monospace family at [fontSize] (the
/// 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,
fontSize: (body.fontSize ?? 14) * 0.95,
height: 1.3,
fontFamilyFallback: const [
terminalSymbolsFamily,
...kTerminalDefaultFontFamilyFallback,
],
fontSize: fontSize ?? chatShellTerminalDefaultFontSize(context),
height: 1.1,
);
}
/// The terminal's text size when the setting is the default.
double chatShellTerminalDefaultFontSize(BuildContext context) {
final body = chatCardBodyStyle(context) ?? const TextStyle();
return (body.fontSize ?? 14) * 0.95;
}
/// The size of one terminal cell in [style] at the context's text scale,
/// measured exactly as the emulator measures it.
Size chatShellTerminalCellSize(BuildContext context, TerminalStyle style) {
@@ -72,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;
}
@@ -6,71 +6,35 @@ import 'package:xterm/xterm.dart';
import '../conversation/chat_composer_paste_focus.dart';
import '../ui/transcript/chat_link_launcher.dart';
import 'chat_shell_metrics.dart';
import 'chat_shell_terminal_bell.dart';
import 'chat_shell_terminal_key_input.dart';
import 'chat_shell_terminal_links.dart';
import 'chat_shell_terminal_session.dart';
import 'chat_shell_terminal_shortcuts.dart';
import 'chat_shell_terminal_theme.dart';
import 'chat_shell_terminal_find_host.dart';
import 'chat_shell_terminal_view_features.dart';
import '../../../ui/input/keyboard_owner.dart';
export 'chat_shell_terminal_shortcuts.dart'
show chatShellTerminalShortcuts, chatShellCopyKey;
/// Whether the soft keyboard is the main way to type here, so the key
/// toolbar offers a text field: the terminal itself takes hardware keys only.
bool chatShellTouchFirst() =>
defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS;
/// The terminal's own key shortcuts. Cmd-C, Cmd-V and Cmd-A on Apple
/// platforms; elsewhere Ctrl-V (and the terminal convention Ctrl-Shift-V)
/// paste and Ctrl-Shift-C or Ctrl-Insert copies, so every other Ctrl key,
/// Ctrl-A included, reaches the process. Ctrl-C copies too while text is
/// selected (see [chatShellCopyKey]); a browser keeps Ctrl-Shift-C for its
/// developer tools, so there it is the key that works.
Map<ShortcutActivator, Intent> chatShellTerminalShortcuts() {
const paste = PasteTextIntent(SelectionChangedCause.keyboard);
final apple =
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
if (apple) {
return const {
SingleActivator(LogicalKeyboardKey.keyC, meta: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.keyV, meta: true): paste,
SingleActivator(LogicalKeyboardKey.keyA, meta: true): SelectAllTextIntent(
SelectionChangedCause.keyboard,
),
};
}
return const {
SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.insert, control: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.keyV, control: true): paste,
SingleActivator(LogicalKeyboardKey.keyV, control: true, shift: true): paste,
};
}
/// Whether [event] is Ctrl-C outside Apple platforms: with text selected in
/// the terminal it copies the selection instead of interrupting the process,
/// as terminals in browsers and on Windows do. Without a selection Ctrl-C
/// stays the process's.
bool chatShellCopyKey(KeyEvent event, HardwareKeyboard keyboard) {
final apple =
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
return !apple &&
event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.keyC &&
keyboard.isControlPressed &&
!keyboard.isShiftPressed &&
!keyboard.isAltPressed &&
!keyboard.isMetaPressed;
}
/// One run's terminal emulator view. In a card it is bounded to
/// [kChatShellOutputCollapsedLines] rows (a finished run shrinks to its
/// output); with [fill] it takes the space its parent gives (full screen).
/// It sizes the terminal to its own layout; a running process is resized to
/// match. Tapping a printed web link opens it in the browser.
///
/// Besides the process's keys it answers its own (see [chatShellLocalKey]):
/// find in the scrollback, text size, and Shift+PgUp/PgDn/Home/End
/// scrolling. A right-click opens its menu (unless the program reports the
/// mouse), a bell flashes its border, and an OSC 52 copy says so.
class ChatShellTerminalView extends StatefulWidget {
const ChatShellTerminalView({
super.key,
@@ -91,63 +55,69 @@ class ChatShellTerminalView extends StatefulWidget {
State<ChatShellTerminalView> createState() => _ChatShellTerminalViewState();
}
class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
final TerminalController _controller = TerminalController();
final FocusNode _focus = FocusNode(debugLabel: 'chat-shell-terminal');
class _ChatShellTerminalViewState extends State<ChatShellTerminalView>
with
SingleTickerProviderStateMixin,
ChatShellTerminalFindHost<ChatShellTerminalView>,
ChatShellTerminalFeatures<ChatShellTerminalView> {
@override
final TerminalController controller = TerminalController();
@override
final FocusNode focus = FocusNode(debugLabel: 'chat-shell-terminal');
final FocusNode _outputFocus = FocusNode(debugLabel: 'chat-shell-output');
final ScrollController _scroll = ScrollController();
@override
final ScrollController scroll = ScrollController();
@override
final GlobalKey<TerminalViewState> viewKey = GlobalKey();
final Map<ShortcutActivator, Intent> _shortcuts =
chatShellTerminalShortcuts();
bool _focused = false;
@override
ChatShellTerminalSession get session => widget.session;
@override
void initState() {
super.initState();
// A paste while the terminal has focus goes to the process, not to the
// chat composer.
ChatComposerPasteFocus.registerInput(_focus);
_focus.addListener(_focusChanged);
ChatComposerPasteFocus.registerInput(focus);
focus.addListener(_focusChanged);
initFeatures();
}
/// Focusing a terminal makes this client the one it is sized for, the
/// way typing in it does.
void _focusChanged() {
final focused = _focus.hasFocus;
final focused = focus.hasFocus;
if (focused && !_focused) widget.session.activate();
_focused = focused;
updateBlink();
}
@override
void dispose() {
_focus.removeListener(_focusChanged);
ChatComposerPasteFocus.unregisterInput(_focus);
_controller.dispose();
_focus.dispose();
focus.removeListener(_focusChanged);
disposeFeatures();
ChatComposerPasteFocus.unregisterInput(focus);
controller.dispose();
focus.dispose();
_outputFocus.dispose();
_scroll.dispose();
scroll.dispose();
super.dispose();
}
/// Copies the selected text and clears the selection; false with none.
bool _copySelection() {
final selection = _controller.selection;
if (selection == null) return false;
final text = widget.session.terminal.buffer.getText(selection);
if (text.isEmpty) return false;
Clipboard.setData(ClipboardData(text: text));
_controller.clearSelection();
return true;
}
/// Ctrl-C with a selection copies; the terminal's own shortcuts (copy,
/// paste) are left to it; any other key xterm encodes differently from
/// Ctrl-C with a selection copies; the view's own keys (find, zoom,
/// scrolling) are answered; the terminal's own shortcuts (copy, paste)
/// are left to it; any other key xterm encodes differently from
/// xterm.dart (Alt as Meta, Ctrl symbols, modified special keys) is sent
/// here with its real character. The rest is the emulator's.
KeyEventResult _key(FocusNode node, KeyEvent event) {
final keyboard = HardwareKeyboard.instance;
if (chatShellCopyKey(event, keyboard) && _copySelection()) {
if (chatShellCopyKey(event, keyboard) && actions.copySelection()) {
return KeyEventResult.handled;
}
if (localKey(event)) return KeyEventResult.handled;
if (_shortcuts.keys.any((key) => key.accepts(event, keyboard))) {
return KeyEventResult.ignored;
}
@@ -160,65 +130,67 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
);
if (bytes == null) return KeyEventResult.ignored;
session.terminal.textInput(bytes);
if (_scroll.hasClients) _scroll.jumpTo(_scroll.position.maxScrollExtent);
if (scroll.hasClients) scroll.jumpTo(scroll.position.maxScrollExtent);
return KeyEventResult.handled;
}
/// A finished run's output takes no keys of its own, so the copy keys are
/// answered here while it has the keyboard.
KeyEventResult _readOnlyKey(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent ||
event.logicalKey != LogicalKeyboardKey.keyC &&
event.logicalKey != LogicalKeyboardKey.insert) {
return KeyEventResult.ignored;
}
final keyboard = HardwareKeyboard.instance;
if (!keyboard.isControlPressed && !keyboard.isMetaPressed) {
return KeyEventResult.ignored;
}
return _copySelection() ? KeyEventResult.handled : KeyEventResult.ignored;
}
void _tapped(TapUpDetails details, CellOffset offset) {
final uri = chatShellLinkAt(widget.session.terminal.buffer, offset);
if (uri != null) openChatLink(context, uri);
final link = chatShellTerminalLinkAt(widget.session.terminal, offset);
if (link != null) openChatLink(context, link.uri);
}
@override
Widget build(BuildContext context) {
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.session.layout,
builder: (context, _) => _build(context),
);
Widget _build(BuildContext context) {
final session = widget.session;
final live = session.live;
final style = chatShellTerminalStyle(context);
final style = chatShellTerminalStyle(
context,
fontSize: session.layout.fontSize,
);
currentFontSize = style.fontSize;
const padding = EdgeInsets.all(8);
Widget view = Semantics(
Widget view = ListenableBuilder(
listenable: hover,
builder: (context, _) => TerminalView(
session.terminal,
key: viewKey,
controller: controller,
scrollController: scroll,
focusNode: focus,
autofocus: widget.autofocus && live,
autoResize: widget.autoResize,
theme: chatShellTerminalTheme(context),
textStyle: style,
padding: padding,
readOnly: !live,
// Desktop keys go straight to the process as key events (a focused
// text input stays closed in desktop browsers). On phones and
// tablets a tap opens the on-screen keyboard and typing goes to the
// terminal; the key toolbar's field stays as an alternative.
hardwareKeyboardOnly: !chatShellTouchFirst(),
// No autocorrect or suggestions rewriting what is sent to a shell.
keyboardType: TextInputType.visiblePassword,
shortcuts: _shortcuts,
cursorType: TerminalCursorType.block,
cursorBlinkVisible: blink.visible,
mouseCursor: hover.link == null
? SystemMouseCursors.text
: SystemMouseCursors.click,
onTapUp: _tapped,
onSecondaryTapUp: (details, _) => openMenu(details.globalPosition),
onKeyEvent: _key,
),
);
view = Semantics(
identifier: 'chat-shell-terminal',
label: live ? 'Terminal, type to send input' : 'Terminal output',
// App-wide shortcuts leave typing in the terminal alone.
child: TypingSurface(
child: TerminalView(
session.terminal,
controller: _controller,
scrollController: _scroll,
focusNode: _focus,
autofocus: widget.autofocus && live,
autoResize: widget.autoResize,
theme: chatShellTerminalTheme(context),
textStyle: style,
padding: padding,
readOnly: !live,
// Desktop keys go straight to the process as key events (a focused
// text input stays closed in desktop browsers). On phones and tablets
// a tap opens the on-screen keyboard and typing goes to the terminal;
// the key toolbar's field stays as an alternative.
hardwareKeyboardOnly: !chatShellTouchFirst(),
// No autocorrect or suggestions rewriting what is sent to a shell.
keyboardType: TextInputType.visiblePassword,
shortcuts: _shortcuts,
cursorType: TerminalCursorType.block,
onTapUp: _tapped,
onKeyEvent: _key,
),
),
child: TypingSurface(child: decorate(view)),
);
if (!live) {
// The read-only emulator attaches no keyboard: a press selects text
@@ -227,7 +199,7 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
onPointerDown: (_) => _outputFocus.requestFocus(),
child: Focus(
focusNode: _outputFocus,
onKeyEvent: _readOnlyKey,
onKeyEvent: readOnlyKey,
child: view,
),
);
@@ -242,6 +214,13 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
child: view,
);
view = ClipRRect(borderRadius: BorderRadius.circular(8), child: view);
view = overlayFindBar(
ChatShellBellFlash(
bells: session.events.bells,
enabled: session.layout.bell,
child: view,
),
);
if (widget.fill) return view;
final cell = chatShellTerminalCellSize(context, style);
return LayoutBuilder(
@@ -0,0 +1,190 @@
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
import 'chat_shell_terminal_actions.dart';
import 'chat_shell_terminal_context_menu.dart';
import 'chat_shell_terminal_cursor_blink.dart';
import 'chat_shell_terminal_find_host.dart';
import 'chat_shell_terminal_link_hover.dart';
import 'chat_shell_terminal_selection_guard.dart';
import 'chat_shell_terminal_shortcuts.dart';
/// The terminal view's own features around the emulator: text size,
/// scrolling keys, the context menu, link hover, the cursor blink,
/// stale-selection clearing and the OSC 52 toast (find in the scrollback is
/// [ChatShellTerminalFindHost]). The view supplies its emulator's parts and
/// calls [initFeatures] and [disposeFeatures].
mixin ChatShellTerminalFeatures<T extends StatefulWidget>
on State<T>, TickerProvider, ChatShellTerminalFindHost<T> {
ScrollController get scroll;
GlobalKey<TerminalViewState> get viewKey;
@override
late final ChatShellTerminalActions actions;
late final ChatShellLinkHover hover;
late final ChatShellCursorBlink blink;
late final ChatShellSelectionGuard _guard;
bool _reduceMotion = false;
bool _hoverQueued = false;
bool _attached = false;
/// The text size the view draws at now, which zooming steps from.
double currentFontSize = 14;
Terminal get _terminal => session.terminal;
void initFeatures() {
actions = ChatShellTerminalActions(
terminal: _terminal,
controller: controller,
scroll: scroll,
view: viewKey,
);
hover = ChatShellLinkHover(_terminal, viewKey);
blink = ChatShellCursorBlink(this);
_guard = ChatShellSelectionGuard(_terminal, controller);
scroll.addListener(hover.refresh);
_terminal.addListener(_terminalChanged);
// Counted as shown once drawn: the tab it clears a bell dot on is
// being built now.
SchedulerBinding.instance.addPostFrameCallback((_) {
if (!mounted || _attached) return;
_attached = true;
session.events.attach(_copied);
});
}
void disposeFeatures() {
if (_attached) session.events.detach(_copied);
_terminal.removeListener(_terminalChanged);
scroll.removeListener(hover.refresh);
_guard.dispose();
blink.dispose();
hover.dispose();
disposeFind();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_reduceMotion = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
updateBlink();
}
/// Blinks only a focused cursor whose program asked for blinking, and
/// never under reduced motion.
void updateBlink() => blink.update(
blink:
focus.hasFocus && !_reduceMotion && _terminal.cursorShapeBlinks == true,
);
/// Output (or an echo) shows the cursor at once and may change its
/// shape; the link under a still pointer is found again after the frame.
void _terminalChanged() {
updateBlink();
blink.restart();
if (_hoverQueued) return;
_hoverQueued = true;
SchedulerBinding.instance.addPostFrameCallback((_) {
_hoverQueued = false;
if (mounted) hover.refresh();
});
}
void _copied(String text) {
if (!mounted) return;
ScaffoldMessenger.maybeOf(context)
?..hideCurrentSnackBar()
..showSnackBar(
const SnackBar(
content: Text('Copied from terminal'),
duration: Duration(seconds: 2),
),
);
}
/// Answers the view's own keys; false for any other.
bool localKey(KeyEvent event) {
final key = chatShellLocalKey(
event,
HardwareKeyboard.instance,
mainBuffer: !_terminal.isUsingAltBuffer,
);
final layout = session.layout;
switch (key) {
case null:
return false;
case ChatShellLocalKey.find:
openFind();
case ChatShellLocalKey.zoomIn:
layout.zoom(1, currentFontSize);
case ChatShellLocalKey.zoomOut:
layout.zoom(-1, currentFontSize);
case ChatShellLocalKey.zoomReset:
layout.setFontSize(null);
case ChatShellLocalKey.pageUp:
actions.scrollPages(-1);
case ChatShellLocalKey.pageDown:
actions.scrollPages(1);
case ChatShellLocalKey.top:
actions.scrollToTop();
case ChatShellLocalKey.bottom:
actions.scrollToBottom();
}
return true;
}
/// A finished run's output takes no keys of its own, so the copy keys
/// (and the view's own) are answered here while it has the keyboard.
KeyEventResult readOnlyKey(FocusNode node, KeyEvent event) {
if (localKey(event)) return KeyEventResult.handled;
if (event is! KeyDownEvent ||
event.logicalKey != LogicalKeyboardKey.keyC &&
event.logicalKey != LogicalKeyboardKey.insert) {
return KeyEventResult.ignored;
}
final keyboard = HardwareKeyboard.instance;
if (!keyboard.isControlPressed && !keyboard.isMetaPressed) {
return KeyEventResult.ignored;
}
return actions.copySelection()
? KeyEventResult.handled
: KeyEventResult.ignored;
}
/// [view] with link hover feedback and the web's browser menu kept off.
Widget decorate(Widget view) => ChatShellNoBrowserMenu(
child: MouseRegion(
onHover: (event) => hover.hover(event.position),
onExit: (_) => hover.exit(),
child: ChatShellLinkUnderline(hover: hover, repaint: scroll, child: view),
),
);
/// The right-click menu at [position] (global).
Future<void> openMenu(Offset position) async {
final choice = await showChatShellTerminalMenu(
context,
position: position,
canCopy: controller.selection != null,
canPaste: session.live,
);
if (!mounted || choice == null) return;
switch (choice) {
case ChatShellTerminalMenuItem.copy:
actions.copySelection();
case ChatShellTerminalMenuItem.paste:
await actions.paste();
case ChatShellTerminalMenuItem.selectAll:
actions.selectAll();
case ChatShellTerminalMenuItem.clear:
actions.clearScrollback();
case ChatShellTerminalMenuItem.find:
openFind();
return;
}
if (mounted && session.live) focus.requestFocus();
}
}
@@ -0,0 +1,76 @@
import 'package:flutter/material.dart';
import '../terminal/terminal_layout.dart';
import 'settings_group.dart';
/// The text sizes the setting offers (besides Default and the current one).
const List<double> _fontSizes = [10, 11, 12, 13, 14, 15, 16, 18, 20, 24];
/// Appearance → Terminal's text size, scrollback and bell controls.
List<Widget> settingsTerminalControls(TerminalLayout layout) => [
SettingsGroupItem(child: _FontSize(layout: layout)),
SettingsGroupItem(child: _Scrollback(layout: layout)),
SwitchListTile(
key: const ValueKey('settings-terminal-bell'),
title: const Text('Visual bell'),
subtitle: const Text(
'A bell from the program flashes the terminal\'s border, and dots its '
'tab while it is not shown.',
),
value: layout.bell,
onChanged: layout.setBell,
),
];
String _lines(int lines) => lines >= 1000 && lines % 1000 == 0
? '${lines ~/ 1000}k lines'
: '$lines lines';
class _FontSize extends StatelessWidget {
const _FontSize({required this.layout});
final TerminalLayout layout;
@override
Widget build(BuildContext context) {
final current = layout.fontSize;
final sizes = {..._fontSizes, ?current}.toList()..sort();
// Keyed by the value, so a zoom from the keyboard shows here at once.
return DropdownMenu<double>(
key: ValueKey('settings-terminal-font-size-$current'),
expandedInsets: EdgeInsets.zero,
label: const Text('Text size'),
helperText:
'Ctrl or Cmd with + and - zooms a focused terminal; '
'with 0 it resets.',
initialSelection: current ?? 0,
dropdownMenuEntries: [
const DropdownMenuEntry(value: 0, label: 'Default'),
for (final size in sizes)
DropdownMenuEntry(value: size, label: '${size.round()} pt'),
],
onSelected: (size) =>
layout.setFontSize(size == null || size == 0 ? null : size),
);
}
}
class _Scrollback extends StatelessWidget {
const _Scrollback({required this.layout});
final TerminalLayout layout;
@override
Widget build(BuildContext context) => DropdownMenu<int>(
key: ValueKey('settings-terminal-scrollback-${layout.scrollback}'),
expandedInsets: EdgeInsets.zero,
label: const Text('Scrollback'),
helperText: 'Lines each terminal keeps; applies to open terminals too.',
initialSelection: layout.scrollback,
dropdownMenuEntries: [
for (final lines in terminalScrollbackChoices)
DropdownMenuEntry(value: lines, label: _lines(lines)),
],
onSelected: (lines) {
if (lines != null) layout.setScrollback(lines);
},
);
}
@@ -3,10 +3,12 @@ import 'package:flutter/material.dart';
import '../terminal/terminal_layout.dart';
import 'settings_group.dart';
import 'settings_terminal_controls.dart';
import 'settings_theme.dart';
/// Appearance → Terminal: whether the terminal docks at the bottom of the
/// window or floats over it (Ctrl+` shows and hides it either way).
/// window or floats over it (Ctrl+` shows and hides it either way), the
/// Option key, text size, scrollback length and visual bell.
class SettingsTerminalSection extends StatelessWidget {
const SettingsTerminalSection({super.key, required this.layout});
@@ -78,6 +80,7 @@ class SettingsTerminalSection extends StatelessWidget {
value: layout.optionAsMeta,
onChanged: layout.setOptionAsMeta,
),
...settingsTerminalControls(layout),
],
);
},
+7 -1
View File
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import '../../core/api_gateway.dart';
import 'terminal_info.dart';
import 'terminal_layout.dart';
import 'terminal_listing.dart';
import 'terminal_machines.dart';
import 'terminal_tab.dart';
@@ -17,9 +18,13 @@ import 'terminal_tab.dart';
/// restart) its terminals are listed, new ones get a tab, and every tab
/// resumes its output from the last byte it holds.
class TerminalHub extends ChangeNotifier {
TerminalHub(this.machines);
TerminalHub(this.machines, {this.layout});
final TerminalMachines machines;
/// The terminal preferences each tab's emulator follows (the app's own
/// when null).
final TerminalLayout? layout;
final Map<String, _Link> _links = {};
bool _active = false;
final List<TerminalTab> _tabs = [];
@@ -151,6 +156,7 @@ class TerminalHub extends ChangeNotifier {
machineName: machine.name,
gateway: machine.gateway,
info: info,
layout: layout,
)..addListener(_notify);
_tabs.add(tab);
unawaited(tab.resume());
@@ -23,6 +23,22 @@ const double terminalPanelMinHeight = 120;
const Size terminalFloatMinSize = Size(320, 200);
const Rect terminalFloatDefaultRect = Rect.fromLTWH(80, 80, 720, 420);
/// The scrollback lengths offered, and the default.
const List<int> terminalScrollbackChoices = [
1000,
5000,
10000,
25000,
50000,
100000,
];
const int terminalScrollbackDefault = 10000;
/// The terminal's text size limits (logical pixels) and one zoom step.
const double terminalFontSizeMin = 8;
const double terminalFontSizeMax = 32;
const double terminalFontSizeStep = 1;
abstract interface class TerminalLayoutStore {
Future<String?> load();
Future<bool> save(String value);
@@ -80,6 +96,16 @@ class TerminalLayout extends ChangeNotifier {
/// platforms' Alt is always Meta.
bool optionAsMeta = true;
/// The terminal's text size, or null for the app's default (the chat
/// card's body size). Ctrl/Cmd+=, - and 0 zoom it.
double? fontSize;
/// Lines each terminal keeps, scrollback included.
int scrollback = terminalScrollbackDefault;
/// Whether a bell (BEL) flashes the terminal and dots a hidden tab.
bool bell = true;
/// Whether the last change could not be saved.
bool saveFailed = false;
@@ -106,6 +132,13 @@ class TerminalLayout extends ChangeNotifier {
}
maximized = json['maximized'] == true;
optionAsMeta = json['option_as_meta'] != false;
final size = _finite(json['font_size']);
fontSize = size?.clamp(terminalFontSizeMin, terminalFontSizeMax);
final lines = json['scrollback'];
if (lines is int && terminalScrollbackChoices.contains(lines)) {
scrollback = lines;
}
bell = json['bell'] != false;
} catch (_) {
return;
}
@@ -114,6 +147,19 @@ class TerminalLayout extends ChangeNotifier {
void setMode(TerminalMode value) => _change(() => mode = value);
void setOptionAsMeta(bool value) => _change(() => optionAsMeta = value);
void setScrollback(int value) => _change(() => scrollback = value);
void setBell(bool value) => _change(() => bell = value);
/// Sets the text size (null: the default), within the limits.
void setFontSize(double? value) => _change(
() => fontSize = value?.clamp(terminalFontSizeMin, terminalFontSizeMax),
);
/// One zoom step in or out ([steps] > 0 larger) from [current], the size
/// the terminal draws at now.
void zoom(int steps, double current) => setFontSize(
(fontSize ?? current).roundToDouble() + steps * terminalFontSizeStep,
);
void toggle() => _change(() => visible = !visible);
void show() => _change(() => visible = true);
void hide() => _change(() => visible = false);
@@ -136,6 +182,9 @@ class TerminalLayout extends ChangeNotifier {
],
'maximized': maximized,
'option_as_meta': optionAsMeta,
'font_size': ?fontSize,
'scrollback': scrollback,
'bell': bell,
}),
);
if (revision != _revision || saved != saveFailed) return;
+15 -2
View File
@@ -25,17 +25,29 @@ class TerminalStream {
int end = 0;
String stream = '';
/// Whether [text] starts with the server's snapshot of the terminal's
/// state at [start] rather than raw output (until its start is dropped).
bool snapshot = false;
/// Whether nothing was received yet.
bool get empty => stream.isEmpty && end == 0;
/// Replaces the held copy with a read of the server's retained tail,
/// covering bytes [outputStart, outputEnd) (the server's offsets: the
/// text's own UTF-8 length differs where invalid bytes were replaced).
void reset(String output, int outputStart, int outputEnd, String name) {
/// text's own UTF-8 length differs where invalid bytes were replaced), or
/// with its [snapshot] of the terminal at [outputStart].
void reset(
String output,
int outputStart,
int outputEnd,
String name, {
bool snapshot = false,
}) {
text = output;
start = outputStart;
end = outputEnd;
stream = name;
this.snapshot = snapshot;
_bound();
}
@@ -59,6 +71,7 @@ class TerminalStream {
if (unit >= 0xDC00 && unit <= 0xDFFF) cut++;
final dropped = text.substring(0, cut);
text = text.substring(cut);
snapshot = false;
// The server's offsets are not re-derived from the text: only the
// dropped part is measured (approximately, for replaced bytes).
start += utf8.encode(dropped).length;
+28 -5
View File
@@ -8,7 +8,11 @@ import '../chat/shell/chat_shell_run.dart';
import '../chat/shell/chat_shell_terminal_session.dart';
import '../chat/shell/chat_shell_terminals.dart';
import 'terminal_info.dart';
import 'terminal_layout.dart';
import 'terminal_stream.dart';
import 'terminal_tab_events.dart';
export 'terminal_tab_events.dart';
/// One open machine terminal in the app: its record, the output held for
/// redraws, and the emulator session the panel, window and page draw (the
@@ -16,12 +20,13 @@ import 'terminal_stream.dart';
///
/// It outlives every view: hiding the panel keeps it, and reconnecting
/// resumes its output from the last byte it holds.
class TerminalTab extends ChangeNotifier {
class TerminalTab extends ChangeNotifier with TerminalTabEvents {
TerminalTab({
required this.machineId,
required this.machineName,
required this._gateway,
required this._info,
TerminalLayout? layout,
}) {
session = ChatShellTerminalSession(
_run(),
@@ -29,15 +34,18 @@ class TerminalTab extends ChangeNotifier {
onReply: (data) => _input(data, reply: true),
onResize: _resized,
onActivate: _activated,
layout: layout,
);
session.terminal.onTitleChange = _titled;
session.onDrawn = _drawn;
followEvents();
}
final String machineId;
String machineName;
ApiGateway _gateway;
TerminalInfo _info;
@override
late final ChatShellTerminalSession session;
final TerminalStream _stream = TerminalStream();
ChatShellInputPipe? _pipe;
@@ -65,13 +73,19 @@ class TerminalTab extends ChangeNotifier {
ApiGateway get gateway => _gateway;
/// The window title the shell set (seen in its output or recorded by the
/// server), else the folder it started in.
/// server), else the folder it last reported (OSC 7), else the folder it
/// started in.
String get title {
if (_oscTitle.isNotEmpty) return _oscTitle;
if (_info.title.isNotEmpty) return _info.title;
return terminalFolderLabel(_info.cwd);
return terminalFolderLabel(cwd);
}
/// The shell's current folder as it reported it (OSC 7), else the one it
/// started in.
@override
String get cwd => super.cwd ?? _info.cwd;
ChatShellRun _run() => ChatShellRun(
id: _info.id,
command: title,
@@ -81,6 +95,7 @@ class TerminalTab extends ChangeNotifier {
output: _stream.text,
outputStart: _stream.start,
outputEnd: _stream.end,
snapshot: _stream.snapshot,
terminal: true,
cols: _info.cols,
rows: _info.rows,
@@ -156,8 +171,12 @@ class TerminalTab extends ChangeNotifier {
// The server counts this connection's window from the reply's end.
_window = (record['window'] as num?)?.toInt() ?? 0;
_acked = end;
if (after == null || start > _stream.end) {
_stream.reset(output, start, end, info.stream);
// A read from before the server's retained tail (a new page, a reload,
// a gap) is its snapshot of the terminal: the screens, scrollback,
// cursor and modes as of the reply's end.
final snapshot = record['output_snapshot'] == true;
if (after == null || start > _stream.end || snapshot) {
_stream.reset(output, start, end, info.stream, snapshot: snapshot);
session.replay(_run());
} else {
_append(output, start, end);
@@ -283,6 +302,9 @@ class TerminalTab extends ChangeNotifier {
_notify();
}
@override
void notifyEvent() => _notify();
void _notify() {
if (!_disposed) notifyListeners();
}
@@ -294,6 +316,7 @@ class TerminalTab extends ChangeNotifier {
_pipe = null;
session.terminal.onTitleChange = null;
session.onDrawn = null;
unfollowEvents();
session.dispose();
super.dispose();
}
@@ -0,0 +1,52 @@
import 'package:flutter/foundation.dart';
import '../chat/shell/chat_shell_terminal_session.dart';
/// What a terminal tab shows of its program's reports: a dot for a bell
/// rung while no view showed the terminal (until it is shown again), and
/// the folder it last reported (OSC 7) for an untitled tab and its tooltip.
mixin TerminalTabEvents on ChangeNotifier {
ChatShellTerminalSession get session;
/// Notifies the tab's listeners unless it is disposed.
void notifyEvent();
/// Whether the bell rang while no view showed this terminal.
bool bellUnseen = false;
/// The folder the shell last reported, if it did.
String? get cwd => _reportedCwd;
String? _reportedCwd;
void followEvents() {
final events = session.events;
events.bells.addListener(_rang);
events.viewers.addListener(_viewed);
events.workingDirectory.addListener(_moved);
}
void unfollowEvents() {
final events = session.events;
events.bells.removeListener(_rang);
events.viewers.removeListener(_viewed);
events.workingDirectory.removeListener(_moved);
}
void _rang() {
if (bellUnseen || !session.layout.bell) return;
if (session.events.viewers.value > 0) return;
bellUnseen = true;
notifyEvent();
}
void _viewed() {
if (!bellUnseen || session.events.viewers.value == 0) return;
bellUnseen = false;
notifyEvent();
}
void _moved() {
_reportedCwd = session.events.workingDirectory.value;
notifyEvent();
}
}
@@ -84,7 +84,7 @@ class TerminalTabStrip extends StatelessWidget {
hub.multiMachine ? '${tab.title} · ${tab.machineName}' : tab.title;
Widget _tab(TerminalTab tab, bool selected) {
final label = Text(
Widget label = Text(
_label(tab),
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -92,12 +92,28 @@ class TerminalTabStrip extends StatelessWidget {
? null
: const TextStyle(fontStyle: FontStyle.italic),
);
if (tab.bellUnseen) {
// The bell rang while the terminal was not shown.
label = Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: label),
Padding(
padding: const EdgeInsetsDirectional.only(start: 6),
child: Semantics(
label: 'Bell',
child: Badge(key: const ValueKey('terminal-tab-bell')),
),
),
],
);
}
void close() => unawaited(hub.close(tab));
return InputChip(
label: label,
selected: selected,
showCheckmark: false,
tooltip: '${tab.machineName}: ${tab.info.cwd}',
tooltip: '${tab.machineName}: ${tab.cwd}',
onSelected: (_) => hub.select(tab),
onDeleted: close,
deleteButtonTooltipMessage: 'Close terminal',
@@ -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<void>? _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<void> ensureTerminalSymbolsFont() => _loading ??= _load();
Future<void> _load() async {
try {
final loader = FontLoader(terminalSymbolsFamily)
..addFont(rootBundle.load(terminalSymbolsAsset));
await loader.load();
} catch (error) {
debugPrint('Terminal symbols font did not load: $error');
}
}
+6 -1
View File
@@ -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(<String>[
'Symbols Nerd Font Mono',
], await rootBundle.loadString(terminalSymbolsLicenseAsset));
});
}
+219 -2
View File
@@ -109,6 +109,69 @@ tmux inside it for work that must survive that).
terminal is opened): each connection sends one request at a time, so the
first screen's read is never queued behind `terminal_list`.
## View features (round 2, 2026-11-26)
Shared by the permanent terminal and chat terminal cards
(`ChatShellTerminalView`); client-side only, no server change. The view's
own keys are answered before the key→byte mapping
(`chatShellLocalKey`, `chat_shell_terminal_shortcuts.dart`):
- **Find in scrollback:** Cmd+F (Apple) / Ctrl+Shift+F (elsewhere; Ctrl+F
stays the shell's forward-char) opens a find bar over the terminal's top
end, or focuses it. Typing searches the whole buffer, wrapped rows joined
(`chat_shell_terminal_search.dart`, at most 1000 matches, "1000+"); every
match is highlighted (controller highlights, the emulator's existing
hook) and the current one more strongly, scrolled into view. It starts
at the newest match; Enter / the down arrow is next, Shift+Enter / up is
previous, wrapping; **Aa** toggles Match case; Esc or × closes it and
gives the terminal the keyboard back. Output arriving meanwhile marks
the result stale; the next step searches again.
- **Text size:** Cmd (Apple) / Ctrl with `=`/`+` and `-` zoom one point,
with `0` back to the default; Settings → Appearance → Terminal → Text size
too. Saved with the layout (`font_size`, 8–32). The view relays out at
the new cell size, so the PTY is resized through the normal resize path.
Note Ctrl+- is readline's undo (`^_`) in xterm; here it zooms.
- **Scrollback:** Settings → Scrollback (1k, 5k, 10k default, 25k, 50k,
100k lines; saved as `scrollback`). It applies at once to open terminals
(`Terminal.maxLines` is settable; shrinking drops the oldest lines).
- **Scrolling keys:** on the main screen Shift+PgUp / Shift+PgDn scroll one
screen (keeping a line), Shift+Home / Shift+End to the top / bottom,
locally. On the alternate screen (less, vim) they reach the program.
- **Context menu:** a right-click offers Copy (with a selection), Paste
(live terminals), Select all (scrollback included), Clear scrollback
(this view's copy; the server keeps the output) and Find…. A program
that tracks the mouse gets the right button instead, unless Shift is
held. On the web the browser's own menu is suppressed while the pointer
is over the terminal (`ChatShellNoBrowserMenu`, the chat links'
`suppressBrowserMenuOverLink`).
- **Bell:** BEL flashes the terminal's border in the accent colour
(300 ms fade; held then gone under reduced motion). A bell while no view
shows the terminal (another tab selected, or the terminal hidden) dots
its tab until it is shown. Settings → Visual bell turns both off.
- **Links:** hovering an OSC 8 hyperlink (by its target, `hyperlinkAt`) or
a printed http(s) address shows a pointer cursor and underlines the
link's cells; a click opens it as before.
- **OSC 52:** a program setting the clipboard copies to the system
clipboard and shows "Copied from terminal" (reads are never answered).
**OSC 7:** the reported folder names an untitled tab and its tooltip.
A replay (reload, reconnect) of old output neither copies nor rings.
- **Cursor blink:** a blinking DECSCUSR shape (odd Ps) blinks (530 ms
phases) on a ticker that runs only while the terminal is focused and
motion is not reduced; output or typing shows it again at once.
- **Stale selection:** a selection clears when its rows on screen are
rewritten or erased, the screen is cleared, its lines drop out of the
scrollback, or the program switches screens.
Evidence: tests `test/features/chat/shell/chat_shell_terminal_{find,
local_keys,menu,events,feedback}_test.dart`, `test/features/terminal/
terminal_tab_events_test.dart`, `test/features/settings/
settings_terminal_controls_test.dart`, `test/third_party_xterm/
scrollback_blink_test.dart`. Chrome captures (capture kit, `?terminals=1
&terminal=panel`, 1200x800): find bar with "2 of 2" PASS highlights,
context menu, Ctrl+= zoom, OSC 8 link hover underline; a synthetic
`contextmenu` event over the terminal is default-prevented, elsewhere not.
The capture kit gained `rightclick=<target>`.
## Protocol (server)
`internal/protocol/terminal.go`; documented in `docs/cli.md` ("Machine
@@ -198,6 +261,150 @@ Emulator (`chat_shell_terminal_feed_test.dart`, 896 KiB replay): one
synchronous write 160 ms; sliced, the same 161 ms over 20 turns, the
longest turn 12.5 ms.
## Screen state across reloads (2026-11-26)
The server keeps each machine terminal's *state*, not only its bytes, so
a client that attaches late is brought to the exact current screen.
- `internal/termstate` is a headless xterm-compatible emulator (own code;
see "Why not a library" below). `terminal_process.go` feeds it every PTY
read under `p.mu`, the same lock as the 1 MiB tail, so its state always
belongs to the tail's end; `applySize` resizes it with the PTY.
- `terminal_output` whose `after` is before the retained tail (the newest
1 MiB; a missing `after` counts as 0) gets `output_snapshot: true`:
`output` is the emulator's snapshot and `output_start == output_end`
is the offset it describes; the frames that follow start there, and the
flow window counts from it as from any reply (`terminal_screen.go`). A
read inside the tail (an ordinary resume, or a stream not longer than
1 MiB) is raw bytes as before.
- The snapshot (`termstate.Snapshot`) is an escape stream for a reset
terminal: `RIS` + `ED 3`, the title (OSC 2), the inactive alternate
screen if it holds anything (`?47h` … `?47l`), the last 1000 scrollback
lines and the main screen row by row (soft wraps wrap again), then, if
the alternate screen is in use, the main screen's saved cursor and
`?1049h` (so the program's exit restores it) and the alternate screen
drawn row by row; then the saved cursor(s), tab stops, scroll region,
origin mode, the cursor (a pending wrap is recreated by rewriting the
last cell; the cell before the cursor is rewritten when it holds the last
character, for REP), modes (DECCKM, DECKPAM, autowrap, IRM, LNM, reverse
video, cursor blink/visibility/shape, mouse tracking 9/1000-1003 and
encoding 1005/1006/1015, focus 1004, bracketed paste 2004, 1007), G0/G1
character sets and SO, the pen (SGR incl. 256/RGB colours and underline
styles) and the start of an unfinished escape sequence or OSC string. An
unfinished UTF-8 character is left out (`output_end` is before it; the
next frame carries it whole).
- Client: `TerminalTab._read` resets its held copy and replays when the
reply is a snapshot (`TerminalStream.snapshot`, `ChatShellRun.snapshot`:
no "earlier output was dropped" line). `ChatShellTerminalSession.replay`
now writes RIS before any replay, so a raw replay no longer inherits
stale mouse/paste/alt-screen modes either.
- Chat shell interactive commands are not covered: their readbacks come
from the run record (DB snapshot every 2 s of the raw tail) on a
separate path; they get only the RIS-on-replay change.
Why not a library: `github.com/charmbracelet/x/vt` v0.1.0 (MIT, active)
keeps scroll region, pen and modes private and scrolls by copying cells:
measured 0.2-1 MB/s for `seq` and 4.5 MB/s for wrapping text, 33 MB/s for
redraws. `github.com/vito/midterm` v0.2.5 (MIT): 1-4 MB/s scrolling,
ignores keypad and most modes. `github.com/hinshun/vt10x`: unmaintained
since 2022, no scrollback or bracketed paste. termstate moves rows by
pointer, keeps blank cells implicit and recycles evicted scrollback rows.
Measured (`go test ./internal/termstate -bench .`, Ryzen 7 5800X, 8 MB
each, 32 KiB writes): `seq` 190 MB/s, coloured full-screen redraws 160-165
MB/s, wrapping mixed text 172-180 MB/s, at 80x24 and 200x50; a snapshot of
1000 full 200-column scrollback rows: 2 ms, 229 KiB (seq: 9 KiB; a 40-row
TUI: 4-39 KiB). Cells: 230 KiB per terminal for `seq`, up to 5.9 MB at
200 columns with 1000 full rows. End to end (`TestMeasureTerminalStream`,
same machine, two runs each, before → after): seq 20.8/22.8 → 25.0/25.3
MB/s, cat 80/102 → 80/76 MB/s, yes 10.4/11.4 → 10.4/10.7 MB/s, echo
median 0.36/0.41 → 0.48/0.38 ms: no measurable cost.
Known gaps: origin mode with the cursor outside the scroll region (a DECRC
can leave it there) is not recreated; hyperlinks (OSC 8), palette changes
(OSC 4/10/11), DECSLRM and kitty keyboard modes are not tracked; DECSC's
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)
- `internal/server/terminal_login.go`. A terminal runs, in its PTY,
@@ -276,7 +483,10 @@ longest turn 12.5 ms.
- Server: `internal/protocol/terminal.go`, `message.go`;
`internal/pipeline/terminals.go`, `store.go`;
`internal/server/terminal_{manager,supervise,process,login,legacy_tmux,clients,title,cwd,handlers}.go`,
`internal/server/terminal_{manager,supervise,process,login,legacy_tmux,clients,title,cwd,handlers,flow,screen}.go`,
`internal/termstate/` (headless emulator and snapshots; tests
`snapshot_test.go`, `random_test.go`, `bench_test.go`),
`terminal_screen_test.go`,
`websocket.go`, `cmd/pipelines-server/main.go`; tests `terminal_ws_test.go`,
`terminal_login_test.go`, `terminal_lifetime_test.go`, `terminal_legacy_tmux_test.go`,
`internal/pipeline/terminals_test.go`; `docs/cli.md`.
@@ -289,7 +499,14 @@ longest turn 12.5 ms.
`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
+3
View File
@@ -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
@@ -0,0 +1,102 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_bell.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_events.dart';
import 'terminal_view_harness.dart';
const _flash = ValueKey('terminal-bell-flash');
String _osc52(String text) =>
'\x1b]52;c;${base64.encode(utf8.encode(text))}\x07';
void main() {
testWidgets('a bell flashes the border briefly; the setting turns it off', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
expect(find.byKey(_flash), findsNothing);
await harness.write(tester, '\x07');
expect(find.byKey(_flash), findsOneWidget);
await tester.pump(chatShellBellFlash + const Duration(milliseconds: 16));
expect(find.byKey(_flash), findsNothing);
harness.layout.setBell(false);
await tester.pump();
await harness.write(tester, '\x07');
expect(find.byKey(_flash), findsNothing);
});
testWidgets('under reduced motion the bell border holds, then goes', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester, reduceMotion: true);
await harness.write(tester, '\x07');
final border =
tester.widget<DecoratedBox>(find.byKey(_flash)).decoration
as BoxDecoration;
expect((border.border! as Border).top.color.a, 1);
await tester.pump(chatShellBellFlash + const Duration(milliseconds: 16));
expect(find.byKey(_flash), findsNothing);
});
testWidgets('OSC 52 from live output sets the clipboard and says so', (
tester,
) async {
final copied = mockClipboard(tester);
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, _osc52('from vim'));
expect(copied, ['from vim']);
await tester.pump();
expect(find.text('Copied from terminal'), findsOneWidget);
await tester.pump(const Duration(seconds: 3));
await tester.pumpAndSettle();
// A read request (?) is ignored.
await harness.write(tester, '\x1b]52;c;?\x07');
expect(copied, ['from vim']);
});
testWidgets('old output drawn again (a replay) neither copies nor rings', (
tester,
) async {
final copied = mockClipboard(tester);
final harness = TerminalViewHarness();
await harness.pump(tester);
final output = 'old ${_osc52('stale')}\x07done';
harness.session.replay(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': 'running',
'started_at': 1,
'output': output,
'output_bytes': utf8.encode(output).length,
'terminal': true,
})!,
);
await tester.pumpAndSettle();
expect(copied, isEmpty);
expect(harness.session.events.bells.value, 0);
expect(find.byKey(_flash), findsNothing);
});
test('OSC 7 reports the folder as a path', () {
expect(
chatShellWorkingDirectoryPath('file://mac.local/Users/op/src%20x'),
'/Users/op/src x',
);
expect(chatShellWorkingDirectoryPath('file:///tmp'), '/tmp');
expect(chatShellWorkingDirectoryPath('https://example.com/a'), isNull);
expect(chatShellWorkingDirectoryPath('file://host'), '/');
final harness = TerminalViewHarness();
addTearDown(harness.session.dispose);
harness.terminal.write('\x1b]7;file://mac/Users/op/work\x1b\\');
expect(harness.session.events.workingDirectory.value, '/Users/op/work');
});
}
@@ -0,0 +1,127 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_cursor_blink.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_links.dart';
import 'package:xterm/xterm.dart';
import 'terminal_view_harness.dart';
const _phase = chatShellCursorBlinkPhase;
void main() {
bool shown(WidgetTester tester, TerminalViewHarness harness) =>
harness.view(tester).cursorBlinkVisible!.value;
testWidgets('a blinking DECSCUSR cursor blinks while focused and is steady '
'once unfocused, leaving no frames scheduled', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, '\x1b[5 q');
await harness.focus(tester);
expect(shown(tester, harness), isTrue);
await tester.pump(_phase + const Duration(milliseconds: 10));
expect(shown(tester, harness), isFalse);
await tester.pump(_phase);
expect(shown(tester, harness), isTrue);
// Output shows it again and restarts the phase.
await tester.pump(_phase);
expect(shown(tester, harness), isFalse);
await harness.write(tester, 'x');
expect(shown(tester, harness), isTrue);
// Unfocused: steady, and the ticker stopped.
harness.view(tester).focusNode!.unfocus();
await tester.pump();
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('a steady shape (even Ps) does not blink', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, '\x1b[2 q');
await harness.focus(tester);
await tester.pump(_phase * 3);
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('reduced motion keeps a blinking cursor steady', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester, reduceMotion: true);
await harness.write(tester, '\x1b[1 q');
await harness.focus(tester);
await tester.pump(_phase + const Duration(milliseconds: 10));
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('a selection clears when its rows are rewritten, the screen is '
'cleared or the program switches screens', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, 'keep this\r\nother\r\n');
final controller = harness.controller(tester);
final buffer = harness.terminal.buffer;
void select() => controller.setSelection(
buffer.createAnchor(0, 0),
buffer.createAnchor(4, 0),
);
select();
// Output elsewhere leaves it.
await harness.write(tester, 'more output\r\n');
expect(controller.selection, isNotNull);
// Rewriting the selected row clears it.
await harness.write(tester, '\x1b[1;1Hgone');
expect(controller.selection, isNull);
select();
await harness.write(tester, '\x1b[2J');
expect(controller.selection, isNull);
select();
await harness.write(tester, '\x1b[?1049h');
expect(controller.selection, isNull);
});
testWidgets('hovering a web or OSC 8 link shows a pointer and underlines '
'it; a click opens it as before', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'see https://example.com/a now\r\n'
'\x1b]8;;https://example.org/b\x1b\\docs\x1b]8;;\x1b\\ plain',
);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
addTearDown(mouse.removePointer);
await mouse.addPointer(location: harness.cellCentre(tester, 0, 0));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.text);
await mouse.moveTo(harness.cellCentre(tester, 8, 0));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.click);
// The OSC 8 link's text is not an address; its target is.
await mouse.moveTo(harness.cellCentre(tester, 1, 1));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.click);
await mouse.moveTo(harness.cellCentre(tester, 7, 1));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.text);
});
test('the link under a cell: OSC 8 first, then printed addresses', () {
final terminal = Terminal(maxLines: 50)..resize(20, 4);
terminal.write(
'\x1b]8;;https://example.org/long\x1b\\0123456789abcdefghijkl'
'\x1b]8;;\x1b\\ x https://e.com/q).',
);
final hyperlink = chatShellTerminalLinkAt(terminal, const CellOffset(5, 0));
expect(hyperlink!.uri.toString(), 'https://example.org/long');
// It wraps onto the next row.
expect(hyperlink.begin, const CellOffset(0, 0));
expect(hyperlink.end, const CellOffset(2, 1));
final printed = chatShellTerminalLinkAt(terminal, const CellOffset(6, 1));
expect(printed!.uri.toString(), 'https://e.com/q');
expect(printed.begin, const CellOffset(5, 1));
expect(printed.end, const CellOffset(20, 1));
});
}
@@ -0,0 +1,149 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_search.dart';
import 'package:xterm/xterm.dart';
import 'terminal_view_harness.dart';
const _field = ValueKey('terminal-find-field');
String _count(WidgetTester tester) => tester
.widget<Text>(find.byKey(const ValueKey('terminal-find-count')))
.data!;
/// Opens the find bar with the platform's key.
Future<void> _openFind(WidgetTester tester) => isApple()
? chordKeys(tester, LogicalKeyboardKey.keyF, [LogicalKeyboardKey.metaLeft])
: chordKeys(tester, LogicalKeyboardKey.keyF, [
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.shiftLeft,
]);
void main() {
test('search joins wrapped rows, folds case unless asked and maps cells', () {
final terminal = Terminal(maxLines: 100)..resize(10, 4);
terminal.write('abc Needle\r\nxxxxxxxneedle NEEDLE\r\n中文needle');
final all = chatShellTerminalSearch(terminal.buffer, 'needle');
expect(all, hasLength(4));
// "Needle" fills the first row's last six cells.
expect(
all[0],
const ChatShellSearchMatch(CellOffset(4, 0), CellOffset(10, 0)),
);
// The second line wraps: its "needle" spans rows 1 and 2.
expect(
all[1],
const ChatShellSearchMatch(CellOffset(7, 1), CellOffset(3, 2)),
);
expect(all[2].begin, const CellOffset(4, 2));
// Wide characters take two cells each; the match starts after both.
expect(all[3].begin, const CellOffset(4, 3));
final exact = chatShellTerminalSearch(
terminal.buffer,
'needle',
caseSensitive: true,
);
expect(exact, hasLength(2));
expect(chatShellTerminalSearch(terminal.buffer, ''), isEmpty);
expect(
chatShellTerminalSearch(terminal.buffer, 'needle', limit: 2),
hasLength(2),
);
});
testWidgets('the find key opens the bar; matches are counted, highlighted '
'and scrolled to; Esc closes it and the terminal has the keys again', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'first needle\r\n'
'${List.filled(60, 'filler').join('\r\n')}\r\n'
'Needle two\r\n'
'last needle',
);
await harness.focus(tester);
await _openFind(tester);
expect(find.byKey(_field), findsOneWidget);
await tester.pump();
// The field has the keyboard, which the terminal held.
expect(
tester.widget<TextField>(find.byKey(_field)).focusNode!.hasFocus,
isTrue,
);
// The keys went to the find bar, not the shell.
expect(harness.typed, isEmpty);
await tester.enterText(find.byKey(_field), 'needle');
await tester.pump();
// Searching upwards: the current match is the last one.
expect(_count(tester), '3 of 3');
expect(harness.controller(tester).highlights, hasLength(3));
final bottom = harness.scroll(tester).maxScrollExtent;
expect(harness.scroll(tester).pixels, bottom);
// Next wraps to the first match, at the top of the scrollback.
await tester.tap(find.byKey(const ValueKey('terminal-find-next')));
await tester.pump();
expect(_count(tester), '1 of 3');
expect(harness.scroll(tester).pixels, lessThan(bottom));
// Shift+Enter goes back.
await chordKeys(tester, LogicalKeyboardKey.enter, [
LogicalKeyboardKey.shiftLeft,
]);
expect(_count(tester), '3 of 3');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(_count(tester), '1 of 3');
// Match case leaves out "Needle".
await tester.tap(find.byKey(const ValueKey('terminal-find-case')));
await tester.pump();
expect(_count(tester), '2 of 2');
await tester.enterText(find.byKey(_field), 'absent');
await tester.pump();
expect(_count(tester), 'No results');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.byKey(_field), findsNothing);
expect(harness.controller(tester).highlights, isEmpty);
expect(harness.view(tester).focusNode!.hasFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.keyX);
await tester.pump();
expect(harness.typed, 'x');
}, variant: desktops);
testWidgets(
'outside Apple platforms Ctrl+F stays the shell\'s',
(tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.focus(tester);
await chordKeys(tester, LogicalKeyboardKey.keyF, [
LogicalKeyboardKey.controlLeft,
]);
expect(find.byKey(_field), findsNothing);
expect(harness.typed, '\x06');
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
testWidgets(
'output after a search is found by the next step',
(tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, 'one match\r\n');
await harness.focus(tester);
await _openFind(tester);
await tester.enterText(find.byKey(_field), 'match');
await tester.pump();
expect(_count(tester), '1 of 1');
await harness.write(tester, 'two match\r\n');
await tester.tap(find.byKey(const ValueKey('terminal-find-next')));
await tester.pump();
expect(_count(tester), '2 of 2');
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
}
@@ -0,0 +1,112 @@
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'terminal_view_harness.dart';
void main() {
testWidgets('Cmd/Ctrl with =, - and 0 zoom a focused terminal; the size '
'is saved and the process is resized to the new cells', (tester) async {
final store = MemoryStore();
final harness = TerminalViewHarness(layout: TerminalLayout(store: store));
await harness.pump(tester);
await harness.focus(tester);
final base = harness.view(tester).textStyle.fontSize;
final cols = harness.terminal.viewWidth;
final command = commandKey();
await chordKeys(tester, LogicalKeyboardKey.equal, [command]);
await chordKeys(tester, LogicalKeyboardKey.equal, [command]);
expect(harness.layout.fontSize, base.roundToDouble() + 2);
expect(harness.view(tester).textStyle.fontSize, base.roundToDouble() + 2);
// Larger cells: fewer columns, through the normal resize path.
expect(harness.terminal.viewWidth, lessThan(cols));
expect(harness.sizes.last.$1, harness.terminal.viewWidth);
await tester.pump();
expect(jsonDecode(store.saved!)['font_size'], base.roundToDouble() + 2);
await chordKeys(tester, LogicalKeyboardKey.minus, [command]);
expect(harness.layout.fontSize, base.roundToDouble() + 1);
await chordKeys(tester, LogicalKeyboardKey.digit0, [command]);
expect(harness.layout.fontSize, isNull);
expect(harness.view(tester).textStyle.fontSize, base);
expect(harness.terminal.viewWidth, cols);
// None of it reached the shell.
expect(harness.typed, isEmpty);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.fontSize, isNull);
}, variant: desktops);
testWidgets(
'zooming stops at the size limits',
(tester) async {
final harness = TerminalViewHarness();
harness.layout.setFontSize(terminalFontSizeMax - 1);
await harness.pump(tester);
await harness.focus(tester);
for (var i = 0; i < 3; i++) {
await chordKeys(tester, LogicalKeyboardKey.equal, [commandKey()]);
}
expect(harness.layout.fontSize, terminalFontSizeMax);
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
testWidgets('Shift+PgUp/PgDn/Home/End scroll the scrollback locally; on the '
'alternate screen they reach the program', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
List.generate(200, (i) => 'line $i').join('\r\n'),
);
await harness.focus(tester);
final bottom = harness.scroll(tester).maxScrollExtent;
expect(harness.scroll(tester).pixels, bottom);
const shift = [LogicalKeyboardKey.shiftLeft];
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
final page = bottom - harness.scroll(tester).pixels;
expect(page, greaterThan(0));
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
expect(harness.scroll(tester).pixels, closeTo(bottom - 2 * page, 0.01));
await chordKeys(tester, LogicalKeyboardKey.pageDown, shift);
expect(harness.scroll(tester).pixels, closeTo(bottom - page, 0.01));
await chordKeys(tester, LogicalKeyboardKey.home, shift);
expect(harness.scroll(tester).pixels, 0);
await chordKeys(tester, LogicalKeyboardKey.end, shift);
expect(harness.scroll(tester).pixels, bottom);
expect(harness.typed, isEmpty);
// A full-screen program (less, vim) gets them.
await harness.write(tester, '\x1b[?1049h');
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
expect(harness.typed, '\x1b[5;2~');
}, variant: desktops);
testWidgets('the scrollback setting applies to new and open terminals', (
tester,
) async {
final harness = TerminalViewHarness();
expect(harness.layout.scrollback, terminalScrollbackDefault);
expect(harness.terminal.maxLines, 10000);
await harness.pump(tester);
await harness.write(
tester,
List.generate(1500, (i) => 'line $i').join('\r\n'),
);
expect(harness.terminal.buffer.height, 1500);
harness.layout.setScrollback(1000);
await tester.pump();
expect(harness.terminal.maxLines, 1000);
expect(harness.terminal.buffer.height, 1000);
// The newest lines are kept.
final buffer = harness.terminal.buffer;
expect(buffer.lines[buffer.height - 1].getText().trim(), 'line 1499');
expect(buffer.lines[0].getText().trim(), 'line 500');
await harness.write(tester, '\r\nmore');
expect(harness.terminal.buffer.height, 1000);
final next = TerminalViewHarness(layout: harness.layout);
addTearDown(next.session.dispose);
expect(next.terminal.maxLines, 1000);
});
}
@@ -0,0 +1,81 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'terminal_view_harness.dart';
Finder _item(String name) => find.byKey(ValueKey('terminal-menu-$name'));
bool _enabled(WidgetTester tester, String name) =>
tester.widget<PopupMenuItem<Object?>>(_item(name)).enabled;
void main() {
testWidgets('right-click offers Copy with a selection, Paste, Select all, '
'Clear scrollback and Find', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'${List.generate(40, (i) => 'old $i').join('\r\n')}\r\nhello world',
);
final copied = mockClipboard(tester, paste: 'pasted');
final screenTop =
harness.terminal.buffer.height - harness.terminal.viewHeight;
final last = harness.terminal.buffer.height - 1;
await harness.rightClick(tester, 2, last);
expect(_item('copy'), findsOneWidget);
expect(_enabled(tester, 'copy'), isFalse);
for (final name in ['paste', 'selectAll', 'clear', 'find']) {
expect(_item(name), findsOneWidget, reason: name);
}
// Paste types the clipboard into the process.
await tester.tap(_item('paste'));
await tester.pumpAndSettle();
expect(harness.typed, 'pasted');
// Select all takes the scrollback too; Copy copies it.
await harness.rightClick(tester, 2, last);
await tester.tap(_item('selectAll'));
await tester.pumpAndSettle();
final selection = harness.controller(tester).selection!.normalized;
expect(selection.begin.y, 0);
expect(selection.end.y, last);
await harness.rightClick(tester, 2, last);
expect(_enabled(tester, 'copy'), isTrue);
await tester.tap(_item('copy'));
await tester.pumpAndSettle();
expect(copied.single, startsWith('old 0\nold 1'));
expect(copied.single, contains('hello world'));
// Clear scrollback keeps only the screen.
expect(screenTop, greaterThan(0));
await harness.rightClick(tester, 2, last);
await tester.tap(_item('clear'));
await tester.pumpAndSettle();
expect(harness.terminal.buffer.height, harness.terminal.viewHeight);
// Find… opens the find bar.
await harness.rightClick(tester, 2, harness.terminal.viewHeight - 1);
await tester.tap(_item('find'));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('terminal-find-field')), findsOneWidget);
}, variant: desktops);
testWidgets('a program tracking the mouse gets the right button unless '
'Shift is held', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, r'$ ');
// X10/normal tracking with SGR coordinates.
await harness.write(tester, '\x1b[?1000h\x1b[?1006h');
await harness.rightClick(tester, 3, 0);
expect(_item('copy'), findsNothing);
expect(harness.typed, '\x1b[<2;4;1M\x1b[<2;4;1m');
await harness.rightClick(tester, 3, 0, shift: true);
expect(_item('copy'), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets('finished output offers no Paste', (tester) async {
final harness = TerminalViewHarness(live: false);
await harness.pump(tester);
await harness.rightClick(tester, 1, 0);
expect(_item('copy'), findsOneWidget);
expect(_item('paste'), findsNothing);
});
}
@@ -0,0 +1,191 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_view.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'package:xterm/xterm.dart';
/// A terminal layout saved in memory.
class MemoryStore implements TerminalLayoutStore {
String? saved;
@override
Future<String?> load() async => saved;
@override
Future<bool> save(String value) async {
saved = value;
return true;
}
}
/// One live terminal view filling an 800x500 app, with what it sends to the
/// process collected in [sent].
class TerminalViewHarness {
TerminalViewHarness({TerminalLayout? layout, bool live = true})
: layout = layout ?? TerminalLayout(store: MemoryStore()) {
session = ChatShellTerminalSession(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': live ? 'running' : 'exited',
'started_at': 1,
'output': '',
'output_bytes': 0,
'terminal': true,
'cols': 80,
'rows': 24,
})!,
onInput: sent.add,
onResize: (cols, rows) => sizes.add((cols, rows)),
layout: this.layout,
);
}
final TerminalLayout layout;
late final ChatShellTerminalSession session;
final List<String> sent = [];
final List<(int, int)> sizes = [];
Terminal get terminal => session.terminal;
String get typed => sent.join();
Future<void> pump(WidgetTester tester, {bool reduceMotion = false}) async {
tester.view.physicalSize = const Size(800, 500);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
addTearDown(session.dispose);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(disableAnimations: reduceMotion),
child: Scaffold(
body: ChatShellTerminalView(
session: session,
fill: true,
autofocus: true,
),
),
),
),
),
);
await tester.pump();
}
TerminalView view(WidgetTester tester) =>
tester.widget<TerminalView>(find.byType(TerminalView));
TerminalViewState viewState(WidgetTester tester) =>
tester.state<TerminalViewState>(find.byType(TerminalView));
TerminalController controller(WidgetTester tester) =>
view(tester).controller!;
ScrollPosition scroll(WidgetTester tester) =>
view(tester).scrollController!.position;
/// The global centre of buffer cell ([x], [y]).
Offset cellCentre(WidgetTester tester, int x, int y) {
final render = viewState(tester).renderTerminal;
final cell = render.cellSize;
return render.localToGlobal(
render.getOffset(CellOffset(x, y)) +
Offset(cell.width / 2, cell.height / 2),
);
}
/// Writes [text] as live output and lets the view redraw.
Future<void> write(WidgetTester tester, String text) async {
terminal.write(text);
await tester.pump();
}
/// Focuses the emulator.
Future<void> focus(WidgetTester tester) async {
final node = view(tester).focusNode!;
node.requestFocus();
await tester.pump();
}
/// Right-clicks buffer cell ([x], [y]) with a mouse, holding Shift when
/// [shift].
Future<void> rightClick(
WidgetTester tester,
int x,
int y, {
bool shift = false,
}) async {
if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
final gesture = await tester.startGesture(
cellCentre(tester, x, y),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await gesture.up();
if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
await tester.pumpAndSettle();
}
}
/// Presses [key] with [modifiers] held.
Future<void> chordKeys(
WidgetTester tester,
LogicalKeyboardKey key, [
List<LogicalKeyboardKey> modifiers = const [],
]) async {
for (final modifier in modifiers) {
await tester.sendKeyDownEvent(modifier);
}
await tester.sendKeyEvent(key);
for (final modifier in modifiers.reversed) {
await tester.sendKeyUpEvent(modifier);
}
await tester.pump();
}
/// The platform's command key: Cmd on Apple platforms, else Ctrl.
LogicalKeyboardKey commandKey() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS
? LogicalKeyboardKey.metaLeft
: LogicalKeyboardKey.controlLeft;
bool isApple() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
/// Collects what the app writes to the clipboard, answering reads with
/// [paste].
List<String> mockClipboard(WidgetTester tester, {String paste = ''}) {
final texts = <String>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
texts.add('${(call.arguments as Map)['text']}');
}
if (call.method == 'Clipboard.getData') return {'text': paste};
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
return texts;
}
/// Desktop platforms: a Mac and one that is not.
final desktops = TargetPlatformVariant({
TargetPlatform.macOS,
TargetPlatform.linux,
});
@@ -0,0 +1,100 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_terminal_section.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
class _Store implements TerminalLayoutStore {
String? saved;
@override
Future<String?> load() async => saved;
@override
Future<bool> save(String value) async {
saved = value;
return true;
}
}
void main() {
late _Store store;
late TerminalLayout layout;
setUp(() {
store = _Store();
layout = TerminalLayout(store: store);
});
Future<void> pump(WidgetTester tester) async {
tester.view.physicalSize = const Size(900, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: SettingsTerminalSection(layout: layout),
),
),
),
);
}
Map<String, dynamic> saved() =>
jsonDecode(store.saved!) as Map<String, dynamic>;
testWidgets('text size, scrollback and the visual bell are chosen in '
'Settings and saved with the layout', (tester) async {
await pump(tester);
expect(find.text('Text size'), findsOneWidget);
expect(find.text('Scrollback'), findsOneWidget);
await tester.tap(find.byType(DropdownMenu<double>));
await tester.pumpAndSettle();
await tester.tap(find.text('16 pt').last);
await tester.pumpAndSettle();
expect(layout.fontSize, 16);
expect(saved()['font_size'], 16);
await tester.tap(find.byType(DropdownMenu<int>));
await tester.pumpAndSettle();
await tester.tap(find.text('50k lines').last);
await tester.pumpAndSettle();
expect(layout.scrollback, 50000);
expect(saved()['scrollback'], 50000);
await tester.tap(find.byKey(const ValueKey('settings-terminal-bell')));
await tester.pumpAndSettle();
expect(layout.bell, isFalse);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.fontSize, 16);
expect(restored.scrollback, 50000);
expect(restored.bell, isFalse);
// Default text size clears it.
await tester.tap(find.byType(DropdownMenu<double>));
await tester.pumpAndSettle();
await tester.tap(find.text('Default').last);
await tester.pumpAndSettle();
expect(layout.fontSize, isNull);
expect(saved().containsKey('font_size'), isFalse);
});
testWidgets('a zoom from the keyboard shows in the menu at once', (
tester,
) async {
await pump(tester);
layout.setFontSize(17);
await tester.pump();
final menu = tester.widget<DropdownMenu<double>>(
find.byType(DropdownMenu<double>),
);
expect(menu.initialSelection, 17);
});
test('a saved scrollback outside the choices and sizes out of range are '
'not restored as they were', () async {
store.saved = jsonEncode({'scrollback': 7, 'font_size': 400});
await layout.restore();
expect(layout.scrollback, terminalScrollbackDefault);
expect(layout.fontSize, terminalFontSizeMax);
expect(layout.bell, isTrue);
});
}
@@ -28,6 +28,12 @@ class TerminalGateway implements ApiGateway {
/// where runs of invalid bytes became one shorter replacement character).
final Map<String, int> byteShift = {};
/// A terminal's state as the server's snapshot: when set, a read from
/// before [snapshotFrom] gets it (as of the output's end) instead of raw
/// output.
final Map<String, String> snapshots = {};
int snapshotFrom = 1 << 30;
@override
Stream<JsonMap> get frames => _frames.stream;
@@ -56,6 +62,19 @@ class TerminalGateway implements ApiGateway {
final text = output[id] ?? '';
final bytes = utf8.encode(text);
final start = after.clamp(0, bytes.length);
final snapshot = snapshots[id];
if (withOutput && snapshot != null && after < snapshotFrom) {
final end = bytes.length + (byteShift[id] ?? 0);
return {
...terminals[id]!,
'stream': stream,
'output': snapshot,
'output_start': end,
'output_end': end,
'output_snapshot': true,
if (window > 0) 'window': window,
};
}
return {
...terminals[id]!,
'stream': stream,
@@ -0,0 +1,149 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
import 'package:pipelines_app/features/terminal/terminal_tab.dart';
import 'package:xterm/core.dart';
import 'terminal_fixtures.dart';
/// What the server's emulator (internal/termstate) writes for a 40x8
/// terminal where a shell ran twelve commands and then nvim, which set
/// mouse, bracketed paste and application cursor/keypad modes on the
/// alternate screen.
const _snapshot =
'\x1bc\x1b[3J\x1b]2;nvim notes.txt\x07'
'\$ echo 1\r\n1\r\n\$ echo 2\r\n2\r\n\$ echo 3\r\n3\r\n\$ echo 4\r\n4\r\n'
'\$ echo 5\r\n5\r\n\$ echo 6\r\n6\r\n\$ echo 7\r\n7\r\n\$ echo 8\r\n8\r\n'
'\$ echo 9\r\n9\r\n\$ echo 10\r\n10\r\n\$ echo 11\r\n11\r\n'
'\$ echo 12\r\n12\r\n\$ nvim notes.txt\r\n'
'\x1b[8;1H\x1b[?1049h\x1b[1;1H\x1b[0;1;34mFRAME\x1b[2;1H\x1b[0mline two'
'\x1b[8;1H\x1b[0;7m-- INSERT --\x1b[2;9H\x1b[?1h\x1b=\x1b[?25l'
'\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[0m';
/// What nvim writes as it exits, then the shell.
const _exit =
'\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?1l\x1b>\x1b[?25h\x1b[?1049l'
'\$ ls\r\nnotes.txt\r\n\$ ';
/// The rows on screen (not the scrollback), trailing blanks trimmed.
List<String> rows(Terminal terminal) {
final buffer = terminal.buffer;
final top = buffer.height - terminal.viewHeight;
return [
for (var y = top; y < buffer.height; y++)
buffer.lines[y].getText().trimRight(),
];
}
void main() {
late TerminalGateway mac;
late TerminalHub hub;
setUp(() {
mac = TerminalGateway()..window = 1 << 18;
hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')]));
});
tearDown(() async {
hub.dispose();
await mac.close();
});
Future<void> settle() async {
for (var i = 0; i < 5; i++) {
await Future<void>.delayed(Duration.zero);
}
}
/// A terminal whose stream is longer than the server's tail.
void longTerminal(String raw) {
mac.add('term_a', text: raw);
mac.terminals['term_a']!['cols'] = 40;
mac.terminals['term_a']!['rows'] = 8;
}
void expectNvim(TerminalTab tab) {
final terminal = tab.session.terminal;
expect(terminal.isUsingAltBuffer, isTrue);
expect(rows(terminal), [
'FRAME',
'line two',
'',
'',
'',
'',
'',
'-- INSERT --',
]);
expect(terminal.buffer.cursorX, 8);
expect(terminal.buffer.cursorY, 1);
expect(terminal.mouseMode, MouseMode.upDownScrollDrag);
expect(terminal.mouseReportMode, MouseReportMode.sgr);
expect(terminal.bracketedPasteMode, isTrue);
expect(terminal.cursorKeysMode, isTrue);
expect(terminal.appKeypadMode, isTrue);
expect(terminal.cursorVisibleMode, isFalse);
expect(tab.title, 'nvim notes.txt');
}
void expectShellAfterExit(TerminalTab tab) {
final terminal = tab.session.terminal;
expect(terminal.isUsingAltBuffer, isFalse);
expect(rows(terminal), [
r'$ echo 11',
'11',
r'$ echo 12',
'12',
r'$ nvim notes.txt',
r'$ ls',
'notes.txt',
r'$',
]);
// The shell's history above the screen came back with it.
expect(terminal.buffer.lines[0].getText().trimRight(), r'$ echo 1');
expect(terminal.mouseMode, MouseMode.none);
expect(terminal.bracketedPasteMode, isFalse);
expect(terminal.cursorKeysMode, isFalse);
expect(terminal.cursorVisibleMode, isTrue);
}
test('a reload draws the snapshot: the program on the alternate screen, '
'its modes, and the shell underneath once it exits', () async {
longTerminal('x' * 3000);
mac.snapshots['term_a'] = _snapshot;
hub.activate();
await settle();
final tab = hub.tabs.single;
expect(mac.bodies('terminal_output').single['after'], isNull);
expect(tab.session.end, 3000);
expectNvim(tab);
// No "earlier output was dropped" line: the snapshot misses nothing.
expect(
tab.session.terminal.mainBuffer.lines[0].getText(),
isNot(contains('dropped')),
);
mac.write('term_a', _exit);
await settle();
expectShellAfterExit(tab);
});
test('after a gap the snapshot replaces what the tab drew, modes '
'included', () async {
longTerminal('stale\x1b[?1000h\x1b[?1049h');
hub.activate();
await settle();
final tab = hub.tabs.single;
expect(tab.session.terminal.mouseMode, MouseMode.upDownScroll);
final held = tab.session.end;
// The tab falls behind past the server's tail, which now starts later.
mac.write('term_a', 'y' * 5000, push: false);
mac.snapshots['term_a'] = _snapshot;
mac.snapshotFrom = held + 100;
final end = held + 5000;
mac.pushOutput('term_a', 'z', end, end: end + 1);
await settle();
expect(mac.bodies('terminal_output').last['after'], held);
expectNvim(tab);
mac.write('term_a', _exit);
await settle();
expectShellAfterExit(tab);
});
}
@@ -0,0 +1,90 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'terminal_app.dart';
import 'terminal_fixtures.dart';
const _dot = ValueKey('terminal-tab-bell');
void main() {
late TerminalGateway mac;
late TerminalHub hub;
late TerminalLayout layout;
setUp(() {
mac = TerminalGateway()
..add('term_a', cwd: '/Users/op/src', text: r'$ ')
..add('term_b', cwd: '/Users/op/docs', text: r'$ ');
layout = TerminalLayout(store: MemoryLayoutStore())..visible = true;
hub = TerminalHub(
TestMachines([machine('mac', mac, name: 'Mac')]),
layout: layout,
);
});
tearDown(() async {
hub.dispose();
await mac.close();
});
/// Lets a pushed frame arrive and draw.
Future<void> drain(WidgetTester tester) async {
for (var i = 0; i < 3; i++) {
await tester.pump(const Duration(milliseconds: 1));
}
}
Future<void> open(WidgetTester tester) async {
await pumpTerminalApp(tester, hub: hub, layout: layout);
await tester.pumpAndSettle();
expect(hub.tabs, hasLength(2));
expect(hub.selected!.info.id, 'term_a');
}
testWidgets('a bell in a tab that is not shown dots it until it is '
'selected; the shown tab only flashes', (tester) async {
final semantics = tester.ensureSemantics();
await open(tester);
mac.write('term_b', '\x07');
await drain(tester);
expect(find.byKey(_dot), findsOneWidget);
expect(find.bySemanticsLabel(RegExp(r'\bBell\b')), findsOneWidget);
semantics.dispose();
// The shown terminal flashes instead.
mac.write('term_a', '\x07');
await drain(tester);
expect(find.byKey(const ValueKey('terminal-bell-flash')), findsOneWidget);
expect(find.byKey(_dot), findsOneWidget);
await tester.tap(find.text('docs'));
await tester.pumpAndSettle();
expect(find.byKey(_dot), findsNothing);
// Hidden, every tab dots; turned off, none does.
layout.hide();
await tester.pumpAndSettle();
mac.write('term_b', '\x07');
await drain(tester);
expect(hub.tabs.last.bellUnseen, isTrue);
layout.show();
await tester.pumpAndSettle();
expect(hub.tabs.last.bellUnseen, isFalse);
layout.setBell(false);
mac.write('term_a', '\x07');
await tester.pumpAndSettle();
expect(hub.tabs.first.bellUnseen, isFalse);
});
testWidgets('a folder reported with OSC 7 names an untitled tab and its '
'tooltip; a shell title still wins', (tester) async {
await open(tester);
mac.write('term_a', '\x1b]7;file://mac/Users/op/src/app\x07');
await drain(tester);
expect(find.text('app'), findsOneWidget);
expect(hub.tabs.first.cwd, '/Users/op/src/app');
expect(find.byTooltip('Mac: /Users/op/src/app'), findsOneWidget);
mac.write('term_a', '\x1b]0;vim notes\x07');
await drain(tester);
expect(find.text('vim notes'), findsOneWidget);
expect(find.text('app'), findsNothing);
});
}
@@ -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<Pixels> paintLines(List<BufferLine> 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<Pixels> 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<void> 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 = <bool>[];
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();
});
});
}
@@ -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}');
});
});
}
@@ -0,0 +1,98 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'paint_fixture.dart';
void main() {
group('maxLines', () {
Terminal filled(int lines) {
final terminal = Terminal(maxLines: 100)..resize(10, 4);
terminal.write(List.generate(lines, (i) => 'l$i').join('\r\n'));
return terminal;
}
test('shrinking drops the oldest lines and keeps anchors right', () {
final terminal = filled(80);
final buffer = terminal.buffer;
expect(buffer.height, 80);
final anchor = buffer.createAnchor(0, 79);
final old = buffer.createAnchor(0, 5);
terminal.maxLines = 30;
expect(terminal.maxLines, 30);
expect(buffer.height, 30);
expect(buffer.lines[0].getText().trim(), 'l50');
expect(buffer.lines[29].getText().trim(), 'l79');
expect(anchor.attached, isTrue);
expect(anchor.y, 29);
expect(old.attached, isFalse);
// Further output keeps to the new length.
terminal.write('\r\nnext');
expect(buffer.height, 30);
expect(buffer.lines[29].getText().trim(), 'next');
});
test('growing keeps every line and makes room for more', () {
final terminal = filled(100);
terminal.maxLines = 300;
expect(terminal.buffer.height, 100);
terminal.write(List.generate(150, (i) => '\r\nm$i').join());
expect(terminal.buffer.height, 250);
expect(terminal.buffer.lines[0].getText().trim(), 'l0');
});
test('never fewer than the screen rows', () {
final terminal = filled(20);
terminal.maxLines = 2;
expect(terminal.buffer.height, 4);
});
test('clearing the scrollback detaches its lines', () {
final terminal = filled(20);
final buffer = terminal.buffer;
final old = buffer.createAnchor(0, 2);
final screen = buffer.createAnchor(0, 18);
buffer.clearScrollback();
expect(buffer.height, 4);
expect(old.attached, isFalse);
expect(screen.y, 2);
});
});
testWidgets('cursorBlinkVisible hides the cursor in its off phase', (
tester,
) async {
final terminal = Terminal()..write('ab');
final phase = ValueNotifier(true);
addTearDown(phase.dispose);
await tester.pumpWidget(
MaterialApp(
home: Center(
child: SizedBox(
width: 200,
height: 100,
child: TerminalView(
terminal,
theme: fixtureTheme,
alwaysShowCursor: false,
cursorBlinkVisible: phase,
hardwareKeyboardOnly: true,
),
),
),
),
);
// The background, then (after the text) the unfocused cursor's outline.
PaintPattern cursor() => paints
..rect(color: backgroundColor)
..rect(color: cursorColor);
final view = find.byType(TerminalView);
expect(view, cursor());
phase.value = false;
await tester.pump();
expect(view, isNot(cursor()));
phase.value = true;
await tester.pump();
expect(view, cursor());
});
}
+23 -1
View File
@@ -21,7 +21,7 @@ Local patches (keep this list current):
- DCS/APC/PM/SOS strings consumed rather than printed; DECRQSS (`m`, `r`,
` q`) answered
- RIS (`ESC c`) full reset and DECSTR (`CSI ! p`)
- DECSCUSR cursor shapes (blinking is stored, not animated); SCOSC/SCORC,
- DECSCUSR cursor shapes (blinking is stored; the host animates it); SCOSC/SCORC,
CHT, CBT, HPA, HPR, VPR; HTS sets tab stops; DSR 6 one-based
- OSC 10/11/12 colour queries from the view's theme; OSC 8 links on cells
(`Terminal.hyperlinkAt`); OSC 52 set (`onClipboardSet`, no reads); OSC 7
@@ -33,3 +33,25 @@ Local patches (keep this list current):
- rendering: block cursor shows the character inverted, underline/bar
cursor position, strikethrough, conceal, overline, underline styles
- focus reporting (`?1004`, `Terminal.focusInput`, called by `TerminalView`)
- `Terminal.maxLines` is settable (`Buffer.setMaxLines`): a smaller value
drops the oldest scrollback at once; `IndexAwareCircularBuffer.trimStart`
detaches the dropped lines and keeps the others' indexes (it left them
attached and off by the trimmed count, so `clearScrollback` broke anchors)
- `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
+61 -12
View File
@@ -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,12 +10,13 @@ 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;
final int maxLines;
/// The lines this buffer keeps, scrollback included; see [setMaxLines].
int get maxLines => lines.maxLength;
final bool isAltBuffer;
@@ -24,10 +26,10 @@ class Buffer {
Buffer(
this.terminal, {
required this.maxLines,
required int maxLines,
required this.isAltBuffer,
this.wordSeparators,
}) {
}) : lines = IndexAwareCircularBuffer<BufferLine>(maxLines) {
for (int i = 0; i < terminal.viewHeight; i++) {
lines.push(_newEmptyLine());
}
@@ -59,7 +61,16 @@ class Buffer {
/// lines of the buffer. the length of [lines] should always be equal or
/// greater than [viewHeight].
late final lines = IndexAwareCircularBuffer<BufferLine>(maxLines);
final IndexAwareCircularBuffer<BufferLine> lines;
/// Keeps at most [value] lines (never fewer than the screen's rows),
/// dropping the oldest scrollback when that is fewer than it holds.
void setMaxLines(int value) {
value = max(value, viewHeight);
final excess = lines.length - value;
if (excess > 0) lines.trimStart(excess);
lines.maxLength = value;
}
/// Total number of lines in the buffer. Always equal or greater than
/// [viewHeight].
@@ -105,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);
@@ -119,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++;
}
}
@@ -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;
}
@@ -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 = <String>[];
final _ids = <String, int>{};
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;
}
+43 -7
View File
@@ -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 = <CellAnchor>[];
List<CellAnchor> 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);
}
+6
View File
@@ -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;
}
+13 -3
View File
@@ -33,7 +33,17 @@ import 'package:xterm/src/utils/circular_buffer.dart';
class Terminal with Observable implements TerminalState, EscapeHandler {
/// The number of lines that the scrollback buffer can hold. If the buffer
/// exceeds this size, the lines at the top of the buffer will be removed.
final int maxLines;
/// Setting it applies to the running terminal: a smaller value drops the
/// oldest scrollback at once.
int get maxLines => _maxLines;
int _maxLines;
set maxLines(int value) {
if (value == _maxLines || value <= 0) return;
_maxLines = value;
_mainBuffer.setMaxLines(value);
_altBuffer.setMaxLines(value);
notifyListeners();
}
/// Function that is called when the program requests the terminal to ring
/// the bell. If not set, the terminal will do nothing.
@@ -105,7 +115,7 @@ class Terminal with Observable implements TerminalState, EscapeHandler {
final Set<int>? wordSeparators;
Terminal({
this.maxLines = 1000,
int maxLines = 1000,
this.onBell,
this.onTitleChange,
this.onIconChange,
@@ -117,7 +127,7 @@ class Terminal with Observable implements TerminalState, EscapeHandler {
this.onPrivateOSC,
this.reflowEnabled = true,
this.wordSeparators,
});
}) : _maxLines = maxLines;
late final _parser = EscapeParser(this);
+13
View File
@@ -1,4 +1,5 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
@@ -44,6 +45,7 @@ class TerminalView extends StatefulWidget {
this.keyboardAppearance = Brightness.dark,
this.cursorType = TerminalCursorType.block,
this.alwaysShowCursor = false,
this.cursorBlinkVisible,
this.deleteDetection = false,
this.shortcuts,
this.onKeyEvent,
@@ -116,6 +118,11 @@ class TerminalView extends StatefulWidget {
/// [false] by default.
final bool alwaysShowCursor;
/// The phase of a blinking cursor: while its value is false the cursor is
/// not drawn. The host animates it (and stops it while unfocused); null
/// draws a steady cursor.
final ValueListenable<bool>? cursorBlinkVisible;
/// Workaround to detect delete key for platforms and IMEs that does not
/// emit hardware delete event. Prefered on mobile platforms. [false] by
/// default.
@@ -256,6 +263,7 @@ class TerminalViewState extends State<TerminalView> {
focusNode: _focusNode,
cursorType: widget.cursorType,
alwaysShowCursor: widget.alwaysShowCursor,
cursorBlinkVisible: widget.cursorBlinkVisible,
onEditableRect: _onEditableRect,
composingText: _composingText,
);
@@ -496,6 +504,7 @@ class _TerminalView extends LeafRenderObjectWidget {
required this.focusNode,
required this.cursorType,
required this.alwaysShowCursor,
this.cursorBlinkVisible,
this.onEditableRect,
this.composingText,
});
@@ -522,6 +531,8 @@ class _TerminalView extends LeafRenderObjectWidget {
final bool alwaysShowCursor;
final ValueListenable<bool>? cursorBlinkVisible;
final EditableRectCallback? onEditableRect;
final String? composingText;
@@ -540,6 +551,7 @@ class _TerminalView extends LeafRenderObjectWidget {
focusNode: focusNode,
cursorType: cursorType,
alwaysShowCursor: alwaysShowCursor,
cursorBlinkVisible: cursorBlinkVisible,
onEditableRect: onEditableRect,
composingText: composingText,
);
@@ -559,6 +571,7 @@ class _TerminalView extends LeafRenderObjectWidget {
..focusNode = focusNode
..cursorType = cursorType
..alwaysShowCursor = alwaysShowCursor
..cursorBlinkVisible = cursorBlinkVisible
..onEditableRect = onEditableRect
..composingText = composingText;
}
+455
View File
@@ -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<int> _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<Offset> 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();
}
+284 -71
View File
@@ -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
+46 -5
View File
@@ -1,6 +1,7 @@
import 'dart:math' show max;
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:xterm/src/core/buffer/cell_offset.dart';
@@ -13,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';
@@ -33,6 +35,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
required FocusNode focusNode,
required TerminalCursorType cursorType,
required bool alwaysShowCursor,
ValueListenable<bool>? cursorBlinkVisible,
EditableRectCallback? onEditableRect,
String? composingText,
}) : _terminal = terminal,
@@ -43,6 +46,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
_focusNode = focusNode,
_cursorType = cursorType,
_alwaysShowCursor = alwaysShowCursor,
_cursorBlinkVisible = cursorBlinkVisible,
_onEditableRect = onEditableRect,
_composingText = composingText,
_painter = TerminalPainter(
@@ -146,6 +150,15 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
markNeedsPaint();
}
ValueListenable<bool>? _cursorBlinkVisible;
set cursorBlinkVisible(ValueListenable<bool>? value) {
if (value == _cursorBlinkVisible) return;
if (attached) _cursorBlinkVisible?.removeListener(markNeedsPaint);
_cursorBlinkVisible = value;
if (attached) _cursorBlinkVisible?.addListener(markNeedsPaint);
markNeedsPaint();
}
EditableRectCallback? _onEditableRect;
set onEditableRect(EditableRectCallback? value) {
if (value == _onEditableRect) return;
@@ -164,6 +177,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
final TerminalPainter _painter;
final _rows = RowPictureCache();
var _stickToBottom = true;
void _onScroll() {
@@ -196,6 +211,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
_terminal.addListener(_onTerminalChange);
_controller.addListener(_onControllerUpdate);
_focusNode.addListener(_onFocusChange);
_cursorBlinkVisible?.addListener(markNeedsPaint);
}
@override
@@ -205,6 +221,14 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
_terminal.removeListener(_onTerminalChange);
_controller.removeListener(_onControllerUpdate);
_focusNode.removeListener(_onFocusChange);
_cursorBlinkVisible?.removeListener(markNeedsPaint);
_rows.clear();
}
@override
void dispose() {
_rows.clear();
super.dispose();
}
@override
@@ -398,7 +422,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
}
bool get _shouldShowCursor {
return _terminal.cursorVisibleMode || _alwaysShowCursor || _isComposingText;
if (_isComposingText || _alwaysShowCursor) return true;
return _terminal.cursorVisibleMode && _cursorBlinkVisible?.value != false;
}
double get _viewportHeight {
@@ -446,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) {
+102
View File
@@ -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<BufferLine, _RowPicture>.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;
}
+23 -3
View File
@@ -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),
);
}
+43
View File
@@ -54,4 +54,47 @@ class TerminalTheme {
final Color searchHitBackground;
final Color searchHitBackgroundCurrent;
final Color searchHitForeground;
List<Color> 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);
}
+147
View File
@@ -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 = <int>[];
final _keys = <int>[];
final _styles = <TextStyle Function()>[];
final _decorated = <bool>[];
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);
@@ -224,8 +224,14 @@ class IndexAwareCircularBuffer<T extends IndexedItem> {
/// instead just adjusts the start index and length.
void trimStart(int count) {
if (count > _length) count = _length;
// The dropped items are detached and the rest keep their indexes, as a
// push that overflows does.
for (var i = 0; i < count; i++) {
_dropChild(i);
}
_startIndex += count;
_startIndex %= _array.length;
_absoluteStartIndex += count;
_length -= count;
}
File diff suppressed because it is too large Load Diff
+104
View File
@@ -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<int> 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<int> 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;
}
}
+1
View File
@@ -3,6 +3,7 @@ export 'src/ui/controller.dart';
export 'src/ui/cursor_type.dart';
export 'src/ui/keyboard_visibility.dart';
export 'src/ui/pointer_input.dart';
export 'src/ui/render.dart' show RenderTerminal;
export 'src/ui/selection_mode.dart';
export 'src/ui/shortcut/shortcuts.dart';
export 'src/ui/terminal_text_style.dart';
+123
View File
@@ -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 <emoji-data.txt> > 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/<version>/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<int> {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()
+1
View File
@@ -55,6 +55,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`.
| `type=text` | type into the focused field (or the first visible one) |
| `press=Enter` | press a key: Enter, Escape, Tab, Backspace, ArrowUp, ArrowDown, a letter or a digit, optionally after `Control+`, `Shift+`, `Alt+` or `Meta+` (`press=Control+2`) |
| `scroll=600` | scroll with the mouse wheel at the centre (JSON `at` sets a target, `dx` a horizontal delta, `repeat` and `gap` a run of ticks) |
| `rightclick=<target>` | click the secondary mouse button on the target (context menus), then wait |
| `hover=<target>` | move the mouse onto the target without pressing (hover states) |
| `drag=<target>>dx,dy` | press on the target, move by dx,dy in `steps` (12) moves `gap` (16) ms apart, release (JSON `dx`, `dy`, `steps`, `gap`; `hold: true` keeps the button down to capture mid-drag) |
| `size=WxH` | resize without reloading |
+7
View File
@@ -25,6 +25,7 @@ steps: open=<route>[@WxH] wait=<ms> shot=<name> click=<target> waitfor=<target
type=<text> press=<Enter|Escape|Tab|...> scroll=<dy> size=WxH
files=<path>[,<path>] (answers the next file chooser)
film=<target> labels=<name> tabs=<name> eval=<js> expect=<js> hover=<target>
rightclick=<target> (secondary button: context menus)
drag=<target>><dx>,<dy> (JSON: drag, dx, dy, steps, gap, hold)
swipe=<target>><dx>,<dy> pinch=<target>><scale> (with --touch true)
target: <label> | label:<label> | key:<semantics identifier> | x,y`;
@@ -113,6 +114,12 @@ try {
await delay(step.wait ?? settle);
break;
}
case 'rightclick': {
const hit = await page.rightClick(value, step.timeout);
log(` right-clicked ${describe(parseTarget(value))} at ${Math.round(hit.x)},${Math.round(hit.y)}`);
await delay(step.wait ?? settle);
break;
}
case 'waitfor': await page.waitFor(value, step.timeout ?? 10000); break;
case 'files': await page.armFiles(String(value).split(',').map((p) => resolve(p))); break;
case 'type': await page.type(String(value)); await delay(step.wait ?? settle); break;
+11 -2
View File
@@ -121,6 +121,14 @@ export function flutterPage(browser, log, { touch = false } = {}) {
await tap(point);
return point;
},
/** Clicks the secondary (right) mouse button on [target] (context menus). */
async rightClick(target, timeout) {
const { x, y } = await locate(target, timeout);
await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y });
await send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'right', buttons: 2, clickCount: 1 });
await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'right', buttons: 0, clickCount: 1 });
return { x, y };
},
waitFor: (target, timeout) => locate(target, timeout),
/** Answers the next file chooser the page opens with [paths] (absolute). */
async armFiles(paths) {
@@ -148,9 +156,10 @@ export function flutterPage(browser, log, { touch = false } = {}) {
const key = parts.pop();
const bits = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
const modifiers = parts.reduce((m, p) => m | (bits[p] ?? 0), 0);
const codes = { Enter: 13, Escape: 27, Tab: 9, Backspace: 8, ArrowDown: 40, ArrowUp: 38, ArrowLeft: 37, ArrowRight: 39, "/": 191 };
const codes = { Enter: 13, Escape: 27, Tab: 9, Backspace: 8, ArrowDown: 40, ArrowUp: 38, ArrowLeft: 37, ArrowRight: 39, "/": 191, '=': 187, '-': 189 };
const digit = /^\d$/.test(key);
const code = key === '/' ? 'Slash' : digit ? `Digit${key}` : /^[a-z]$/i.test(key) ? `Key${key.toUpperCase()}` : key;
const named = { '/': 'Slash', '=': 'Equal', '-': 'Minus' };
const code = named[key] ? named[key] : digit ? `Digit${key}` : /^[a-z]$/i.test(key) ? `Key${key.toUpperCase()}` : key;
const vk = codes[key] ?? (key.length === 1 ? key.toUpperCase().charCodeAt(0) : 0);
const text = key === 'Enter' ? '\r' : key.length === 1 && !modifiers ? key : undefined;
const base = { key, code, windowsVirtualKeyCode: vk, modifiers, text };
+31
View File
@@ -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<String, String> params) {
_enabled = params['terminals'] == '1';
if (!_enabled) return;
@@ -65,6 +93,9 @@ void configureTerminalFixture(Map<String, String> 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,
+215
View File
@@ -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<String, String> 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<FrameTiming> _timings = [];
final List<double> _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<FrameTiming> 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<double> 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<String, double> _quantiles(List<double> 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,
),
),
),
);
}
}
+74
View File
@@ -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?.();
}
+3 -1
View File
@@ -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
+9 -2
View File
@@ -1330,8 +1330,15 @@ app's terminal panel). Every request carries `terminal_request`
- `terminal_output {terminal_id, after, flow?}` replies with the retained
output (1 MiB tail) from byte `after` of the stream named `stream`, covering
bytes `[output_start, output_end)`; the output frames that follow the reply
start at `output_end`. Opening or reading subscribes the connection to the
terminal's output frames.
start at `output_end`. When `after` is before the retained tail (or
missing) and the stream is longer than the tail, the reply carries
`output_snapshot: true` instead: `output` is the server's redraw of the
terminal as of `output_end` (= `output_start`): a reset, the scrollback
(last 1000 lines), the main screen, the alternate screen when in use, the
cursor, modes (mouse, bracketed paste, cursor keys, keypad, ...) and pen,
from a headless emulator the server feeds with the terminal's output. A
client writes it into its emulator as it would a replay. Opening or
reading subscribes the connection to the terminal's output frames.
- `terminal_ack {terminal_id, after}` (flow-controlled subscriptions only):
the connection has drawn the output up to byte `after`. Not logged.
- `terminal_close {terminal_id}` kills the login or shell.
+1 -1
View File
@@ -11,6 +11,7 @@ require (
github.com/charmbracelet/x/ansi v0.10.1
github.com/coder/websocket v1.8.15
github.com/hashicorp/mdns v1.0.7
github.com/mattn/go-runewidth v0.0.16
github.com/miekg/dns v1.1.72
github.com/muesli/termenv v0.16.0
github.com/pmezard/go-difflib v1.0.0
@@ -42,7 +43,6 @@ require (
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
+11 -3
View File
@@ -31,9 +31,11 @@ const (
// terminal is its first active client. The reply echoes the terminal.
TerminalResize = "terminal_resize"
// TerminalOutput reads one terminal with its retained output from the
// absolute byte After on (all of it when After precedes the retained
// tail; OutputStart says where it starts). It also subscribes the
// connection to the terminal's terminal_event output frames.
// absolute byte After on (OutputStart says where it starts). When After
// precedes the retained tail (the newest TerminalRetained bytes; a stream
// no longer than that is read whole), the reply is a snapshot of the
// terminal's state instead (OutputSnapshot). It also subscribes the connection to the terminal's
// terminal_event output frames.
TerminalOutput = "terminal_output"
// TerminalClose ends a terminal: its login or shell is killed
// and its record removed. The reply echoes the last record.
@@ -127,6 +129,12 @@ type TerminalRecord struct {
OutputEnd int64 `json:"output_end"`
Output string `json:"output,omitempty"`
OutputStart int64 `json:"output_start,omitempty"`
// OutputSnapshot marks a terminal_output reply whose Output is not raw
// output but the server's redraw of the terminal as of OutputEnd (which
// OutputStart equals): it resets the emulator and restores the
// scrollback, the screens, the cursor and the modes. A client writes it
// into a reset emulator as it would a replay.
OutputSnapshot bool `json:"output_snapshot,omitempty"`
// Window is set on the terminal_open and terminal_output replies of a
// flow-controlled subscription: the bytes the server sends past the
// last terminal_ack. Its absence means the server takes no acks.
+1
View File
@@ -287,6 +287,7 @@ func (p *terminalProcess) applySize(cols, rows int) error {
cols, rows = chatShellTerminalSize(cols, rows)
p.mu.Lock()
p.record.Cols, p.record.Rows = cols, rows
p.screen.Resize(cols, rows)
terminal := p.pty
p.mu.Unlock()
if terminal != nil {
+12 -1
View File
@@ -11,6 +11,7 @@ import (
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/termstate"
)
// terminalProcess is one terminal this server process holds: running (its
@@ -20,6 +21,8 @@ type terminalProcess struct {
mu sync.Mutex
record protocol.TerminalRecord
out *chatShellOutput
// screen follows the output (terminal_screen.go).
screen *termstate.Terminal
titles terminalTitles
// login follows the output until the login completes; loginChanged is
// signalled when it changes.
@@ -54,6 +57,7 @@ func newTerminalProcess(record protocol.TerminalRecord) *terminalProcess {
return &terminalProcess{
record: record,
out: newChatShellOutput(protocol.TerminalRetained),
screen: termstate.New(record.Cols, record.Rows, termstate.DefaultScrollback),
input: make(chan []byte, protocol.ChatShellInputQueue),
done: make(chan struct{}),
views: map[*terminalView]struct{}{},
@@ -87,10 +91,16 @@ func (p *terminalProcess) snapshot(output bool, after int64) protocol.TerminalRe
}
// snapshotLocked is snapshot with p.mu held. The output ends at OutputEnd:
// an incomplete trailing character waits for the next frame.
// an incomplete trailing character waits for the next frame. A read from
// before the retained tail gets the screen's snapshot instead of the tail
// (terminal_screen.go).
func (p *terminalProcess) snapshotLocked(output bool, after int64) protocol.TerminalRecord {
record := p.record
record.OutputEnd = p.out.total
if output && after < p.retainedFromLocked() {
p.screenLocked(&record)
return record
}
if output {
from := max(after, p.out.start)
text, start, end, ok := p.out.chunk(from, p.out.total, protocol.TerminalRetained, p.outDone)
@@ -150,6 +160,7 @@ func (p *terminalProcess) read(terminal *os.File, titled func(string)) {
if n > 0 {
p.mu.Lock()
p.out.write(buffer[:n])
p.screen.Write(buffer[:n])
p.pokeViewsLocked()
if p.login.feed(buffer[:n]) {
select {
+37
View File
@@ -0,0 +1,37 @@
package server
import "git.a-wan.net/alan/pipelines/internal/protocol"
// A machine terminal's output also feeds a headless emulator
// (internal/termstate), under the same lock as the retained tail, so its
// state always belongs to the tail's end. A client that reads from before
// the tail (a new page, a reload, a reconnect after the tail moved on, a
// gap) would otherwise redraw from an arbitrary cut: a full-screen program
// that wrote more than the tail since it started would land on the main
// screen, and its modes (mouse, bracketed paste, cursor keys, ...) would be
// lost. Such a read gets the emulator's snapshot instead: an escape
// sequence stream that resets the client's emulator and redraws the
// scrollback, the main screen, the alternate screen when in use, the
// cursor, the modes and the pen, as of OutputEnd; the frames that follow
// start there. A read inside the tail (an ordinary resume, or a stream not
// longer than the tail) gets the raw bytes as before.
// retainedFromLocked is where the retained tail starts: the newest
// TerminalRetained bytes (the buffer may hold more until it compacts).
func (p *terminalProcess) retainedFromLocked() int64 {
return max(p.out.start, p.out.total-protocol.TerminalRetained)
}
// screenLocked sets record's output to the screen's snapshot. p.mu is held.
func (p *terminalProcess) screenLocked(record *protocol.TerminalRecord) {
snap, partial := p.screen.Snapshot()
end := p.out.total
if !p.outDone {
// An unfinished character is left out of the snapshot and sent
// whole in the next frame.
end -= int64(partial)
}
record.Output = validChatShellText(snap)
record.OutputStart, record.OutputEnd = end, end
record.OutputSnapshot = true
}
+75
View File
@@ -0,0 +1,75 @@
//go:build darwin || linux
package server
import (
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/termstate"
)
// tuiCommand enters the alternate screen, sets mouse, bracketed paste and
// application cursor/keypad modes, writes more than the retained tail
// there, draws a last frame and waits for a line; then it restores the
// modes, leaves the alternate screen and prints a marker. The markers are
// computed, so the command's own echo does not contain them.
const tuiCommand = `echo before-$((1))tui; ` +
`printf '\033[?1049h\033[?1000h\033[?1006h\033[?2004h\033[?1h\033=\033[H\033[2J'; ` +
`head -c 1300000 /dev/zero | tr '\0' x; ` +
`printf '\033[H\033[2JFRAME-%s\033[24;1Hstatus-%s' $((7)) $((8)); read x; ` +
`printf '\033[?2004l\033[?1006l\033[?1000l\033[?1l\033>\033[?1049l'; echo after-$((2))tui` + "\r"
// A client that attaches (a reload, or one that fell behind the retained
// tail) while a full-screen program runs gets the terminal's state, not the
// tail: the program's screen on the alternate screen with its modes, and
// the shell's screen underneath, which the program's exit brings back.
func TestTerminalSnapshotAfterReload(t *testing.T) {
terminalHome(t)
ctx, conns := dialTerminalConns(t, 2, 60*time.Second)
term := openLoggedIn(t, ctx, conns[0], true)
reader := &terminalReader{t: t, ctx: ctx, conn: conns[0], id: term.ID, end: term.OutputEnd, ack: true}
typeInto(t, ctx, conns[0], term.ID, tuiCommand)
reader.until("status-8", nil)
// The reload: no After at all, and one far before the tail.
var reply *protocol.TerminalRecord
for _, after := range []int64{0, 5} {
reply = terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalOutput, "reload", protocol.TerminalRequest{TerminalID: term.ID, After: after, Flow: true})).Terminal
if !reply.OutputSnapshot || reply.OutputStart != reply.OutputEnd || reply.OutputEnd != reader.end || reply.Window != protocol.TerminalFlowWindow {
t.Fatalf("after %d: reply start %d end %d (reader at %d) snapshot %v window %d", after, reply.OutputStart, reply.OutputEnd, reader.end, reply.OutputSnapshot, reply.Window)
}
}
for _, want := range []string{"\x1b[?1049h", "\x1b[?1000h", "\x1b[?1006h", "\x1b[?2004h", "\x1b[?1h", "\x1b=", "FRAME-7", "status-8", "before-1tui"} {
if !strings.Contains(reply.Output, want) {
t.Fatalf("snapshot lacks %q", want)
}
}
if len(reply.Output) > 64<<10 {
t.Fatalf("snapshot is %d bytes", len(reply.Output))
}
// A resume inside the tail is raw output, as before.
if resume := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalOutput, "resume", protocol.TerminalRequest{TerminalID: term.ID, After: reply.OutputEnd, Flow: true})).Terminal; resume.OutputSnapshot || resume.Output != "" {
t.Fatalf("resume = %+v", resume)
}
screen := termstate.New(term.Cols, term.Rows, termstate.DefaultScrollback)
screen.Write([]byte(reply.Output))
if !screen.AltScreen() || !strings.HasPrefix(screen.Text(), "FRAME-7") || !strings.Contains(screen.Text(), "status-8") {
t.Fatalf("snapshot screen (alt %v):\n%s", screen.AltScreen(), screen.Text())
}
// The program exits; the frames continue exactly after the snapshot.
typeInto(t, ctx, conns[0], term.ID, "\r")
late := &terminalReader{t: t, ctx: ctx, conn: conns[1], id: term.ID, end: reply.OutputEnd, ack: true}
late.until("after-2tui", nil)
if late.gaps != 0 {
t.Fatalf("frames after the snapshot skipped %d bytes", late.gaps)
}
screen.Write([]byte(late.text.String()))
text := screen.Text()
if screen.AltScreen() || !strings.Contains(text, "before-1tui") || !strings.Contains(text, "after-2tui") || strings.Contains(text, "FRAME-7") || strings.Contains(text, "xxxx") {
t.Fatalf("main screen after the exit (alt %v):\n%s", screen.AltScreen(), text)
}
}
+60
View File
@@ -0,0 +1,60 @@
package termstate
import (
"fmt"
"math/rand"
"strings"
"testing"
)
// Workloads of the throughput the terminal output path sustains (about 30
// MB/s): `seq`, a full-screen program redrawing coloured frames, long
// wrapping lines of mixed text.
func workloads() map[string][]byte {
var b strings.Builder
for i := 1; b.Len() < 8<<20; i++ {
fmt.Fprintf(&b, "%d\r\n", i)
}
seq := b.String()
b.Reset()
r := rand.New(rand.NewSource(1))
b.WriteString("\x1b[?1049h")
for b.Len() < 8<<20 {
fmt.Fprintf(&b, "\x1b[%d;%dH\x1b[38;5;%dm\x1b[48;2;%d;%d;%dm%s\x1b[0m", r.Intn(50)+1, r.Intn(150)+1, r.Intn(256), r.Intn(256), r.Intn(256), r.Intn(256), strings.Repeat("x", r.Intn(40)))
}
tui := b.String()
b.Reset()
for b.Len() < 8<<20 {
b.WriteString("the quick brown fox jumps over the lazy dog ünïcödé 日本語 ")
}
return map[string][]byte{"seq": []byte(seq), "tui": []byte(tui), "text": []byte(b.String())}
}
func BenchmarkWrite(b *testing.B) {
loads := workloads()
for _, name := range []string{"seq", "tui", "text"} {
for _, size := range [][2]int{{80, 24}, {200, 50}} {
data := loads[name]
b.Run(fmt.Sprintf("%s/%dx%d", name, size[0], size[1]), func(b *testing.B) {
b.SetBytes(int64(len(data)))
for b.Loop() {
term := New(size[0], size[1], DefaultScrollback)
for i := 0; i < len(data); i += 32 << 10 {
term.Write(data[i:min(i+32<<10, len(data))])
}
}
})
}
}
}
// A snapshot of a full scrollback of wide rows.
func BenchmarkSnapshot(b *testing.B) {
term := New(200, 50, DefaultScrollback)
term.Write(workloads()["text"])
snap, _ := term.Snapshot()
b.ReportMetric(float64(len(snap)), "bytes")
for b.Loop() {
term.Snapshot()
}
}
+171
View File
@@ -0,0 +1,171 @@
// Package termstate is a headless terminal emulator that follows one
// pseudo-terminal's output stream and can write a snapshot: an escape
// sequence stream that brings a freshly reset terminal to the same state
// (main screen with bounded scrollback, the alternate screen when it is in
// use, cursor, pen, scroll region, character sets and terminal modes).
//
// It interprets what xterm-compatible programs write (the subset of xterm
// that full-screen programs use, the same one the app's emulator follows);
// it never answers queries, since the clients' emulators do. It is built for
// throughput: a line scrolled off the top is moved, not copied, and blank
// cells past a line's written part are not stored.
package termstate
// Color is a cell colour: 0 is the default colour, colorIndexed|n is
// palette entry n, colorRGB|0xRRGGBB a direct colour.
type Color uint32
const (
colorIndexed Color = 1 << 24
colorRGB Color = 2 << 24
colorKind Color = 3 << 24
)
// Attribute flags of a cell (SGR).
const (
attrBold uint16 = 1 << iota
attrFaint
attrItalic
attrBlink
attrInverse
attrHidden
attrStrike
attrOverline
// The underline style (SGR 4:n, 1 to 5) is held in three bits.
attrUnderlineShift = 13
attrUnderlineMask = 7 << attrUnderlineShift
)
// Attr is the pen a cell was written with.
type Attr struct {
Fg, Bg Color
Flags uint16
}
func (a Attr) underline() int { return int(a.Flags&attrUnderlineMask) >> attrUnderlineShift }
func (a *Attr) setUnderline(style int) {
a.Flags = a.Flags&^attrUnderlineMask | uint16(style&7)<<attrUnderlineShift
}
// Cell kinds: a wide character takes its cell and a tail cell after it.
const (
cellNarrow uint8 = iota
cellWide
cellWideTail
)
// Cell is one character cell. R is 0 for a blank (never written or erased)
// cell, which still carries the background it was erased with.
type Cell struct {
R rune
A Attr
Kind uint8
}
// line is one row. Cells past len(cells) are blank with the default pen.
type line struct {
cells []Cell
// cont: the row was filled and the text went on in the next row (a soft
// wrap), so the two are one logical line.
cont bool
// marks are combining characters drawn on the cell at a column.
marks map[int]string
}
func (l *line) reset() {
l.cells = l.cells[:0]
l.cont = false
l.marks = nil
}
// ensure makes at least n cells addressable.
func (l *line) ensure(n int) {
if n <= len(l.cells) {
return
}
if n <= cap(l.cells) {
old := len(l.cells)
l.cells = l.cells[:n]
clear(l.cells[old:])
return
}
grown := make([]Cell, n, max(n, 2*cap(l.cells)))
copy(grown, l.cells)
l.cells = grown
}
// blank fills [from, to) with blank cells of background bg, truncating
// instead when the default background reaches the end.
func (l *line) blank(from, to int, bg Color) {
if from >= to {
return
}
l.dropMarks(from, to)
if bg == 0 && to >= len(l.cells) {
if from < len(l.cells) {
l.cells = l.cells[:from]
}
return
}
l.ensure(to)
fill := Cell{A: Attr{Bg: bg}}
for i := from; i < to; i++ {
l.cells[i] = fill
}
}
func (l *line) dropMarks(from, to int) {
if l.marks == nil {
return
}
for x := range l.marks {
if x >= from && x < to {
delete(l.marks, x)
}
}
}
// repair blanks half of a wide character whose other half is gone, at x.
func (l *line) repair(x int) {
if x < 0 || x >= len(l.cells) {
return
}
switch l.cells[x].Kind {
case cellWideTail:
if x == 0 || l.cells[x-1].Kind != cellWide {
l.clearCell(x)
}
case cellWide:
if x+1 >= len(l.cells) || l.cells[x+1].Kind != cellWideTail {
l.clearCell(x)
}
}
}
// clearCell blanks the cell at x, keeping its background.
func (l *line) clearCell(x int) {
l.cells[x] = Cell{A: Attr{Bg: l.cells[x].A.Bg}}
if l.marks != nil {
delete(l.marks, x)
}
}
// truncate cuts the row at width cols.
func (l *line) truncate(cols int) {
if len(l.cells) > cols {
l.cells = l.cells[:cols]
l.dropMarks(cols, int(^uint(0)>>1))
l.repair(cols - 1)
}
}
// empty reports whether nothing visible is on the row.
func (l *line) empty() bool {
for i := range l.cells {
if l.cells[i] != (Cell{}) {
return false
}
}
return true
}
+519
View File
@@ -0,0 +1,519 @@
package termstate
import (
"strconv"
"strings"
)
// esc runs an ESC sequence with at most one intermediate byte.
func (t *Terminal) esc(inter, final byte) {
switch inter {
case 0:
case '(', ')':
if final == '0' || final == 'A' || final == 'B' {
t.cur.charsets[inter-'('] = final
}
return
case '#':
if final == '8' {
t.alignmentTest()
}
return
default:
return
}
switch final {
case '7':
t.saveCursor()
case '8':
t.restoreCursor()
case 'D':
t.lineFeed()
case 'E':
t.lineFeed()
t.cur.x = 0
case 'H':
t.tabs[t.cur.x] = true
case 'M':
t.reverseIndex()
case 'c':
t.reset()
case '=':
t.m.appKeypad = true
case '>':
t.m.appKeypad = false
}
}
func (t *Terminal) saveCursor() {
t.scr.saved, t.scr.savedValid = t.cur, true
}
// restoreCursor is DECRC. As in the app's emulator, origin mode is not part
// of what it restores.
func (t *Terminal) restoreCursor() {
origin := t.cur.origin
if t.scr.savedValid {
t.cur = t.scr.saved
} else {
t.cur = cursor{charsets: [2]byte{'B', 'B'}}
}
t.cur.origin = origin
t.cur.x, t.cur.y = min(t.cur.x, t.cols-1), min(t.cur.y, t.rows-1)
}
// alignmentTest is DECALN: the screen fills with E.
func (t *Terminal) alignmentTest() {
t.top, t.bottom = 0, t.rows-1
for _, l := range t.scr.lines {
l.reset()
l.ensure(t.cols)
for x := range l.cells {
l.cells[x] = Cell{R: 'E'}
}
}
t.cur.x, t.cur.y, t.cur.wrap = 0, 0, false
}
// csi runs a CSI sequence.
func (t *Terminal) csi(final byte) {
p := &t.p.ps
switch t.p.prefix {
case 0:
case '?':
if t.p.inter == 0 && (final == 'h' || final == 'l') {
for i := 0; i < p.n; i++ {
t.setDecMode(p.get(i, 0), final == 'h')
}
}
return
default:
return
}
switch t.p.inter {
case 0:
case ' ':
if final == 'q' {
t.cursorShape = p.get(0, 0)
}
return
case '!':
if final == 'p' {
t.softReset()
}
return
default:
return
}
switch final {
case '@':
t.insertCells(p.count(0))
case 'A':
t.moveRows(-p.count(0))
case 'B', 'e':
t.moveRows(p.count(0))
case 'C', 'a':
t.moveTo(t.cur.x+p.count(0), t.cur.y)
case 'D':
t.moveTo(t.cur.x-p.count(0), t.cur.y)
case 'E':
t.moveRows(p.count(0))
t.cur.x = 0
case 'F':
t.moveRows(-p.count(0))
t.cur.x = 0
case 'G', '`':
t.moveTo(p.count(0)-1, t.cur.y)
case 'H', 'f':
t.position(p.count(0)-1, p.count(1)-1)
case 'd':
t.position(p.count(0)-1, t.cur.x)
case 'I':
t.tab(p.count(0))
case 'Z':
t.backTab(p.count(0))
case 'J':
t.eraseDisplay(p.get(0, 0))
case 'K':
t.eraseLine(p.get(0, 0))
case 'L':
t.insertLines(p.count(0))
case 'M':
t.deleteLines(p.count(0))
case 'P':
t.deleteCells(p.count(0))
case 'S':
if p.n <= 1 {
t.scrollUp(p.count(0))
}
case 'T':
if p.n <= 1 {
t.scrollDown(p.count(0))
}
case 'X':
n := min(p.count(0), t.cols-t.cur.x)
l := t.scr.lines[t.cur.y]
l.blank(t.cur.x, t.cur.x+n, t.cur.pen.Bg)
l.repair(t.cur.x - 1)
l.repair(t.cur.x + n)
t.cur.wrap = false
case 'b':
if t.lastChar != 0 {
for n := min(p.count(0), 65535); n > 0; n-- {
t.print(t.lastChar)
}
}
case 'g':
switch p.get(0, 0) {
case 0:
t.tabs[t.cur.x] = false
case 3:
clear(t.tabs)
}
case 'h', 'l':
for i := 0; i < p.n; i++ {
switch p.get(i, 0) {
case 4:
t.m.insert = final == 'h'
case 20:
t.m.newline = final == 'h'
}
}
case 'm':
t.sgr()
case 'r':
top, bottom := p.count(0)-1, p.get(1, t.rows)
if bottom <= 0 || bottom > t.rows {
bottom = t.rows
}
if top < bottom-1 {
t.top, t.bottom = top, bottom-1
t.position(0, 0)
}
case 's':
t.saveCursor()
case 'u':
t.restoreCursor()
}
}
// moveRows moves the cursor n rows, stopping at the scroll region's margin
// when it starts inside the region.
func (t *Terminal) moveRows(n int) {
y, lo, hi := t.cur.y+n, 0, t.rows-1
if t.cur.y >= t.top && t.cur.y <= t.bottom {
lo, hi = t.top, t.bottom
}
t.cur.y = min(max(y, lo), hi)
t.cur.wrap = false
}
func (t *Terminal) moveTo(x, y int) {
t.cur.x = min(max(x, 0), t.cols-1)
t.cur.y = min(max(y, 0), t.rows-1)
t.cur.wrap = false
}
// position is CUP: relative to the scroll region in origin mode.
func (t *Terminal) position(row, col int) {
if t.cur.origin {
t.moveTo(col, min(t.top+row, t.bottom))
return
}
t.moveTo(col, row)
}
func (t *Terminal) eraseDisplay(mode int) {
bg := t.cur.pen.Bg
lines := t.scr.lines
switch mode {
case 0:
t.eraseLine(0)
for y := t.cur.y + 1; y < t.rows; y++ {
lines[y].reset()
lines[y].blank(0, t.cols, bg)
}
case 1:
t.eraseLine(1)
for y := 0; y < t.cur.y; y++ {
lines[y].reset()
lines[y].blank(0, t.cols, bg)
}
case 2:
for _, l := range lines {
l.reset()
l.blank(0, t.cols, bg)
}
case 3:
t.clearScrollback()
}
t.cur.wrap = false
}
func (t *Terminal) eraseLine(mode int) {
l := t.scr.lines[t.cur.y]
x := t.cur.x
switch mode {
case 0:
l.blank(x, t.cols, t.cur.pen.Bg)
l.repair(x - 1)
l.cont = false
case 1:
l.blank(0, x+1, t.cur.pen.Bg)
l.repair(x + 1)
case 2:
l.reset()
l.blank(0, t.cols, t.cur.pen.Bg)
}
t.cur.wrap = false
}
// setDecMode sets or resets DEC private mode n.
func (t *Terminal) setDecMode(n int, on bool) {
switch n {
case 1:
t.m.appCursor = on
case 5:
t.m.reverse = on
case 6:
t.cur.origin = on
t.position(0, 0)
case 7:
t.m.autowrap = on
if !on {
t.cur.wrap = false
}
case 12:
t.m.cursorBlink = on
case 25:
t.m.cursorVisible = on
case 66:
t.m.appKeypad = on
case 9, 1000, 1001, 1002, 1003:
if on {
t.m.mouse = n
} else {
t.m.mouse = 0
}
case 1005, 1006, 1015:
if on {
t.m.mouseEncoding = n
} else {
t.m.mouseEncoding = 0
}
case 1004:
t.m.focus = on
case 1007:
t.m.altScroll = on
case 2004:
t.m.bracketedPaste = on
case 47:
t.useScreen(on)
case 1047:
if !on && t.scr == &t.alt {
t.clearAlt()
}
t.useScreen(on)
case 1048:
if on {
t.saveCursor()
} else {
t.restoreCursor()
}
case 1049:
if on {
if t.scr != &t.alt {
t.saveCursor()
t.useScreen(true)
t.clearAlt()
}
} else if t.scr == &t.alt {
t.useScreen(false)
t.restoreCursor()
}
}
}
func (t *Terminal) useScreen(alt bool) {
if alt {
t.scr = &t.alt
} else {
t.scr = &t.main
}
t.cur.wrap = false
}
func (t *Terminal) clearAlt() {
for _, l := range t.alt.lines {
l.reset()
}
}
// sgr applies SGR parameters to the pen.
func (t *Terminal) sgr() {
p := &t.p.ps
pen := &t.cur.pen
if p.n == 0 {
*pen = Attr{}
return
}
for i := 0; i < p.n; i++ {
code := p.get(i, 0)
// Colon subparameters belong to the parameter before them.
subs := i + 1
for subs < p.n && p.isSub(subs) {
subs++
}
switch {
case code == 0:
*pen = Attr{}
case code == 1:
pen.Flags |= attrBold
case code == 2:
pen.Flags |= attrFaint
case code == 3:
pen.Flags |= attrItalic
case code == 4:
style := 1
if subs > i+1 {
style = p.get(i+1, 1)
}
if style > 5 {
style = 1
}
pen.setUnderline(style)
case code == 5 || code == 6:
pen.Flags |= attrBlink
case code == 7:
pen.Flags |= attrInverse
case code == 8:
pen.Flags |= attrHidden
case code == 9:
pen.Flags |= attrStrike
case code == 21:
pen.setUnderline(2)
case code == 22:
pen.Flags &^= attrBold | attrFaint
case code == 23:
pen.Flags &^= attrItalic
case code == 24:
pen.setUnderline(0)
case code == 25:
pen.Flags &^= attrBlink
case code == 27:
pen.Flags &^= attrInverse
case code == 28:
pen.Flags &^= attrHidden
case code == 29:
pen.Flags &^= attrStrike
case code >= 30 && code <= 37:
pen.Fg = colorIndexed | Color(code-30)
case code == 39:
pen.Fg = 0
case code >= 40 && code <= 47:
pen.Bg = colorIndexed | Color(code-40)
case code == 49:
pen.Bg = 0
case code == 53:
pen.Flags |= attrOverline
case code == 55:
pen.Flags &^= attrOverline
case code >= 90 && code <= 97:
pen.Fg = colorIndexed | Color(code-90+8)
case code >= 100 && code <= 107:
pen.Bg = colorIndexed | Color(code-100+8)
case code == 38 || code == 48 || code == 58:
var c Color
var ok bool
if subs > i+1 {
c, ok = t.colorFrom(i+1, subs, true)
} else {
var used int
c, used, ok = t.semicolonColor(i + 1)
subs = i + 1 + used
}
if ok {
switch code {
case 38:
pen.Fg = c
case 48:
pen.Bg = c
}
}
}
i = subs - 1
}
}
// colorFrom reads an extended colour from parameters [from, to): 5;n, or
// 2;r;g;b (with a colour space before r in the colon form when there are
// five of them).
func (t *Terminal) colorFrom(from, to int, colon bool) (Color, bool) {
p := &t.p.ps
switch p.get(from, -1) {
case 5:
if to-from >= 2 {
if n := p.get(from+1, 0); n >= 0 && n < 256 {
return colorIndexed | Color(n), true
}
}
case 2:
rgb := from + 1
if colon && to-from >= 5 {
rgb++
}
if to-rgb >= 3 {
r, g, b := p.get(rgb, 0)&0xFF, p.get(rgb+1, 0)&0xFF, p.get(rgb+2, 0)&0xFF
return colorRGB | Color(r<<16|g<<8|b), true
}
}
return 0, false
}
// semicolonColor reads the legacy form 38;5;n or 38;2;r;g;b starting at i,
// returning how many parameters it used.
func (t *Terminal) semicolonColor(i int) (Color, int, bool) {
p := &t.p.ps
switch p.get(i, -1) {
case 5:
if i+2 <= p.n {
c, ok := t.colorFrom(i, i+2, false)
return c, 2, ok
}
case 2:
if i+4 <= p.n {
c, ok := t.colorFrom(i, i+4, false)
return c, 4, ok
}
}
return 0, p.n - i, false
}
// osc runs an OSC string: the window title is kept.
func (t *Terminal) osc(data []byte) {
s := string(data)
code, rest, ok := strings.Cut(s, ";")
if !ok {
return
}
if n, err := strconv.Atoi(code); err == nil && (n == 0 || n == 2) {
t.title = sanitizeTitle(rest)
}
}
// sanitizeTitle drops control characters (a title is written back inside an
// OSC string) and bounds it.
func sanitizeTitle(s string) string {
s = strings.ToValidUTF8(s, "")
var b strings.Builder
for _, r := range s {
if r < 0x20 || r == 0x7F || (r >= 0x80 && r < 0xA0) {
continue
}
if b.Len() >= 1024 {
break
}
b.WriteRune(r)
}
return b.String()
}
+105
View File
@@ -0,0 +1,105 @@
package termstate
import (
"fmt"
"strings"
)
// dump describes everything a snapshot restores, normalised where two
// states look and behave the same: a never-written cell and a written space
// of the same pen, trailing blanks, a soft wrap into an empty row, and the
// content of the screen not in use.
func dump(t *Terminal) string {
var b strings.Builder
fmt.Fprintf(&b, "size %dx%d alt=%v region=%d-%d title=%q shape=%d\n", t.cols, t.rows, t.scr == &t.alt, t.top, t.bottom, t.title, t.cursorShape)
c := t.cur
fmt.Fprintf(&b, "cursor %d,%d wrap=%v origin=%v pen=%+v charsets=%c%c shift=%d\n", c.x, c.y, c.wrap, c.origin, c.pen, c.charsets[0], c.charsets[1], c.shift)
fmt.Fprintf(&b, "modes %+v\n", t.m)
for _, s := range []*screen{&t.main, &t.alt} {
if s.savedValid {
fmt.Fprintf(&b, "saved %d,%d pen=%+v\n", s.saved.x, s.saved.y, s.saved.pen)
} else {
b.WriteString("saved none\n")
}
}
fmt.Fprintf(&b, "tabs %v\n", t.tabs)
var main []*line
for i := 0; i < t.scrollbackLen(); i++ {
main = append(main, t.scrollbackLine(i))
}
fmt.Fprintf(&b, "scrollback %d\n", t.scrollbackLen())
main = append(main, t.main.lines...)
for i, l := range main {
cont := l.cont && i+1 < len(main) && !blankLine(main[i+1])
b.WriteString(dumpLine(l, cont))
}
{
b.WriteString("alt\n")
for _, l := range t.alt.lines {
b.WriteString(dumpLine(l, false))
}
}
return b.String()
}
func dumpLine(l *line, cont bool) string {
cells := make([]Cell, len(l.cells))
copy(cells, l.cells)
for i := range cells {
if cells[i].R == 0 && cells[i].Kind == cellNarrow {
cells[i].R = ' '
}
}
for len(cells) > 0 && cells[len(cells)-1] == (Cell{R: ' '}) {
cells = cells[:len(cells)-1]
}
var b strings.Builder
if cont {
b.WriteString("+")
}
pen := Attr{}
for x, c := range cells {
if c.A != pen {
fmt.Fprintf(&b, "{%x/%x/%x}", c.A.Fg, c.A.Bg, c.A.Flags)
pen = c.A
}
switch c.Kind {
case cellWideTail:
b.WriteString("~")
default:
b.WriteRune(c.R)
}
if m := l.marks[x]; m != "" {
b.WriteString("<" + m + ">")
}
}
b.WriteString("|\n")
return b.String()
}
func text(t *Terminal) string { return t.Text() }
// history is the scrollback's text, oldest first.
func history(t *Terminal) []string {
var lines []string
for i := 0; i < t.scrollbackLen(); i++ {
var b strings.Builder
for _, c := range t.scrollbackLine(i).cells {
if c.R != 0 && c.Kind != cellWideTail {
b.WriteRune(c.R)
}
}
lines = append(lines, b.String())
}
return lines
}
// blankLine: nothing but spaces and never-written cells of the default pen.
func blankLine(l *line) bool {
for _, c := range l.cells {
if c != (Cell{}) && c != (Cell{R: ' '}) {
return false
}
}
return len(l.marks) == 0
}
+296
View File
@@ -0,0 +1,296 @@
package termstate
// Parser states (the DEC ANSI parser of vt100.net, with DCS, SOS, PM and
// APC strings ignored as a whole).
const (
stGround uint8 = iota
stEscape
stEscInter
stCSI
stCSIInter
stCSIIgnore
stOSC
stString
)
const (
maxParams = 32
// maxSeq bounds the bytes of an unfinished escape sequence kept for a
// snapshot; longer ones are malformed and only their start is kept.
maxSeq = 256
// maxOSC bounds a kept OSC payload (titles); the rest is dropped.
maxOSC = 4096
)
// params are a CSI sequence's parameters: -1 for an empty one; sub marks
// those introduced by a colon (SGR subparameters).
type params struct {
v [maxParams]int32
sub uint32
n int
}
func (p *params) get(i int, def int) int {
if i >= p.n || p.v[i] < 0 {
return def
}
return int(p.v[i])
}
// count is get with a zero meaning one (counts and positions).
func (p *params) count(i int) int {
if n := p.get(i, 1); n > 0 {
return n
}
return 1
}
func (p *params) isSub(i int) bool { return i < p.n && p.sub&(1<<uint(i)) != 0 }
// parser is the decoding state between writes.
type parser struct {
st uint8
inter byte // the last intermediate byte of an ESC or CSI sequence
prefix byte // a CSI private marker (< = > ?)
strEsc bool // an ESC inside a string: ST if a backslash follows
strKind byte // the introducer of the string being skipped
digits bool // the current parameter has digits
ps params
// seq holds the bytes of the unfinished ESC or CSI sequence.
seq []byte
osc []byte
// An unfinished UTF-8 character: its bytes so far and how many follow.
utf rune
utfNeed int
utfHave int
}
func (t *Terminal) advance(b byte) {
p := &t.p
if p.utfNeed > 0 {
if b&0xC0 == 0x80 {
p.utf = p.utf<<6 | rune(b&0x3F)
p.utfHave++
if p.utfNeed--; p.utfNeed == 0 {
p.utfHave = 0
t.print(p.utf)
}
return
}
p.utfNeed, p.utfHave = 0, 0
t.print(0xFFFD)
}
switch b {
case 0x18, 0x1A: // CAN, SUB abort a sequence
if p.st != stGround {
p.st, p.strEsc = stGround, false
return
}
case 0x1B:
if p.st == stOSC || p.st == stString {
if !p.strEsc {
p.strEsc = true
return
}
}
p.st, p.strEsc, p.inter = stEscape, false, 0
p.seq = append(p.seq[:0], b)
return
}
switch p.st {
case stGround:
t.ground(b)
case stEscape:
t.escape(b)
case stEscInter:
switch {
case b < 0x20:
t.control(b)
case b < 0x30:
p.keep(b)
p.inter = b
default:
p.st = stGround
if b != 0x7F {
t.esc(p.inter, b)
}
}
case stCSI, stCSIInter, stCSIIgnore:
t.csiByte(b)
case stOSC:
if p.strEsc {
p.strEsc = false
p.st = stGround
if b == '\\' {
t.osc(p.osc)
return
}
// ESC then something else: the string ends, a sequence starts.
p.st, p.inter = stEscape, 0
p.seq = append(p.seq[:0], 0x1B)
t.escape(b)
return
}
switch {
case b == 0x07:
p.st = stGround
t.osc(p.osc)
case b < 0x20:
case len(p.osc) < maxOSC:
p.osc = append(p.osc, b)
}
case stString:
if p.strEsc {
p.strEsc = false
p.st = stGround
if b != '\\' {
p.st, p.inter = stEscape, 0
p.seq = append(p.seq[:0], 0x1B)
t.escape(b)
}
}
}
}
func (p *parser) keep(b byte) {
if len(p.seq) < maxSeq {
p.seq = append(p.seq, b)
}
}
func (t *Terminal) ground(b byte) {
p := &t.p
switch {
case b < 0x20:
t.control(b)
case b < 0x7F:
t.print(rune(b))
case b == 0x7F:
case b&0xE0 == 0xC0:
p.utf, p.utfNeed, p.utfHave = rune(b&0x1F), 1, 1
case b&0xF0 == 0xE0:
p.utf, p.utfNeed, p.utfHave = rune(b&0x0F), 2, 1
case b&0xF8 == 0xF0:
p.utf, p.utfNeed, p.utfHave = rune(b&0x07), 3, 1
default:
t.print(0xFFFD)
}
}
func (t *Terminal) escape(b byte) {
p := &t.p
switch {
case b < 0x20:
t.control(b)
return
case b == 0x7F:
return
}
p.keep(b)
switch {
case b < 0x30:
p.inter = b
p.st = stEscInter
case b == '[':
p.st, p.prefix, p.inter, p.digits = stCSI, 0, 0, false
p.ps.n, p.ps.sub = 0, 0
case b == ']':
p.st, p.osc = stOSC, p.osc[:0]
case b == 'P' || b == 'X' || b == '^' || b == '_':
p.st, p.strKind = stString, b
default:
p.st = stGround
t.esc(0, b)
}
}
func (t *Terminal) csiByte(b byte) {
p := &t.p
if b < 0x20 {
t.control(b)
return
}
if b == 0x7F {
return
}
p.keep(b)
if b >= 0x40 {
state := p.st
p.st = stGround
if state != stCSIIgnore {
if p.ps.n > 0 || p.digits {
if !p.digits && p.ps.n < maxParams {
p.ps.v[p.ps.n] = -1
}
p.ps.n = min(p.ps.n+1, maxParams)
}
t.csi(b)
}
return
}
if p.st == stCSIIgnore {
return
}
if b < 0x30 {
p.inter = b
p.st = stCSIInter
return
}
if p.st == stCSIInter {
p.st = stCSIIgnore
return
}
switch {
case b <= '9':
i := p.ps.n
if i >= maxParams {
return
}
if !p.digits {
p.ps.v[i] = 0
p.digits = true
}
if v := p.ps.v[i]*10 + int32(b-'0'); v <= 1<<20 {
p.ps.v[i] = v
}
case b == ';' || b == ':':
i := p.ps.n
if i < maxParams {
if !p.digits {
p.ps.v[i] = -1
}
p.ps.n++
if b == ':' && p.ps.n < maxParams {
p.ps.sub |= 1 << uint(p.ps.n)
}
}
p.digits = false
default: // < = > ?
if p.ps.n == 0 && !p.digits && p.prefix == 0 {
p.prefix = b
} else {
p.st = stCSIIgnore
}
}
}
// pending is what of an unfinished sequence a snapshot ends with, so that
// the bytes after the snapshot's offset complete it; partial is the length
// of an unfinished UTF-8 character, which a snapshot leaves out (it is
// sent again from its first byte).
func (p *parser) pending() (seq []byte, partial int) {
switch p.st {
case stGround:
return nil, p.utfHave
case stOSC:
seq = append([]byte("\x1b]"), p.osc...)
case stString:
seq = []byte{0x1B, p.strKind}
default:
return append([]byte(nil), p.seq...), 0
}
if p.strEsc {
seq = append(seq, 0x1B)
}
return seq, 0
}
+100
View File
@@ -0,0 +1,100 @@
package termstate
import (
"fmt"
"math/rand"
"strings"
"testing"
)
// randomOutput mixes text and the sequences full-screen programs write.
func randomOutput(r *rand.Rand, n int) []byte {
pieces := []func() string{
func() string {
s := strings.Repeat(string(rune('a'+r.Intn(26))), 1+r.Intn(30))
if r.Intn(4) == 0 {
// A repeat follows the character it repeats.
s += fmt.Sprintf("\x1b[%db", r.Intn(30))
}
return s
},
func() string { return []string{"日本", "é", "é", "😀", "€", "​"}[r.Intn(6)] },
func() string { return []string{"\r", "\n", "\r\n", "\t", "\b", "\x0e", "\x0f", "\x07"}[r.Intn(8)] },
func() string { return fmt.Sprintf("\x1b[%d;%dH", r.Intn(12), r.Intn(30)) },
func() string { return fmt.Sprintf("\x1b[%d%c", r.Intn(4), "ABCDEFGIJKLMPSTXZ@`adeg"[r.Intn(23)]) },
func() string { return fmt.Sprintf("\x1b[%d;%dr", r.Intn(10), r.Intn(12)) },
func() string {
return fmt.Sprintf("\x1b[%sm", []string{"0", "1", "4:3", "7", "31", "38;5;99", "48;2;1;2;3", "38:2::4:5:6", "22;24;27", "44", ""}[r.Intn(11)])
},
func() string {
modes := []int{1, 5, 6, 7, 12, 25, 47, 66, 1000, 1002, 1003, 1004, 1006, 1015, 1047, 1048, 1049, 2004}
return fmt.Sprintf("\x1b[?%d%c", modes[r.Intn(len(modes))], "hl"[r.Intn(2)])
},
func() string {
return []string{"\x1b[4h", "\x1b[4l", "\x1b[20h", "\x1b[20l", "\x1b[3 q", "\x1b[!p"}[r.Intn(6)]
},
func() string {
return []string{"\x1b7", "\x1b8", "\x1bD", "\x1bE", "\x1bM", "\x1bH", "\x1b=", "\x1b>", "\x1b(0", "\x1b(B", "\x1b)0", "\x1b#8"}[r.Intn(12)]
},
func() string {
return []string{"\x1b]2;t\x07", "\x1b]0;title\x1b\\", "\x1bPq#0;1\x1b\\", "\x1b_apc\x1b\\", "\x1b[>4;1m", "\x1b[?u"}[r.Intn(6)]
},
func() string { return "\x1bc" },
}
var b strings.Builder
for b.Len() < n {
i := r.Intn(len(pieces))
if i == len(pieces)-1 && r.Intn(20) != 0 {
continue
}
b.WriteString(pieces[i]())
}
return []byte(b.String())
}
// Snapshots of random output at random cuts reproduce the state, and the
// rest of the output then gives the same state as writing it all.
func TestSnapshotRandomOutput(t *testing.T) {
for seed := int64(0); seed < 500; seed++ {
r := rand.New(rand.NewSource(seed))
stream := randomOutput(r, 3000)
cols, rows := 10+r.Intn(30), 3+r.Intn(10)
whole := New(cols, rows, 20)
whole.Write(stream)
for k := 0; k < 8; k++ {
cut := r.Intn(len(stream) + 1)
term := New(cols, rows, 20)
term.Write(stream[:cut])
if term.cur.origin && (term.cur.y < term.top || term.cur.y > term.bottom) {
// Origin mode with the cursor outside the scroll region (a
// DECRC can leave it there) has no sequence to recreate it.
continue
}
rep := replica(term, stream[:cut])
sameState(t, fmt.Sprintf("seed %d cut %d", seed, cut), term, rep)
rep.Write(stream[cut:])
sameState(t, fmt.Sprintf("seed %d cut %d then rest", seed, cut), whole, rep)
}
}
}
// Arbitrary bytes and resizes never panic.
func TestArbitraryBytes(t *testing.T) {
r := rand.New(rand.NewSource(1))
term := New(13, 5, 7)
buf := make([]byte, 4096)
for i := 0; i < 400; i++ {
r.Read(buf)
for j := range buf {
if r.Intn(4) == 0 {
buf[j] = "\x1b[;?0123456789mHJKr\x07\n\r"[r.Intn(21)]
}
}
term.Write(buf)
if i%50 == 0 {
term.Resize(1+r.Intn(40), 1+r.Intn(20))
}
snap, _ := term.Snapshot()
New(term.cols, term.rows, 7).Write(snap)
}
}
+76
View File
@@ -0,0 +1,76 @@
package termstate
// Resize changes the terminal's size without reflowing, as the app's live
// emulator does: narrowing cuts rows (scrollback too) at the new width;
// fewer rows move the rows above the cursor into the scrollback (main
// screen) so the cursor's row stays on screen; more rows bring scrollback
// back. The scroll region becomes the whole screen.
func (t *Terminal) Resize(cols, rows int) {
cols, rows = max(cols, 1), max(rows, 1)
if cols == t.cols && rows == t.rows {
return
}
if cols < t.cols {
for _, lines := range [][]*line{t.main.lines, t.alt.lines, t.history} {
for _, l := range lines {
l.truncate(cols)
}
}
}
mainY, altY := &t.main.saved.y, &t.alt.saved.y
if t.scr == &t.main {
mainY = &t.cur.y
} else {
altY = &t.cur.y
}
t.main.lines = t.resizeRows(t.main.lines, rows, cols, mainY, true)
t.alt.lines = t.resizeRows(t.alt.lines, rows, cols, altY, false)
// The last row's continuation (if any) is gone.
t.main.lines[rows-1].cont, t.alt.lines[rows-1].cont = false, false
old := t.tabs
t.cols, t.rows = cols, rows
t.resetTabs()
copy(t.tabs, old)
t.top, t.bottom = 0, rows-1
t.cur.x, t.cur.y = min(t.cur.x, cols-1), min(max(t.cur.y, 0), rows-1)
t.cur.wrap = t.cur.wrap && t.cur.x == cols-1
for _, s := range []*screen{&t.main, &t.alt} {
s.saved.x, s.saved.y = min(s.saved.x, cols-1), min(max(s.saved.y, 0), rows-1)
}
}
// resizeRows gives one screen rows rows, keeping the row at *anchor
// visible and moving it with the content.
func (t *Terminal) resizeRows(lines []*line, rows, cols int, anchor *int, main bool) []*line {
n := len(lines)
if rows < n {
push := min(max(0, *anchor-(rows-1)), n-rows)
for _, l := range lines[:push] {
if main {
t.keep(l)
}
}
*anchor -= push
return append([]*line(nil), lines[push:push+rows]...)
}
resized := make([]*line, 0, rows)
if main {
var back []*line
for len(back) < rows-n {
l := t.popScrollback()
if l == nil {
break
}
back = append(back, l)
}
for i := len(back) - 1; i >= 0; i-- {
resized = append(resized, back[i])
}
*anchor += len(back)
}
resized = append(resized, lines...)
for len(resized) < rows {
resized = append(resized, &line{})
}
return resized
}
+347
View File
@@ -0,0 +1,347 @@
package termstate
import "strconv"
// Snapshot returns an escape sequence stream that brings a terminal of the
// same size, from any state, to this one: it resets the terminal (RIS and
// ED 3), draws the scrollback and the main screen row by row (soft-wrapped
// rows wrap again), switches to the alternate screen and draws it when that
// is in use, then restores the saved cursors, tab stops, scroll region,
// cursor (including a pending wrap), modes, character sets, pen and title.
// It ends with the start of a sequence still unfinished in the output, so
// the bytes written next complete it.
//
// partial is how many of the newest bytes written are an unfinished UTF-8
// character, which the stream leaves out: the caller sends those bytes again
// after it.
func (t *Terminal) Snapshot() (out []byte, partial int) {
w := &snapWriter{t: t}
w.raw("\x1bc\x1b[3J")
if t.title != "" {
w.raw("\x1b]2;" + t.title + "\x07")
}
if t.scr != &t.alt && (t.alt.savedValid || !emptyRows(t.alt.lines)) {
// The alternate screen not in use: what a switch with 47 or 1047
// (which do not clear it) would show again.
w.raw("\x1b[?47h")
w.altScreen()
if t.alt.savedValid {
w.saved(&t.alt, "\x1b7")
}
w.raw("\x1b[?47l\x1b[H")
}
w.mainScreen()
if t.scr == &t.alt {
if t.main.savedValid {
// 1049 saves the main screen's cursor as it switches.
w.saved(&t.main, "\x1b[?1049h")
} else {
// Nothing saved: switch without saving (the reset cleared it).
w.raw("\x1b[?47h")
}
w.altScreen()
if t.alt.savedValid {
w.saved(&t.alt, "\x1b7")
}
} else if t.main.savedValid {
w.saved(&t.main, "\x1b7")
}
w.tabs()
if t.top != 0 || t.bottom != t.rows-1 {
w.raw("\x1b[" + strconv.Itoa(t.top+1) + ";" + strconv.Itoa(t.bottom+1) + "r")
}
w.cursor()
w.modes()
w.pen(t.cur.pen)
seq, partial := t.p.pending()
w.b = append(w.b, seq...)
return w.b, partial
}
type snapWriter struct {
t *Terminal
b []byte
cur Attr
}
func (w *snapWriter) raw(s string) { w.b = append(w.b, s...) }
func (w *snapWriter) num(n int) { w.b = strconv.AppendInt(w.b, int64(n), 10) }
// goTo is CUP to row, col (zero-based, absolute).
func (w *snapWriter) goTo(row, col int) {
w.raw("\x1b[")
w.num(row + 1)
w.b = append(w.b, ';')
w.num(col + 1)
w.b = append(w.b, 'H')
}
// mainScreen writes the scrollback then the main screen's rows, each after
// a line break unless the row before wrapped into it.
func (w *snapWriter) mainScreen() {
t := w.t
n := t.scrollbackLen()
total := n + len(t.main.lines)
at := func(i int) *line {
if i < n {
return t.scrollbackLine(i)
}
return t.main.lines[i-n]
}
for i := 0; i < total; i++ {
l := at(i)
wraps := l.cont && i+1 < total
w.row(l, wraps)
if wraps && at(i+1).empty() {
// Wrap into the empty row with a space, then erase it again.
w.pen(Attr{})
w.raw(" \b\x1b[K")
}
if !wraps && i+1 < total {
if w.cur.Bg != 0 {
// A scrolled-in row takes the pen's background.
w.pen(Attr{})
}
w.raw("\r\n")
}
}
}
// altScreen draws each row of the alternate screen at its position.
func (w *snapWriter) altScreen() {
for y, l := range w.t.alt.lines {
if len(l.cells) == 0 {
continue
}
w.goTo(y, 0)
w.row(l, false)
}
}
// row writes l's cells from the cursor at its start; full writes every
// column (blank ones as spaces), so the next character wraps.
func (w *snapWriter) row(l *line, full bool) {
n := len(l.cells)
if full {
n = w.t.cols
} else {
for n > 0 && l.cells[n-1] == (Cell{}) {
n--
}
}
for x := 0; x < n; x++ {
var c Cell
if x < len(l.cells) {
c = l.cells[x]
}
if c.Kind == cellWideTail {
continue
}
w.cell(l, x, c)
}
}
func (w *snapWriter) cell(l *line, x int, c Cell) {
w.pen(c.A)
if c.R == 0 {
w.b = append(w.b, ' ')
} else {
w.b = append(w.b, string(c.R)...)
}
if l.marks != nil {
w.b = append(w.b, l.marks[x]...)
}
}
// saved places the cursor, pen and character sets of a saved cursor of
// screen s and writes then (which saves them), then sets ASCII again for
// what follows. (Origin mode saved with a cursor is not restored.)
func (w *snapWriter) saved(s *screen, then string) {
c := s.saved
w.place(s.lines[c.y], c.y, c.x, c.wrap, false)
w.pen(c.pen)
w.charsets(c)
w.raw(then)
if c.charsets != [2]byte{'B', 'B'} || c.shift != 0 {
w.raw("\x1b(B\x1b)B\x0f")
}
}
func (w *snapWriter) charsets(c cursor) {
if g := c.charsets[0]; g != 'B' {
w.raw("\x1b(" + string(rune(g)))
}
if g := c.charsets[1]; g != 'B' {
w.raw("\x1b)" + string(rune(g)))
}
if c.shift == 1 {
w.raw("\x0e")
}
}
// tabs sets the tab stops when they are not the default ones.
func (w *snapWriter) tabs() {
t := w.t
custom := false
for x, set := range t.tabs {
if set != (x > 0 && x%8 == 0) {
custom = true
break
}
}
if !custom {
return
}
w.raw("\x1b[3g")
for x, set := range t.tabs {
if set {
w.goTo(0, x)
w.raw("\x1bH")
}
}
}
// cursor places the cursor (in origin mode, after setting it).
func (w *snapWriter) cursor() {
t := w.t
row := t.cur.y
if t.cur.origin {
w.raw("\x1b[?6h")
row -= t.top
}
w.place(t.scr.lines[t.cur.y], row, t.cur.x, t.cur.wrap, true)
}
// place moves the cursor to column x of row (a CUP row) showing l. A
// pending wrap is recreated by writing the last column's cell again; with
// repeat, the cell before the cursor is written again when it holds the
// last character written, so a repeat (REP) that follows repeats it.
func (w *snapWriter) place(l *line, row, x int, wrap, repeat bool) {
t := w.t
at := func(x int) Cell {
if x < len(l.cells) {
return l.cells[x]
}
return Cell{}
}
if wrap {
x = t.cols - 1
if at(x).Kind == cellWideTail && x > 0 {
x--
}
w.goTo(row, x)
w.cell(l, x, at(x))
return
}
last := x - 1
if last > 0 && at(last).Kind == cellWideTail {
last--
}
c := at(max(last, 0))
if !repeat || last < 0 || c.R == 0 || c.R != t.lastChar || (c.Kind == cellWide && last+2 != x) {
w.goTo(row, x)
return
}
w.goTo(row, last)
w.cell(l, last, c)
}
func (w *snapWriter) modes() {
t := w.t
m := t.m
flag := func(on bool, s string) {
if on {
w.raw(s)
}
}
flag(!m.autowrap, "\x1b[?7l")
flag(m.insert, "\x1b[4h")
flag(m.newline, "\x1b[20h")
flag(m.appCursor, "\x1b[?1h")
flag(m.appKeypad, "\x1b=")
flag(m.reverse, "\x1b[?5h")
flag(m.cursorBlink, "\x1b[?12h")
flag(!m.cursorVisible, "\x1b[?25l")
for _, mode := range []int{m.mouse, m.mouseEncoding} {
if mode != 0 {
w.raw("\x1b[?")
w.num(mode)
w.b = append(w.b, 'h')
}
}
flag(m.focus, "\x1b[?1004h")
flag(m.bracketedPaste, "\x1b[?2004h")
flag(m.altScroll, "\x1b[?1007h")
if t.cursorShape != 0 {
w.raw("\x1b[")
w.num(t.cursorShape)
w.raw(" q")
}
w.charsets(t.cur)
}
// pen switches the written pen to a.
func (w *snapWriter) pen(a Attr) {
if a == w.cur {
return
}
w.cur = a
w.raw("\x1b[0")
flags := []struct {
bit uint16
code string
}{
{attrBold, ";1"}, {attrFaint, ";2"}, {attrItalic, ";3"}, {attrBlink, ";5"},
{attrInverse, ";7"}, {attrHidden, ";8"}, {attrStrike, ";9"}, {attrOverline, ";53"},
}
for _, f := range flags {
if a.Flags&f.bit != 0 {
w.raw(f.code)
}
}
switch u := a.underline(); u {
case 0:
case 1:
w.raw(";4")
default:
w.raw(";4:")
w.num(u)
}
w.color(a.Fg, 30, 90, "38")
w.color(a.Bg, 40, 100, "48")
w.b = append(w.b, 'm')
}
func (w *snapWriter) color(c Color, base, bright int, extended string) {
switch c & colorKind {
case colorIndexed:
n := int(c & 0xFF)
w.b = append(w.b, ';')
switch {
case n < 8:
w.num(base + n)
case n < 16:
w.num(bright + n - 8)
default:
w.raw(extended + ";5;")
w.num(n)
}
case colorRGB:
w.raw(";" + extended + ";2;")
w.num(int(c>>16) & 0xFF)
w.b = append(w.b, ';')
w.num(int(c>>8) & 0xFF)
w.b = append(w.b, ';')
w.num(int(c) & 0xFF)
}
}
func emptyRows(lines []*line) bool {
for _, l := range lines {
if len(l.cells) > 0 {
return false
}
}
return true
}
+163
View File
@@ -0,0 +1,163 @@
package termstate
import (
"fmt"
"math/rand"
"strings"
"testing"
)
// replica is a fresh terminal of t's size brought to t's state by t's
// snapshot (and the unfinished character the snapshot leaves out).
func replica(t *Terminal, written []byte) *Terminal {
snap, partial := t.Snapshot()
r := New(t.cols, t.rows, t.limit)
// Whatever state it was in before, the snapshot resets it first.
r.Write([]byte("\x1b[?1049h\x1b[?1000h\x1b[5;9r\x1b[31mjunk\x1b(0"))
r.Write(snap)
r.Write(written[len(written)-partial:])
return r
}
func sameState(t *testing.T, what string, want, got *Terminal) {
t.Helper()
w, g := dump(want), dump(got)
if w == g {
return
}
wl, gl := strings.Split(w, "\n"), strings.Split(g, "\n")
for i := range min(len(wl), len(gl)) {
if wl[i] != gl[i] {
t.Fatalf("%s: line %d differs:\nwant %s\ngot %s", what, i, wl[i], gl[i])
}
}
t.Fatalf("%s: dumps differ in length %d vs %d", what, len(wl), len(gl))
}
// shellThenTUI is a shell session (history past the scrollback), then a
// full-screen program that sets mouse, bracketed paste, application
// cursor and keypad modes, a scroll region and colours and draws frames
// until it has written more than limit bytes.
func shellThenTUI(limit int) (shell, tui []byte) {
var b strings.Builder
for i := 0; i < 3000; i++ {
fmt.Fprintf(&b, "$ echo line %d\r\nline %d\r\n", i, i)
}
b.WriteString("$ nvim\r\n")
shell = []byte(b.String())
b.Reset()
b.WriteString("\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[?1h\x1b=\x1b[?25l\x1b[2 q\x1b]2;nvim file.go\x07")
r := rand.New(rand.NewSource(7))
for frame := 0; b.Len() < limit; frame++ {
b.WriteString("\x1b[1;23r\x1b[H\x1b[2J")
for y := 1; y <= 23; y++ {
fmt.Fprintf(&b, "\x1b[%d;1H\x1b[38;5;%dm\x1b[48;2;%d;%d;%dm%4d \x1b[0;1m%s\x1b[0m", y, r.Intn(256), r.Intn(256), r.Intn(256), r.Intn(256), frame*23+y, strings.Repeat("é日x", r.Intn(20)))
}
fmt.Fprintf(&b, "\x1b[r\x1b[24;1H\x1b[7m-- INSERT -- frame %d\x1b[K\x1b[0m\x1b[5;7H", frame)
}
return shell, []byte(b.String())
}
// A full-screen program that wrote more than the retained tail is
// restored exactly: its screen and modes, and underneath the shell's
// screen and scrollback, which its exit brings back.
func TestSnapshotRestoresFullScreenProgramAndShell(t *testing.T) {
shell, tui := shellThenTUI(1200 << 10)
term := New(80, 24, DefaultScrollback)
term.Write(shell)
term.Write(tui)
if len(tui) <= 1<<20 || term.scr != &term.alt {
t.Fatalf("tui wrote %d bytes, alt=%v", len(tui), term.scr == &term.alt)
}
r := replica(term, tui)
sameState(t, "after snapshot", term, r)
if !r.m.bracketedPaste || r.m.mouse != 1002 || r.m.mouseEncoding != 1006 || !r.m.appCursor || !r.m.appKeypad || r.m.cursorVisible || r.title != "nvim file.go" {
t.Fatalf("modes = %+v title %q", r.m, r.title)
}
// The program exits: the shell's screen and history come back.
exit := []byte("\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?1l\x1b>\x1b[?25h\x1b[?1049l$ ls\r\nfile.go\r\n$ ")
term.Write(exit)
r.Write(exit)
sameState(t, "after exit", term, r)
screen := text(r)
if !strings.Contains(screen, "line 2999") || !strings.Contains(screen, "$ nvim") || !strings.Contains(screen, "file.go") || strings.Contains(screen, "INSERT") {
t.Fatalf("main screen after exit:\n%s", screen)
}
h := history(r)
if len(h) != DefaultScrollback || !strings.HasPrefix(h[len(h)-1], "line ") {
t.Fatalf("scrollback %d lines, last %q", len(h), h[len(h)-1])
}
}
// Wrapped rows, wide and combining characters, a pending wrap, DEC line
// drawing, origin mode, tab stops, insert mode and the saved cursor.
func TestSnapshotRestoresCursorAndModes(t *testing.T) {
term := New(20, 6, 50)
stream := []byte("" +
"0123456789abcdefghijKLMNO\r\n" + // wraps
"wide 日本語 é \x1b[4:3mcurly\x1b[24m\r\n" +
"\x1b(0lqqk\x1b(B \x0e\x1b)0abc\x0f\r\n" +
"\x1b[3g\x1b[1;4H\x1bH\x1b[1;11H\x1bH" +
"\x1b[44m\x1b[2K\x1b[0m\x1b[3;18H\x1b7\x1b[31;1m" +
"\x1b[2;5r\x1b[?6h\x1b[4h\x1b[20h\x1b[?7h\x1b[5 q" +
"\x1b[1;1Hxyz\x1b[4;16H\x1b[33;3mendof")
term.Write(stream)
if !term.cur.wrap {
t.Fatalf("no pending wrap: cursor %+v", term.cur)
}
r := replica(term, stream)
sameState(t, "snapshot", term, r)
more := []byte("Q\r\n\tT\x1b8W\x1b[2;1H\x1b[L")
term.Write(more)
r.Write(more)
sameState(t, "after more", term, r)
}
// A snapshot taken between any two bytes of the output, followed by the
// rest of the output, ends in the state of the whole output: unfinished
// escape sequences, strings and characters at the cut are completed.
func TestSnapshotAtEveryCut(t *testing.T) {
stream := []byte("ab\x1b[1;31mred\x1b[0m é日\r\n\x1b]2;titéle\x07\x1b]0;x\x1b\\" +
"\x1bP1$qm\x1b\\\x1b[?2004h\x1b[38:2::10:20:30mrgb\x1b[38;5;200mpal\x1b[m" +
"\x1b[?1049h\x1b[5;5Halt\x1b[?1000;1006h\x1b7\x1b[10;1H\x1b[K\x1b(0q\x1b(B" +
"\x1b[?1049l\x1b[3Cdone\x1b[2;3r\x1b[2;1H\n\n\n\x1b[r€\r\n")
whole := New(16, 8, 10)
whole.Write(stream)
for cut := 0; cut <= len(stream); cut++ {
term := New(16, 8, 10)
term.Write(stream[:cut])
r := replica(term, stream[:cut])
sameState(t, fmt.Sprintf("cut %d", cut), term, r)
r.Write(stream[cut:])
sameState(t, fmt.Sprintf("cut %d then rest", cut), whole, r)
}
}
// The scrollback is bounded and kept in order across the ring's wrap.
func TestScrollbackRing(t *testing.T) {
term := New(10, 3, 5)
for i := 0; i < 20; i++ {
term.Write([]byte(fmt.Sprintf("l%d\r\n", i)))
}
if got := strings.Join(history(term), ","); got != "l13,l14,l15,l16,l17" {
t.Fatalf("history = %s", got)
}
r := replica(term, nil)
sameState(t, "snapshot", term, r)
}
// Resizing keeps the cursor's row: fewer rows push the top into the
// scrollback, more bring it back; a narrower screen cuts rows.
func TestResize(t *testing.T) {
term := New(10, 4, 100)
term.Write([]byte("a\r\nb\r\nc\r\nd12345678"))
term.Resize(6, 2)
if got := text(term); got != "c\nd12345" || term.cur.y != 1 {
t.Fatalf("shrunk = %q cursor %+v", got, term.cur)
}
term.Resize(6, 4)
if got := text(term); got != "a\nb\nc\nd12345" || term.cur.y != 3 {
t.Fatalf("grown = %q cursor %+v", got, term.cur)
}
sameState(t, "snapshot", term, replica(term, nil))
}
+526
View File
@@ -0,0 +1,526 @@
package termstate
import (
"strings"
"github.com/mattn/go-runewidth"
)
// DefaultScrollback is how many lines scrolled off the main screen a
// terminal keeps (and a snapshot redraws).
const DefaultScrollback = 1000
// cursor is the cursor with what DECSC saves alongside it.
type cursor struct {
x, y int
pen Attr
// wrap: the last column was written; the next character wraps first.
wrap bool
origin bool
charsets [2]byte
shift int // 0: G0 is in use, 1: G1 (SO)
}
// screen is the main or the alternate screen.
type screen struct {
lines []*line
// saved is the DECSC cursor of this screen (valid once set).
saved cursor
savedValid bool
}
// modes are the terminal modes a snapshot restores.
type modes struct {
appCursor, reverse, autowrap, cursorBlink, cursorVisible bool
appKeypad, insert, newline, focus, bracketedPaste, altScroll bool
// mouse is the tracking mode (9, 1000, 1001, 1002, 1003, or 0) and
// mouseEncoding the coordinate encoding (1005, 1006, 1015, or 0); as in
// xterm, setting one replaces the previous one.
mouse, mouseEncoding int
}
// Terminal is the emulated state of one pseudo-terminal.
type Terminal struct {
p parser
cols, rows int
main, alt screen
scr *screen
cur cursor
// top and bottom are the scroll region's rows (inclusive).
top, bottom int
m modes
// cursorShape is the DECSCUSR parameter (0: the default).
cursorShape int
tabs []bool
title string
lastChar rune
// history holds the lines scrolled off the main screen, oldest first,
// in a ring of at most limit lines starting at head.
history []*line
head int
limit int
}
var widths = &runewidth.Condition{EastAsianWidth: false, StrictEmojiNeutral: true}
// New returns a terminal of cols x rows that keeps scrollback lines.
func New(cols, rows, scrollback int) *Terminal {
cols, rows = max(cols, 1), max(rows, 1)
t := &Terminal{cols: cols, rows: rows, limit: max(scrollback, 0)}
t.main.lines = newLines(rows)
t.alt.lines = newLines(rows)
t.reset()
return t
}
func newLines(n int) []*line {
lines := make([]*line, n)
for i := range lines {
lines[i] = &line{}
}
return lines
}
// reset is RIS: everything but the scrollback and the title.
func (t *Terminal) reset() {
for _, l := range t.main.lines {
l.reset()
}
for _, l := range t.alt.lines {
l.reset()
}
t.main.savedValid, t.alt.savedValid = false, false
t.scr = &t.main
t.cur = cursor{charsets: [2]byte{'B', 'B'}}
t.top, t.bottom = 0, t.rows-1
t.m = modes{autowrap: true, cursorVisible: true}
t.cursorShape = 0
t.resetTabs()
}
// softReset is DECSTR.
func (t *Terminal) softReset() {
t.m.insert, t.m.appCursor, t.m.appKeypad = false, false, false
t.m.autowrap, t.m.cursorVisible = true, true
t.cur.origin, t.cur.pen, t.cur.wrap = false, Attr{}, false
t.cur.charsets, t.cur.shift = [2]byte{'B', 'B'}, 0
t.top, t.bottom = 0, t.rows-1
t.scr.saved, t.scr.savedValid = cursor{charsets: [2]byte{'B', 'B'}}, true
}
func (t *Terminal) resetTabs() {
t.tabs = make([]bool, t.cols)
for x := 8; x < t.cols; x += 8 {
t.tabs[x] = true
}
}
// Size is the terminal's columns and rows.
func (t *Terminal) Size() (cols, rows int) { return t.cols, t.rows }
// AltScreen reports whether the alternate screen is in use.
func (t *Terminal) AltScreen() bool { return t.scr == &t.alt }
// Text is the screen in use as text, one line per row without trailing
// blanks.
func (t *Terminal) Text() string {
rows := make([]string, len(t.scr.lines))
var b []rune
for y, l := range t.scr.lines {
b = b[:0]
for _, c := range l.cells {
switch {
case c.Kind == cellWideTail:
case c.R == 0:
b = append(b, ' ')
default:
b = append(b, c.R)
}
}
rows[y] = strings.TrimRight(string(b), " ")
}
return strings.Join(rows, "\n")
}
// Write interprets output of the program.
func (t *Terminal) Write(data []byte) {
for i := 0; i < len(data); i++ {
b := data[i]
if t.p.st == stGround && t.p.utfNeed == 0 && b >= 0x20 && b < 0x7F {
j := i + 1
for j < len(data) && data[j] >= 0x20 && data[j] < 0x7F {
j++
}
t.printASCII(data[i:j])
i = j - 1
continue
}
t.advance(b)
}
}
// control executes a C0 control character.
func (t *Terminal) control(b byte) {
switch b {
case 0x08: // BS
t.cur.wrap = false
if t.cur.x > 0 {
t.cur.x--
}
case 0x09: // HT
t.tab(1)
case 0x0A, 0x0B, 0x0C: // LF, VT, FF
t.lineFeed()
if t.m.newline {
t.cur.x = 0
}
case 0x0D: // CR
t.cur.x, t.cur.wrap = 0, false
case 0x0E: // SO
t.cur.shift = 1
case 0x0F: // SI
t.cur.shift = 0
}
}
func (t *Terminal) tab(n int) {
x := t.cur.x
for ; n > 0 && x < t.cols-1; n-- {
x++
for x < t.cols-1 && !t.tabs[x] {
x++
}
}
t.cur.x = x
t.cur.wrap = false
}
func (t *Terminal) backTab(n int) {
x := t.cur.x
for ; n > 0 && x > 0; n-- {
x--
for x > 0 && !t.tabs[x] {
x--
}
}
t.cur.x, t.cur.wrap = x, false
}
// lineFeed moves down a row, scrolling the region at its bottom margin.
// It reports whether the row changed (the cursor moved or the row scrolled
// up): below the region, the last row stays.
func (t *Terminal) lineFeed() bool {
t.cur.wrap = false
switch {
case t.cur.y == t.bottom:
t.scrollUp(1)
case t.cur.y < t.rows-1:
t.cur.y++
default:
return false
}
return true
}
func (t *Terminal) reverseIndex() {
t.cur.wrap = false
switch {
case t.cur.y == t.top:
t.scrollDown(1)
case t.cur.y > 0:
t.cur.y--
}
}
// scrollUp moves the scroll region's rows up n, adding blank rows (default
// background, as the app's emulator does) at its bottom. Rows leaving the
// top of the main screen go to the scrollback.
func (t *Terminal) scrollUp(n int) {
t.shiftUp(t.top, n, t.top == 0 && t.scr == &t.main)
}
// shiftUp moves rows top to the region's bottom up n; the rows leaving at
// top go to the scrollback when keep is set.
func (t *Terminal) shiftUp(top, n int, keep bool) {
bottom := t.bottom
n = min(n, bottom-top+1)
lines := t.scr.lines
for i := 0; i < n; i++ {
gone := lines[top]
copy(lines[top:bottom], lines[top+1:bottom+1])
if keep {
gone = t.keep(gone)
}
gone.reset()
lines[bottom] = gone
}
// Rows that wrapped into a row now gone no longer continue.
t.unpair(top - 1)
if bottom-n >= top {
t.unpair(bottom - n)
}
}
func (t *Terminal) unpair(y int) {
if y >= 0 && y < len(t.scr.lines) {
t.scr.lines[y].cont = false
}
}
// keep adds l to the scrollback and returns a line to reuse in its place
// (the one the full scrollback drops, or a new one).
func (t *Terminal) keep(l *line) *line {
if t.limit == 0 {
return l
}
if len(t.history) < t.limit {
t.history = append(t.history, l)
return &line{}
}
old := t.history[t.head]
t.history[t.head] = l
t.head = (t.head + 1) % len(t.history)
return old
}
// scrollDown moves the scroll region's rows down n, adding blank rows at
// its top.
func (t *Terminal) scrollDown(n int) {
top, bottom := t.top, t.bottom
n = min(n, bottom-top+1)
lines := t.scr.lines
for i := 0; i < n; i++ {
gone := lines[bottom]
copy(lines[top+1:bottom+1], lines[top:bottom])
gone.reset()
lines[top] = gone
}
t.unpair(top - 1)
t.unpair(bottom)
}
// scrollbackLen is the number of lines in the scrollback.
func (t *Terminal) scrollbackLen() int { return len(t.history) }
// scrollbackLine is scrollback line i, oldest first.
func (t *Terminal) scrollbackLine(i int) *line {
return t.history[(t.head+i)%len(t.history)]
}
// popScrollback takes the newest scrollback line back (a taller screen).
func (t *Terminal) popScrollback() *line {
n := len(t.history)
if n == 0 {
return nil
}
if t.head != 0 {
// Unroll the ring so the newest line is last.
t.history = append(t.history[t.head:], t.history[:t.head]...)
t.head = 0
}
l := t.history[n-1]
t.history = t.history[:n-1]
return l
}
// clearScrollback is ED 3.
func (t *Terminal) clearScrollback() {
t.history, t.head = nil, 0
}
func (t *Terminal) charset() byte { return t.cur.charsets[t.cur.shift] }
// printASCII writes a run of printable ASCII characters.
func (t *Terminal) printASCII(s []byte) {
for len(s) > 0 {
if t.charset() != 'B' || t.m.insert || !t.m.autowrap {
for _, b := range s {
t.print(rune(b))
}
return
}
if t.cur.wrap {
t.wrapLine()
}
l := t.scr.lines[t.cur.y]
x := t.cur.x
n := min(len(s), t.cols-x)
l.ensure(x + n)
if l.cells[x].Kind == cellWideTail && x > 0 {
l.clearCell(x - 1)
}
cells := l.cells[x : x+n]
pen := t.cur.pen
for i, b := range s[:n] {
cells[i] = Cell{R: rune(b), A: pen}
}
l.repair(x + n)
if l.marks != nil {
l.dropMarks(x, x+n)
}
t.lastChar = rune(s[n-1])
if x+n >= t.cols {
t.cur.x, t.cur.wrap = t.cols-1, true
} else {
t.cur.x = x + n
}
s = s[n:]
}
}
// wrapLine moves to the next row's start, marking the row as continued.
func (t *Terminal) wrapLine() {
l := t.scr.lines[t.cur.y]
t.cur.x = 0
if t.lineFeed() {
l.cont = true
}
}
// decSpecial is the DEC Special Graphics set for 0x5F to 0x7E.
var decSpecial = []rune(" ◆▒␉␌␍␊°±␤␋┘┐┌└┼⎺⎻─⎼⎽├┤┴┬│≤≥π≠£·")
// print writes one character at the cursor.
func (t *Terminal) print(r rune) {
switch t.charset() {
case '0':
if r >= 0x5F && r <= 0x7E {
r = decSpecial[r-0x5F]
}
case 'A':
if r == '#' {
r = '£'
}
}
w := 1
if r >= 0x7F {
w = widths.RuneWidth(r)
}
if w == 0 {
t.mark(r)
return
}
if t.cur.wrap && t.m.autowrap {
t.wrapLine()
}
t.cur.wrap = false
if w == 2 && t.cur.x == t.cols-1 {
if t.cols < 2 {
return
}
if t.m.autowrap {
edge := t.scr.lines[t.cur.y]
edge.blank(t.cur.x, t.cur.x+1, t.cur.pen.Bg)
edge.repair(t.cur.x - 1)
t.wrapLine()
} else {
t.cur.x--
}
}
l := t.scr.lines[t.cur.y]
x := t.cur.x
if t.m.insert {
t.insertCells(w)
}
l.ensure(x + w)
if l.cells[x].Kind == cellWideTail && x > 0 {
l.clearCell(x - 1)
}
l.cells[x] = Cell{R: r, A: t.cur.pen}
if w == 2 {
l.cells[x].Kind = cellWide
l.cells[x+1] = Cell{A: t.cur.pen, Kind: cellWideTail}
}
l.repair(x + w)
if l.marks != nil {
l.dropMarks(x, x+w)
}
t.lastChar = r
if x+w >= t.cols {
t.cur.x = t.cols - 1
t.cur.wrap = t.m.autowrap
} else {
t.cur.x = x + w
}
}
// mark draws a combining character on the last written cell.
func (t *Terminal) mark(r rune) {
x := t.cur.x
if !t.cur.wrap {
x--
}
l := t.scr.lines[t.cur.y]
if x >= 0 && x < len(l.cells) && l.cells[x].Kind == cellWideTail {
x--
}
if x < 0 || x >= len(l.cells) {
return
}
if l.marks == nil {
l.marks = map[int]string{}
}
if len(l.marks[x]) < 32 {
l.marks[x] += string(r)
}
}
// insertCells is ICH: n blanks at the cursor, the rest of the row shifts
// right (what passes the edge is lost).
func (t *Terminal) insertCells(n int) {
l := t.scr.lines[t.cur.y]
x := t.cur.x
if x >= len(l.cells) {
return
}
n = min(n, t.cols-x)
l.ensure(min(len(l.cells)+n, t.cols))
copy(l.cells[x+n:], l.cells[x:])
l.blank(x, x+n, t.cur.pen.Bg)
l.repair(x - 1)
l.repair(x + n)
// A wide character pushed to the edge lost its tail.
l.repair(len(l.cells) - 1)
l.marks = nil
}
// deleteCells is DCH: n cells at the cursor go, the rest shifts left.
func (t *Terminal) deleteCells(n int) {
l := t.scr.lines[t.cur.y]
x := t.cur.x
t.cur.wrap = false
if x >= len(l.cells) && t.cur.pen.Bg == 0 {
return
}
n = min(n, t.cols-x)
l.ensure(t.cols)
copy(l.cells[x:], l.cells[x+n:])
l.blank(t.cols-n, t.cols, t.cur.pen.Bg)
l.repair(x - 1)
l.repair(x)
l.repair(t.cols - n - 1)
l.marks = nil
}
// insertLines is IL: n blank rows at the cursor's row within the scroll
// region, pushing the rows below down.
func (t *Terminal) insertLines(n int) {
if t.cur.y < t.top || t.cur.y > t.bottom {
return
}
top := t.top
t.top = t.cur.y
t.scrollDown(n)
t.top = top
t.cur.x, t.cur.wrap = 0, false
}
// deleteLines is DL: n rows at the cursor's row go, the region below moves
// up (nothing reaches the scrollback).
func (t *Terminal) deleteLines(n int) {
if t.cur.y < t.top || t.cur.y > t.bottom {
return
}
t.shiftUp(t.cur.y, n, false)
t.cur.x, t.cur.wrap = 0, false
}