From f4ffda713039be790c1487ef6b477256265c21ae Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 26 Nov 2026 00:24:50 +0000 Subject: [PATCH 1/6] Terminal stream bench: frame timings while streaming generated output Co-Authored-By: Claude Opus 5.5 --- app/tool/perf/terminal_stream_bench.dart | 199 +++++++++++++++++++++++ app/tool/perf/terminal_stream_bench.mjs | 72 ++++++++ 2 files changed, 271 insertions(+) create mode 100644 app/tool/perf/terminal_stream_bench.dart create mode 100644 app/tool/perf/terminal_stream_bench.mjs diff --git a/app/tool/perf/terminal_stream_bench.dart b/app/tool/perf/terminal_stream_bench.dart new file mode 100644 index 00000000..bd198076 --- /dev/null +++ b/app/tool/perf/terminal_stream_bench.dart @@ -0,0 +1,199 @@ +// 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&mb=30&rate=30` (the window size sets the grid). +// When the stream ends `window.__benchResult` holds a JSON summary: +// frames, build/raster/total quantiles (ms), rAF interval quantiles (ms), +// MB written, seconds and MB/s. +import 'dart:async'; +import 'dart:convert'; +import 'dart:js_interop'; +import 'dart:ui'; + +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_feed.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_theme.dart'; +import 'package:xterm/xterm.dart'; + +@JS('__benchResult') +external set _benchResult(JSString value); + +void main() { + final params = Uri.base.queryParameters; + runApp(_Bench(params)); +} + +class _Bench extends StatefulWidget { + const _Bench(this.params); + + final Map params; + + @override + State<_Bench> createState() => _BenchState(); +} + +class _BenchState extends State<_Bench> { + late final Terminal _terminal = Terminal(maxLines: 10000); + late final ChatShellTerminalFeed _feed = ChatShellTerminalFeed( + (text, _) => _terminal.write(text), + ); + final List _timings = []; + final List _intervals = []; + Duration? _lastFrame; + Timer? _producer; + final Stopwatch _clock = Stopwatch(); + int _written = 0; + int _counter = 0; + bool _done = false; + + String get _workload => widget.params['workload'] ?? 'seq'; + double get _megabytes => double.tryParse(widget.params['mb'] ?? '') ?? 30; + double get _rate => double.tryParse(widget.params['rate'] ?? '') ?? 30; + + @override + void initState() { + super.initState(); + SchedulerBinding.instance.addTimingsCallback(_onTimings); + SchedulerBinding.instance.addPersistentFrameCallback(_onFrame); + // Let the first frames settle before streaming. + Timer(const Duration(milliseconds: 1500), _start); + } + + void _onTimings(List timings) { + if (_clock.isRunning) _timings.addAll(timings); + } + + void _onFrame(Duration stamp) { + if (_clock.isRunning && _lastFrame != null) { + _intervals.add((stamp - _lastFrame!).inMicroseconds / 1000); + } + _lastFrame = stamp; + } + + void _start() { + _clock.start(); + const tick = Duration(milliseconds: 4); + final perTick = (_rate * 1e6 * tick.inMicroseconds / 1e6).round(); + _producer = Timer.periodic(tick, (_) { + if (_written >= _megabytes * 1e6) { + _producer?.cancel(); + _feed.then(_finish); + return; + } + final chunk = _chunk(perTick); + _written += chunk.length; + _feed.add(chunk, _written); + }); + } + + String _chunk(int size) { + final out = StringBuffer(); + while (out.length < size) { + _counter++; + switch (_workload) { + case 'yes': + out.write('y\r\n'); + case 'unicode': + out.write( + '$_counter รฉ รฑ ไธญๆ–‡ ๐Ÿ˜€ ๐Ÿ‘๐Ÿฝ ๐Ÿ‡ต๐Ÿ‡น โ”‚ โ•ญโ”€โ•ฎ โ–“โ–’โ–‘ \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', + ); + } + default: + out.write('$_counter\r\n'); + } + } + return out.toString(); + } + + void _finish() { + if (_done) return; + _done = true; + // A last frame flushes the engine's batched timings. + SchedulerBinding.instance.scheduleFrame(); + Timer(const Duration(milliseconds: 600), () { + _clock.stop(); + final seconds = _clock.elapsedMicroseconds / 1e6; + List ms(Duration Function(FrameTiming t) pick) => [ + for (final t in _timings) pick(t).inMicroseconds / 1000, + ]; + final result = { + 'workload': _workload, + 'frames': _timings.length, + 'build': _quantiles(ms((t) => t.buildDuration)), + 'raster': _quantiles(ms((t) => t.rasterDuration)), + 'total': _quantiles(ms((t) => t.totalSpan)), + 'interval': _quantiles(_intervals), + 'mb': _written / 1e6, + 'seconds': seconds, + 'mbPerSecond': _written / 1e6 / seconds, + }; + _benchResult = jsonEncode(result).toJS; + // ignore: avoid_print + print('BENCH_RESULT ${jsonEncode(result)}'); + }); + } + + static Map _quantiles(List values) { + if (values.isEmpty) return const {}; + final sorted = [...values]..sort(); + double at(double q) => + sorted[(q * (sorted.length - 1)).round().clamp(0, sorted.length - 1)]; + double round(double v) => (v * 100).roundToDouble() / 100; + return { + 'p50': round(at(0.5)), + 'p90': round(at(0.9)), + 'p99': round(at(0.99)), + 'max': round(sorted.last), + 'mean': round(sorted.reduce((a, b) => a + b) / sorted.length), + }; + } + + @override + void dispose() { + _producer?.cancel(); + _feed.dispose(); + SchedulerBinding.instance.removeTimingsCallback(_onTimings); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + theme: ThemeData(brightness: Brightness.dark), + home: Builder( + builder: (context) => Scaffold( + body: TerminalView( + _terminal, + theme: chatShellTerminalTheme(context), + textStyle: chatShellTerminalStyle(context), + padding: const EdgeInsets.all(8), + readOnly: true, + ), + ), + ), + ); + } +} diff --git a/app/tool/perf/terminal_stream_bench.mjs b/app/tool/perf/terminal_stream_bench.mjs new file mode 100644 index 00000000..8f7bb6b1 --- /dev/null +++ b/app/tool/perf/terminal_stream_bench.mjs @@ -0,0 +1,72 @@ +#!/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] [--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' }, + mb: { type: 'string', default: '30' }, + rate: { type: 'string', default: '30' }, + size: { type: 'string', default: '1280x800' }, + timeout: { type: 'string', default: '120000' }, + }, +}); +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); + 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?.(); +} From 6832ec789ea5d665f3f32db2f7d31221a7b9a913 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 26 Nov 2026 00:33:53 +0000 Subject: [PATCH 2/6] Terminal: find, zoom, scrollback, scroll keys, context menu, bell, link hover, OSC 52/7, cursor blink, stale selection Co-Authored-By: Claude Opus 5.5 --- .../shell/chat_shell_terminal_actions.dart | 97 ++++++++ .../chat/shell/chat_shell_terminal_bell.dart | 94 +++++++ .../chat_shell_terminal_context_menu.dart | 93 +++++++ .../chat_shell_terminal_cursor_blink.dart | 58 +++++ .../shell/chat_shell_terminal_emulator.dart | 63 +++++ .../shell/chat_shell_terminal_events.dart | 87 +++++++ .../chat/shell/chat_shell_terminal_find.dart | 145 +++++++++++ .../shell/chat_shell_terminal_find_bar.dart | 147 +++++++++++ .../shell/chat_shell_terminal_link_hover.dart | 150 ++++++++++++ .../chat/shell/chat_shell_terminal_links.dart | 96 +++++++- .../shell/chat_shell_terminal_search.dart | 97 ++++++++ .../chat_shell_terminal_selection_guard.dart | 63 +++++ .../shell/chat_shell_terminal_session.dart | 93 +++---- .../shell/chat_shell_terminal_shortcuts.dart | 110 +++++++++ .../chat/shell/chat_shell_terminal_theme.dart | 14 +- .../chat/shell/chat_shell_terminal_view.dart | 211 ++++++++-------- .../chat_shell_terminal_view_features.dart | 230 ++++++++++++++++++ .../settings/settings_font_section.dart | 7 +- .../settings/settings_terminal_controls.dart | 76 ++++++ .../settings/settings_terminal_section.dart | 5 +- app/lib/features/terminal/terminal_hub.dart | 8 +- .../features/terminal/terminal_layout.dart | 49 ++++ app/lib/features/terminal/terminal_tab.dart | 41 +++- .../features/terminal/terminal_tab_strip.dart | 20 +- .../shell/chat_shell_terminal_find_test.dart | 138 +++++++++++ .../chat/shell/terminal_view_harness.dart | 191 +++++++++++++++ .../xterm/lib/src/core/buffer/buffer.dart | 18 +- app/third_party/xterm/lib/src/terminal.dart | 16 +- .../xterm/lib/src/terminal_view.dart | 13 + app/third_party/xterm/lib/src/ui/render.dart | 17 +- .../xterm/lib/src/utils/circular_buffer.dart | 6 + app/third_party/xterm/lib/ui.dart | 1 + 32 files changed, 2260 insertions(+), 194 deletions(-) create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_actions.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_bell.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_context_menu.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_cursor_blink.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_emulator.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_events.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_find.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_link_hover.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_search.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_selection_guard.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_shortcuts.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_view_features.dart create mode 100644 app/lib/features/settings/settings_terminal_controls.dart create mode 100644 app/test/features/chat/shell/chat_shell_terminal_find_test.dart create mode 100644 app/test/features/chat/shell/terminal_view_harness.dart diff --git a/app/lib/features/chat/shell/chat_shell_terminal_actions.dart b/app/lib/features/chat/shell/chat_shell_terminal_actions.dart new file mode 100644 index 00000000..d62d55ce --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_actions.dart @@ -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 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 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), + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_bell.dart b/app/lib/features/chat/shell/chat_shell_terminal_bell.dart new file mode 100644 index 00000000..dd61e94e --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_bell.dart @@ -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 bells; + final bool enabled; + final Widget child; + + @override + State createState() => _ChatShellBellFlashState(); +} + +class _ChatShellBellFlashState extends State + 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, + ), + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_context_menu.dart b/app/lib/features/chat/shell/chat_shell_terminal_context_menu.dart new file mode 100644 index 00000000..750474b7 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_context_menu.dart @@ -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 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 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( + 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 createState() => _ChatShellNoBrowserMenuState(); +} + +class _ChatShellNoBrowserMenuState extends State { + 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, + ); +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_cursor_blink.dart b/app/lib/features/chat/shell/chat_shell_terminal_cursor_blink.dart new file mode 100644 index 00000000..7d817239 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_cursor_blink.dart @@ -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 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(); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_emulator.dart b/app/lib/features/chat/shell/chat_shell_terminal_emulator.dart new file mode 100644 index 00000000..08bc75d7 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_emulator.dart @@ -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); + } + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_events.dart b/app/lib/features/chat/shell/chat_shell_terminal_events.dart new file mode 100644 index 00000000..bf7b3bde --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_events.dart @@ -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 bells = ValueNotifier(0); + + /// The folder the program last reported (OSC 7), as a path; null before. + final ValueNotifier workingDirectory = ValueNotifier(null); + + /// How many views draw this terminal now: a bell while none does dots the + /// terminal's tab. + final ValueNotifier viewers = ValueNotifier(0); + + final List _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; +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_find.dart b/app/lib/features/chat/shell/chat_shell_terminal_find.dart new file mode 100644 index 00000000..56adc5be --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_find.dart @@ -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 _matches = const []; + final List _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(); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart b/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart new file mode 100644 index 00000000..3096fb14 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_find_bar.dart @@ -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 onStep; + final VoidCallback onClose; + + @override + State createState() => + _ChatShellTerminalFindBarState(); +} + +class _ChatShellTerminalFindBarState extends State { + 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), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_link_hover.dart b/app/lib/features/chat/shell/chat_shell_terminal_link_hover.dart new file mode 100644 index 00000000..86693b25 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_link_hover.dart @@ -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 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 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 createState() => _ChatShellLinkUnderlineState(); +} + +class _ChatShellLinkUnderlineState extends State { + 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; +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_links.dart b/app/lib/features/chat/shell/chat_shell_terminal_links.dart index a445ffa6..a64e9cef 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_links.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_links.dart @@ -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 = []; 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; } diff --git a/app/lib/features/chat/shell/chat_shell_terminal_search.dart b/app/lib/features/chat/shell/chat_shell_terminal_search.dart new file mode 100644 index 00000000..ed0e7fef --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_search.dart @@ -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 chatShellTerminalSearch( + Buffer buffer, + String query, { + bool caseSensitive = false, + int limit = chatShellSearchLimit, +}) { + final matches = []; + 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 = []; + 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 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(); diff --git a/app/lib/features/chat/shell/chat_shell_terminal_selection_guard.dart b/app/lib/features/chat/shell/chat_shell_terminal_selection_guard.dart new file mode 100644 index 00000000..a46e54ab --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_selection_guard.dart @@ -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); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_session.dart b/app/lib/features/chat/shell/chat_shell_terminal_session.dart index b8cfaba4..82b74a7f 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_session.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_session.dart @@ -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; @@ -146,7 +163,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 +223,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); - } - } -} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_shortcuts.dart b/app/lib/features/chat/shell/chat_shell_terminal_shortcuts.dart new file mode 100644 index 00000000..d8e37498 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_shortcuts.dart @@ -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 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, + }; +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_theme.dart b/app/lib/features/chat/shell/chat_shell_terminal_theme.dart index 319b86af..3c3a5a37 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_theme.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_theme.dart @@ -53,16 +53,22 @@ 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. +TerminalStyle chatShellTerminalStyle(BuildContext context, {double? fontSize}) { return TerminalStyle( fontFamily: appMonospaceFamily, - fontSize: (body.fontSize ?? 14) * 0.95, + fontSize: fontSize ?? chatShellTerminalDefaultFontSize(context), height: 1.3, ); } +/// 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) { diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view.dart b/app/lib/features/chat/shell/chat_shell_terminal_view.dart index 2dfc70c9..3317937b 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view.dart @@ -6,71 +6,34 @@ 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_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 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 +54,68 @@ class ChatShellTerminalView extends StatefulWidget { State createState() => _ChatShellTerminalViewState(); } -class _ChatShellTerminalViewState extends State { - final TerminalController _controller = TerminalController(); - final FocusNode _focus = FocusNode(debugLabel: 'chat-shell-terminal'); +class _ChatShellTerminalViewState extends State + with + SingleTickerProviderStateMixin, + ChatShellTerminalFeatures { + @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 viewKey = GlobalKey(); final Map _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,13 +128,14 @@ class _ChatShellTerminalViewState extends State { ); 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. + /// 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) { @@ -176,49 +145,68 @@ class _ChatShellTerminalViewState extends State { if (!keyboard.isControlPressed && !keyboard.isMetaPressed) { return KeyEventResult.ignored; } - return _copySelection() ? KeyEventResult.handled : KeyEventResult.ignored; + return actions.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 @@ -242,6 +230,13 @@ class _ChatShellTerminalViewState extends State { 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( diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart b/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart new file mode 100644 index 00000000..e77764e7 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart @@ -0,0 +1,230 @@ +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.dart'; +import 'chat_shell_terminal_find_bar.dart'; +import 'chat_shell_terminal_link_hover.dart'; +import 'chat_shell_terminal_selection_guard.dart'; +import 'chat_shell_terminal_session.dart'; +import 'chat_shell_terminal_shortcuts.dart'; + +/// The terminal view's own features around the emulator: find in the +/// scrollback, text size, scrolling keys, the context menu, link hover, +/// the cursor blink, stale-selection clearing and the OSC 52 toast. The +/// view supplies its emulator's parts and calls [initFeatures] and +/// [disposeFeatures]. +mixin ChatShellTerminalFeatures + on State, TickerProvider { + ChatShellTerminalSession get session; + TerminalController get controller; + FocusNode get focus; + ScrollController get scroll; + GlobalKey get viewKey; + + late final ChatShellTerminalActions actions; + late final ChatShellLinkHover hover; + late final ChatShellCursorBlink blink; + late final ChatShellSelectionGuard _guard; + final FocusNode _findFocus = FocusNode(debugLabel: 'terminal-find'); + ChatShellTerminalFind? _find; + bool _reduceMotion = false; + bool _hoverQueued = 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); + session.events.attach(_copied); + } + + void disposeFeatures() { + session.events.detach(_copied); + _terminal.removeListener(_terminalChanged); + scroll.removeListener(hover.refresh); + _guard.dispose(); + blink.dispose(); + hover.dispose(); + _find?.dispose(); + _findFocus.dispose(); + } + + @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; + } + + /// 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: _terminal, + controller: controller, + hit: scheme.tertiary.withValues(alpha: 0.3), + current: scheme.tertiary.withValues(alpha: 0.6), + ); + }); + } + + 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, + ), + ), + ), + ], + ); + } + + /// [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 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(); + } +} diff --git a/app/lib/features/settings/settings_font_section.dart b/app/lib/features/settings/settings_font_section.dart index d692daf3..35aa647a 100644 --- a/app/lib/features/settings/settings_font_section.dart +++ b/app/lib/features/settings/settings_font_section.dart @@ -188,7 +188,6 @@ class _SettingsFontSectionState extends State { /// The platform's own interface family (Roboto), independent of the font the /// theme currently applies. -String? _systemFamily(BuildContext context) => - Typography.material2021( - platform: Theme.of(context).platform, - ).black.bodyLarge?.fontFamily; +String? _systemFamily(BuildContext context) => Typography.material2021( + platform: Theme.of(context).platform, +).black.bodyLarge?.fontFamily; diff --git a/app/lib/features/settings/settings_terminal_controls.dart b/app/lib/features/settings/settings_terminal_controls.dart new file mode 100644 index 00000000..326b3a0b --- /dev/null +++ b/app/lib/features/settings/settings_terminal_controls.dart @@ -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 _fontSizes = [10, 11, 12, 13, 14, 15, 16, 18, 20, 24]; + +/// Appearance โ†’ Terminal's text size, scrollback and bell controls. +List 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( + 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( + 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); + }, + ); +} diff --git a/app/lib/features/settings/settings_terminal_section.dart b/app/lib/features/settings/settings_terminal_section.dart index 400a30a8..a30056bf 100644 --- a/app/lib/features/settings/settings_terminal_section.dart +++ b/app/lib/features/settings/settings_terminal_section.dart @@ -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), ], ); }, diff --git a/app/lib/features/terminal/terminal_hub.dart b/app/lib/features/terminal/terminal_hub.dart index cf0b39c2..516d8968 100644 --- a/app/lib/features/terminal/terminal_hub.dart +++ b/app/lib/features/terminal/terminal_hub.dart @@ -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 _links = {}; bool _active = false; final List _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()); diff --git a/app/lib/features/terminal/terminal_layout.dart b/app/lib/features/terminal/terminal_layout.dart index 227fab51..06c0bfe1 100644 --- a/app/lib/features/terminal/terminal_layout.dart +++ b/app/lib/features/terminal/terminal_layout.dart @@ -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 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 load(); Future 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; diff --git a/app/lib/features/terminal/terminal_tab.dart b/app/lib/features/terminal/terminal_tab.dart index edfcf958..7f6546b0 100644 --- a/app/lib/features/terminal/terminal_tab.dart +++ b/app/lib/features/terminal/terminal_tab.dart @@ -8,6 +8,7 @@ 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'; /// One open machine terminal in the app: its record, the output held for @@ -22,6 +23,7 @@ class TerminalTab extends ChangeNotifier { required this.machineName, required this._gateway, required this._info, + TerminalLayout? layout, }) { session = ChatShellTerminalSession( _run(), @@ -29,9 +31,13 @@ class TerminalTab extends ChangeNotifier { onReply: (data) => _input(data, reply: true), onResize: _resized, onActivate: _activated, + layout: layout, ); session.terminal.onTitleChange = _titled; session.onDrawn = _drawn; + session.events.bells.addListener(_rang); + session.events.viewers.addListener(_viewed); + session.events.workingDirectory.addListener(_moved); } final String machineId; @@ -60,16 +66,31 @@ class TerminalTab extends ChangeNotifier { /// The last refusal of input, a resize or a read, in the server's words. String? error; + /// Whether the bell rang while no view showed this terminal: its tab + /// shows a dot until it is shown again. + bool bellUnseen = false; + String get key => terminalKey(machineId, _info.id); TerminalInfo get info => _info; 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. + String get cwd => _reportedCwd ?? _info.cwd; + String? _reportedCwd; + + void _moved() { + _reportedCwd = session.events.workingDirectory.value; + _notify(); } ChatShellRun _run() => ChatShellRun( @@ -217,6 +238,19 @@ class TerminalTab extends ChangeNotifier { ); } + void _rang() { + if (bellUnseen || !session.layout.bell) return; + if (session.events.viewers.value > 0) return; + bellUnseen = true; + _notify(); + } + + void _viewed() { + if (!bellUnseen || session.events.viewers.value == 0) return; + bellUnseen = false; + _notify(); + } + void _titled(String title) { if (title == _oscTitle) return; _oscTitle = title.trim(); @@ -294,6 +328,9 @@ class TerminalTab extends ChangeNotifier { _pipe = null; session.terminal.onTitleChange = null; session.onDrawn = null; + session.events.bells.removeListener(_rang); + session.events.viewers.removeListener(_viewed); + session.events.workingDirectory.removeListener(_moved); session.dispose(); super.dispose(); } diff --git a/app/lib/features/terminal/terminal_tab_strip.dart b/app/lib/features/terminal/terminal_tab_strip.dart index fce1c28f..cd663d1a 100644 --- a/app/lib/features/terminal/terminal_tab_strip.dart +++ b/app/lib/features/terminal/terminal_tab_strip.dart @@ -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', diff --git a/app/test/features/chat/shell/chat_shell_terminal_find_test.dart b/app/test/features/chat/shell/chat_shell_terminal_find_test.dart new file mode 100644 index 00000000..8d480cd6 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_find_test.dart @@ -0,0 +1,138 @@ +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(find.byKey(const ValueKey('terminal-find-count'))).data!; + +/// Opens the find bar with the platform's key. +Future _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); + // 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)); +} diff --git a/app/test/features/chat/shell/terminal_view_harness.dart b/app/test/features/chat/shell/terminal_view_harness.dart new file mode 100644 index 00000000..e6d5f55c --- /dev/null +++ b/app/test/features/chat/shell/terminal_view_harness.dart @@ -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 load() async => saved; + @override + Future 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 sent = []; + final List<(int, int)> sizes = []; + + Terminal get terminal => session.terminal; + String get typed => sent.join(); + + Future 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(find.byType(TerminalView)); + + TerminalViewState viewState(WidgetTester tester) => + tester.state(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 write(WidgetTester tester, String text) async { + terminal.write(text); + await tester.pump(); + } + + /// Focuses the emulator. + Future 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 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 chordKeys( + WidgetTester tester, + LogicalKeyboardKey key, [ + List 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 mockClipboard(WidgetTester tester, {String paste = ''}) { + final texts = []; + 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, +}); diff --git a/app/third_party/xterm/lib/src/core/buffer/buffer.dart b/app/third_party/xterm/lib/src/core/buffer/buffer.dart index ecc504e3..b4658a3c 100644 --- a/app/third_party/xterm/lib/src/core/buffer/buffer.dart +++ b/app/third_party/xterm/lib/src/core/buffer/buffer.dart @@ -14,7 +14,8 @@ import 'package:xterm/src/utils/unicode_v11.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 +25,10 @@ class Buffer { Buffer( this.terminal, { - required this.maxLines, + required int maxLines, required this.isAltBuffer, this.wordSeparators, - }) { + }) : lines = IndexAwareCircularBuffer(maxLines) { for (int i = 0; i < terminal.viewHeight; i++) { lines.push(_newEmptyLine()); } @@ -59,7 +60,16 @@ class Buffer { /// lines of the buffer. the length of [lines] should always be equal or /// greater than [viewHeight]. - late final lines = IndexAwareCircularBuffer(maxLines); + final IndexAwareCircularBuffer 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]. diff --git a/app/third_party/xterm/lib/src/terminal.dart b/app/third_party/xterm/lib/src/terminal.dart index 07aea210..a031daaf 100644 --- a/app/third_party/xterm/lib/src/terminal.dart +++ b/app/third_party/xterm/lib/src/terminal.dart @@ -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? 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); diff --git a/app/third_party/xterm/lib/src/terminal_view.dart b/app/third_party/xterm/lib/src/terminal_view.dart index 2fc16a90..98699926 100644 --- a/app/third_party/xterm/lib/src/terminal_view.dart +++ b/app/third_party/xterm/lib/src/terminal_view.dart @@ -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? 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 { 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? 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; } diff --git a/app/third_party/xterm/lib/src/ui/render.dart b/app/third_party/xterm/lib/src/ui/render.dart index 8314de75..f448a175 100644 --- a/app/third_party/xterm/lib/src/ui/render.dart +++ b/app/third_party/xterm/lib/src/ui/render.dart @@ -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'; @@ -33,6 +34,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { required FocusNode focusNode, required TerminalCursorType cursorType, required bool alwaysShowCursor, + ValueListenable? cursorBlinkVisible, EditableRectCallback? onEditableRect, String? composingText, }) : _terminal = terminal, @@ -43,6 +45,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { _focusNode = focusNode, _cursorType = cursorType, _alwaysShowCursor = alwaysShowCursor, + _cursorBlinkVisible = cursorBlinkVisible, _onEditableRect = onEditableRect, _composingText = composingText, _painter = TerminalPainter( @@ -146,6 +149,15 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { markNeedsPaint(); } + ValueListenable? _cursorBlinkVisible; + set cursorBlinkVisible(ValueListenable? 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; @@ -196,6 +208,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { _terminal.addListener(_onTerminalChange); _controller.addListener(_onControllerUpdate); _focusNode.addListener(_onFocusChange); + _cursorBlinkVisible?.addListener(markNeedsPaint); } @override @@ -205,6 +218,7 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { _terminal.removeListener(_onTerminalChange); _controller.removeListener(_onControllerUpdate); _focusNode.removeListener(_onFocusChange); + _cursorBlinkVisible?.removeListener(markNeedsPaint); } @override @@ -398,7 +412,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 { diff --git a/app/third_party/xterm/lib/src/utils/circular_buffer.dart b/app/third_party/xterm/lib/src/utils/circular_buffer.dart index f74fb436..3b3ee3a1 100644 --- a/app/third_party/xterm/lib/src/utils/circular_buffer.dart +++ b/app/third_party/xterm/lib/src/utils/circular_buffer.dart @@ -224,8 +224,14 @@ class IndexAwareCircularBuffer { /// 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; } diff --git a/app/third_party/xterm/lib/ui.dart b/app/third_party/xterm/lib/ui.dart index bc2c8a94..5636267c 100644 --- a/app/third_party/xterm/lib/ui.dart +++ b/app/third_party/xterm/lib/ui.dart @@ -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'; From e65354496ad9059520bd00b1aeb65967ff8fc8d6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 26 Nov 2026 00:48:11 +0000 Subject: [PATCH 3/6] Terminal round 2: tests for every feature; split find host and tab events Co-Authored-By: Claude Opus 5.5 --- .../shell/chat_shell_terminal_find_host.dart | 83 ++++++++++++ .../chat/shell/chat_shell_terminal_view.dart | 22 +-- .../chat_shell_terminal_view_features.dart | 106 +++++---------- .../settings/settings_font_section.dart | 7 +- app/lib/features/terminal/terminal_tab.dart | 43 ++---- .../terminal/terminal_tab_events.dart | 52 +++++++ .../chat_shell_terminal_events_test.dart | 102 ++++++++++++++ .../chat_shell_terminal_feedback_test.dart | 127 ++++++++++++++++++ .../shell/chat_shell_terminal_find_test.dart | 65 ++++----- .../chat_shell_terminal_local_keys_test.dart | 112 +++++++++++++++ .../shell/chat_shell_terminal_menu_test.dart | 81 +++++++++++ .../settings_terminal_controls_test.dart | 100 ++++++++++++++ .../terminal/terminal_tab_events_test.dart | 90 +++++++++++++ .../scrollback_blink_test.dart | 98 ++++++++++++++ 14 files changed, 932 insertions(+), 156 deletions(-) create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_find_host.dart create mode 100644 app/lib/features/terminal/terminal_tab_events.dart create mode 100644 app/test/features/chat/shell/chat_shell_terminal_events_test.dart create mode 100644 app/test/features/chat/shell/chat_shell_terminal_feedback_test.dart create mode 100644 app/test/features/chat/shell/chat_shell_terminal_local_keys_test.dart create mode 100644 app/test/features/chat/shell/chat_shell_terminal_menu_test.dart create mode 100644 app/test/features/settings/settings_terminal_controls_test.dart create mode 100644 app/test/features/terminal/terminal_tab_events_test.dart create mode 100644 app/test/third_party_xterm/scrollback_blink_test.dart diff --git a/app/lib/features/chat/shell/chat_shell_terminal_find_host.dart b/app/lib/features/chat/shell/chat_shell_terminal_find_host.dart new file mode 100644 index 00000000..474ac7cc --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_find_host.dart @@ -0,0 +1,83 @@ +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 on State { + 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), + ); + }); + } + + 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, + ), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view.dart b/app/lib/features/chat/shell/chat_shell_terminal_view.dart index 3317937b..0355ccf5 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view.dart @@ -12,6 +12,7 @@ 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'; @@ -57,6 +58,7 @@ class ChatShellTerminalView extends StatefulWidget { class _ChatShellTerminalViewState extends State with SingleTickerProviderStateMixin, + ChatShellTerminalFindHost, ChatShellTerminalFeatures { @override final TerminalController controller = TerminalController(); @@ -132,24 +134,6 @@ class _ChatShellTerminalViewState extends State return KeyEventResult.handled; } - /// 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; - } - void _tapped(TapUpDetails details, CellOffset offset) { final link = chatShellTerminalLinkAt(widget.session.terminal, offset); if (link != null) openChatLink(context, link.uri); @@ -215,7 +199,7 @@ class _ChatShellTerminalViewState extends State onPointerDown: (_) => _outputFocus.requestFocus(), child: Focus( focusNode: _outputFocus, - onKeyEvent: _readOnlyKey, + onKeyEvent: readOnlyKey, child: view, ), ); diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart b/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart index e77764e7..0afb8404 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart @@ -6,34 +6,29 @@ 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.dart'; -import 'chat_shell_terminal_find_bar.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_session.dart'; import 'chat_shell_terminal_shortcuts.dart'; -/// The terminal view's own features around the emulator: find in the -/// scrollback, text size, scrolling keys, the context menu, link hover, -/// the cursor blink, stale-selection clearing and the OSC 52 toast. The -/// view supplies its emulator's parts and calls [initFeatures] and -/// [disposeFeatures]. +/// 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 - on State, TickerProvider { - ChatShellTerminalSession get session; - TerminalController get controller; - FocusNode get focus; + on State, TickerProvider, ChatShellTerminalFindHost { ScrollController get scroll; GlobalKey get viewKey; + @override late final ChatShellTerminalActions actions; late final ChatShellLinkHover hover; late final ChatShellCursorBlink blink; late final ChatShellSelectionGuard _guard; - final FocusNode _findFocus = FocusNode(debugLabel: 'terminal-find'); - ChatShellTerminalFind? _find; bool _reduceMotion = false; bool _hoverQueued = false; + bool _attached = false; /// The text size the view draws at now, which zooming steps from. double currentFontSize = 14; @@ -52,18 +47,23 @@ mixin ChatShellTerminalFeatures _guard = ChatShellSelectionGuard(_terminal, controller); scroll.addListener(hover.refresh); _terminal.addListener(_terminalChanged); - session.events.attach(_copied); + // 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() { - session.events.detach(_copied); + if (_attached) session.events.detach(_copied); _terminal.removeListener(_terminalChanged); scroll.removeListener(hover.refresh); _guard.dispose(); blink.dispose(); hover.dispose(); - _find?.dispose(); - _findFocus.dispose(); + disposeFind(); } @override @@ -136,62 +136,22 @@ mixin ChatShellTerminalFeatures return true; } - /// Opens the find bar, or focuses its field when it is open. - void openFind() { - if (_find != null) { - _findFocus.requestFocus(); - return; + /// 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 scheme = Theme.of(context).colorScheme; - setState(() { - _find = ChatShellTerminalFind( - terminal: _terminal, - controller: controller, - hit: scheme.tertiary.withValues(alpha: 0.3), - current: scheme.tertiary.withValues(alpha: 0.6), - ); - }); - } - - 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, - ), - ), - ), - ], - ); + 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. diff --git a/app/lib/features/settings/settings_font_section.dart b/app/lib/features/settings/settings_font_section.dart index 35aa647a..d692daf3 100644 --- a/app/lib/features/settings/settings_font_section.dart +++ b/app/lib/features/settings/settings_font_section.dart @@ -188,6 +188,7 @@ class _SettingsFontSectionState extends State { /// The platform's own interface family (Roboto), independent of the font the /// theme currently applies. -String? _systemFamily(BuildContext context) => Typography.material2021( - platform: Theme.of(context).platform, -).black.bodyLarge?.fontFamily; +String? _systemFamily(BuildContext context) => + Typography.material2021( + platform: Theme.of(context).platform, + ).black.bodyLarge?.fontFamily; diff --git a/app/lib/features/terminal/terminal_tab.dart b/app/lib/features/terminal/terminal_tab.dart index 7f6546b0..3c4a13e1 100644 --- a/app/lib/features/terminal/terminal_tab.dart +++ b/app/lib/features/terminal/terminal_tab.dart @@ -10,6 +10,9 @@ 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 @@ -17,7 +20,7 @@ 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, @@ -35,15 +38,14 @@ class TerminalTab extends ChangeNotifier { ); session.terminal.onTitleChange = _titled; session.onDrawn = _drawn; - session.events.bells.addListener(_rang); - session.events.viewers.addListener(_viewed); - session.events.workingDirectory.addListener(_moved); + followEvents(); } final String machineId; String machineName; ApiGateway _gateway; TerminalInfo _info; + @override late final ChatShellTerminalSession session; final TerminalStream _stream = TerminalStream(); ChatShellInputPipe? _pipe; @@ -66,10 +68,6 @@ class TerminalTab extends ChangeNotifier { /// The last refusal of input, a resize or a read, in the server's words. String? error; - /// Whether the bell rang while no view showed this terminal: its tab - /// shows a dot until it is shown again. - bool bellUnseen = false; - String get key => terminalKey(machineId, _info.id); TerminalInfo get info => _info; ApiGateway get gateway => _gateway; @@ -85,13 +83,8 @@ class TerminalTab extends ChangeNotifier { /// The shell's current folder as it reported it (OSC 7), else the one it /// started in. - String get cwd => _reportedCwd ?? _info.cwd; - String? _reportedCwd; - - void _moved() { - _reportedCwd = session.events.workingDirectory.value; - _notify(); - } + @override + String get cwd => super.cwd ?? _info.cwd; ChatShellRun _run() => ChatShellRun( id: _info.id, @@ -238,19 +231,6 @@ class TerminalTab extends ChangeNotifier { ); } - void _rang() { - if (bellUnseen || !session.layout.bell) return; - if (session.events.viewers.value > 0) return; - bellUnseen = true; - _notify(); - } - - void _viewed() { - if (!bellUnseen || session.events.viewers.value == 0) return; - bellUnseen = false; - _notify(); - } - void _titled(String title) { if (title == _oscTitle) return; _oscTitle = title.trim(); @@ -317,6 +297,9 @@ class TerminalTab extends ChangeNotifier { _notify(); } + @override + void notifyEvent() => _notify(); + void _notify() { if (!_disposed) notifyListeners(); } @@ -328,9 +311,7 @@ class TerminalTab extends ChangeNotifier { _pipe = null; session.terminal.onTitleChange = null; session.onDrawn = null; - session.events.bells.removeListener(_rang); - session.events.viewers.removeListener(_viewed); - session.events.workingDirectory.removeListener(_moved); + unfollowEvents(); session.dispose(); super.dispose(); } diff --git a/app/lib/features/terminal/terminal_tab_events.dart b/app/lib/features/terminal/terminal_tab_events.dart new file mode 100644 index 00000000..3c5461f4 --- /dev/null +++ b/app/lib/features/terminal/terminal_tab_events.dart @@ -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(); + } +} diff --git a/app/test/features/chat/shell/chat_shell_terminal_events_test.dart b/app/test/features/chat/shell/chat_shell_terminal_events_test.dart new file mode 100644 index 00000000..c9f23e64 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_events_test.dart @@ -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(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'); + }); +} diff --git a/app/test/features/chat/shell/chat_shell_terminal_feedback_test.dart b/app/test/features/chat/shell/chat_shell_terminal_feedback_test.dart new file mode 100644 index 00000000..7100a2f7 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_feedback_test.dart @@ -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)); + }); +} diff --git a/app/test/features/chat/shell/chat_shell_terminal_find_test.dart b/app/test/features/chat/shell/chat_shell_terminal_find_test.dart index 8d480cd6..f04eb205 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_find_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_find_test.dart @@ -8,8 +8,9 @@ import 'terminal_view_harness.dart'; const _field = ValueKey('terminal-find-field'); -String _count(WidgetTester tester) => - tester.widget(find.byKey(const ValueKey('terminal-find-count'))).data!; +String _count(WidgetTester tester) => tester + .widget(find.byKey(const ValueKey('terminal-find-count'))) + .data!; /// Opens the find bar with the platform's key. Future _openFind(WidgetTester tester) => isApple() @@ -106,33 +107,37 @@ void main() { 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( + '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)); + 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), + ); } diff --git a/app/test/features/chat/shell/chat_shell_terminal_local_keys_test.dart b/app/test/features/chat/shell/chat_shell_terminal_local_keys_test.dart new file mode 100644 index 00000000..1860ecce --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_local_keys_test.dart @@ -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); + }); +} diff --git a/app/test/features/chat/shell/chat_shell_terminal_menu_test.dart b/app/test/features/chat/shell/chat_shell_terminal_menu_test.dart new file mode 100644 index 00000000..f5eeb57d --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_menu_test.dart @@ -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>(_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); + }); +} diff --git a/app/test/features/settings/settings_terminal_controls_test.dart b/app/test/features/settings/settings_terminal_controls_test.dart new file mode 100644 index 00000000..51b82fe3 --- /dev/null +++ b/app/test/features/settings/settings_terminal_controls_test.dart @@ -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 load() async => saved; + @override + Future save(String value) async { + saved = value; + return true; + } +} + +void main() { + late _Store store; + late TerminalLayout layout; + + setUp(() { + store = _Store(); + layout = TerminalLayout(store: store); + }); + + Future 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 saved() => + jsonDecode(store.saved!) as Map; + + 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)); + 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)); + 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)); + 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>( + find.byType(DropdownMenu), + ); + 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); + }); +} diff --git a/app/test/features/terminal/terminal_tab_events_test.dart b/app/test/features/terminal/terminal_tab_events_test.dart new file mode 100644 index 00000000..25101b1b --- /dev/null +++ b/app/test/features/terminal/terminal_tab_events_test.dart @@ -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 drain(WidgetTester tester) async { + for (var i = 0; i < 3; i++) { + await tester.pump(const Duration(milliseconds: 1)); + } + } + + Future 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); + }); +} diff --git a/app/test/third_party_xterm/scrollback_blink_test.dart b/app/test/third_party_xterm/scrollback_blink_test.dart new file mode 100644 index 00000000..1f09de1a --- /dev/null +++ b/app/test/third_party_xterm/scrollback_blink_test.dart @@ -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()); + }); +} From 9ab7f50cceb34a67bec2434219c189d6b3b02d32 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 26 Nov 2026 00:52:19 +0000 Subject: [PATCH 4/6] Terminal: find field takes the keyboard; docs, capture kit right-click Co-Authored-By: Claude Opus 5.5 --- .../shell/chat_shell_terminal_find_host.dart | 5 ++ app/notes/terminal-panel.md | 63 +++++++++++++++++++ .../shell/chat_shell_terminal_find_test.dart | 6 ++ app/third_party/xterm/README.md | 9 ++- app/tool/capture/README.md | 1 + app/tool/capture/capture.mjs | 7 +++ app/tool/capture/page.mjs | 13 +++- 7 files changed, 101 insertions(+), 3 deletions(-) diff --git a/app/lib/features/chat/shell/chat_shell_terminal_find_host.dart b/app/lib/features/chat/shell/chat_shell_terminal_find_host.dart index 474ac7cc..7198bd61 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_find_host.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_find_host.dart @@ -38,6 +38,11 @@ mixin ChatShellTerminalFindHost on State { 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() { diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index 47f4ca9b..fa15b4c5 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -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=`. + ## Protocol (server) `internal/protocol/terminal.go`; documented in `docs/cli.md` ("Machine diff --git a/app/test/features/chat/shell/chat_shell_terminal_find_test.dart b/app/test/features/chat/shell/chat_shell_terminal_find_test.dart index f04eb205..d3282745 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_find_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_find_test.dart @@ -68,6 +68,12 @@ void main() { 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(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'); diff --git a/app/third_party/xterm/README.md b/app/third_party/xterm/README.md index fa2ffc63..83e2e235 100644 --- a/app/third_party/xterm/README.md +++ b/app/third_party/xterm/README.md @@ -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,10 @@ 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) diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index 7a9609de..19b648cf 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -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=` | click the secondary mouse button on the target (context menus), then wait | | `hover=` | move the mouse onto the target without pressing (hover states) | | `drag=>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 | diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index 4624e305..29ebcaf4 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -25,6 +25,7 @@ steps: open=[@WxH] wait= shot= click= waitfor= press= scroll= size=WxH files=[,] (answers the next file chooser) film= labels= tabs= eval= expect= hover= + rightclick= (secondary button: context menus) drag=>, (JSON: drag, dx, dy, steps, gap, hold) swipe=>, pinch=> (with --touch true) target: