Merge branch 'main' into worktree-agent-a3f5466412d4c7d5d

This commit is contained in:
2026-11-26 01:58:57 +00:00
91 changed files with 10011 additions and 320 deletions
@@ -0,0 +1,102 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_bell.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_events.dart';
import 'terminal_view_harness.dart';
const _flash = ValueKey('terminal-bell-flash');
String _osc52(String text) =>
'\x1b]52;c;${base64.encode(utf8.encode(text))}\x07';
void main() {
testWidgets('a bell flashes the border briefly; the setting turns it off', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
expect(find.byKey(_flash), findsNothing);
await harness.write(tester, '\x07');
expect(find.byKey(_flash), findsOneWidget);
await tester.pump(chatShellBellFlash + const Duration(milliseconds: 16));
expect(find.byKey(_flash), findsNothing);
harness.layout.setBell(false);
await tester.pump();
await harness.write(tester, '\x07');
expect(find.byKey(_flash), findsNothing);
});
testWidgets('under reduced motion the bell border holds, then goes', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester, reduceMotion: true);
await harness.write(tester, '\x07');
final border =
tester.widget<DecoratedBox>(find.byKey(_flash)).decoration
as BoxDecoration;
expect((border.border! as Border).top.color.a, 1);
await tester.pump(chatShellBellFlash + const Duration(milliseconds: 16));
expect(find.byKey(_flash), findsNothing);
});
testWidgets('OSC 52 from live output sets the clipboard and says so', (
tester,
) async {
final copied = mockClipboard(tester);
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, _osc52('from vim'));
expect(copied, ['from vim']);
await tester.pump();
expect(find.text('Copied from terminal'), findsOneWidget);
await tester.pump(const Duration(seconds: 3));
await tester.pumpAndSettle();
// A read request (?) is ignored.
await harness.write(tester, '\x1b]52;c;?\x07');
expect(copied, ['from vim']);
});
testWidgets('old output drawn again (a replay) neither copies nor rings', (
tester,
) async {
final copied = mockClipboard(tester);
final harness = TerminalViewHarness();
await harness.pump(tester);
final output = 'old ${_osc52('stale')}\x07done';
harness.session.replay(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': 'running',
'started_at': 1,
'output': output,
'output_bytes': utf8.encode(output).length,
'terminal': true,
})!,
);
await tester.pumpAndSettle();
expect(copied, isEmpty);
expect(harness.session.events.bells.value, 0);
expect(find.byKey(_flash), findsNothing);
});
test('OSC 7 reports the folder as a path', () {
expect(
chatShellWorkingDirectoryPath('file://mac.local/Users/op/src%20x'),
'/Users/op/src x',
);
expect(chatShellWorkingDirectoryPath('file:///tmp'), '/tmp');
expect(chatShellWorkingDirectoryPath('https://example.com/a'), isNull);
expect(chatShellWorkingDirectoryPath('file://host'), '/');
final harness = TerminalViewHarness();
addTearDown(harness.session.dispose);
harness.terminal.write('\x1b]7;file://mac/Users/op/work\x1b\\');
expect(harness.session.events.workingDirectory.value, '/Users/op/work');
});
}
@@ -0,0 +1,127 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_cursor_blink.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_links.dart';
import 'package:xterm/xterm.dart';
import 'terminal_view_harness.dart';
const _phase = chatShellCursorBlinkPhase;
void main() {
bool shown(WidgetTester tester, TerminalViewHarness harness) =>
harness.view(tester).cursorBlinkVisible!.value;
testWidgets('a blinking DECSCUSR cursor blinks while focused and is steady '
'once unfocused, leaving no frames scheduled', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, '\x1b[5 q');
await harness.focus(tester);
expect(shown(tester, harness), isTrue);
await tester.pump(_phase + const Duration(milliseconds: 10));
expect(shown(tester, harness), isFalse);
await tester.pump(_phase);
expect(shown(tester, harness), isTrue);
// Output shows it again and restarts the phase.
await tester.pump(_phase);
expect(shown(tester, harness), isFalse);
await harness.write(tester, 'x');
expect(shown(tester, harness), isTrue);
// Unfocused: steady, and the ticker stopped.
harness.view(tester).focusNode!.unfocus();
await tester.pump();
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('a steady shape (even Ps) does not blink', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, '\x1b[2 q');
await harness.focus(tester);
await tester.pump(_phase * 3);
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('reduced motion keeps a blinking cursor steady', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester, reduceMotion: true);
await harness.write(tester, '\x1b[1 q');
await harness.focus(tester);
await tester.pump(_phase + const Duration(milliseconds: 10));
expect(shown(tester, harness), isTrue);
expect(tester.binding.hasScheduledFrame, isFalse);
});
testWidgets('a selection clears when its rows are rewritten, the screen is '
'cleared or the program switches screens', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, 'keep this\r\nother\r\n');
final controller = harness.controller(tester);
final buffer = harness.terminal.buffer;
void select() => controller.setSelection(
buffer.createAnchor(0, 0),
buffer.createAnchor(4, 0),
);
select();
// Output elsewhere leaves it.
await harness.write(tester, 'more output\r\n');
expect(controller.selection, isNotNull);
// Rewriting the selected row clears it.
await harness.write(tester, '\x1b[1;1Hgone');
expect(controller.selection, isNull);
select();
await harness.write(tester, '\x1b[2J');
expect(controller.selection, isNull);
select();
await harness.write(tester, '\x1b[?1049h');
expect(controller.selection, isNull);
});
testWidgets('hovering a web or OSC 8 link shows a pointer and underlines '
'it; a click opens it as before', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'see https://example.com/a now\r\n'
'\x1b]8;;https://example.org/b\x1b\\docs\x1b]8;;\x1b\\ plain',
);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
addTearDown(mouse.removePointer);
await mouse.addPointer(location: harness.cellCentre(tester, 0, 0));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.text);
await mouse.moveTo(harness.cellCentre(tester, 8, 0));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.click);
// The OSC 8 link's text is not an address; its target is.
await mouse.moveTo(harness.cellCentre(tester, 1, 1));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.click);
await mouse.moveTo(harness.cellCentre(tester, 7, 1));
await tester.pump();
expect(harness.view(tester).mouseCursor, SystemMouseCursors.text);
});
test('the link under a cell: OSC 8 first, then printed addresses', () {
final terminal = Terminal(maxLines: 50)..resize(20, 4);
terminal.write(
'\x1b]8;;https://example.org/long\x1b\\0123456789abcdefghijkl'
'\x1b]8;;\x1b\\ x https://e.com/q).',
);
final hyperlink = chatShellTerminalLinkAt(terminal, const CellOffset(5, 0));
expect(hyperlink!.uri.toString(), 'https://example.org/long');
// It wraps onto the next row.
expect(hyperlink.begin, const CellOffset(0, 0));
expect(hyperlink.end, const CellOffset(2, 1));
final printed = chatShellTerminalLinkAt(terminal, const CellOffset(6, 1));
expect(printed!.uri.toString(), 'https://e.com/q');
expect(printed.begin, const CellOffset(5, 1));
expect(printed.end, const CellOffset(20, 1));
});
}
@@ -0,0 +1,149 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_search.dart';
import 'package:xterm/xterm.dart';
import 'terminal_view_harness.dart';
const _field = ValueKey('terminal-find-field');
String _count(WidgetTester tester) => tester
.widget<Text>(find.byKey(const ValueKey('terminal-find-count')))
.data!;
/// Opens the find bar with the platform's key.
Future<void> _openFind(WidgetTester tester) => isApple()
? chordKeys(tester, LogicalKeyboardKey.keyF, [LogicalKeyboardKey.metaLeft])
: chordKeys(tester, LogicalKeyboardKey.keyF, [
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.shiftLeft,
]);
void main() {
test('search joins wrapped rows, folds case unless asked and maps cells', () {
final terminal = Terminal(maxLines: 100)..resize(10, 4);
terminal.write('abc Needle\r\nxxxxxxxneedle NEEDLE\r\n中文needle');
final all = chatShellTerminalSearch(terminal.buffer, 'needle');
expect(all, hasLength(4));
// "Needle" fills the first row's last six cells.
expect(
all[0],
const ChatShellSearchMatch(CellOffset(4, 0), CellOffset(10, 0)),
);
// The second line wraps: its "needle" spans rows 1 and 2.
expect(
all[1],
const ChatShellSearchMatch(CellOffset(7, 1), CellOffset(3, 2)),
);
expect(all[2].begin, const CellOffset(4, 2));
// Wide characters take two cells each; the match starts after both.
expect(all[3].begin, const CellOffset(4, 3));
final exact = chatShellTerminalSearch(
terminal.buffer,
'needle',
caseSensitive: true,
);
expect(exact, hasLength(2));
expect(chatShellTerminalSearch(terminal.buffer, ''), isEmpty);
expect(
chatShellTerminalSearch(terminal.buffer, 'needle', limit: 2),
hasLength(2),
);
});
testWidgets('the find key opens the bar; matches are counted, highlighted '
'and scrolled to; Esc closes it and the terminal has the keys again', (
tester,
) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'first needle\r\n'
'${List.filled(60, 'filler').join('\r\n')}\r\n'
'Needle two\r\n'
'last needle',
);
await harness.focus(tester);
await _openFind(tester);
expect(find.byKey(_field), findsOneWidget);
await tester.pump();
// The field has the keyboard, which the terminal held.
expect(
tester.widget<TextField>(find.byKey(_field)).focusNode!.hasFocus,
isTrue,
);
// The keys went to the find bar, not the shell.
expect(harness.typed, isEmpty);
await tester.enterText(find.byKey(_field), 'needle');
await tester.pump();
// Searching upwards: the current match is the last one.
expect(_count(tester), '3 of 3');
expect(harness.controller(tester).highlights, hasLength(3));
final bottom = harness.scroll(tester).maxScrollExtent;
expect(harness.scroll(tester).pixels, bottom);
// Next wraps to the first match, at the top of the scrollback.
await tester.tap(find.byKey(const ValueKey('terminal-find-next')));
await tester.pump();
expect(_count(tester), '1 of 3');
expect(harness.scroll(tester).pixels, lessThan(bottom));
// Shift+Enter goes back.
await chordKeys(tester, LogicalKeyboardKey.enter, [
LogicalKeyboardKey.shiftLeft,
]);
expect(_count(tester), '3 of 3');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(_count(tester), '1 of 3');
// Match case leaves out "Needle".
await tester.tap(find.byKey(const ValueKey('terminal-find-case')));
await tester.pump();
expect(_count(tester), '2 of 2');
await tester.enterText(find.byKey(_field), 'absent');
await tester.pump();
expect(_count(tester), 'No results');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.byKey(_field), findsNothing);
expect(harness.controller(tester).highlights, isEmpty);
expect(harness.view(tester).focusNode!.hasFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.keyX);
await tester.pump();
expect(harness.typed, 'x');
}, variant: desktops);
testWidgets(
'outside Apple platforms Ctrl+F stays the shell\'s',
(tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.focus(tester);
await chordKeys(tester, LogicalKeyboardKey.keyF, [
LogicalKeyboardKey.controlLeft,
]);
expect(find.byKey(_field), findsNothing);
expect(harness.typed, '\x06');
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
testWidgets(
'output after a search is found by the next step',
(tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, 'one match\r\n');
await harness.focus(tester);
await _openFind(tester);
await tester.enterText(find.byKey(_field), 'match');
await tester.pump();
expect(_count(tester), '1 of 1');
await harness.write(tester, 'two match\r\n');
await tester.tap(find.byKey(const ValueKey('terminal-find-next')));
await tester.pump();
expect(_count(tester), '2 of 2');
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
}
@@ -0,0 +1,112 @@
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'terminal_view_harness.dart';
void main() {
testWidgets('Cmd/Ctrl with =, - and 0 zoom a focused terminal; the size '
'is saved and the process is resized to the new cells', (tester) async {
final store = MemoryStore();
final harness = TerminalViewHarness(layout: TerminalLayout(store: store));
await harness.pump(tester);
await harness.focus(tester);
final base = harness.view(tester).textStyle.fontSize;
final cols = harness.terminal.viewWidth;
final command = commandKey();
await chordKeys(tester, LogicalKeyboardKey.equal, [command]);
await chordKeys(tester, LogicalKeyboardKey.equal, [command]);
expect(harness.layout.fontSize, base.roundToDouble() + 2);
expect(harness.view(tester).textStyle.fontSize, base.roundToDouble() + 2);
// Larger cells: fewer columns, through the normal resize path.
expect(harness.terminal.viewWidth, lessThan(cols));
expect(harness.sizes.last.$1, harness.terminal.viewWidth);
await tester.pump();
expect(jsonDecode(store.saved!)['font_size'], base.roundToDouble() + 2);
await chordKeys(tester, LogicalKeyboardKey.minus, [command]);
expect(harness.layout.fontSize, base.roundToDouble() + 1);
await chordKeys(tester, LogicalKeyboardKey.digit0, [command]);
expect(harness.layout.fontSize, isNull);
expect(harness.view(tester).textStyle.fontSize, base);
expect(harness.terminal.viewWidth, cols);
// None of it reached the shell.
expect(harness.typed, isEmpty);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.fontSize, isNull);
}, variant: desktops);
testWidgets(
'zooming stops at the size limits',
(tester) async {
final harness = TerminalViewHarness();
harness.layout.setFontSize(terminalFontSizeMax - 1);
await harness.pump(tester);
await harness.focus(tester);
for (var i = 0; i < 3; i++) {
await chordKeys(tester, LogicalKeyboardKey.equal, [commandKey()]);
}
expect(harness.layout.fontSize, terminalFontSizeMax);
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
testWidgets('Shift+PgUp/PgDn/Home/End scroll the scrollback locally; on the '
'alternate screen they reach the program', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
List.generate(200, (i) => 'line $i').join('\r\n'),
);
await harness.focus(tester);
final bottom = harness.scroll(tester).maxScrollExtent;
expect(harness.scroll(tester).pixels, bottom);
const shift = [LogicalKeyboardKey.shiftLeft];
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
final page = bottom - harness.scroll(tester).pixels;
expect(page, greaterThan(0));
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
expect(harness.scroll(tester).pixels, closeTo(bottom - 2 * page, 0.01));
await chordKeys(tester, LogicalKeyboardKey.pageDown, shift);
expect(harness.scroll(tester).pixels, closeTo(bottom - page, 0.01));
await chordKeys(tester, LogicalKeyboardKey.home, shift);
expect(harness.scroll(tester).pixels, 0);
await chordKeys(tester, LogicalKeyboardKey.end, shift);
expect(harness.scroll(tester).pixels, bottom);
expect(harness.typed, isEmpty);
// A full-screen program (less, vim) gets them.
await harness.write(tester, '\x1b[?1049h');
await chordKeys(tester, LogicalKeyboardKey.pageUp, shift);
expect(harness.typed, '\x1b[5;2~');
}, variant: desktops);
testWidgets('the scrollback setting applies to new and open terminals', (
tester,
) async {
final harness = TerminalViewHarness();
expect(harness.layout.scrollback, terminalScrollbackDefault);
expect(harness.terminal.maxLines, 10000);
await harness.pump(tester);
await harness.write(
tester,
List.generate(1500, (i) => 'line $i').join('\r\n'),
);
expect(harness.terminal.buffer.height, 1500);
harness.layout.setScrollback(1000);
await tester.pump();
expect(harness.terminal.maxLines, 1000);
expect(harness.terminal.buffer.height, 1000);
// The newest lines are kept.
final buffer = harness.terminal.buffer;
expect(buffer.lines[buffer.height - 1].getText().trim(), 'line 1499');
expect(buffer.lines[0].getText().trim(), 'line 500');
await harness.write(tester, '\r\nmore');
expect(harness.terminal.buffer.height, 1000);
final next = TerminalViewHarness(layout: harness.layout);
addTearDown(next.session.dispose);
expect(next.terminal.maxLines, 1000);
});
}
@@ -0,0 +1,81 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'terminal_view_harness.dart';
Finder _item(String name) => find.byKey(ValueKey('terminal-menu-$name'));
bool _enabled(WidgetTester tester, String name) =>
tester.widget<PopupMenuItem<Object?>>(_item(name)).enabled;
void main() {
testWidgets('right-click offers Copy with a selection, Paste, Select all, '
'Clear scrollback and Find', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(
tester,
'${List.generate(40, (i) => 'old $i').join('\r\n')}\r\nhello world',
);
final copied = mockClipboard(tester, paste: 'pasted');
final screenTop =
harness.terminal.buffer.height - harness.terminal.viewHeight;
final last = harness.terminal.buffer.height - 1;
await harness.rightClick(tester, 2, last);
expect(_item('copy'), findsOneWidget);
expect(_enabled(tester, 'copy'), isFalse);
for (final name in ['paste', 'selectAll', 'clear', 'find']) {
expect(_item(name), findsOneWidget, reason: name);
}
// Paste types the clipboard into the process.
await tester.tap(_item('paste'));
await tester.pumpAndSettle();
expect(harness.typed, 'pasted');
// Select all takes the scrollback too; Copy copies it.
await harness.rightClick(tester, 2, last);
await tester.tap(_item('selectAll'));
await tester.pumpAndSettle();
final selection = harness.controller(tester).selection!.normalized;
expect(selection.begin.y, 0);
expect(selection.end.y, last);
await harness.rightClick(tester, 2, last);
expect(_enabled(tester, 'copy'), isTrue);
await tester.tap(_item('copy'));
await tester.pumpAndSettle();
expect(copied.single, startsWith('old 0\nold 1'));
expect(copied.single, contains('hello world'));
// Clear scrollback keeps only the screen.
expect(screenTop, greaterThan(0));
await harness.rightClick(tester, 2, last);
await tester.tap(_item('clear'));
await tester.pumpAndSettle();
expect(harness.terminal.buffer.height, harness.terminal.viewHeight);
// Find… opens the find bar.
await harness.rightClick(tester, 2, harness.terminal.viewHeight - 1);
await tester.tap(_item('find'));
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('terminal-find-field')), findsOneWidget);
}, variant: desktops);
testWidgets('a program tracking the mouse gets the right button unless '
'Shift is held', (tester) async {
final harness = TerminalViewHarness();
await harness.pump(tester);
await harness.write(tester, r'$ ');
// X10/normal tracking with SGR coordinates.
await harness.write(tester, '\x1b[?1000h\x1b[?1006h');
await harness.rightClick(tester, 3, 0);
expect(_item('copy'), findsNothing);
expect(harness.typed, '\x1b[<2;4;1M\x1b[<2;4;1m');
await harness.rightClick(tester, 3, 0, shift: true);
expect(_item('copy'), findsOneWidget);
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets('finished output offers no Paste', (tester) async {
final harness = TerminalViewHarness(live: false);
await harness.pump(tester);
await harness.rightClick(tester, 1, 0);
expect(_item('copy'), findsOneWidget);
expect(_item('paste'), findsNothing);
});
}
@@ -0,0 +1,191 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_view.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'package:xterm/xterm.dart';
/// A terminal layout saved in memory.
class MemoryStore implements TerminalLayoutStore {
String? saved;
@override
Future<String?> load() async => saved;
@override
Future<bool> save(String value) async {
saved = value;
return true;
}
}
/// One live terminal view filling an 800x500 app, with what it sends to the
/// process collected in [sent].
class TerminalViewHarness {
TerminalViewHarness({TerminalLayout? layout, bool live = true})
: layout = layout ?? TerminalLayout(store: MemoryStore()) {
session = ChatShellTerminalSession(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': live ? 'running' : 'exited',
'started_at': 1,
'output': '',
'output_bytes': 0,
'terminal': true,
'cols': 80,
'rows': 24,
})!,
onInput: sent.add,
onResize: (cols, rows) => sizes.add((cols, rows)),
layout: this.layout,
);
}
final TerminalLayout layout;
late final ChatShellTerminalSession session;
final List<String> sent = [];
final List<(int, int)> sizes = [];
Terminal get terminal => session.terminal;
String get typed => sent.join();
Future<void> pump(WidgetTester tester, {bool reduceMotion = false}) async {
tester.view.physicalSize = const Size(800, 500);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
addTearDown(session.dispose);
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(disableAnimations: reduceMotion),
child: Scaffold(
body: ChatShellTerminalView(
session: session,
fill: true,
autofocus: true,
),
),
),
),
),
);
await tester.pump();
}
TerminalView view(WidgetTester tester) =>
tester.widget<TerminalView>(find.byType(TerminalView));
TerminalViewState viewState(WidgetTester tester) =>
tester.state<TerminalViewState>(find.byType(TerminalView));
TerminalController controller(WidgetTester tester) =>
view(tester).controller!;
ScrollPosition scroll(WidgetTester tester) =>
view(tester).scrollController!.position;
/// The global centre of buffer cell ([x], [y]).
Offset cellCentre(WidgetTester tester, int x, int y) {
final render = viewState(tester).renderTerminal;
final cell = render.cellSize;
return render.localToGlobal(
render.getOffset(CellOffset(x, y)) +
Offset(cell.width / 2, cell.height / 2),
);
}
/// Writes [text] as live output and lets the view redraw.
Future<void> write(WidgetTester tester, String text) async {
terminal.write(text);
await tester.pump();
}
/// Focuses the emulator.
Future<void> focus(WidgetTester tester) async {
final node = view(tester).focusNode!;
node.requestFocus();
await tester.pump();
}
/// Right-clicks buffer cell ([x], [y]) with a mouse, holding Shift when
/// [shift].
Future<void> rightClick(
WidgetTester tester,
int x,
int y, {
bool shift = false,
}) async {
if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
final gesture = await tester.startGesture(
cellCentre(tester, x, y),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await gesture.up();
if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
await tester.pumpAndSettle();
}
}
/// Presses [key] with [modifiers] held.
Future<void> chordKeys(
WidgetTester tester,
LogicalKeyboardKey key, [
List<LogicalKeyboardKey> modifiers = const [],
]) async {
for (final modifier in modifiers) {
await tester.sendKeyDownEvent(modifier);
}
await tester.sendKeyEvent(key);
for (final modifier in modifiers.reversed) {
await tester.sendKeyUpEvent(modifier);
}
await tester.pump();
}
/// The platform's command key: Cmd on Apple platforms, else Ctrl.
LogicalKeyboardKey commandKey() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS
? LogicalKeyboardKey.metaLeft
: LogicalKeyboardKey.controlLeft;
bool isApple() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
/// Collects what the app writes to the clipboard, answering reads with
/// [paste].
List<String> mockClipboard(WidgetTester tester, {String paste = ''}) {
final texts = <String>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
texts.add('${(call.arguments as Map)['text']}');
}
if (call.method == 'Clipboard.getData') return {'text': paste};
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
return texts;
}
/// Desktop platforms: a Mac and one that is not.
final desktops = TargetPlatformVariant({
TargetPlatform.macOS,
TargetPlatform.linux,
});
@@ -0,0 +1,100 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/settings/settings_terminal_section.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
class _Store implements TerminalLayoutStore {
String? saved;
@override
Future<String?> load() async => saved;
@override
Future<bool> save(String value) async {
saved = value;
return true;
}
}
void main() {
late _Store store;
late TerminalLayout layout;
setUp(() {
store = _Store();
layout = TerminalLayout(store: store);
});
Future<void> pump(WidgetTester tester) async {
tester.view.physicalSize = const Size(900, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: SettingsTerminalSection(layout: layout),
),
),
),
);
}
Map<String, dynamic> saved() =>
jsonDecode(store.saved!) as Map<String, dynamic>;
testWidgets('text size, scrollback and the visual bell are chosen in '
'Settings and saved with the layout', (tester) async {
await pump(tester);
expect(find.text('Text size'), findsOneWidget);
expect(find.text('Scrollback'), findsOneWidget);
await tester.tap(find.byType(DropdownMenu<double>));
await tester.pumpAndSettle();
await tester.tap(find.text('16 pt').last);
await tester.pumpAndSettle();
expect(layout.fontSize, 16);
expect(saved()['font_size'], 16);
await tester.tap(find.byType(DropdownMenu<int>));
await tester.pumpAndSettle();
await tester.tap(find.text('50k lines').last);
await tester.pumpAndSettle();
expect(layout.scrollback, 50000);
expect(saved()['scrollback'], 50000);
await tester.tap(find.byKey(const ValueKey('settings-terminal-bell')));
await tester.pumpAndSettle();
expect(layout.bell, isFalse);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.fontSize, 16);
expect(restored.scrollback, 50000);
expect(restored.bell, isFalse);
// Default text size clears it.
await tester.tap(find.byType(DropdownMenu<double>));
await tester.pumpAndSettle();
await tester.tap(find.text('Default').last);
await tester.pumpAndSettle();
expect(layout.fontSize, isNull);
expect(saved().containsKey('font_size'), isFalse);
});
testWidgets('a zoom from the keyboard shows in the menu at once', (
tester,
) async {
await pump(tester);
layout.setFontSize(17);
await tester.pump();
final menu = tester.widget<DropdownMenu<double>>(
find.byType(DropdownMenu<double>),
);
expect(menu.initialSelection, 17);
});
test('a saved scrollback outside the choices and sizes out of range are '
'not restored as they were', () async {
store.saved = jsonEncode({'scrollback': 7, 'font_size': 400});
await layout.restore();
expect(layout.scrollback, terminalScrollbackDefault);
expect(layout.fontSize, terminalFontSizeMax);
expect(layout.bell, isTrue);
});
}
@@ -28,6 +28,12 @@ class TerminalGateway implements ApiGateway {
/// where runs of invalid bytes became one shorter replacement character).
final Map<String, int> byteShift = {};
/// A terminal's state as the server's snapshot: when set, a read from
/// before [snapshotFrom] gets it (as of the output's end) instead of raw
/// output.
final Map<String, String> snapshots = {};
int snapshotFrom = 1 << 30;
@override
Stream<JsonMap> get frames => _frames.stream;
@@ -56,6 +62,19 @@ class TerminalGateway implements ApiGateway {
final text = output[id] ?? '';
final bytes = utf8.encode(text);
final start = after.clamp(0, bytes.length);
final snapshot = snapshots[id];
if (withOutput && snapshot != null && after < snapshotFrom) {
final end = bytes.length + (byteShift[id] ?? 0);
return {
...terminals[id]!,
'stream': stream,
'output': snapshot,
'output_start': end,
'output_end': end,
'output_snapshot': true,
if (window > 0) 'window': window,
};
}
return {
...terminals[id]!,
'stream': stream,
@@ -0,0 +1,149 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
import 'package:pipelines_app/features/terminal/terminal_tab.dart';
import 'package:xterm/core.dart';
import 'terminal_fixtures.dart';
/// What the server's emulator (internal/termstate) writes for a 40x8
/// terminal where a shell ran twelve commands and then nvim, which set
/// mouse, bracketed paste and application cursor/keypad modes on the
/// alternate screen.
const _snapshot =
'\x1bc\x1b[3J\x1b]2;nvim notes.txt\x07'
'\$ echo 1\r\n1\r\n\$ echo 2\r\n2\r\n\$ echo 3\r\n3\r\n\$ echo 4\r\n4\r\n'
'\$ echo 5\r\n5\r\n\$ echo 6\r\n6\r\n\$ echo 7\r\n7\r\n\$ echo 8\r\n8\r\n'
'\$ echo 9\r\n9\r\n\$ echo 10\r\n10\r\n\$ echo 11\r\n11\r\n'
'\$ echo 12\r\n12\r\n\$ nvim notes.txt\r\n'
'\x1b[8;1H\x1b[?1049h\x1b[1;1H\x1b[0;1;34mFRAME\x1b[2;1H\x1b[0mline two'
'\x1b[8;1H\x1b[0;7m-- INSERT --\x1b[2;9H\x1b[?1h\x1b=\x1b[?25l'
'\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[0m';
/// What nvim writes as it exits, then the shell.
const _exit =
'\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?1l\x1b>\x1b[?25h\x1b[?1049l'
'\$ ls\r\nnotes.txt\r\n\$ ';
/// The rows on screen (not the scrollback), trailing blanks trimmed.
List<String> rows(Terminal terminal) {
final buffer = terminal.buffer;
final top = buffer.height - terminal.viewHeight;
return [
for (var y = top; y < buffer.height; y++)
buffer.lines[y].getText().trimRight(),
];
}
void main() {
late TerminalGateway mac;
late TerminalHub hub;
setUp(() {
mac = TerminalGateway()..window = 1 << 18;
hub = TerminalHub(TestMachines([machine('mac', mac, name: 'Mac')]));
});
tearDown(() async {
hub.dispose();
await mac.close();
});
Future<void> settle() async {
for (var i = 0; i < 5; i++) {
await Future<void>.delayed(Duration.zero);
}
}
/// A terminal whose stream is longer than the server's tail.
void longTerminal(String raw) {
mac.add('term_a', text: raw);
mac.terminals['term_a']!['cols'] = 40;
mac.terminals['term_a']!['rows'] = 8;
}
void expectNvim(TerminalTab tab) {
final terminal = tab.session.terminal;
expect(terminal.isUsingAltBuffer, isTrue);
expect(rows(terminal), [
'FRAME',
'line two',
'',
'',
'',
'',
'',
'-- INSERT --',
]);
expect(terminal.buffer.cursorX, 8);
expect(terminal.buffer.cursorY, 1);
expect(terminal.mouseMode, MouseMode.upDownScrollDrag);
expect(terminal.mouseReportMode, MouseReportMode.sgr);
expect(terminal.bracketedPasteMode, isTrue);
expect(terminal.cursorKeysMode, isTrue);
expect(terminal.appKeypadMode, isTrue);
expect(terminal.cursorVisibleMode, isFalse);
expect(tab.title, 'nvim notes.txt');
}
void expectShellAfterExit(TerminalTab tab) {
final terminal = tab.session.terminal;
expect(terminal.isUsingAltBuffer, isFalse);
expect(rows(terminal), [
r'$ echo 11',
'11',
r'$ echo 12',
'12',
r'$ nvim notes.txt',
r'$ ls',
'notes.txt',
r'$',
]);
// The shell's history above the screen came back with it.
expect(terminal.buffer.lines[0].getText().trimRight(), r'$ echo 1');
expect(terminal.mouseMode, MouseMode.none);
expect(terminal.bracketedPasteMode, isFalse);
expect(terminal.cursorKeysMode, isFalse);
expect(terminal.cursorVisibleMode, isTrue);
}
test('a reload draws the snapshot: the program on the alternate screen, '
'its modes, and the shell underneath once it exits', () async {
longTerminal('x' * 3000);
mac.snapshots['term_a'] = _snapshot;
hub.activate();
await settle();
final tab = hub.tabs.single;
expect(mac.bodies('terminal_output').single['after'], isNull);
expect(tab.session.end, 3000);
expectNvim(tab);
// No "earlier output was dropped" line: the snapshot misses nothing.
expect(
tab.session.terminal.mainBuffer.lines[0].getText(),
isNot(contains('dropped')),
);
mac.write('term_a', _exit);
await settle();
expectShellAfterExit(tab);
});
test('after a gap the snapshot replaces what the tab drew, modes '
'included', () async {
longTerminal('stale\x1b[?1000h\x1b[?1049h');
hub.activate();
await settle();
final tab = hub.tabs.single;
expect(tab.session.terminal.mouseMode, MouseMode.upDownScroll);
final held = tab.session.end;
// The tab falls behind past the server's tail, which now starts later.
mac.write('term_a', 'y' * 5000, push: false);
mac.snapshots['term_a'] = _snapshot;
mac.snapshotFrom = held + 100;
final end = held + 5000;
mac.pushOutput('term_a', 'z', end, end: end + 1);
await settle();
expect(mac.bodies('terminal_output').last['after'], held);
expectNvim(tab);
mac.write('term_a', _exit);
await settle();
expectShellAfterExit(tab);
});
}
@@ -0,0 +1,90 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
import 'terminal_app.dart';
import 'terminal_fixtures.dart';
const _dot = ValueKey('terminal-tab-bell');
void main() {
late TerminalGateway mac;
late TerminalHub hub;
late TerminalLayout layout;
setUp(() {
mac = TerminalGateway()
..add('term_a', cwd: '/Users/op/src', text: r'$ ')
..add('term_b', cwd: '/Users/op/docs', text: r'$ ');
layout = TerminalLayout(store: MemoryLayoutStore())..visible = true;
hub = TerminalHub(
TestMachines([machine('mac', mac, name: 'Mac')]),
layout: layout,
);
});
tearDown(() async {
hub.dispose();
await mac.close();
});
/// Lets a pushed frame arrive and draw.
Future<void> drain(WidgetTester tester) async {
for (var i = 0; i < 3; i++) {
await tester.pump(const Duration(milliseconds: 1));
}
}
Future<void> open(WidgetTester tester) async {
await pumpTerminalApp(tester, hub: hub, layout: layout);
await tester.pumpAndSettle();
expect(hub.tabs, hasLength(2));
expect(hub.selected!.info.id, 'term_a');
}
testWidgets('a bell in a tab that is not shown dots it until it is '
'selected; the shown tab only flashes', (tester) async {
final semantics = tester.ensureSemantics();
await open(tester);
mac.write('term_b', '\x07');
await drain(tester);
expect(find.byKey(_dot), findsOneWidget);
expect(find.bySemanticsLabel(RegExp(r'\bBell\b')), findsOneWidget);
semantics.dispose();
// The shown terminal flashes instead.
mac.write('term_a', '\x07');
await drain(tester);
expect(find.byKey(const ValueKey('terminal-bell-flash')), findsOneWidget);
expect(find.byKey(_dot), findsOneWidget);
await tester.tap(find.text('docs'));
await tester.pumpAndSettle();
expect(find.byKey(_dot), findsNothing);
// Hidden, every tab dots; turned off, none does.
layout.hide();
await tester.pumpAndSettle();
mac.write('term_b', '\x07');
await drain(tester);
expect(hub.tabs.last.bellUnseen, isTrue);
layout.show();
await tester.pumpAndSettle();
expect(hub.tabs.last.bellUnseen, isFalse);
layout.setBell(false);
mac.write('term_a', '\x07');
await tester.pumpAndSettle();
expect(hub.tabs.first.bellUnseen, isFalse);
});
testWidgets('a folder reported with OSC 7 names an untitled tab and its '
'tooltip; a shell title still wins', (tester) async {
await open(tester);
mac.write('term_a', '\x1b]7;file://mac/Users/op/src/app\x07');
await drain(tester);
expect(find.text('app'), findsOneWidget);
expect(hub.tabs.first.cwd, '/Users/op/src/app');
expect(find.byTooltip('Mac: /Users/op/src/app'), findsOneWidget);
mac.write('term_a', '\x1b]0;vim notes\x07');
await drain(tester);
expect(find.text('vim notes'), findsOneWidget);
expect(find.text('app'), findsNothing);
});
}
@@ -0,0 +1,311 @@
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/src/ui/painter.dart';
import 'package:xterm/src/ui/row_pictures.dart';
import 'package:xterm/xterm.dart';
import 'paint_fixture.dart';
/// Box drawing, block and Powerline characters are geometry that fills the
/// cell, so they join across cells and rows; text runs land on the grid.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final painter = fixturePainter();
final w = painter.cellSize.width.round();
final h = painter.cellSize.height.round();
/// A line of [cols] cells written with [text] by a terminal.
BufferLine lineOf(String text, {int cols = 6}) {
final terminal = Terminal(maxLines: 100)..resize(cols, 5);
terminal.write(text);
return terminal.buffer.lines[0];
}
/// [lines] painted one under the other.
Future<Pixels> paintLines(List<BufferLine> lines, {int cols = 6}) =>
Pixels.paint(cols * w, lines.length * h, (canvas) {
for (var i = 0; i < lines.length; i++) {
painter.paintLine(canvas, Offset(0, i * h.toDouble()), lines[i]);
}
});
Rect cellRect(int x, int y) => Rect.fromLTWH(
x * w.toDouble(),
y * h.toDouble(),
w.toDouble(),
h.toDouble(),
);
test('cells are whole pixels high', () {
final odd = TerminalPainter(
theme: fixtureTheme,
textStyle: const TerminalStyle(fontSize: 13, height: 1.15),
textScaler: TextScaler.noScaling,
);
final height = odd.cellSize.height;
expect(height, height.roundToDouble());
});
test('a full block fills its cell exactly', () async {
final pixels = await paintLines([lineOf('\u2588')]);
expect(pixels.count(foregroundColor, cellRect(0, 0)), w * h);
expect(pixels.count(foregroundColor, cellRect(1, 0)), 0);
});
test('half and eighth blocks fill their part of the cell', () async {
final pixels = await paintLines([lineOf('\u2580\u2584\u258C\u2581')]);
expect(pixels.count(foregroundColor, cellRect(0, 0)), w * h ~/ 2);
expect(pixels.at(w ~/ 2, 0), foregroundColor); // upper half
expect(pixels.at(w + w ~/ 2, h - 1), foregroundColor); // lower half
expect(pixels.at(w + w ~/ 2, 0).a, 0);
expect(pixels.at(2 * w, h ~/ 2), foregroundColor); // left half
expect(pixels.at(3 * w - 1, h ~/ 2).a, 0);
// The lower eighth: whole pixel rows, about an eighth of the height.
final rows = [
for (var y = 0; y < h; y++)
if (pixels.count(
foregroundColor,
Rect.fromLTWH(3.0 * w, y.toDouble(), w.toDouble(), 1),
) ==
w)
y,
];
expect(rows.length, closeTo(h / 8, 1));
expect(rows.last, h - 1);
for (var y = 0; y < h; y++) {
if (!rows.contains(y)) expect(pixels.at(3 * w + w ~/ 2, y).a, 0);
}
});
test('a horizontal line runs unbroken across cells', () async {
final pixels = await paintLines([lineOf('\u2500\u2500\u2500')]);
final row = [
for (var y = 0; y < h; y++)
if (pixels.at(1, y) == foregroundColor) y,
];
expect(row, isNotEmpty);
for (var x = 0; x < 3 * w; x++) {
expect(pixels.at(x, row.first), foregroundColor, reason: 'x=$x');
}
});
test('a vertical line runs unbroken across rows', () async {
final pixels = await paintLines([lineOf('\u2502'), lineOf('\u2502')]);
final column = [
for (var x = 0; x < w; x++)
if (pixels.at(x, 1) == foregroundColor) x,
];
expect(column, isNotEmpty);
for (var y = 0; y < 2 * h; y++) {
expect(pixels.at(column.first, y), foregroundColor, reason: 'y=$y');
}
});
test('corners and tees join the lines they meet', () async {
// \u250C\u2500\u2510 over \u2502 \u2502: the corner's arms reach the cell edges.
final pixels = await paintLines([
lineOf('\u250C\u2500\u2510'),
lineOf('\u2502 \u2502'),
]);
final lineY = [
for (var y = 0; y < h; y++)
if (pixels.at(w + 1, y) == foregroundColor) y,
].first;
final lineX = [
for (var x = 0; x < w; x++)
if (pixels.at(x, h + 1) == foregroundColor) x,
].first;
// The corner's right arm reaches its right edge, the down arm its bottom.
expect(pixels.at(w - 1, lineY), foregroundColor);
expect(pixels.at(lineX, h - 1), foregroundColor);
// Nothing left of or above the corner's elbow.
expect(pixels.at(0, lineY).a, 0);
expect(pixels.at(lineX, 0).a, 0);
});
test('double lines draw two strokes', () async {
final pixels = await paintLines([lineOf('\u2550')]);
final rows = [
for (var y = 0; y < h; y++)
if (pixels.at(w ~/ 2, y) == foregroundColor) y,
];
// Two separate strokes: a gap between the first and last painted rows.
expect(rows.length, lessThan(rows.last - rows.first + 1));
for (var x = 0; x < w; x++) {
expect(pixels.at(x, rows.first), foregroundColor);
expect(pixels.at(x, rows.last), foregroundColor);
}
});
test('a Powerline arrow fills the cell height at its base', () async {
final pixels = await paintLines([lineOf('\uE0B0\uE0B2')]);
// Right-pointing: the whole left column; left-pointing: the right (the
// top and bottom pixels are the antialiased points of the triangle).
for (var y = 1; y < h - 1; y++) {
expect(pixels.at(0, y), foregroundColor, reason: 'y=$y');
expect(pixels.at(2 * w - 1, y), foregroundColor, reason: 'y=$y');
}
expect(pixels.at(0, 0).a, greaterThan(0.4));
expect(pixels.at(0, h - 1).a, greaterThan(0.4));
// The tip reaches the far side only in the middle.
expect(pixels.at(w - 1, h ~/ 2).a, greaterThan(0));
expect(pixels.at(w - 1, 0).a, 0);
expect(pixels.at(w, 0).a, 0);
// About half the cell.
final filled = pixels.count(foregroundColor, cellRect(0, 0));
expect(filled, closeTo(w * h / 2, w * h * 0.1));
});
test('Powerline diagonals fill a triangle', () async {
final pixels = await paintLines([lineOf('\uE0B8\uE0BC')]);
expect(pixels.at(0, h - 1), foregroundColor); // lower left
expect(pixels.at(w - 2, 0).a, 0);
expect(pixels.at(w, 0), foregroundColor); // upper left
expect(pixels.at(2 * w - 1, h - 1).a, 0);
});
/// [line] drawn cell by cell with [TerminalPainter.paintCell].
Future<Pixels> paintCells(BufferLine line, int cols) =>
Pixels.paint(cols * w, h, (canvas) {
final cell = CellData.empty();
for (var x = 0; x < cols; x++) {
line.getCellData(x, cell);
painter.paintCell(canvas, Offset(x * w.toDouble(), 0), cell);
}
});
Future<void> expectSamePixels(Pixels a, Pixels b) async {
for (var y = 0; y < a.height; y++) {
for (var x = 0; x < a.width; x++) {
expect(a.at(x, y), b.at(x, y), reason: '($x, $y)');
}
}
}
test('a line of text paints exactly as cell by cell', () async {
// Long enough to be one paragraph, with spans of three styles.
const cols = 24;
final line = lineOf(
'plain \x1b[31mred\x1b[0m and \x1b[1;34mbold\x1b[0m text!',
cols: cols,
);
await expectSamePixels(
await paintLines([line], cols: cols),
await paintCells(line, cols),
);
});
test('a short line is drawn cell by cell, the same', () async {
final line = lineOf('Ab c-d');
await expectSamePixels(await paintLines([line]), await paintCells(line, 6));
});
test('text after a wide character and an emoji stays on the grid', () async {
const cols = 24;
final line = lineOf('\u4E2D\u{1F600}x text after them', cols: cols);
final pixels = await paintLines([line], cols: cols);
// Each plain character's cell is inked, the spaces are not.
for (var x = 4; x < 4 + 'x text after them'.length; x++) {
final blank = ' x text after them'[x - 3] == ' ';
final ink = pixels.count(foregroundColor, cellRect(x, 0));
expect(ink > 0, !blank, reason: 'cell $x');
}
});
test('an underline does not run under undecorated blanks', () async {
const cols = 24;
final line = lineOf(
'\x1b[4munderline\x1b[24m \x1b[4mmore text\x1b[0m',
cols: cols,
);
final pixels = await paintLines([line], cols: cols);
for (var x = 9; x < 12; x++) {
expect(pixels.count(foregroundColor, cellRect(x, 0)), 0, reason: 'x=$x');
}
await expectSamePixels(pixels, await paintCells(line, cols));
});
test('a styled run breaks where the colour changes', () async {
final pixels = await paintLines([lineOf('a\x1b[31mb\x1b[0mc')]);
expect(pixels.count(foregroundColor, cellRect(0, 0)), greaterThan(0));
expect(pixels.count(foregroundColor, cellRect(1, 0)), 0);
expect(pixels.count(fixtureTheme.red, cellRect(1, 0)), greaterThan(0));
expect(pixels.count(foregroundColor, cellRect(2, 0)), greaterThan(0));
});
test('backgrounds merge into runs that meet without a gap', () async {
final pixels = await paintLines([lineOf('\x1b[44m \x1b[0m')]);
for (var x = 0; x < 3 * w; x++) {
expect(pixels.at(x, h ~/ 2), fixtureTheme.blue, reason: 'x=$x');
}
expect(pixels.at(3 * w + 1, h ~/ 2).a, 0);
});
test('a grapheme cluster is drawn in its own cell', () async {
final pixels = await paintLines([lineOf('e\u0301\u{1F1F5}\u{1F1F9}x')]);
expect(pixels.count(foregroundColor, cellRect(0, 0)), greaterThan(0));
expect(pixels.count(foregroundColor, cellRect(3, 0)), greaterThan(0));
});
group('row pictures', () {
test('a line is recorded again only when it changes', () {
final cache = RowPictureCache(settleAfter: 100);
final line = lineOf('abc');
var recorded = 0;
void paint(Canvas canvas, bool settled) => recorded++;
final first = cache.pictureOf(line, 0, paint);
expect(cache.pictureOf(line, 0, paint), same(first));
expect(recorded, 1);
line.setCodePoint(0, 0x7A);
expect(cache.pictureOf(line, 0, paint), isNot(same(first)));
expect(recorded, 2);
// A new painter generation (theme, font) records every line again.
cache.pictureOf(line, 1, paint);
expect(recorded, 3);
cache.clear();
});
test('a line drawn unchanged settles into laid out text, within the '
'frame budget', () {
final cache = RowPictureCache(settleAfter: 2, settlePerFrame: 1);
final lines = [lineOf('one'), lineOf('two')];
final settledCalls = <bool>[];
void paint(Canvas canvas, bool settled) => settledCalls.add(settled);
for (var frame = 0; frame < 4; frame++) {
cache.beginFrame();
for (final line in lines) {
cache.pictureOf(line, 0, paint);
}
}
// Recorded new (not settled), then each settled in its own frame.
expect(settledCalls, [false, false, true, true]);
expect(cache.isSettled(lines[0]), isTrue);
expect(cache.isSettled(lines[1]), isTrue);
// A change starts the line over.
lines[0].setCodePoint(0, 0x7A);
cache.beginFrame();
cache.pictureOf(lines[0], 0, paint);
expect(settledCalls.last, isFalse);
expect(cache.isSettled(lines[0]), isFalse);
cache.clear();
});
test('trim keeps the most recently used lines', () {
final cache = RowPictureCache();
final lines = [for (var i = 0; i < 4; i++) lineOf('$i')];
for (final line in lines) {
cache.pictureOf(line, 0, (_, _) {});
}
cache.pictureOf(lines[0], 0, (_, _) {});
cache.trim(2);
expect(cache.length, 2);
var recorded = 0;
cache.pictureOf(lines[0], 0, (_, _) => recorded++);
expect(recorded, 0);
cache.pictureOf(lines[1], 0, (_, _) => recorded++);
expect(recorded, 1);
cache.clear();
});
});
}
@@ -0,0 +1,203 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/src/utils/unicode_width.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
/// Widths and grapheme clusters: what each character sequence occupies and
/// where the cursor ends, byte for byte as a program writes it.
void main() {
int widthOf(CellData cell) => cell.content >> CellContent.widthShift;
String grapheme(FixtureTerminal t, int x, int y) =>
t.buffer.lines[t.buffer.scrollBack + y].getGrapheme(x);
group('widths follow glibc wcwidth', () {
test('ASCII, Latin, CJK, emoji, combining, format characters', () {
expect(UnicodeWidth.width(0x41), 1);
expect(UnicodeWidth.width(0xE9), 1); // \u00E9
expect(UnicodeWidth.width(0x4E2D), 2); // \u4E2D
expect(UnicodeWidth.width(0xFF21), 2); // fullwidth A
expect(UnicodeWidth.width(0x1F600), 2); // \u{1F600}
expect(UnicodeWidth.width(0x1FAE8), 2); // Unicode 15 shaking face
expect(UnicodeWidth.width(0x0301), 0); // combining acute
expect(UnicodeWidth.width(0x200D), 0); // ZWJ
expect(UnicodeWidth.width(0xFE0F), 0); // VS16
expect(UnicodeWidth.width(0x1160), 0); // Hangul medial vowel filler
expect(UnicodeWidth.width(0x00AD), 1); // soft hyphen, as glibc
expect(UnicodeWidth.width(0x0600), 1); // prepended mark, as glibc
expect(UnicodeWidth.width(0x2764), 1); // \u2764 text default
expect(UnicodeWidth.width(0x1F1F5), 1); // regional indicator
expect(UnicodeWidth.width(0xE0B0), 1); // Powerline (private use)
expect(UnicodeWidth.width(0x2500), 1); // box drawing
});
});
group('combining marks join the previous cell', () {
test('e + U+0301 is one cell, and the cursor moves one column', () {
final t = FixtureTerminal();
t.feed('e\u0301|');
expect(grapheme(t, 0, 0), 'e\u0301');
expect(t.charAt(1, 0), '|');
expect(t.buffer.cursorX, 2);
expect(t.row(0), 'e\u0301|');
});
test('several marks stack on one base', () {
final t = FixtureTerminal();
t.feed('a\u0300\u0316\u0317b');
expect(grapheme(t, 0, 0), 'a\u0300\u0316\u0317');
expect(t.charAt(1, 0), 'b');
});
test('a mark with nothing before it on the line takes no column', () {
final t = FixtureTerminal();
t.feed('\u0301x');
expect(t.charAt(0, 0), 'x');
expect(t.buffer.cursorX, 1);
});
test('a mark after a wide character joins it, not its second column', () {
final t = FixtureTerminal();
t.feed('\u4E2D\u0301x');
expect(grapheme(t, 0, 0), '\u4E2D\u0301');
expect(widthOf(t.cell(0, 0)), 2);
expect(t.charAt(2, 0), 'x');
});
test('a mark in the pending-wrap column joins the last cell', () {
final t = FixtureTerminal(width: 4);
t.feed('abcd\u0301');
expect(grapheme(t, 3, 0), 'd\u0301');
expect(t.row(1), '');
t.feed('e');
expect(t.row(1), 'e');
});
test('Hangul conjoining jamo make one syllable cell', () {
final t = FixtureTerminal();
t.feed('\u1100\u1161\u11A8|');
expect(grapheme(t, 0, 0), '\u1100\u1161\u11A8');
expect(t.charAt(2, 0), '|');
});
});
group('emoji sequences', () {
test('VS16 widens a text-default emoji to two columns', () {
final t = FixtureTerminal();
t.feed('\u2764\uFE0F|');
expect(grapheme(t, 0, 0), '\u2764\uFE0F');
expect(widthOf(t.cell(0, 0)), 2);
expect(t.charAt(2, 0), '|');
expect(t.buffer.cursorX, 3);
});
test('VS16 at the last column cannot widen and stays one column', () {
final t = FixtureTerminal(width: 4);
t.feed('abc\u2764\uFE0F');
expect(grapheme(t, 3, 0), '\u2764\uFE0F');
expect(widthOf(t.cell(3, 0)), 1);
});
test('VS15 keeps one column', () {
final t = FixtureTerminal();
t.feed('\u2764\uFE0E|');
expect(widthOf(t.cell(0, 0)), 1);
expect(t.charAt(1, 0), '|');
});
test('a skin tone joins its base: two columns, not four', () {
final t = FixtureTerminal();
t.feed('\u{1F44D}\u{1F3FD}|');
expect(grapheme(t, 0, 0), '\u{1F44D}\u{1F3FD}');
expect(widthOf(t.cell(0, 0)), 2);
expect(t.charAt(2, 0), '|');
});
test('a ZWJ family is one two-column cell', () {
const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}';
final t = FixtureTerminal();
t.feed('$family|');
expect(grapheme(t, 0, 0), family);
expect(widthOf(t.cell(0, 0)), 2);
expect(t.charAt(2, 0), '|');
expect(t.row(0), '$family|');
});
test('two regional indicators are one two-column flag', () {
final t = FixtureTerminal();
t.feed('\u{1F1F5}\u{1F1F9}|');
expect(grapheme(t, 0, 0), '\u{1F1F5}\u{1F1F9}');
expect(widthOf(t.cell(0, 0)), 2);
expect(t.charAt(2, 0), '|');
});
test('a third regional indicator starts the next flag', () {
final t = FixtureTerminal();
t.feed('\u{1F1F5}\u{1F1F9}\u{1F1EC}\u{1F1E7}');
expect(grapheme(t, 0, 0), '\u{1F1F5}\u{1F1F9}');
expect(grapheme(t, 2, 0), '\u{1F1EC}\u{1F1E7}');
expect(t.buffer.cursorX, 4);
});
test('a keycap is one cell', () {
final t = FixtureTerminal();
t.feed('1\uFE0F\u20E3|');
expect(grapheme(t, 0, 0), '1\uFE0F\u20E3');
expect(t.charAt(2, 0), '|');
});
test('a letter after ZWJ does not join: only pictographs do', () {
final t = FixtureTerminal();
t.feed('a\u200Db');
expect(grapheme(t, 0, 0), 'a\u200D');
expect(t.charAt(1, 0), 'b');
});
});
group('wide characters', () {
test('a wide character in the last column wraps whole', () {
final t = FixtureTerminal(width: 5);
t.feed('abcd\u4E2D');
expect(t.row(0), 'abcd');
expect(t.row(1), '\u4E2D');
expect(t.buffer.lines[t.buffer.scrollBack + 1].isWrapped, isTrue);
});
test('overwriting the second column of a wide character blanks it', () {
final t = FixtureTerminal();
t.feed('\u4E2D\x1b[2Gx');
expect(t.charAt(0, 0), '');
expect(t.charAt(1, 0), 'x');
});
});
group('copy returns whole graphemes', () {
test('selected text keeps marks, sequences and flags', () {
const text = 'e\u0301 \u{1F44D}\u{1F3FD} \u{1F1F5}\u{1F1F9} \u4E2D';
final t = FixtureTerminal(width: 30);
t.feed(text);
final range = BufferRangeLine(
CellOffset(0, t.buffer.scrollBack),
CellOffset(30, t.buffer.scrollBack),
);
expect(t.buffer.getText(range).trimRight(), text);
});
test('a selection ending inside a wide cluster leaves it out', () {
final t = FixtureTerminal();
t.feed('a\u{1F1F5}\u{1F1F9}b');
final line = t.buffer.lines[t.buffer.scrollBack];
expect(line.getText(0, 2), 'a');
expect(line.getText(0, 3), 'a\u{1F1F5}\u{1F1F9}');
});
test('clusters survive reflow', () {
final t = FixtureTerminal(width: 6);
t.feed('abcde\u0301f\u{1F1F5}\u{1F1F9}');
t.terminal.resize(4, 5);
t.terminal.resize(10, 5);
expect(t.row(0), 'abcde\u0301f\u{1F1F5}\u{1F1F9}');
});
});
}
@@ -0,0 +1,98 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'paint_fixture.dart';
void main() {
group('maxLines', () {
Terminal filled(int lines) {
final terminal = Terminal(maxLines: 100)..resize(10, 4);
terminal.write(List.generate(lines, (i) => 'l$i').join('\r\n'));
return terminal;
}
test('shrinking drops the oldest lines and keeps anchors right', () {
final terminal = filled(80);
final buffer = terminal.buffer;
expect(buffer.height, 80);
final anchor = buffer.createAnchor(0, 79);
final old = buffer.createAnchor(0, 5);
terminal.maxLines = 30;
expect(terminal.maxLines, 30);
expect(buffer.height, 30);
expect(buffer.lines[0].getText().trim(), 'l50');
expect(buffer.lines[29].getText().trim(), 'l79');
expect(anchor.attached, isTrue);
expect(anchor.y, 29);
expect(old.attached, isFalse);
// Further output keeps to the new length.
terminal.write('\r\nnext');
expect(buffer.height, 30);
expect(buffer.lines[29].getText().trim(), 'next');
});
test('growing keeps every line and makes room for more', () {
final terminal = filled(100);
terminal.maxLines = 300;
expect(terminal.buffer.height, 100);
terminal.write(List.generate(150, (i) => '\r\nm$i').join());
expect(terminal.buffer.height, 250);
expect(terminal.buffer.lines[0].getText().trim(), 'l0');
});
test('never fewer than the screen rows', () {
final terminal = filled(20);
terminal.maxLines = 2;
expect(terminal.buffer.height, 4);
});
test('clearing the scrollback detaches its lines', () {
final terminal = filled(20);
final buffer = terminal.buffer;
final old = buffer.createAnchor(0, 2);
final screen = buffer.createAnchor(0, 18);
buffer.clearScrollback();
expect(buffer.height, 4);
expect(old.attached, isFalse);
expect(screen.y, 2);
});
});
testWidgets('cursorBlinkVisible hides the cursor in its off phase', (
tester,
) async {
final terminal = Terminal()..write('ab');
final phase = ValueNotifier(true);
addTearDown(phase.dispose);
await tester.pumpWidget(
MaterialApp(
home: Center(
child: SizedBox(
width: 200,
height: 100,
child: TerminalView(
terminal,
theme: fixtureTheme,
alwaysShowCursor: false,
cursorBlinkVisible: phase,
hardwareKeyboardOnly: true,
),
),
),
),
);
// The background, then (after the text) the unfocused cursor's outline.
PaintPattern cursor() => paints
..rect(color: backgroundColor)
..rect(color: cursorColor);
final view = find.byType(TerminalView);
expect(view, cursor());
phase.value = false;
await tester.pump();
expect(view, isNot(cursor()));
phase.value = true;
await tester.pump();
expect(view, cursor());
});
}