Terminal round 2: tests for every feature; split find host and tab events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 00:48:11 +00:00
parent 6832ec789e
commit e65354496a
14 changed files with 932 additions and 156 deletions
@@ -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<T extends StatefulWidget> on State<T> {
ChatShellTerminalSession get session;
TerminalController get controller;
FocusNode get focus;
ChatShellTerminalActions get actions;
final FocusNode _findFocus = FocusNode(debugLabel: 'terminal-find');
ChatShellTerminalFind? _find;
void disposeFind() {
_find?.dispose();
_findFocus.dispose();
}
/// Opens the find bar, or focuses its field when it is open.
void openFind() {
if (_find != null) {
_findFocus.requestFocus();
return;
}
final scheme = Theme.of(context).colorScheme;
setState(() {
_find = ChatShellTerminalFind(
terminal: session.terminal,
controller: controller,
hit: scheme.tertiary.withValues(alpha: 0.3),
current: scheme.tertiary.withValues(alpha: 0.6),
);
});
}
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,
),
),
),
],
);
}
}
@@ -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<ChatShellTerminalView>
with
SingleTickerProviderStateMixin,
ChatShellTerminalFindHost<ChatShellTerminalView>,
ChatShellTerminalFeatures<ChatShellTerminalView> {
@override
final TerminalController controller = TerminalController();
@@ -132,24 +134,6 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView>
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<ChatShellTerminalView>
onPointerDown: (_) => _outputFocus.requestFocus(),
child: Focus(
focusNode: _outputFocus,
onKeyEvent: _readOnlyKey,
onKeyEvent: readOnlyKey,
child: view,
),
);
@@ -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<T extends StatefulWidget>
on State<T>, TickerProvider {
ChatShellTerminalSession get session;
TerminalController get controller;
FocusNode get focus;
on State<T>, TickerProvider, ChatShellTerminalFindHost<T> {
ScrollController get scroll;
GlobalKey<TerminalViewState> get viewKey;
@override
late final ChatShellTerminalActions actions;
late final ChatShellLinkHover hover;
late final ChatShellCursorBlink blink;
late final ChatShellSelectionGuard _guard;
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<T extends StatefulWidget>
_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<T extends StatefulWidget>
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.
@@ -188,6 +188,7 @@ class _SettingsFontSectionState extends State<SettingsFontSection> {
/// 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;
+12 -31
View File
@@ -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();
}
@@ -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();
}
}
@@ -0,0 +1,102 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_bell.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_events.dart';
import 'terminal_view_harness.dart';
const _flash = ValueKey('terminal-bell-flash');
String _osc52(String text) =>
'\x1b]52;c;${base64.encode(utf8.encode(text))}\x07';
void main() {
testWidgets('a bell flashes the border briefly; the setting turns it off', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
expect(find.byKey(_flash), findsNothing);
await harness.write(tester, '\x07');
expect(find.byKey(_flash), findsOneWidget);
await tester.pump(chatShellBellFlash + const Duration(milliseconds: 16));
expect(find.byKey(_flash), findsNothing);
harness.layout.setBell(false);
await tester.pump();
await harness.write(tester, '\x07');
expect(find.byKey(_flash), findsNothing);
});
testWidgets('under reduced motion the bell border holds, then goes', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester, reduceMotion: true);
await harness.write(tester, '\x07');
final border =
tester.widget<DecoratedBox>(find.byKey(_flash)).decoration
as BoxDecoration;
expect((border.border! as Border).top.color.a, 1);
await tester.pump(chatShellBellFlash + const Duration(milliseconds: 16));
expect(find.byKey(_flash), findsNothing);
});
testWidgets('OSC 52 from live output sets the clipboard and says so', (
tester,
) async {
final copied = mockClipboard(tester);
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, _osc52('from vim'));
expect(copied, ['from vim']);
await tester.pump();
expect(find.text('Copied from terminal'), findsOneWidget);
await tester.pump(const Duration(seconds: 3));
await tester.pumpAndSettle();
// A read request (?) is ignored.
await harness.write(tester, '\x1b]52;c;?\x07');
expect(copied, ['from vim']);
});
testWidgets('old output drawn again (a replay) neither copies nor rings', (
tester,
) async {
final copied = mockClipboard(tester);
final harness = TerminalViewHarness();
await harness.pump(tester);
final output = 'old ${_osc52('stale')}\x07done';
harness.session.replay(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': 'running',
'started_at': 1,
'output': output,
'output_bytes': utf8.encode(output).length,
'terminal': true,
})!,
);
await tester.pumpAndSettle();
expect(copied, isEmpty);
expect(harness.session.events.bells.value, 0);
expect(find.byKey(_flash), findsNothing);
});
test('OSC 7 reports the folder as a path', () {
expect(
chatShellWorkingDirectoryPath('file://mac.local/Users/op/src%20x'),
'/Users/op/src x',
);
expect(chatShellWorkingDirectoryPath('file:///tmp'), '/tmp');
expect(chatShellWorkingDirectoryPath('https://example.com/a'), isNull);
expect(chatShellWorkingDirectoryPath('file://host'), '/');
final harness = TerminalViewHarness();
addTearDown(harness.session.dispose);
harness.terminal.write('\x1b]7;file://mac/Users/op/work\x1b\\');
expect(harness.session.events.workingDirectory.value, '/Users/op/work');
});
}
@@ -0,0 +1,127 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_cursor_blink.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_links.dart';
import 'package:xterm/xterm.dart';
import 'terminal_view_harness.dart';
const _phase = chatShellCursorBlinkPhase;
void main() {
bool shown(WidgetTester tester, TerminalViewHarness harness) =>
harness.view(tester).cursorBlinkVisible!.value;
testWidgets('a blinking DECSCUSR cursor blinks while focused and is steady '
'once unfocused, leaving no frames scheduled', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, '\x1b[5 q');
await harness.focus(tester);
expect(shown(tester, harness), isTrue);
await tester.pump(_phase + const Duration(milliseconds: 10));
expect(shown(tester, harness), isFalse);
await tester.pump(_phase);
expect(shown(tester, harness), isTrue);
// Output shows it again and restarts the phase.
await tester.pump(_phase);
expect(shown(tester, harness), isFalse);
await harness.write(tester, 'x');
expect(shown(tester, harness), isTrue);
// Unfocused: steady, and the ticker stopped.
harness.view(tester).focusNode!.unfocus();
await tester.pump();
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('a steady shape (even Ps) does not blink', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, '\x1b[2 q');
await harness.focus(tester);
await tester.pump(_phase * 3);
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('reduced motion keeps a blinking cursor steady', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester, reduceMotion: true);
await harness.write(tester, '\x1b[1 q');
await harness.focus(tester);
await tester.pump(_phase + const Duration(milliseconds: 10));
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('a selection clears when its rows are rewritten, the screen is '
'cleared or the program switches screens', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, 'keep this\r\nother\r\n');
final controller = harness.controller(tester);
final buffer = harness.terminal.buffer;
void select() => controller.setSelection(
buffer.createAnchor(0, 0),
buffer.createAnchor(4, 0),
);
select();
// Output elsewhere leaves it.
await harness.write(tester, 'more output\r\n');
expect(controller.selection, isNotNull);
// Rewriting the selected row clears it.
await harness.write(tester, '\x1b[1;1Hgone');
expect(controller.selection, isNull);
select();
await harness.write(tester, '\x1b[2J');
expect(controller.selection, isNull);
select();
await harness.write(tester, '\x1b[?1049h');
expect(controller.selection, isNull);
});
testWidgets('hovering a web or OSC 8 link shows a pointer and underlines '
'it; a click opens it as before', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'see https://example.com/a now\r\n'
'\x1b]8;;https://example.org/b\x1b\\docs\x1b]8;;\x1b\\ plain',
);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
addTearDown(mouse.removePointer);
await mouse.addPointer(location: harness.cellCentre(tester, 0, 0));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.text);
await mouse.moveTo(harness.cellCentre(tester, 8, 0));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.click);
// The OSC 8 link's text is not an address; its target is.
await mouse.moveTo(harness.cellCentre(tester, 1, 1));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.click);
await mouse.moveTo(harness.cellCentre(tester, 7, 1));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.text);
});
test('the link under a cell: OSC 8 first, then printed addresses', () {
final terminal = Terminal(maxLines: 50)..resize(20, 4);
terminal.write(
'\x1b]8;;https://example.org/long\x1b\\0123456789abcdefghijkl'
'\x1b]8;;\x1b\\ x https://e.com/q).',
);
final hyperlink = chatShellTerminalLinkAt(terminal, const CellOffset(5, 0));
expect(hyperlink!.uri.toString(), 'https://example.org/long');
// It wraps onto the next row.
expect(hyperlink.begin, const CellOffset(0, 0));
expect(hyperlink.end, const CellOffset(2, 1));
final printed = chatShellTerminalLinkAt(terminal, const CellOffset(6, 1));
expect(printed!.uri.toString(), 'https://e.com/q');
expect(printed.begin, const CellOffset(5, 1));
expect(printed.end, const CellOffset(20, 1));
});
}
@@ -8,8 +8,9 @@ import 'terminal_view_harness.dart';
const _field = ValueKey('terminal-find-field');
String _count(WidgetTester tester) =>
tester.widget<Text>(find.byKey(const ValueKey('terminal-find-count'))).data!;
String _count(WidgetTester tester) => tester
.widget<Text>(find.byKey(const ValueKey('terminal-find-count')))
.data!;
/// Opens the find bar with the platform's key.
Future<void> _openFind(WidgetTester tester) => isApple()
@@ -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),
);
}
@@ -0,0 +1,112 @@
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'terminal_view_harness.dart';
void main() {
testWidgets('Cmd/Ctrl with =, - and 0 zoom a focused terminal; the size '
'is saved and the process is resized to the new cells', (tester) async {
final store = MemoryStore();
final harness = TerminalViewHarness(layout: TerminalLayout(store: store));
await harness.pump(tester);
await harness.focus(tester);
final base = harness.view(tester).textStyle.fontSize;
final cols = harness.terminal.viewWidth;
final command = commandKey();
await chordKeys(tester, LogicalKeyboardKey.equal, [command]);
await chordKeys(tester, LogicalKeyboardKey.equal, [command]);
expect(harness.layout.fontSize, base.roundToDouble() + 2);
expect(harness.view(tester).textStyle.fontSize, base.roundToDouble() + 2);
// Larger cells: fewer columns, through the normal resize path.
expect(harness.terminal.viewWidth, lessThan(cols));
expect(harness.sizes.last.$1, harness.terminal.viewWidth);
await tester.pump();
expect(jsonDecode(store.saved!)['font_size'], base.roundToDouble() + 2);
await chordKeys(tester, LogicalKeyboardKey.minus, [command]);
expect(harness.layout.fontSize, base.roundToDouble() + 1);
await chordKeys(tester, LogicalKeyboardKey.digit0, [command]);
expect(harness.layout.fontSize, isNull);
expect(harness.view(tester).textStyle.fontSize, base);
expect(harness.terminal.viewWidth, cols);
// None of it reached the shell.
expect(harness.typed, isEmpty);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.fontSize, isNull);
}, variant: desktops);
testWidgets(
'zooming stops at the size limits',
(tester) async {
final harness = TerminalViewHarness();
harness.layout.setFontSize(terminalFontSizeMax - 1);
await harness.pump(tester);
await harness.focus(tester);
for (var i = 0; i < 3; i++) {
await chordKeys(tester, LogicalKeyboardKey.equal, [commandKey()]);
}
expect(harness.layout.fontSize, terminalFontSizeMax);
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
testWidgets('Shift+PgUp/PgDn/Home/End scroll the scrollback locally; on the '
'alternate screen they reach the program', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
List.generate(200, (i) => 'line $i').join('\r\n'),
);
await harness.focus(tester);
final bottom = harness.scroll(tester).maxScrollExtent;
expect(harness.scroll(tester).pixels, bottom);
const shift = [LogicalKeyboardKey.shiftLeft];
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
final page = bottom - harness.scroll(tester).pixels;
expect(page, greaterThan(0));
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
expect(harness.scroll(tester).pixels, closeTo(bottom - 2 * page, 0.01));
await chordKeys(tester, LogicalKeyboardKey.pageDown, shift);
expect(harness.scroll(tester).pixels, closeTo(bottom - page, 0.01));
await chordKeys(tester, LogicalKeyboardKey.home, shift);
expect(harness.scroll(tester).pixels, 0);
await chordKeys(tester, LogicalKeyboardKey.end, shift);
expect(harness.scroll(tester).pixels, bottom);
expect(harness.typed, isEmpty);
// A full-screen program (less, vim) gets them.
await harness.write(tester, '\x1b[?1049h');
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
expect(harness.typed, '\x1b[5;2~');
}, variant: desktops);
testWidgets('the scrollback setting applies to new and open terminals', (
tester,
) async {
final harness = TerminalViewHarness();
expect(harness.layout.scrollback, terminalScrollbackDefault);
expect(harness.terminal.maxLines, 10000);
await harness.pump(tester);
await harness.write(
tester,
List.generate(1500, (i) => 'line $i').join('\r\n'),
);
expect(harness.terminal.buffer.height, 1500);
harness.layout.setScrollback(1000);
await tester.pump();
expect(harness.terminal.maxLines, 1000);
expect(harness.terminal.buffer.height, 1000);
// The newest lines are kept.
final buffer = harness.terminal.buffer;
expect(buffer.lines[buffer.height - 1].getText().trim(), 'line 1499');
expect(buffer.lines[0].getText().trim(), 'line 500');
await harness.write(tester, '\r\nmore');
expect(harness.terminal.buffer.height, 1000);
final next = TerminalViewHarness(layout: harness.layout);
addTearDown(next.session.dispose);
expect(next.terminal.maxLines, 1000);
});
}
@@ -0,0 +1,81 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'terminal_view_harness.dart';
Finder _item(String name) => find.byKey(ValueKey('terminal-menu-$name'));
bool _enabled(WidgetTester tester, String name) =>
tester.widget<PopupMenuItem<Object?>>(_item(name)).enabled;
void main() {
testWidgets('right-click offers Copy with a selection, Paste, Select all, '
'Clear scrollback and Find', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'${List.generate(40, (i) => 'old $i').join('\r\n')}\r\nhello world',
);
final copied = mockClipboard(tester, paste: 'pasted');
final screenTop =
harness.terminal.buffer.height - harness.terminal.viewHeight;
final last = harness.terminal.buffer.height - 1;
await harness.rightClick(tester, 2, last);
expect(_item('copy'), findsOneWidget);
expect(_enabled(tester, 'copy'), isFalse);
for (final name in ['paste', 'selectAll', 'clear', 'find']) {
expect(_item(name), findsOneWidget, reason: name);
}
// Paste types the clipboard into the process.
await tester.tap(_item('paste'));
await tester.pumpAndSettle();
expect(harness.typed, 'pasted');
// Select all takes the scrollback too; Copy copies it.
await harness.rightClick(tester, 2, last);
await tester.tap(_item('selectAll'));
await tester.pumpAndSettle();
final selection = harness.controller(tester).selection!.normalized;
expect(selection.begin.y, 0);
expect(selection.end.y, last);
await harness.rightClick(tester, 2, last);
expect(_enabled(tester, 'copy'), isTrue);
await tester.tap(_item('copy'));
await tester.pumpAndSettle();
expect(copied.single, startsWith('old 0\nold 1'));
expect(copied.single, contains('hello world'));
// Clear scrollback keeps only the screen.
expect(screenTop, greaterThan(0));
await harness.rightClick(tester, 2, last);
await tester.tap(_item('clear'));
await tester.pumpAndSettle();
expect(harness.terminal.buffer.height, harness.terminal.viewHeight);
// Find… opens the find bar.
await harness.rightClick(tester, 2, harness.terminal.viewHeight - 1);
await tester.tap(_item('find'));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('terminal-find-field')), findsOneWidget);
}, variant: desktops);
testWidgets('a program tracking the mouse gets the right button unless '
'Shift is held', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, r'$ ');
// X10/normal tracking with SGR coordinates.
await harness.write(tester, '\x1b[?1000h\x1b[?1006h');
await harness.rightClick(tester, 3, 0);
expect(_item('copy'), findsNothing);
expect(harness.typed, '\x1b[<2;4;1M\x1b[<2;4;1m');
await harness.rightClick(tester, 3, 0, shift: true);
expect(_item('copy'), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets('finished output offers no Paste', (tester) async {
final harness = TerminalViewHarness(live: false);
await harness.pump(tester);
await harness.rightClick(tester, 1, 0);
expect(_item('copy'), findsOneWidget);
expect(_item('paste'), findsNothing);
});
}
@@ -0,0 +1,100 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_terminal_section.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
class _Store implements TerminalLayoutStore {
String? saved;
@override
Future<String?> load() async => saved;
@override
Future<bool> save(String value) async {
saved = value;
return true;
}
}
void main() {
late _Store store;
late TerminalLayout layout;
setUp(() {
store = _Store();
layout = TerminalLayout(store: store);
});
Future<void> pump(WidgetTester tester) async {
tester.view.physicalSize = const Size(900, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: SettingsTerminalSection(layout: layout),
),
),
),
);
}
Map<String, dynamic> saved() =>
jsonDecode(store.saved!) as Map<String, dynamic>;
testWidgets('text size, scrollback and the visual bell are chosen in '
'Settings and saved with the layout', (tester) async {
await pump(tester);
expect(find.text('Text size'), findsOneWidget);
expect(find.text('Scrollback'), findsOneWidget);
await tester.tap(find.byType(DropdownMenu<double>));
await tester.pumpAndSettle();
await tester.tap(find.text('16 pt').last);
await tester.pumpAndSettle();
expect(layout.fontSize, 16);
expect(saved()['font_size'], 16);
await tester.tap(find.byType(DropdownMenu<int>));
await tester.pumpAndSettle();
await tester.tap(find.text('50k lines').last);
await tester.pumpAndSettle();
expect(layout.scrollback, 50000);
expect(saved()['scrollback'], 50000);
await tester.tap(find.byKey(const ValueKey('settings-terminal-bell')));
await tester.pumpAndSettle();
expect(layout.bell, isFalse);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.fontSize, 16);
expect(restored.scrollback, 50000);
expect(restored.bell, isFalse);
// Default text size clears it.
await tester.tap(find.byType(DropdownMenu<double>));
await tester.pumpAndSettle();
await tester.tap(find.text('Default').last);
await tester.pumpAndSettle();
expect(layout.fontSize, isNull);
expect(saved().containsKey('font_size'), isFalse);
});
testWidgets('a zoom from the keyboard shows in the menu at once', (
tester,
) async {
await pump(tester);
layout.setFontSize(17);
await tester.pump();
final menu = tester.widget<DropdownMenu<double>>(
find.byType(DropdownMenu<double>),
);
expect(menu.initialSelection, 17);
});
test('a saved scrollback outside the choices and sizes out of range are '
'not restored as they were', () async {
store.saved = jsonEncode({'scrollback': 7, 'font_size': 400});
await layout.restore();
expect(layout.scrollback, terminalScrollbackDefault);
expect(layout.fontSize, terminalFontSizeMax);
expect(layout.bell, isTrue);
});
}
@@ -0,0 +1,90 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'terminal_app.dart';
import 'terminal_fixtures.dart';
const _dot = ValueKey('terminal-tab-bell');
void main() {
late TerminalGateway mac;
late TerminalHub hub;
late TerminalLayout layout;
setUp(() {
mac = TerminalGateway()
..add('term_a', cwd: '/Users/op/src', text: r'$ ')
..add('term_b', cwd: '/Users/op/docs', text: r'$ ');
layout = TerminalLayout(store: MemoryLayoutStore())..visible = true;
hub = TerminalHub(
TestMachines([machine('mac', mac, name: 'Mac')]),
layout: layout,
);
});
tearDown(() async {
hub.dispose();
await mac.close();
});
/// Lets a pushed frame arrive and draw.
Future<void> drain(WidgetTester tester) async {
for (var i = 0; i < 3; i++) {
await tester.pump(const Duration(milliseconds: 1));
}
}
Future<void> open(WidgetTester tester) async {
await pumpTerminalApp(tester, hub: hub, layout: layout);
await tester.pumpAndSettle();
expect(hub.tabs, hasLength(2));
expect(hub.selected!.info.id, 'term_a');
}
testWidgets('a bell in a tab that is not shown dots it until it is '
'selected; the shown tab only flashes', (tester) async {
final semantics = tester.ensureSemantics();
await open(tester);
mac.write('term_b', '\x07');
await drain(tester);
expect(find.byKey(_dot), findsOneWidget);
expect(find.bySemanticsLabel(RegExp(r'\bBell\b')), findsOneWidget);
semantics.dispose();
// The shown terminal flashes instead.
mac.write('term_a', '\x07');
await drain(tester);
expect(find.byKey(const ValueKey('terminal-bell-flash')), findsOneWidget);
expect(find.byKey(_dot), findsOneWidget);
await tester.tap(find.text('docs'));
await tester.pumpAndSettle();
expect(find.byKey(_dot), findsNothing);
// Hidden, every tab dots; turned off, none does.
layout.hide();
await tester.pumpAndSettle();
mac.write('term_b', '\x07');
await drain(tester);
expect(hub.tabs.last.bellUnseen, isTrue);
layout.show();
await tester.pumpAndSettle();
expect(hub.tabs.last.bellUnseen, isFalse);
layout.setBell(false);
mac.write('term_a', '\x07');
await tester.pumpAndSettle();
expect(hub.tabs.first.bellUnseen, isFalse);
});
testWidgets('a folder reported with OSC 7 names an untitled tab and its '
'tooltip; a shell title still wins', (tester) async {
await open(tester);
mac.write('term_a', '\x1b]7;file://mac/Users/op/src/app\x07');
await drain(tester);
expect(find.text('app'), findsOneWidget);
expect(hub.tabs.first.cwd, '/Users/op/src/app');
expect(find.byTooltip('Mac: /Users/op/src/app'), findsOneWidget);
mac.write('term_a', '\x1b]0;vim notes\x07');
await drain(tester);
expect(find.text('vim notes'), findsOneWidget);
expect(find.text('app'), findsNothing);
});
}
@@ -0,0 +1,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());
});
}