Merge main into the terminal flow-control branch

Conflicts resolved keeping both sides: main's active-client rules, input
lane, reply marking and key input, and this branch's flow control,
acknowledgements, subscriptions and sliced emulator feed. terminal_ack
joins the terminal lane; the feed marks each live slice it writes as
drawing, so the emulator's answers still go to onReply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 00:03:20 +00:00
148 changed files with 18443 additions and 153 deletions
@@ -72,6 +72,76 @@ void main() {
await client.dispose();
});
test('terminal keystrokes do not wait behind a slow request', () async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
final connecting = client.connect(Uri.parse('ws://example.test'));
channel.readyCompleter.complete();
await connecting;
Map<String, dynamic> sent(int i) =>
jsonDecode(channel.outgoing[i] as String) as Map<String, dynamic>;
// A terminal_open waiting for its login prompt.
final open = client.call('terminal_open');
final later = client.call('terminal_list');
await Future<void>.delayed(Duration.zero);
final keys = [
for (final data in ['l', 's', '\r'])
client.call('terminal_input', {
'terminal_request': {'terminal_id': 't', 'data': data},
}),
];
final size = client.call('chat_shell_resize', {
'chat_shell_run_request': {'cols': 80, 'rows': 24},
});
await Future<void>.delayed(Duration.zero);
// The keystrokes and the size went out at once, in order; the ordinary
// request behind the slow one still waits for it.
expect(channel.outgoing, hasLength(5));
expect(
[for (var i = 0; i < 5; i++) sent(i)['type']],
[
'terminal_open',
'terminal_input',
'terminal_input',
'terminal_input',
'chat_shell_resize',
],
);
expect(
[for (var i = 1; i < 4; i++) sent(i)['terminal_request']['data']],
['l', 's', '\r'],
);
for (var i = 1; i < 5; i++) {
channel.incoming.add(
jsonEncode({'id': sent(i)['id'], 'type': sent(i)['type']}),
);
}
for (final key in keys) {
expect((await key)['type'], 'terminal_input');
}
expect((await size)['type'], 'chat_shell_resize');
channel.incoming.add(
jsonEncode({'id': sent(0)['id'], 'type': 'terminal_open'}),
);
expect((await open)['type'], 'terminal_open');
await Future<void>.delayed(Duration.zero);
expect(sent(5)['type'], 'terminal_list');
channel.incoming.add(
jsonEncode({'id': sent(5)['id'], 'type': 'terminal_list'}),
);
expect((await later)['type'], 'terminal_list');
await client.dispose();
});
test('a keystroke while disconnected fails at once', () async {
final client = PipelinesClient(channelFactory: (_) => FakeChannel());
await expectLater(
client.call('terminal_input', {'terminal_request': {}}),
throwsA(isA<NotConnectedError>()),
);
await client.dispose();
});
test('disconnect fails pending requests', () async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
@@ -0,0 +1,309 @@
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_key_input.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart';
import 'package:xterm/core.dart';
/// Modifiers held, as [chatShellKeyEventBytes] reads them.
class _Held extends HardwareKeyboard {
_Held(String mods)
: shift = mods.contains('S'),
alt = mods.contains('A'),
ctrl = mods.contains('C'),
meta = mods.contains('M');
final bool shift, alt, ctrl, meta;
@override
bool get isShiftPressed => shift;
@override
bool get isAltPressed => alt;
@override
bool get isControlPressed => ctrl;
@override
bool get isMetaPressed => meta;
}
KeyDownEvent _down(
LogicalKeyboardKey logical, {
PhysicalKeyboardKey? physical,
String? character,
}) => KeyDownEvent(
physicalKey: physical ?? PhysicalKeyboardKey.keyA,
logicalKey: logical,
character: character,
timeStamp: Duration.zero,
);
/// The bytes a key sends with [mods] (S Shift, A Alt, C Ctrl, M Meta).
String? _bytes(
LogicalKeyboardKey logical, {
String mods = '',
String? character,
PhysicalKeyboardKey? physical,
Terminal? terminal,
bool optionAsMeta = true,
}) => chatShellKeyEventBytes(
_down(logical, physical: physical, character: character),
_Held(mods),
terminal ?? Terminal(),
optionAsMeta: optionAsMeta,
);
const _l = LogicalKeyboardKey.new;
void main() {
final linux = TargetPlatformVariant.only(TargetPlatform.linux);
final mac = TargetPlatformVariant.only(TargetPlatform.macOS);
testWidgets('Alt is Meta: ESC and the character typed, Shift and layout '
'included', (tester) async {
expect(_bytes(LogicalKeyboardKey.keyB, mods: 'A', character: 'b'), '\x1bb');
expect(_bytes(LogicalKeyboardKey.keyF, mods: 'A', character: 'f'), '\x1bf');
expect(_bytes(LogicalKeyboardKey.keyD, mods: 'A', character: 'd'), '\x1bd');
expect(
_bytes(LogicalKeyboardKey.keyB, mods: 'AS', character: 'B'),
'\x1bB',
);
expect(
_bytes(LogicalKeyboardKey.period, mods: 'A', character: '.'),
'\x1b.',
);
expect(
_bytes(LogicalKeyboardKey.digit1, mods: 'A', character: '1'),
'\x1b1',
);
// Without a character (some platforms send none with Alt): the key's.
expect(_bytes(LogicalKeyboardKey.keyT, mods: 'A'), '\x1bt');
expect(_bytes(LogicalKeyboardKey.period, mods: 'AS'), '\x1b>');
// A non-US layout's own character (AZERTY's A key types "q").
expect(_bytes(LogicalKeyboardKey.keyQ, mods: 'A', character: 'q'), '\x1bq');
expect(_bytes(LogicalKeyboardKey.backspace, mods: 'A'), '\x1b\x7f');
expect(_bytes(LogicalKeyboardKey.enter, mods: 'A'), '\x1b\r');
expect(
_bytes(LogicalKeyboardKey.space, mods: 'A', character: ' '),
'\x1b ',
);
}, variant: linux);
testWidgets('Ctrl sends the control code of letters and symbols', (
tester,
) async {
final table = <(LogicalKeyboardKey, String, String), String>{
(LogicalKeyboardKey.keyA, '', 'a'): '\x01',
(LogicalKeyboardKey.keyT, '', 't'): '\x14',
(LogicalKeyboardKey.keyT, 'S', 'T'): '\x14',
(LogicalKeyboardKey.slash, '', '/'): '\x1f',
(LogicalKeyboardKey.bracketRight, '', ']'): '\x1d',
(LogicalKeyboardKey.backslash, '', '\\'): '\x1c',
(LogicalKeyboardKey.bracketLeft, '', '['): '\x1b',
(LogicalKeyboardKey.minus, 'S', '_'): '\x1f',
(LogicalKeyboardKey.digit2, '', '2'): '\x00',
(LogicalKeyboardKey.digit2, 'S', '@'): '\x00',
(LogicalKeyboardKey.digit6, 'S', '^'): '\x1e',
(LogicalKeyboardKey.digit8, '', '8'): '\x7f',
(LogicalKeyboardKey.space, '', ' '): '\x00',
(LogicalKeyboardKey.keyB, 'A', 'b'): '\x1b\x02',
};
for (final MapEntry(key: (key, mods, character), value: bytes)
in table.entries) {
expect(
_bytes(key, mods: 'C$mods', character: character),
bytes,
reason: 'Ctrl+$mods $character',
);
}
// A control character as the event's character still maps by key.
expect(
_bytes(LogicalKeyboardKey.slash, mods: 'C', character: '\x1f'),
'\x1f',
);
expect(_bytes(LogicalKeyboardKey.backspace, mods: 'C'), '\b');
// Ctrl+1 has no control code: the emulator types it.
expect(
_bytes(LogicalKeyboardKey.digit1, mods: 'C', character: '1'),
isNull,
);
}, variant: linux);
testWidgets('modified special keys use the xterm modifier parameter', (
tester,
) async {
const up = LogicalKeyboardKey.arrowUp;
expect(_bytes(up), '\x1b[A');
expect(_bytes(up, mods: 'S'), '\x1b[1;2A');
expect(_bytes(LogicalKeyboardKey.arrowLeft, mods: 'A'), '\x1b[1;3D');
expect(_bytes(LogicalKeyboardKey.arrowDown, mods: 'AS'), '\x1b[1;4B');
expect(_bytes(LogicalKeyboardKey.arrowRight, mods: 'C'), '\x1b[1;5C');
expect(_bytes(up, mods: 'CS'), '\x1b[1;6A');
expect(_bytes(up, mods: 'CA'), '\x1b[1;7A');
expect(_bytes(up, mods: 'CAS'), '\x1b[1;8A');
expect(_bytes(LogicalKeyboardKey.home), '\x1b[H');
expect(_bytes(LogicalKeyboardKey.end, mods: 'S'), '\x1b[1;2F');
expect(_bytes(LogicalKeyboardKey.home, mods: 'C'), '\x1b[1;5H');
expect(_bytes(LogicalKeyboardKey.pageUp), '\x1b[5~');
expect(_bytes(LogicalKeyboardKey.pageUp, mods: 'S'), '\x1b[5;2~');
expect(_bytes(LogicalKeyboardKey.pageDown, mods: 'C'), '\x1b[6;5~');
expect(_bytes(LogicalKeyboardKey.insert), '\x1b[2~');
expect(_bytes(LogicalKeyboardKey.delete), '\x1b[3~');
expect(_bytes(LogicalKeyboardKey.delete, mods: 'A'), '\x1b[3;3~');
expect(_bytes(LogicalKeyboardKey.f1), '\x1bOP');
expect(_bytes(LogicalKeyboardKey.f1, mods: 'S'), '\x1b[1;2P');
expect(_bytes(LogicalKeyboardKey.f4, mods: 'C'), '\x1b[1;5S');
expect(_bytes(LogicalKeyboardKey.f5), '\x1b[15~');
expect(_bytes(LogicalKeyboardKey.f12, mods: 'C'), '\x1b[24;5~');
expect(_bytes(LogicalKeyboardKey.tab, mods: 'S'), '\x1b[Z');
expect(_bytes(LogicalKeyboardKey.tab), '\t');
expect(_bytes(LogicalKeyboardKey.enter), '\r');
expect(_bytes(LogicalKeyboardKey.escape), '\x1b');
expect(_bytes(LogicalKeyboardKey.backspace), '\x7f');
}, variant: linux);
testWidgets('application cursor keys and keypad mode', (tester) async {
final terminal = Terminal()..write('\x1b[?1h');
String? bytes(LogicalKeyboardKey key, [String mods = '']) =>
_bytes(key, mods: mods, terminal: terminal);
expect(bytes(LogicalKeyboardKey.arrowUp), '\x1bOA');
expect(bytes(LogicalKeyboardKey.arrowLeft), '\x1bOD');
expect(bytes(LogicalKeyboardKey.home), '\x1bOH');
expect(bytes(LogicalKeyboardKey.end), '\x1bOF');
// Modified keys are the same in either mode.
expect(bytes(LogicalKeyboardKey.arrowUp, 'C'), '\x1b[1;5A');
// The keypad's operators and Enter follow DECKPAM; digits keep typing.
expect(bytes(LogicalKeyboardKey.numpadAdd), isNull);
expect(bytes(LogicalKeyboardKey.numpadEnter), '\r');
terminal.write('\x1b=');
expect(bytes(LogicalKeyboardKey.numpadAdd), '\x1bOk');
expect(bytes(LogicalKeyboardKey.numpadEnter), '\x1bOM');
expect(bytes(LogicalKeyboardKey.numpadDivide), '\x1bOo');
expect(bytes(LogicalKeyboardKey.numpad1), isNull);
terminal.write('\x1b>\x1b[?1l');
expect(bytes(LogicalKeyboardKey.arrowUp), '\x1b[A');
expect(bytes(LogicalKeyboardKey.numpadAdd), isNull);
// Enter in line feed mode (LNM).
terminal.write('\x1b[20h');
expect(bytes(LogicalKeyboardKey.enter), '\r\n');
}, variant: linux);
testWidgets('plain typing, Cmd chords and AltGr are left to the emulator', (
tester,
) async {
expect(_bytes(LogicalKeyboardKey.keyA, character: 'a'), isNull);
expect(_bytes(LogicalKeyboardKey.keyA, mods: 'S', character: 'A'), isNull);
expect(_bytes(LogicalKeyboardKey.space, character: ' '), isNull);
expect(_bytes(LogicalKeyboardKey.keyK, mods: 'M', character: 'k'), isNull);
// German AltGr+Q types @.
expect(
_bytes(
LogicalKeyboardKey.keyQ,
mods: 'CA',
character: '@',
physical: PhysicalKeyboardKey.keyQ,
),
isNull,
);
}, variant: linux);
testWidgets('a Mac\'s Option is Meta while the setting is on', (
tester,
) async {
// Option+B types ∫; its logical key is B (natively) or ∫ (browsers).
expect(_bytes(LogicalKeyboardKey.keyB, mods: 'A', character: '∫'), '\x1bb');
expect(
_bytes(
_l(0x222b),
mods: 'A',
character: '∫',
physical: PhysicalKeyboardKey.keyB,
),
'\x1bb',
);
expect(
_bytes(
_l(0x0131),
mods: 'AS',
character: 'ı',
physical: PhysicalKeyboardKey.keyB,
),
'\x1bB',
);
expect(
_bytes(
_l(0x2265),
mods: 'A',
character: '≥',
physical: PhysicalKeyboardKey.period,
),
'\x1b.',
);
expect(_bytes(LogicalKeyboardKey.backspace, mods: 'A'), '\x1b\x7f');
expect(_bytes(LogicalKeyboardKey.slash, mods: 'C', character: '/'), '\x1f');
// Off, Option types its symbol; special keys keep the Alt parameter.
expect(
_bytes(
LogicalKeyboardKey.keyB,
mods: 'A',
character: '∫',
optionAsMeta: false,
),
isNull,
);
expect(
_bytes(LogicalKeyboardKey.backspace, mods: 'A', optionAsMeta: false),
'\x7f',
);
expect(
_bytes(LogicalKeyboardKey.arrowLeft, mods: 'A', optionAsMeta: false),
'\x1b[1;3D',
);
expect(
_bytes(LogicalKeyboardKey.arrowLeft, mods: 'A', optionAsMeta: true),
'\x1b[1;3D',
);
}, variant: mac);
ChatShellTerminalSession session(List<String> sent, bool Function() meta) =>
ChatShellTerminalSession(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': 'running',
'started_at': 1,
'output': '',
'output_bytes': 0,
'terminal': true,
'cols': 40,
'rows': 10,
})!,
onInput: sent.add,
onResize: (_, _) {},
optionAsMeta: meta,
);
testWidgets('the toolbar and soft keyboard keys go through the same '
'encoding', (tester) async {
final sent = <String>[];
final terminal = session(sent, () => true).terminal;
terminal.keyInput(TerminalKey.arrowUp);
terminal.write('\x1b[?1h');
terminal.keyInput(TerminalKey.arrowUp);
terminal.keyInput(TerminalKey.keyB, alt: true);
terminal.keyInput(TerminalKey.keyB, alt: true, shift: true);
terminal.keyInput(TerminalKey.slash, ctrl: true);
terminal.keyInput(TerminalKey.arrowLeft, alt: true);
// A plain letter is typed as its text instead.
expect(terminal.keyInput(TerminalKey.keyB), isFalse);
expect(sent, ['\x1b[A', '\x1bOA', '\x1bb', '\x1bB', '\x1f', '\x1b[1;3D']);
}, variant: linux);
testWidgets('on a Mac with Option as Meta off, the package does not '
'send its own Alt sequence', (tester) async {
final sent = <String>[];
var meta = false;
final terminal = session(sent, () => meta).terminal;
expect(terminal.keyInput(TerminalKey.keyB, alt: true), isFalse);
meta = true;
expect(terminal.keyInput(TerminalKey.keyB, alt: true), isTrue);
expect(sent, ['\x1bb']);
}, variant: mac);
}
@@ -0,0 +1,165 @@
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_session.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_view.dart';
import 'package:xterm/core.dart';
ChatShellTerminalSession _session({int cols = 40, int rows = 10}) =>
ChatShellTerminalSession(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': 'running',
'started_at': 1,
'output': '',
'output_bytes': 0,
'terminal': true,
'cols': cols,
'rows': rows,
})!,
onInput: (_) {},
onResize: (_, _) {},
);
/// The rows on screen, trimmed.
List<String> _screen(Terminal terminal) {
final buffer = terminal.buffer;
final top = buffer.height - terminal.viewHeight;
return [
for (var y = 0; y < terminal.viewHeight; y++)
buffer.lines[top + y].getText().trimRight(),
];
}
String _cursorRow(Terminal terminal) => terminal
.buffer
.lines[terminal.buffer.absoluteCursorY]
.getText()
.trimRight();
/// Twelve output lines of 58 characters (two rows each at 40 columns), then
/// a prompt.
String _longLines() => [
for (var i = 0; i < 12; i++)
'line ${i.toString().padLeft(2, '0')} ${'x' * 50}',
r'$ ',
].join('\r\n');
void main() {
test('shrinking keeps the prompt on the cursor row at the bottom, and '
'growing brings the rows above back in order', () {
final terminal = _session().terminal..write(_longLines());
expect(terminal.buffer.cursorY, 9);
expect(_cursorRow(terminal), r'$');
terminal.resize(20, 5);
expect(terminal.buffer.cursorY, 4);
expect(_cursorRow(terminal), r'$');
// Line 11's second row (cut at 20 columns), then the prompt.
expect(_screen(terminal), [
'line 10 ${'x' * 12}',
'x' * 18,
'line 11 ${'x' * 12}',
'x' * 18,
r'$',
]);
// The shell redraws its prompt and runs a command: nothing lands on
// old rows and no rows merge.
terminal.write('\r\x1b[K\$ ls\r\nout\r\n\$ ');
expect(_screen(terminal).sublist(2), [r'$ ls', 'out', r'$']);
terminal.resize(40, 10);
expect(terminal.buffer.cursorY, 9);
expect(_cursorRow(terminal), r'$');
final screen = _screen(terminal);
expect(screen.sublist(7), [r'$ ls', 'out', r'$']);
// Rows cut while narrow stay cut: no stale text past column 20.
for (final row in screen) {
expect(row.length, lessThanOrEqualTo(20), reason: row);
}
});
test('a prompt redrawn while narrow does not grow stale text when the '
'terminal widens again', () {
final terminal = _session().terminal..write('\$ ${'abcdefghij' * 3}');
terminal.resize(10, 10);
terminal.write('\r\x1b[K\$ ');
terminal.resize(40, 10);
expect(_cursorRow(terminal), r'$');
expect(terminal.buffer.cursorX, 2);
});
test('a cleared screen and scrollback stay cleared across resizes', () {
final terminal = _session().terminal..write(_longLines());
terminal.write('\x1b[H\x1b[2J\x1b[3J\$ ');
terminal.resize(20, 5);
terminal.resize(40, 12);
expect(_screen(terminal), [r'$', for (var i = 0; i < 11; i++) '']);
expect(terminal.buffer.height, 12);
expect(terminal.buffer.absoluteCursorY, 0);
});
test('fewer rows than the output drop blank rows below the cursor first', () {
final terminal = _session().terminal..write('a\r\nb\r\n\$ ');
terminal.resize(40, 4);
expect(_screen(terminal), ['a', 'b', r'$', '']);
expect(terminal.buffer.absoluteCursorY, 2);
terminal.resize(40, 10);
expect(_screen(terminal).take(3), ['a', 'b', r'$']);
expect(terminal.buffer.absoluteCursorY, 2);
});
testWidgets('the view resizes the live terminal as its box changes, '
'keeping the prompt on the cursor row', (tester) async {
final session = _session(cols: 80, rows: 24);
final sizes = <(int, int)>[];
session.terminal.onResize = (cols, rows, _, _) => sizes.add((cols, rows));
session.terminal.write(_longLines());
var size = const Size(600, 300);
late StateSetter setSize;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: StatefulBuilder(
builder: (context, setState) {
setSize = setState;
return SizedBox.fromSize(
size: size,
child: ChatShellTerminalView(session: session, fill: true),
);
},
),
),
),
),
);
await tester.pump();
final wide = session.terminal.viewWidth;
// The prompt is the 13th line; the screen has room below it.
final row = session.terminal.buffer.cursorY;
expect(row, 12);
expect(_cursorRow(session.terminal), r'$');
setSize(() => size = const Size(250, 120));
await tester.pump();
final terminal = session.terminal;
expect(terminal.viewWidth, lessThan(wide));
expect(terminal.buffer.cursorY, terminal.viewHeight - 1);
expect(_cursorRow(terminal), r'$');
setSize(() => size = const Size(600, 300));
await tester.pump();
expect(terminal.viewWidth, wide);
// The rows that scrolled off come back above the prompt.
expect(terminal.buffer.cursorY, row);
expect(_cursorRow(terminal), r'$');
expect(_screen(terminal)[row - 1], startsWith('line 11'));
expect(_screen(terminal)[0], startsWith('line 00'));
expect(sizes.length, greaterThanOrEqualTo(3));
});
}
@@ -67,6 +67,35 @@ void main() {
expect(sent, hasLength(2));
});
test('query answers go to onReply; focus reports the laid out size', () {
final typed = <String>[];
final replies = <String>[];
final activations = <(int, int)>[];
final session = ChatShellTerminalSession(
_run('prompt'),
onInput: typed.add,
onReply: replies.add,
onResize: (_, _) {},
onActivate: (cols, rows) => activations.add((cols, rows)),
);
session.append(_run('prompt\x1b[6n'), '\x1b[6n', 6, 10);
session.terminal.textInput('y');
expect(replies, ['\x1b[1;7R']);
expect(typed, ['y']);
// Drawn at the run's own size until a view lays it out.
expect(session.viewSize, isNull);
session.activate();
expect(activations, isEmpty);
session.terminal.resize(90, 20);
expect(session.viewSize, (90, 20));
session.activate();
expect(activations, [(90, 20)]);
// A finished run claims nothing.
session.finish(_run('prompt', status: 'exited'));
session.activate();
expect(activations, hasLength(1));
});
test('a chunk after a hole redraws the held copy', () {
final session = ChatShellTerminalSession(
_run('a\r\n'),
@@ -85,7 +114,8 @@ void main() {
);
});
test('narrowing rewraps without pushing the first line out of view', () {
test('narrowing a live terminal cuts rows instead of rewrapping, keeping '
'the first line and the cursor on its own', () {
final session = ChatShellTerminalSession(
_run('first\r\n${'u' * 30}\r\nprompt: '),
onInput: (_) {},
@@ -95,11 +125,26 @@ void main() {
final buffer = session.terminal.buffer;
expect(buffer.height, 6);
expect(buffer.lines[0].getText().trim(), 'first');
expect(buffer.lines[3].getText().trim(), 'prompt:');
expect(buffer.absoluteCursorY, 3);
expect(buffer.lines[1].getText().trim(), 'u' * 20);
expect(buffer.lines[2].getText().trim(), 'prompt:');
expect(buffer.absoluteCursorY, 2);
expect(buffer.cursorX, 8);
});
test('finished output still rewraps to the width it is shown at', () {
final session = ChatShellTerminalSession(
_run('first\r\n${'u' * 30}\r\nend', status: 'exited'),
onInput: (_) {},
onResize: (_, _) {},
);
session.terminal.resize(20, 6);
final buffer = session.terminal.buffer;
expect(buffer.lines[0].getText().trim(), 'first');
expect(buffer.lines[1].getText().trim(), 'u' * 20);
expect(buffer.lines[2].getText().trim(), 'u' * 10);
expect(buffer.lines[3].getText().trim(), 'end');
});
test('a finished run counts the rows its output takes at a width', () {
final session = ChatShellTerminalSession(
_run('a\r\n${'x' * 50}\r\nend\r\n', status: 'exited'),
@@ -110,6 +110,109 @@ void main() {
);
}
Future<void> press(
WidgetTester tester,
LogicalKeyboardKey key, {
List<LogicalKeyboardKey> modifiers = const [],
String? character,
PhysicalKeyboardKey? physical,
}) async {
for (final modifier in modifiers) {
await tester.sendKeyDownEvent(modifier);
}
await tester.sendKeyDownEvent(
key,
character: character,
physicalKey: physical,
);
await tester.sendKeyUpEvent(key, physicalKey: physical);
for (final modifier in modifiers.reversed) {
await tester.sendKeyUpEvent(modifier);
}
await tester.pump();
}
testWidgets('the focused terminal sends xterm bytes for Alt, Ctrl and '
'modified keys, and the copy and paste keys still work', (tester) async {
await openRunning(tester, output: r'$ ');
await tester.tap(find.byType(TerminalView));
await tester.pump();
const alt = [LogicalKeyboardKey.altLeft];
const ctrl = [LogicalKeyboardKey.controlLeft];
const shift = [LogicalKeyboardKey.shiftLeft];
await press(tester, LogicalKeyboardKey.keyB, modifiers: alt);
await press(tester, LogicalKeyboardKey.keyF, modifiers: alt);
await press(tester, LogicalKeyboardKey.period, modifiers: alt);
await press(
tester,
LogicalKeyboardKey.keyB,
modifiers: [...alt, ...shift],
character: 'B',
);
await press(tester, LogicalKeyboardKey.backspace, modifiers: alt);
await press(tester, LogicalKeyboardKey.slash, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.bracketRight, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.arrowUp, modifiers: shift);
await press(tester, LogicalKeyboardKey.arrowLeft, modifiers: alt);
await press(tester, LogicalKeyboardKey.arrowRight, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.keyT, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.keyX);
expect(
typed(),
'\x1bb\x1bf\x1b.\x1bB\x1b\x7f\x1f\x1d'
'\x1b[1;2A\x1b[1;3D\x1b[1;5C\x14x',
);
// Application cursor keys from the process's own mode switch.
gateway.emitOutput('run_t', '\x1b[?1h', 2);
await tester.pump();
gateway.calls.clear();
await press(tester, LogicalKeyboardKey.arrowUp);
expect(typed(), '\x1bOA');
// Ctrl-V is still paste, not ^V.
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async =>
call.method == 'Clipboard.getData' ? {'text': 'tok'} : null,
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
await press(tester, LogicalKeyboardKey.keyV, modifiers: ctrl);
for (var i = 0; i < 5; i++) {
await tester.pump(const Duration(milliseconds: 20));
}
expect(typed(), '\x1bOAtok');
await tester.pump(const Duration(milliseconds: 400));
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets(
'on a Mac, Option is Meta in the terminal',
(tester) async {
await openRunning(tester, output: r'$ ');
await tester.tap(find.byType(TerminalView));
await tester.pump();
await press(
tester,
LogicalKeyboardKey.keyB,
modifiers: [LogicalKeyboardKey.altLeft],
character: '∫',
);
await press(
tester,
const LogicalKeyboardKey(0x2202),
modifiers: [LogicalKeyboardKey.altLeft],
character: '∂',
physical: PhysicalKeyboardKey.keyD,
);
expect(typed(), '\x1bb\x1bd');
await tester.pump(const Duration(milliseconds: 400));
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets('on Linux, Ctrl-C copies a selection and interrupts without one; '
'Ctrl-Insert copies too', (tester) async {
await openRunning(tester, output: 'Paste your token: ');
@@ -274,6 +377,47 @@ void main() {
expect(gateway.bodies('chat_shell_input'), isEmpty);
});
testWidgets('focusing the terminal claims it at its size; typing carries '
'the size and query answers are marked', (tester) async {
await openRunning(tester, output: 'size? \x1b[6n');
await tester.pump(const Duration(milliseconds: 200));
final laidOut = gateway.bodies('chat_shell_resize').single;
// The replayed query is not answered; nothing was claimed yet.
expect(gateway.bodies('chat_shell_input'), isEmpty);
await tester.tap(find.byType(TerminalView));
await tester.pump();
final claim = gateway.bodies('chat_shell_resize').last;
expect(claim['activate'], isTrue);
expect((claim['cols'], claim['rows']), (laidOut['cols'], laidOut['rows']));
// Typing carries this client's size.
await tester.sendKeyEvent(LogicalKeyboardKey.keyG);
await tester.pump();
var inputs = gateway.bodies('chat_shell_input');
expect(inputs.single['data'], 'g');
expect(inputs.single['reply'], isNull);
expect(
(inputs.single['cols'], inputs.single['rows']),
(laidOut['cols'], laidOut['rows']),
);
// A live query is answered with the answer marked, without a size.
gateway.emitOutput('run_t', '\x1b[6n', 'size? \x1b[6n'.length);
await tester.pump();
await tester.pump();
inputs = gateway.bodies('chat_shell_input');
expect(inputs.last['data'], '\x1b[1;7R');
expect(inputs.last['reply'], isTrue);
expect(inputs.last['cols'], isNull);
// Focusing again after the focus left claims again.
FocusManager.instance.primaryFocus?.unfocus();
await tester.pump();
await tester.tap(find.byType(TerminalView));
await tester.pump();
expect(
gateway.bodies('chat_shell_resize').where((b) => b['activate'] == true),
hasLength(2),
);
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets('coloured output is drawn without its escape codes', (
tester,
) async {
@@ -0,0 +1,101 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminals.dart';
import 'package:pipelines_app/features/terminal/terminal_info.dart';
import 'package:pipelines_app/features/terminal/terminal_tab.dart';
import 'terminal_fixtures.dart';
void main() {
testWidgets('answers are marked, typing carries the size, focus activates', (
tester,
) async {
final gateway = TerminalGateway();
final tab = TerminalTab(
machineId: 'm',
machineName: 'm',
gateway: gateway,
info: TerminalInfo.fromJson(gateway.add('t1')),
);
// Before a view lays it out, focus has no size to claim.
tab.session.activate();
await tester.pump();
expect(gateway.bodies('terminal_resize'), isEmpty);
tab.session.terminal.resize(100, 30);
await tester.pump(chatShellResizeDelay);
expect(gateway.bodies('terminal_resize'), [
{'terminal_id': 't1', 'cols': 100, 'rows': 30},
]);
// A cursor position query in the output: the answer is marked.
tab.frame({'output': '\x1b[6n', 'offset': 0, 'end': 4});
await tester.pump();
// Typing carries the size this client draws at.
tab.session.terminal.textInput('ls');
await tester.pump();
expect(gateway.bodies('terminal_input'), [
{'terminal_id': 't1', 'data': '\x1b[1;1R', 'reply': true},
{'terminal_id': 't1', 'data': 'ls', 'cols': 100, 'rows': 30},
]);
// A view gaining focus claims the terminal at once, at its size.
tab.session.activate();
await tester.pump();
expect(gateway.bodies('terminal_resize').last, {
'terminal_id': 't1',
'cols': 100,
'rows': 30,
'activate': true,
});
// A new connection reports its size again.
tab.attach(gateway, TerminalInfo.fromJson(gateway.terminals['t1']!));
await tester.pump(chatShellResizeDelay);
expect(gateway.bodies('terminal_resize'), hasLength(3));
expect(gateway.bodies('terminal_resize').last, {
'terminal_id': 't1',
'cols': 100,
'rows': 30,
});
tab.dispose();
});
test('the input pipe keeps answers and typing apart, in order', () async {
final sent = <(String, bool)>[];
final pipe = ChatShellInputPipe((data, reply) async {
sent.add((data, reply));
await Future<void>.delayed(Duration.zero);
}, (_) {});
pipe.add('a');
// While the first is in flight, typing, an answer and typing wait.
pipe.add('b');
pipe.add('c');
pipe.add('\x1b[1;1R', reply: true);
pipe.add('d');
pipe.add('${'x' * chatShellInputChunk}y');
await pumpEventQueue();
expect(sent, [
('a', false),
('bc', false),
('\x1b[1;1R', true),
('d${'x' * (chatShellInputChunk - 1)}', false),
('xy', false),
]);
});
test('a refusal drops what was waiting and reports once', () async {
final failures = <Object>[];
final sent = <String>[];
final pipe = ChatShellInputPipe((data, reply) async {
sent.add(data);
await Future<void>.delayed(Duration.zero);
throw StateError('not running');
}, failures.add);
pipe.add('a');
pipe.add('b');
pipe.add('?', reply: true);
await pumpEventQueue();
expect(sent, ['a']);
expect(failures, hasLength(1));
});
}
+11 -3
View File
@@ -90,9 +90,7 @@ class TerminalTestAppState extends State<TerminalTestApp> {
child: Scaffold(
appBar: AppBar(
title: const Text('App'),
actions: [
TerminalToggleButton(layout: widget.layout),
],
actions: [TerminalToggleButton(layout: widget.layout)],
),
body: const TextField(key: appField),
),
@@ -125,6 +123,8 @@ Future<void> chord(
}
}
/// Alt+T: shows or hides the terminal from outside it (inside, it is the
/// shell's ESC t).
Future<void> altT(WidgetTester tester, {bool settle = true}) => chord(
tester,
LogicalKeyboardKey.keyT,
@@ -132,6 +132,14 @@ Future<void> altT(WidgetTester tester, {bool settle = true}) => chord(
settle: settle,
);
/// Ctrl+`: shows or hides the terminal wherever the keyboard is.
Future<void> toggleTerminal(WidgetTester tester, {bool settle = true}) => chord(
tester,
LogicalKeyboardKey.backquote,
[LogicalKeyboardKey.controlLeft],
settle: settle,
);
Future<void> ctrlTab(WidgetTester tester, {bool reverse = false}) => chord(
tester,
LogicalKeyboardKey.tab,
@@ -57,9 +57,7 @@ Future<Widget?> _pumpBar(
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: actions == null
? bar
: TerminalScope(actions: actions, child: bar),
home: actions == null ? bar : TerminalScope(actions: actions, child: bar),
),
);
await tester.pump();
@@ -106,7 +106,7 @@ void main() {
// Hidden again: the composer that had the keyboard gets it back, and
// Ctrl+Tab is the chat's once more.
await altT(tester);
await toggleTerminal(tester);
expect(_composer(tester, 'a').focusNode.hasPrimaryFocus, isTrue);
await ctrlTab(tester);
expect(workspace.activePane?.sessionId, 'b');
@@ -48,7 +48,7 @@ void main() {
await pumpTerminalApp(tester, hub: hub, layout: layout);
await tester.tap(find.byKey(appField));
await tester.pump();
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump(const Duration(milliseconds: 100));
expect(panelFinder, findsOneWidget);
// Midway: the app has given up part of the panel's height, and the
@@ -61,7 +61,7 @@ void main() {
expect(appBottom(tester), shown);
expect(panelOpacity(tester), 1);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
// The keyboard is back in the field at once; the panel leaves after.
expect(appFieldFocused(tester), isTrue);
await tester.pump(const Duration(milliseconds: 100));
@@ -77,7 +77,7 @@ void main() {
'shrinks away', (tester) async {
layout.setMode(TerminalMode.float);
await pumpTerminalApp(tester, hub: hub, layout: layout);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
// The window is built, then its motion starts.
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
@@ -87,7 +87,7 @@ void main() {
expect(appBottom(tester), 800);
await tester.pumpAndSettle();
expect(floatScale(tester).scale.value, 1);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump(const Duration(milliseconds: 100));
// Hiding: no longer shown, still painted while it shrinks away.
expect(floatFinder, findsNothing);
@@ -100,7 +100,7 @@ void main() {
// AnimationSpeedController plays animations at half speed this way.
timeDilation = 2;
await pumpTerminalApp(tester, hub: hub, layout: layout);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump(const Duration(milliseconds: 300));
expect(appBottom(tester), inExclusiveRange(shown, 800));
await tester.pumpAndSettle();
@@ -112,16 +112,16 @@ void main() {
tester,
) async {
await pumpTerminalApp(tester, hub: hub, layout: layout, reduceMotion: true);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump();
expect(appBottom(tester), shown);
expect(panelOpacity(tester), 1);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump();
expect(panelFinder, findsNothing);
expect(appBottom(tester), 800);
layout.setMode(TerminalMode.float);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump();
expect(floatScale(tester).scale.value, 1);
// The emulator's size reaches the server after its debounce.
@@ -31,16 +31,48 @@ void main() {
String key(String id) => terminalKey('mac', id);
/// Each toggle chord, and what it sends to the shell from inside the
/// terminal (null: it hides the terminal there too).
const toggles = {
'Alt+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.altLeft),
'Ctrl+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.controlLeft),
'Cmd+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.metaLeft),
'Ctrl+`': (LogicalKeyboardKey.backquote, LogicalKeyboardKey.controlLeft),
'Alt+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.altLeft, '\x1bt'),
'Ctrl+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.controlLeft, '\x14'),
'Cmd+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.metaLeft, null),
'Ctrl+`': (
LogicalKeyboardKey.backquote,
LogicalKeyboardKey.controlLeft,
null,
),
};
for (final mode in TerminalMode.values) {
for (final MapEntry(key: name, value: (letter, modifier))
for (final MapEntry(key: name, value: (letter, modifier, sent))
in toggles.entries) {
if (sent != null) {
desktopTestWidgets(
'$name shows the ${mode.label.toLowerCase()} from a text field; '
'inside the terminal it reaches the shell',
(tester) async {
layout.setMode(mode);
await pumpTerminalApp(tester, hub: hub, layout: layout);
await tester.tap(find.byKey(appField));
await tester.pump();
await chord(tester, letter, [modifier]);
expect(layout.visible, isTrue);
expect(find.text('t'), findsNothing);
expect(terminalFocused(key('term_a')), isTrue);
await chord(tester, letter, [modifier]);
expect(layout.visible, isTrue);
expect(mac.bodies('terminal_input').last['data'], sent);
// Cmd+T and Ctrl+` still hide it from inside.
await chord(tester, LogicalKeyboardKey.backquote, [
LogicalKeyboardKey.controlLeft,
]);
expect(layout.visible, isFalse);
await tester.pump(const Duration(milliseconds: 300));
},
);
continue;
}
desktopTestWidgets(
'$name toggles the ${mode.label.toLowerCase()} from a text '
'field and from inside the terminal',
@@ -58,8 +90,7 @@ void main() {
// The shortcut never types into the field it was pressed in.
expect(find.text('t'), findsNothing);
expect(terminalFocused(key('term_a')), isTrue);
// Inside the terminal the same keys hide it instead of reaching the
// shell (Ctrl+T would be transpose-chars there).
// Inside the terminal the same keys hide it.
final typed = mac.bodies('terminal_input').length;
await chord(tester, letter, [modifier]);
expect(surface, findsNothing);
@@ -79,6 +110,54 @@ void main() {
timeStamp: Duration.zero,
);
expect(terminalToggleShortcut(event, _AltHeld()), isTrue);
// Inside the terminal Option+T is the shell's (ESC t, or † when Option
// is not Meta).
expect(
terminalToggleShortcut(event, _AltHeld(), inTerminal: true),
isFalse,
);
});
test('inside the terminal only Cmd+T and Ctrl+` toggle', () {
KeyDownEvent down(LogicalKeyboardKey key, PhysicalKeyboardKey physical) =>
KeyDownEvent(
physicalKey: physical,
logicalKey: key,
timeStamp: Duration.zero,
);
final t = down(LogicalKeyboardKey.keyT, PhysicalKeyboardKey.keyT);
final tick = down(
LogicalKeyboardKey.backquote,
PhysicalKeyboardKey.backquote,
);
bool inside(KeyDownEvent event, HardwareKeyboard keyboard) =>
terminalToggleShortcut(event, keyboard, inTerminal: true);
expect(inside(t, _AltHeld()), isFalse);
expect(inside(t, _Held(control: true)), isFalse);
expect(inside(t, _Held(meta: true)), isTrue);
expect(inside(tick, _Held(control: true)), isTrue);
expect(terminalToggleShortcut(t, _Held(control: true)), isTrue);
});
test('the menu and cheatsheet say which keys reach the shell', () {
expect(
const TerminalShortcutLabels(
web: false,
platform: TargetPlatform.macOS,
).inTerminalNote,
'Inside the terminal, Option+T and Ctrl+T reach the shell; Cmd+T or '
'Ctrl+` hides it.',
);
const linuxWeb = TerminalShortcutLabels(
web: true,
platform: TargetPlatform.linux,
);
expect(
linuxWeb.inTerminalNote,
'Inside the terminal, Alt+T and Ctrl+T reach the shell; Ctrl+` hides '
'it.',
);
expect(linuxWeb.summary, contains(linuxWeb.inTerminalNote));
});
desktopTestWidgets('holding the chord toggles once and types nothing', (
@@ -127,7 +206,7 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.keyX);
await tester.pump();
expect(mac.bodies('terminal_input').last['data'], 'x');
await altT(tester);
await toggleTerminal(tester);
expect(appFieldFocused(tester), isTrue);
// The bar button focuses it as well.
await tester.tap(find.byIcon(Icons.terminal));
@@ -170,7 +249,7 @@ void main() {
await ctrlTab(tester);
expect(hub.selected!.info.id, 'term_a');
expect(terminalFocused(key('term_a')), isTrue);
await altT(tester);
await toggleTerminal(tester);
await ctrlTab(tester);
expect(hub.selected!.info.id, 'term_a');
});
@@ -195,8 +274,8 @@ void main() {
expect(empty.bodies('terminal_open'), hasLength(1));
expect(bare.tabs, hasLength(1));
expect(terminalFocused(bare.tabs.single.key), isTrue);
await altT(tester);
await altT(tester);
await toggleTerminal(tester);
await toggleTerminal(tester);
expect(empty.bodies('terminal_open'), hasLength(1));
});
@@ -220,7 +299,7 @@ void main() {
await ctrlTab(tester, reverse: true);
expect(hub.selected!.info.id, 'term_c');
expect(terminalFocused(key('term_c')), isTrue);
await chord(tester, LogicalKeyboardKey.keyT, [
await chord(tester, LogicalKeyboardKey.backquote, [
LogicalKeyboardKey.controlLeft,
]);
expect(find.widgetWithText(AppBar, 'Terminal'), findsNothing);
@@ -284,6 +363,21 @@ void main() {
});
}
/// A keyboard with the given modifiers held.
class _Held extends HardwareKeyboard {
_Held({this.control = false, this.meta = false});
final bool control;
final bool meta;
@override
bool get isAltPressed => false;
@override
bool get isControlPressed => control;
@override
bool get isMetaPressed => meta;
@override
bool get isShiftPressed => false;
}
/// A keyboard on which only Alt (Option) is held.
class _AltHeld extends HardwareKeyboard {
@override
@@ -265,6 +265,39 @@ void main() {
expect(layout.mode, TerminalMode.panel);
});
Future<void> pumpSettings(WidgetTester tester) => tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: SettingsTerminalSection(layout: layout),
),
),
),
);
const optionAsMeta = ValueKey('settings-terminal-option-as-meta');
desktopTestWidgets('on a Mac, Settings chooses whether Option is Meta, '
'saved with the layout', (tester) async {
await pumpSettings(tester);
expect(layout.optionAsMeta, isTrue);
await tester.tap(find.byKey(optionAsMeta));
await tester.pumpAndSettle();
expect(layout.optionAsMeta, isFalse);
expect(saved()['option_as_meta'], isFalse);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.optionAsMeta, isFalse);
});
testWidgets(
'elsewhere Alt is always Meta and there is no Option switch',
(tester) async {
await pumpSettings(tester);
expect(find.byKey(optionAsMeta), findsNothing);
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
desktopTestWidgets(
'a narrow window opens the terminal full screen with the key '
'toolbar',
@@ -0,0 +1,75 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'paint_fixture.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final size = fixturePainter().cellSize;
final w = size.width.ceil();
final h = size.height.ceil();
Future<Pixels> cell(CellData data) => Pixels.paint(
w,
h * 2, // room for decorations drawn below the cell
(canvas) => fixturePainter().paintCell(canvas, Offset.zero, data),
);
/// The rows of the cell that contain painted pixels.
Future<List<int>> inkRows(CellData data) async {
final pixels = await cell(data);
return [
for (var y = 0; y < h * 2; y++)
if (pixels.rowHasInk(y)) y,
];
}
test('a plain space draws nothing', () async {
expect(await inkRows(cellOf(' ')), isEmpty);
});
test('strikethrough (SGR 9) draws a line through the middle', () async {
final rows = await inkRows(cellOf(' ', flags: CellAttr.strikethrough));
expect(rows, isNotEmpty);
expect(rows.every((y) => y > h * 0.2 && y < h * 0.8), isTrue);
});
test('overline (SGR 53) draws at the top, underline at the bottom', () async {
final over = await inkRows(cellOf(' ', flags: CellAttr.overline));
expect(over, isNotEmpty);
expect(over.first, lessThan(h * 0.3));
final under = await inkRows(cellOf(' ', flags: CellAttr.underline));
expect(under, isNotEmpty);
expect(under.last, greaterThan(h * 0.6));
});
test('double underline (SGR 21) draws two lines', () async {
const doubled = CellAttr.underline | (2 << CellAttr.underlineStyleShift);
final single = await inkRows(cellOf(' ', flags: CellAttr.underline));
final two = await inkRows(cellOf(' ', flags: doubled));
expect(two.length, greaterThan(single.length));
});
test(
'concealed text (SGR 8) keeps its background, hides the glyph',
() async {
final shown = await cell(cellOf('M'));
expect(shown.count(foregroundColor), greaterThan(0));
final hidden = await cell(cellOf('M', flags: CellAttr.invisible));
expect(hidden.count(foregroundColor), 0);
final inverse = await cell(
cellOf('M', flags: CellAttr.invisible | CellAttr.inverse),
);
expect(
inverse.count(foregroundColor),
greaterThan(0),
reason: 'background',
);
expect(inverse.count(backgroundColor), 0, reason: 'no glyph');
},
);
}
@@ -0,0 +1,61 @@
import 'package:flutter_test/flutter_test.dart';
import 'xterm_fixture.dart';
void main() {
test('DCS, APC, PM and SOS bodies are swallowed, not printed', () {
final t = FixtureTerminal()
..feed('a\x1bP+q544e\x1b\\b')
..feed('\x1b_Gf=24;AAAA\x1b\\c')
..feed('\x1b^private\x1b\\d')
..feed('\x1bXstring\x1b\\e');
expect(t.row(0), 'abcde');
});
test('a control string split across writes is still swallowed', () {
final t = FixtureTerminal()
..feed('x\x1bPtmux;')
..feed('\x1b')
..feed('\x1b[31mhidden')
..feed('\x1b')
..feed('\\y');
// An ESC that is not ST aborts the string, as on a VT; the next ESC
// starts a CSI, so the output after it is ordinary text again.
expect(t.row(0), 'xhiddeny');
expect(t.cell(1, 0).foreground, named(1));
});
test('ST split between writes ends the string', () {
final t = FixtureTerminal()
..feed('1\x1bPq#0;2;0;0;0#0~~@@')
..feed('\x1b')
..feed('\\2');
expect(t.row(0), '12');
});
test('CAN aborts a control string', () {
final t = FixtureTerminal()..feed('\x1bPjunk\x18ok');
expect(t.row(0), 'ok');
});
test('DECRQSS m reports the current SGR', () {
final t = FixtureTerminal()..feed('\x1b[1;4:3;38;5;196;48;2;1;2;3m');
t.takeReplies();
t.feed('\x1bP\$qm\x1b\\');
expect(t.takeReplies(), '\x1bP1\$r0;1;4:3;38;5;196;48;2;1;2;3m\x1b\\');
expect(t.row(0), '');
});
test('DECRQSS r reports margins; unknown requests are refused', () {
final t = FixtureTerminal()..feed('\x1b[2;4r');
t.feed('\x1bP\$qr\x1b\\');
expect(t.takeReplies(), '\x1bP1\$r2;4r\x1b\\');
t.feed('\x1bP\$qbogus\x1b\\');
expect(t.takeReplies(), '\x1bP0\$r\x1b\\');
});
test('a DCS other than DECRQSS sends nothing', () {
final t = FixtureTerminal()..feed('\x1bP+q544e\x1b\\');
expect(t.takeReplies(), '');
});
}
@@ -0,0 +1,65 @@
import 'package:flutter_test/flutter_test.dart';
import 'xterm_fixture.dart';
void main() {
test('CSI s / CSI u save and restore the cursor (SCOSC / SCORC)', () {
final t = FixtureTerminal()..feed('\x1b[2;3H\x1b[s\x1b[5;9Hx\x1b[uy');
expect(t.charAt(2, 1), 'y');
expect(t.charAt(8, 4), 'x');
expect(t.buffer.cursorX, 3);
expect(t.buffer.cursorY, 1);
});
test('CSI ? u (kitty keyboard query) does not restore the cursor', () {
final t = FixtureTerminal()..feed('\x1b[s\x1b[3;3H\x1b[?u');
expect(t.buffer.cursorX, 2);
expect(t.buffer.cursorY, 2);
expect(t.takeReplies(), '');
});
test('CHT moves forward by tab stops and stops at the last column', () {
final t = FixtureTerminal()..feed('\x1b[I');
expect(t.buffer.cursorX, 8);
t.feed('\x1b[2I');
expect(t.buffer.cursorX, 19);
});
test('CBT moves back by tab stops and stops at column 0', () {
final t = FixtureTerminal()..feed('\x1b[1;19H\x1b[Z');
expect(t.buffer.cursorX, 16);
t.feed('\x1b[5Z');
expect(t.buffer.cursorX, 0);
});
test('HTS sets a tab stop that HT and CBT use', () {
final t = FixtureTerminal()..feed('\x1b[1;4H\x1bH\r\t');
expect(t.buffer.cursorX, 3);
t.feed('\x1b[1;7H\x1b[Z');
expect(t.buffer.cursorX, 3);
});
test('HPA, HPR and VPR', () {
final t = FixtureTerminal()..feed('\x1b[7`');
expect(t.buffer.cursorX, 6);
t.feed('\x1b[3a');
expect(t.buffer.cursorX, 9);
t.feed('\x1b[a');
expect(t.buffer.cursorX, 10);
t.feed('\x1b[2e');
expect(t.buffer.cursorY, 2);
t.feed('\x1b[e');
expect(t.buffer.cursorY, 3);
});
test('DSR 6 reports the one-based cursor position', () {
final t = FixtureTerminal()..feed('\x1b[3;7H\x1b[6n');
expect(t.takeReplies(), '\x1b[3;7R');
});
test('zero counts mean one', () {
final t = FixtureTerminal()..feed('\x1b[0C\x1b[0B');
expect(t.buffer.cursorX, 1);
expect(t.buffer.cursorY, 1);
});
}
@@ -0,0 +1,97 @@
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'paint_fixture.dart';
import 'xterm_fixture.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('DECSCUSR', () {
test('stores the requested shape and blinking', () {
final t = FixtureTerminal();
expect(t.terminal.cursorShape, isNull);
const expected = {
1: (TerminalCursorType.block, true),
2: (TerminalCursorType.block, false),
3: (TerminalCursorType.underline, true),
4: (TerminalCursorType.underline, false),
5: (TerminalCursorType.verticalBar, true),
6: (TerminalCursorType.verticalBar, false),
};
for (final MapEntry(key: ps, value: (shape, blinks))
in expected.entries) {
t.feed('\x1b[$ps q');
expect(t.terminal.cursorShape, shape, reason: 'Ps $ps');
expect(t.terminal.cursorShapeBlinks, blinks, reason: 'Ps $ps');
}
t.feed('\x1b[0 q');
expect(t.terminal.cursorShape, isNull);
t.feed('\x1b[6 q\x1bc');
expect(t.terminal.cursorShape, isNull);
});
test('does not print and is reported by DECRQSS', () {
final t = FixtureTerminal()..feed('\x1b[5 qa');
expect(t.row(0), 'a');
t.feed('\x1bP\$q q\x1b\\');
expect(t.takeReplies(), '\x1bP1\$r5 q\x1b\\');
});
});
group('cursor painting', () {
final cell = fixturePainter().cellSize;
final w = cell.width.ceil();
final h = cell.height.ceil();
final area = Rect.fromLTWH(0, 0, cell.width, cell.height);
Future<Pixels> cursor(TerminalCursorType type, {CellData? under}) =>
Pixels.paint(
w * 2,
h,
(canvas) => fixturePainter().paintCursor(
canvas,
Offset.zero,
cursorType: type,
cell: under,
),
);
test('a block cursor draws the character under it inverted', () async {
final empty = await cursor(TerminalCursorType.block);
expect(empty.count(backgroundColor, area), 0);
expect(empty.count(cursorColor, area), greaterThan(0));
final withChar = await cursor(
TerminalCursorType.block,
under: cellOf('M'),
);
// The test font's glyphs fill the whole cell; before the fix the
// block hid them and every pixel was the cursor colour.
expect(
withChar.count(backgroundColor, area),
greaterThan(0),
reason: 'the glyph is drawn in the background colour',
);
});
test('a block cursor over a wide character spans two cells', () async {
final pixels = await cursor(
TerminalCursorType.block,
under: cellOf('中', width: 2),
);
expect(pixels.at(w + w ~/ 2, 0), cursorColor);
});
test('underline and bar cursors sit in the cell, not at the top', () async {
final underline = await cursor(TerminalCursorType.underline);
expect(underline.at(w ~/ 2, h - 1), cursorColor);
expect(underline.at(w ~/ 2, 0), isNot(cursorColor));
final bar = await cursor(TerminalCursorType.verticalBar);
expect(bar.at(0, h ~/ 2), cursorColor);
expect(bar.at(w - 1, h ~/ 2), isNot(cursorColor));
});
});
}
@@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
test('focusInput sends CSI I / CSI O only with ?1004 set', () {
final t = FixtureTerminal();
expect(t.terminal.focusInput(true), isFalse);
expect(t.takeReplies(), '');
t.feed('\x1b[?1004h');
expect(t.terminal.focusInput(true), isTrue);
t.terminal.focusInput(false);
expect(t.takeReplies(), '\x1b[I\x1b[O');
t.feed('\x1b[?1004l');
t.terminal.focusInput(true);
expect(t.takeReplies(), '');
});
testWidgets('TerminalView reports its focus changes', (tester) async {
final terminal = Terminal();
final replies = <String>[];
terminal.onOutput = replies.add;
final focus = FocusNode();
addTearDown(focus.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: TerminalView(
terminal,
focusNode: focus,
hardwareKeyboardOnly: true,
),
),
),
);
terminal.write('\x1b[?1004h');
focus.requestFocus();
await tester.pump();
focus.unfocus();
await tester.pump();
expect(replies.join(), '\x1b[I\x1b[O');
});
}
@@ -0,0 +1,45 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
test('leaving the 1049 alternate screen restores the saved cursor', () {
final t = FixtureTerminal()..feed('main\x1b[3;5H\x1b[31m');
t.feed('\x1b[?1049h');
expect(t.terminal.isUsingAltBuffer, isTrue);
t.feed('\x1b[1;1H\x1b[0malt screen');
t.feed('\x1b[?1049l');
expect(t.terminal.isUsingAltBuffer, isFalse);
expect(t.buffer.cursorX, 4);
expect(t.buffer.cursorY, 2);
expect(t.row(0), 'main');
t.feed('z');
expect(t.cell(4, 2).foreground, named(NamedColor.red));
});
test('DECCKM (CSI ? 1 h/l) is its own mode, not the keypad mode', () {
final t = FixtureTerminal();
expect(t.terminal.cursorKeysMode, isFalse);
t.feed('\x1b[?1h');
expect(t.terminal.cursorKeysMode, isTrue);
expect(t.terminal.appKeypadMode, isFalse);
t.feed('\x1b[?1l\x1b=');
expect(t.terminal.cursorKeysMode, isFalse);
expect(t.terminal.appKeypadMode, isTrue);
});
test('arrow keys follow DECCKM, not DECKPAM', () {
final t = FixtureTerminal();
t.terminal.keyInput(TerminalKey.arrowUp);
expect(t.takeReplies(), '\x1b[A');
t.feed('\x1b=');
t.terminal.keyInput(TerminalKey.arrowUp);
expect(t.takeReplies(), '\x1b[A');
t.feed('\x1b>\x1b[?1h');
t.terminal.keyInput(TerminalKey.arrowUp);
expect(t.takeReplies(), '\x1bOA');
});
}
@@ -0,0 +1,105 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
const down = TerminalMouseButtonState.down;
const up = TerminalMouseButtonState.up;
const at = CellOffset(4, 2); // column 5, row 3 one-based
String report(
String modes,
TerminalMouseButton button,
TerminalMouseButtonState state, {
bool motion = false,
bool ctrl = false,
}) {
final t = FixtureTerminal()..feed(modes);
t.terminal.mouseInput(button, state, at, motion: motion, ctrl: ctrl);
return t.takeReplies();
}
test('SGR wheel is 64 up and 65 down', () {
const sgr = '\x1b[?1000h\x1b[?1006h';
expect(report(sgr, TerminalMouseButton.wheelUp, down), '\x1b[<64;5;3M');
expect(report(sgr, TerminalMouseButton.wheelDown, down), '\x1b[<65;5;3M');
expect(report(sgr, TerminalMouseButton.wheelUp, up), '');
});
test('default encoding: 32 + code, 32 + column, 32 + row', () {
const normal = '\x1b[?1000h';
expect(
report(normal, TerminalMouseButton.left, down),
'\x1b[M\x20\x25\x23',
);
expect(report(normal, TerminalMouseButton.left, up), '\x1b[M\x23\x25\x23');
expect(
report(normal, TerminalMouseButton.wheelDown, down),
'\x1b[M\x61\x25\x23',
);
});
test('SGR reports which button was released', () {
const sgr = '\x1b[?1000h\x1b[?1006h';
expect(report(sgr, TerminalMouseButton.middle, down), '\x1b[<1;5;3M');
expect(report(sgr, TerminalMouseButton.middle, up), '\x1b[<1;5;3m');
expect(report(sgr, TerminalMouseButton.right, up), '\x1b[<2;5;3m');
});
test('modifiers add 4/8/16', () {
const sgr = '\x1b[?1000h\x1b[?1006h';
expect(
report(sgr, TerminalMouseButton.left, down, ctrl: true),
'\x1b[<16;5;3M',
);
});
group('motion', () {
test('1000 reports no motion', () {
expect(
report(
'\x1b[?1000h\x1b[?1006h',
TerminalMouseButton.left,
down,
motion: true,
),
'',
);
});
test('1002 reports drags with the button held, plus 32', () {
const drag = '\x1b[?1002h\x1b[?1006h';
expect(
report(drag, TerminalMouseButton.left, down, motion: true),
'\x1b[<32;5;3M',
);
expect(report(drag, TerminalMouseButton.none, down, motion: true), '');
});
test('1003 reports motion without a button as 35', () {
expect(
report(
'\x1b[?1003h\x1b[?1006h',
TerminalMouseButton.none,
down,
motion: true,
),
'\x1b[<35;5;3M',
);
expect(
report('\x1b[?1003h', TerminalMouseButton.none, down, motion: true),
'\x1b[M\x43\x25\x23',
);
});
});
test('X10 mode (9) reports presses only', () {
expect(
report('\x1b[?9h', TerminalMouseButton.left, down),
'\x1b[M\x20\x25\x23',
);
expect(report('\x1b[?9h', TerminalMouseButton.left, up), '');
expect(report('\x1b[?9h', TerminalMouseButton.wheelUp, down), '');
});
}
@@ -0,0 +1,159 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
/// A TerminalView placed away from the window's origin, so a report that
/// used window coordinates instead of the view's own would be wrong.
class _Harness {
_Harness(this.tester);
final WidgetTester tester;
final terminal = Terminal();
final controller = TerminalController();
final replies = <String>[];
Future<void> pump() async {
terminal.onOutput = replies.add;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Padding(
padding: const EdgeInsets.only(left: 100, top: 60),
child: SizedBox(
width: 400,
height: 200,
child: TerminalView(
terminal,
controller: controller,
hardwareKeyboardOnly: true,
),
),
),
),
),
);
}
TerminalViewState get _view =>
tester.state<TerminalViewState>(find.byType(TerminalView));
/// The global centre of zero-based screen cell ([x], [y]).
Offset cell(int x, int y) {
final render = _view.renderTerminal;
final size = render.cellSize;
return render.localToGlobal(
Offset((x + 0.5) * size.width, (y + 0.5) * size.height),
);
}
double get lineHeight => _view.renderTerminal.lineHeight;
String take() {
final all = replies.join();
replies.clear();
return all;
}
}
void main() {
testWidgets('a left drag with 1002 is reported, not selected', (
tester,
) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('\x1b[?1002h\x1b[?1006h');
await tester.pump();
final gesture = await tester.startGesture(
h.cell(1, 1),
kind: PointerDeviceKind.mouse,
);
await gesture.moveTo(h.cell(4, 1));
await gesture.moveTo(h.cell(6, 2));
await gesture.up();
await tester.pumpAndSettle();
expect(h.take(), '\x1b[<0;2;2M\x1b[<32;5;2M\x1b[<32;7;3M\x1b[<0;7;3m');
expect(h.controller.selection, isNull);
});
testWidgets('1003 reports plain motion; 1000 does not', (tester) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('\x1b[?1003h\x1b[?1006h');
final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: h.cell(0, 0));
await gesture.moveTo(h.cell(3, 2));
expect(h.take(), '\x1b[<35;4;3M');
h.terminal.write('\x1b[?1003l\x1b[?1000h');
await gesture.moveTo(h.cell(5, 2));
expect(h.take(), '');
await gesture.removePointer();
});
testWidgets('a middle click is reported as middle press and release', (
tester,
) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('\x1b[?1000h\x1b[?1006h');
final gesture = await tester.startGesture(
h.cell(2, 0),
kind: PointerDeviceKind.mouse,
buttons: kMiddleMouseButton,
);
await gesture.up();
await tester.pumpAndSettle();
expect(h.take(), '\x1b[<1;3;1M\x1b[<1;3;1m');
});
testWidgets('Shift+drag selects text even while the program has the mouse', (
tester,
) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('hello world\x1b[?1002h\x1b[?1006h');
await tester.pump();
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
final gesture = await tester.startGesture(
h.cell(0, 0),
kind: PointerDeviceKind.mouse,
);
await gesture.moveTo(h.cell(2, 0));
await gesture.moveTo(h.cell(4, 0));
await gesture.up();
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
await tester.pumpAndSettle();
expect(h.take(), '');
final selection = h.controller.selection;
expect(selection, isNotNull);
expect(h.terminal.buffer.getText(selection), startsWith('hell'));
});
testWidgets('the wheel reports 65 down / 64 up at the view cell', (
tester,
) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('\x1b[?1049h\x1b[?1000h\x1b[?1006h');
await tester.pump();
final pointer = TestPointer(1, PointerDeviceKind.mouse);
final at = h.cell(3, 1);
await tester.sendEventToBinding(pointer.hover(at));
await tester.sendEventToBinding(
pointer.scroll(Offset(0, h.lineHeight * 2)),
);
await tester.pump();
expect(h.take(), '\x1b[<65;4;2M\x1b[<65;4;2M');
await tester.sendEventToBinding(pointer.scroll(Offset(0, -h.lineHeight)));
await tester.pump();
expect(h.take(), '\x1b[<64;4;2M');
});
}
+105
View File
@@ -0,0 +1,105 @@
import 'package:flutter_test/flutter_test.dart';
import 'xterm_fixture.dart';
void main() {
group('OSC 10/11/12 colour queries', () {
FixtureTerminal themed() {
final t = FixtureTerminal();
t.terminal.setReportedColors(
foreground: 0xFFC0C0C0,
background: 0xFF102030,
cursor: 0xFFFF8000,
);
return t;
}
test('answer with the theme colours and the query terminator', () {
final t = themed()..feed('\x1b]11;?\x1b\\');
expect(t.takeReplies(), '\x1b]11;rgb:1010/2020/3030\x1b\\');
t.feed('\x1b]10;?\x07');
expect(t.takeReplies(), '\x1b]10;rgb:c0c0/c0c0/c0c0\x07');
t.feed('\x1b]12;?\x07');
expect(t.takeReplies(), '\x1b]12;rgb:ffff/8080/0000\x07');
});
test('a multi-colour query answers each colour in turn', () {
final t = themed()..feed('\x1b]10;?;?\x07');
expect(
t.takeReplies(),
'\x1b]10;rgb:c0c0/c0c0/c0c0\x07\x1b]11;rgb:1010/2020/3030\x07',
);
});
test('setting a colour sends nothing and prints nothing', () {
final t = themed()..feed('\x1b]11;#000000\x07x');
expect(t.takeReplies(), '');
expect(t.row(0), 'x');
});
});
group('OSC 8 hyperlinks', () {
test('link cells without printing the sequence', () {
final t = FixtureTerminal()
..feed('a\x1b]8;id=1;https://example.com/a;b\x1b\\link\x1b]8;;\x1b\\z');
expect(t.row(0), 'alinkz');
final line = t.buffer.lines[0];
expect(t.terminal.hyperlinkAt(line, 0), isNull);
for (var x = 1; x <= 4; x++) {
expect(t.terminal.hyperlinkAt(line, x), 'https://example.com/a;b');
}
expect(t.terminal.hyperlinkAt(line, 5), isNull);
});
test('a link survives SGR changes and ends with an empty URI', () {
final t = FixtureTerminal()
..feed('\x1b]8;;https://x.test\x07\x1b[1ma\x1b[0mb\x1b]8;;\x07c');
final line = t.buffer.lines[0];
expect(t.terminal.hyperlinkAt(line, 0), 'https://x.test');
expect(t.terminal.hyperlinkAt(line, 1), 'https://x.test');
expect(t.terminal.hyperlinkAt(line, 2), isNull);
expect(t.cell(1, 0).flags & 0xFFFF, 0, reason: 'no SGR attributes');
});
});
group('OSC 52 clipboard', () {
test('a set reaches the callback decoded', () {
final t = FixtureTerminal();
final sets = <(String, String)>[];
t.terminal.onClipboardSet = (text, selection) =>
sets.add((text, selection));
t.feed('\x1b]52;c;aGVsbG8gd8O2cmxk\x07x');
expect(sets, [('hello wörld', 'c')]);
expect(t.row(0), 'x');
});
test('a read request and invalid data are ignored', () {
final t = FixtureTerminal();
var calls = 0;
t.terminal.onClipboardSet = (_, _) => calls++;
t.feed('\x1b]52;c;?\x07\x1b]52;c;not base64!\x07');
expect(calls, 0);
expect(t.takeReplies(), '');
});
});
test('OSC 7 reports the working directory', () {
final t = FixtureTerminal();
final dirs = <String>[];
t.terminal.onWorkingDirectoryChange = dirs.add;
t.feed('\x1b]7;file://host/home/me/a;b\x1b\\');
expect(dirs, ['file://host/home/me/a;b']);
expect(t.row(0), '');
});
test('titles keep their semicolons; an aborted OSC prints nothing', () {
final t = FixtureTerminal();
final titles = <String>[];
t.terminal.onTitleChange = titles.add;
t.feed('\x1b]2;vim; a.txt\x07');
t.feed('\x1b]2;cut\x1b[1mB');
expect(titles, ['vim; a.txt']);
expect(t.row(0), 'B');
expect(t.cell(0, 0).flags, isNot(0));
});
}
@@ -0,0 +1,107 @@
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/painting.dart';
import 'package:xterm/src/ui/painter.dart';
import 'package:xterm/xterm.dart';
const cursorColor = Color(0xFFFF0000);
const backgroundColor = Color(0xFF0000FF);
const foregroundColor = Color(0xFF00FF00);
/// A theme whose cursor, background and foreground are pure red, blue and
/// green, so painted pixels say which of them they are.
const fixtureTheme = TerminalTheme(
cursor: cursorColor,
selection: Color(0x80FFFFFF),
foreground: foregroundColor,
background: backgroundColor,
black: Color(0xFF000000),
red: Color(0xFF800000),
green: Color(0xFF008000),
yellow: Color(0xFF808000),
blue: Color(0xFF000080),
magenta: Color(0xFF800080),
cyan: Color(0xFF008080),
white: Color(0xFFC0C0C0),
brightBlack: Color(0xFF808080),
brightRed: Color(0xFFFF8080),
brightGreen: Color(0xFF80FF80),
brightYellow: Color(0xFFFFFF80),
brightBlue: Color(0xFF8080FF),
brightMagenta: Color(0xFFFF80FF),
brightCyan: Color(0xFF80FFFF),
brightWhite: Color(0xFFFFFFFF),
searchHitBackground: Color(0xFFFFFF00),
searchHitBackgroundCurrent: Color(0xFFFF8000),
searchHitForeground: Color(0xFF000000),
);
TerminalPainter fixturePainter() => TerminalPainter(
theme: fixtureTheme,
textStyle: const TerminalStyle(fontSize: 20, height: 1),
textScaler: TextScaler.noScaling,
);
/// The pixels [paint] draws on a transparent canvas of [width] x [height].
class Pixels {
Pixels._(this.width, this.height, this._rgba);
final int width;
final int height;
final ByteData _rgba;
static Future<Pixels> paint(
int width,
int height,
void Function(Canvas canvas) paint,
) async {
final recorder = ui.PictureRecorder();
paint(Canvas(recorder));
final image = await recorder.endRecording().toImage(width, height);
final data = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
image.dispose();
return Pixels._(width, height, data!);
}
/// The colour at ([x], [y]), opaque or transparent.
Color at(int x, int y) {
final i = (y * width + x) * 4;
return Color.fromARGB(
_rgba.getUint8(i + 3),
_rgba.getUint8(i),
_rgba.getUint8(i + 1),
_rgba.getUint8(i + 2),
);
}
/// Whether row [y] has any painted (non-transparent) pixel; decorations
/// are antialiased, so their exact colour varies.
bool rowHasInk(int y) {
for (var x = 0; x < width; x++) {
if (_rgba.getUint8((y * width + x) * 4 + 3) != 0) return true;
}
return false;
}
/// How many pixels in [rect] are exactly [color].
int count(Color color, [Rect? rect]) {
final area =
rect ?? Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble());
var n = 0;
for (var y = area.top.floor(); y < area.bottom.ceil(); y++) {
for (var x = area.left.floor(); x < area.right.ceil(); x++) {
if (at(x, y) == color) n++;
}
}
return n;
}
}
/// A cell holding [char] with [flags] and default colours.
CellData cellOf(String char, {int flags = 0, int width = 1}) => CellData(
foreground: 0,
background: 0,
flags: flags,
content: char.codeUnitAt(0) | (width << CellContent.widthShift),
);
@@ -0,0 +1,75 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
/// Puts the terminal in the state a crashed full-screen program leaves.
FixtureTerminal messedUp() {
return FixtureTerminal()..feed(
'shell\r\n'
'\x1b[?1049h' // alternate screen
'\x1b[2;4r' // scroll region
'\x1b[?25l' // cursor hidden
'\x1b[?1h\x1b=' // application cursor keys and keypad
'\x1b[?7l\x1b[4h\x1b[?6h' // no autowrap, insert, origin
'\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[?1004h' // mouse, paste, focus
'\x1b(0' // DEC graphics in G0
'\x1b[1;7;38;5;9m' // attributes
'\x1b[3;3Hjunk',
);
}
test('RIS (ESC c) recovers every mode, the screen and the cursor', () {
final t = messedUp()..feed('\x1bc');
final term = t.terminal;
expect(term.isUsingAltBuffer, isFalse);
expect(term.cursorVisibleMode, isTrue);
expect(term.cursorKeysMode, isFalse);
expect(term.appKeypadMode, isFalse);
expect(term.autoWrapMode, isTrue);
expect(term.insertMode, isFalse);
expect(term.originMode, isFalse);
expect(term.mouseMode, MouseMode.none);
expect(term.mouseReportMode, MouseReportMode.normal);
expect(term.bracketedPasteMode, isFalse);
expect(term.reportFocusMode, isFalse);
expect(t.buffer.marginTop, 0);
expect(t.buffer.marginBottom, 4);
expect(t.buffer.cursorX, 0);
expect(t.buffer.cursorY, 0);
for (var y = 0; y < 5; y++) {
expect(t.row(y), '', reason: 'row $y is cleared');
}
// Plain ASCII and plain attributes again.
t.feed('q');
expect(t.charAt(0, 0), 'q');
expect(t.cell(0, 0).flags, 0);
expect(t.cell(0, 0).foreground, 0);
});
test('RIS keeps the main screen scrollback', () {
final t = FixtureTerminal();
for (var i = 0; i < 8; i++) {
t.feed('line $i\r\n');
}
final scrollBack = t.buffer.scrollBack;
t.feed('\x1bc');
expect(t.buffer.scrollBack, scrollBack);
expect(t.buffer.lines[0].getText().trimRight(), 'line 0');
});
test('DECSTR (CSI ! p) resets modes and attributes but keeps the text', () {
final t = FixtureTerminal()
..feed('keep\x1b[?25l\x1b[?1h\x1b[2;4r\x1b[4h\x1b[1m\x1b[!p');
expect(t.row(0), 'keep');
expect(t.terminal.cursorVisibleMode, isTrue);
expect(t.terminal.cursorKeysMode, isFalse);
expect(t.terminal.insertMode, isFalse);
expect(t.terminal.cursor.attrs, 0);
expect(t.buffer.marginTop, 0);
expect(t.buffer.marginBottom, 4);
});
}
+98
View File
@@ -0,0 +1,98 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
CellData styled(String sgr) {
final t = FixtureTerminal()..feed('\x1b[${sgr}mX');
return t.cell(0, 0);
}
int underlineStyle(CellData cell) => cell.flags & CellAttr.underline == 0
? 0
: (cell.flags & CellAttr.underlineStyleMask) >>
CellAttr.underlineStyleShift;
test('4:3 is a curly underline, not a yellow background', () {
final cell = styled('4:3');
expect(underlineStyle(cell), 3);
expect(cell.background, 0);
expect(cell.flags & CellAttr.italic, 0);
});
test('underline styles 4:0 to 4:5 and plain 4 / 24 / 21', () {
expect(underlineStyle(styled('4')), 1);
expect(underlineStyle(styled('4:0')), 0);
expect(underlineStyle(styled('4:1')), 1);
expect(underlineStyle(styled('4:2')), 2);
expect(underlineStyle(styled('4:4')), 4);
expect(underlineStyle(styled('4:5')), 5);
expect(underlineStyle(styled('4:3;24')), 0);
expect(underlineStyle(styled('4:3;4:0')), 0);
expect(underlineStyle(styled('21')), 2);
expect(styled('21').flags & CellAttr.bold, 0);
});
test('colon direct colours with and without a colour space id', () {
expect(styled('38:2::10:20:30').foreground, rgb(10, 20, 30));
expect(styled('38:2:1:10:20:30').foreground, rgb(10, 20, 30));
expect(styled('38:2:10:20:30').foreground, rgb(10, 20, 30));
expect(styled('48:2::1:2:3').background, rgb(1, 2, 3));
});
test('colon and semicolon indexed colours', () {
expect(styled('38:5:196').foreground, palette(196));
expect(styled('48:5:21').background, palette(21));
expect(styled('38;5;196').foreground, palette(196));
expect(styled('38;2;1;2;3;1').foreground, rgb(1, 2, 3));
expect(styled('38;2;1;2;3;1').flags & CellAttr.bold, isNot(0));
});
test('colon groups end at the next semicolon', () {
final cell = styled('38:5:2;41;1');
expect(cell.foreground, palette(2));
expect(cell.background, named(NamedColor.red));
expect(cell.flags & CellAttr.bold, isNot(0));
});
test('underline colour 58 / 59 is consumed, not applied elsewhere', () {
var cell = styled('58:2::255:0:0;4:3');
expect(cell.foreground, 0);
expect(cell.background, 0);
expect(underlineStyle(cell), 3);
cell = styled('58;5;9;1');
expect(cell.foreground, 0);
expect(cell.flags & CellAttr.bold, isNot(0));
cell = styled('58;2;1;2;3;59;7');
expect(cell.flags & CellAttr.inverse, isNot(0));
expect(cell.background, 0);
});
test('truncated extended colours do not throw or misapply', () {
expect(styled('38;5').foreground, 0);
expect(styled('38;2;1;2').foreground, 0);
expect(styled('48').background, 0);
});
test('22 clears bold and faint; 53/55 toggle overline', () {
expect(styled('1;2;22').flags & (CellAttr.bold | CellAttr.faint), 0);
expect(styled('53').flags & CellAttr.overline, isNot(0));
expect(styled('53;55').flags & CellAttr.overline, 0);
});
test('a private-prefixed m (modifyOtherKeys) is not SGR', () {
final t = FixtureTerminal()..feed('\x1b[>4;2mX');
expect(t.cell(0, 0).flags, 0);
expect(t.row(0), 'X');
});
test('empty parameters default: CSI ; 5 H and CSI 3 H', () {
final t = FixtureTerminal()..feed('\x1b[;5H');
expect(t.buffer.cursorX, 4);
expect(t.buffer.cursorY, 0);
t.feed('\x1b[3H');
expect(t.buffer.cursorX, 0);
expect(t.buffer.cursorY, 2);
});
}
@@ -0,0 +1,47 @@
import 'package:xterm/xterm.dart';
/// A terminal fed raw bytes in byte-fixture tests, with every reply it sends
/// to the program collected in [replies].
class FixtureTerminal {
FixtureTerminal({int width = 20, int height = 5}) {
terminal.onOutput = replies.add;
terminal.resize(width, height);
}
final terminal = Terminal(maxLines: 100);
final replies = <String>[];
Buffer get buffer => terminal.buffer;
void feed(String bytes) => terminal.write(bytes);
/// The text of screen row [y], trailing blanks trimmed.
String row(int y) =>
buffer.lines[buffer.scrollBack + y].getText().trimRight();
/// The cell at column [x] of screen row [y].
CellData cell(int x, int y) {
final data = CellData.empty();
buffer.lines[buffer.scrollBack + y].getCellData(x, data);
return data;
}
/// The character at column [x] of screen row [y], '' for an empty cell.
String charAt(int x, int y) {
final code = cell(x, y).content & CellContent.codepointMask;
return code == 0 ? '' : String.fromCharCode(code);
}
/// The replies sent so far, joined, and then forgotten.
String takeReplies() {
final all = replies.join();
replies.clear();
return all;
}
}
int rgb(int r, int g, int b) => CellColor.rgb | (r << 16) | (g << 8) | b;
int palette(int index) => CellColor.palette | index;
int named(int index) => CellColor.named | index;