Terminal: xterm key encoding, no live reflow on resize, Alt+T/Ctrl+T reach the shell

- Live terminals no longer reflow (xterm.dart 4.0.0 left the cursor on the
  wrong row); narrowing cuts and erases cells past the width, rows scroll
  into scrollback keeping the cursor row; finished output still reflows.
- App-side key encoding before xterm.dart's defaults: Alt as Meta (ESC +
  the typed character), Ctrl symbol table, xterm modifier parameter for
  arrows/Home/End/PgUp/PgDn/Ins/Del/F-keys, DECCKM and DECKPAM, Alt+BS.
- Settings > Appearance > Terminal: Use Option as Meta key (Macs, on).
- Inside a focused terminal only Cmd+T and Ctrl+` toggle it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 23:32:29 +00:00
parent 5ab1ec9e00
commit 7d1ffe8ad3
22 changed files with 1408 additions and 61 deletions
@@ -0,0 +1,163 @@
import 'package:flutter/foundation.dart';
import 'package:xterm/core.dart';
/// The bytes xterm sends for keys, where xterm.dart 4.0.0's own handlers
/// differ (Alt+letter upper-cased, no Ctrl symbols, the wrong modifier codes,
/// application cursor keys read from the keypad mode).
///
/// Modified special keys use xterm's parameter: 1 + Shift(1) + Alt(2) +
/// Ctrl(4), so Shift+Up is `CSI 1;2A`, Alt+Left `CSI 1;3D`, Ctrl+Right
/// `CSI 1;5C`, Ctrl+Shift+Home `CSI 1;6H`, Shift+PgUp `CSI 5;2~`.
const String _esc = '\x1b';
/// Whether Alt is Meta here: always outside Apple platforms; on them the
/// Option key is Meta only while [optionAsMeta] (else it types its symbol).
bool chatShellAltIsMeta({required bool optionAsMeta}) {
final apple =
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
return !apple || optionAsMeta;
}
int _modifier({required bool shift, required bool alt, required bool ctrl}) =>
1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0);
/// Cursor keys and Home/End: their final letter. DECCKM (application cursor
/// keys) sends them unmodified as SS3.
const Map<TerminalKey, String> _cursorKeys = {
TerminalKey.arrowUp: 'A',
TerminalKey.arrowDown: 'B',
TerminalKey.arrowRight: 'C',
TerminalKey.arrowLeft: 'D',
TerminalKey.home: 'H',
TerminalKey.end: 'F',
};
/// F1–F4: SS3 unmodified, `CSI 1;m P` modified.
const Map<TerminalKey, String> _pfKeys = {
TerminalKey.f1: 'P',
TerminalKey.f2: 'Q',
TerminalKey.f3: 'R',
TerminalKey.f4: 'S',
};
/// Keys sent as `CSI n ~` (`CSI n;m ~` modified).
const Map<TerminalKey, int> _tildeKeys = {
TerminalKey.insert: 2,
TerminalKey.delete: 3,
TerminalKey.pageUp: 5,
TerminalKey.pageDown: 6,
TerminalKey.f5: 15,
TerminalKey.f6: 17,
TerminalKey.f7: 18,
TerminalKey.f8: 19,
TerminalKey.f9: 20,
TerminalKey.f10: 21,
TerminalKey.f11: 23,
TerminalKey.f12: 24,
};
/// Keypad keys in application keypad mode (DECKPAM). The digits and the
/// decimal point keep typing their characters, as xterm does while NumLock
/// is on (a keypad digit only arrives with NumLock on).
const Map<TerminalKey, String> _keypadKeys = {
TerminalKey.numpadEnter: 'M',
TerminalKey.numpadMultiply: 'j',
TerminalKey.numpadAdd: 'k',
TerminalKey.numpadSubtract: 'm',
TerminalKey.numpadDivide: 'o',
TerminalKey.numpadEqual: 'X',
};
/// The bytes for a non-printing key, or null for a key that types a
/// character (letters, digits, symbols, Space, the keypad outside its
/// application mode). [alt] counts in the modifier parameter; [meta] (Alt
/// as Meta) prefixes ESC to the keys that have no parameter.
String? chatShellSpecialKeyBytes(
TerminalKey key, {
required bool shift,
required bool alt,
required bool meta,
required bool ctrl,
required TerminalState state,
}) {
final m = _modifier(shift: shift, alt: alt, ctrl: ctrl);
final prefix = meta ? _esc : '';
final cursor = _cursorKeys[key];
if (cursor != null) {
if (m > 1) return '$_esc[1;$m$cursor';
return state.cursorKeysMode ? '${_esc}O$cursor' : '$_esc[$cursor';
}
final pf = _pfKeys[key];
if (pf != null) return m > 1 ? '$_esc[1;$m$pf' : '${_esc}O$pf';
final tilde = _tildeKeys[key];
if (tilde != null) return m > 1 ? '$_esc[$tilde;$m~' : '$_esc[$tilde~';
if (state.appKeypadMode) {
final keypad = _keypadKeys[key];
if (keypad != null) return '${_esc}O$keypad';
}
switch (key) {
case TerminalKey.enter || TerminalKey.numpadEnter || TerminalKey.returnKey:
return '$prefix${state.lineFeedMode ? '\r\n' : '\r'}';
case TerminalKey.tab:
return shift ? '$prefix$_esc[Z' : '$prefix\t';
case TerminalKey.backtab:
return '$prefix$_esc[Z';
case TerminalKey.escape:
return '$prefix$_esc';
case TerminalKey.backspace:
return '$prefix${ctrl ? '\b' : '\x7f'}';
case TerminalKey.space:
if (ctrl) return '$prefix\x00';
return meta ? '$_esc ' : null;
default:
return null;
}
}
/// Ctrl with a character: the C0 code xterm sends for it.
const Map<String, int> _ctrlSymbols = {
' ': 0x00,
'@': 0x00,
'2': 0x00,
'[': 0x1b,
'3': 0x1b,
'\\': 0x1c,
'4': 0x1c,
']': 0x1d,
'5': 0x1d,
'^': 0x1e,
'6': 0x1e,
'_': 0x1f,
'/': 0x1f,
'-': 0x1f,
'7': 0x1f,
'?': 0x7f,
'8': 0x7f,
};
/// The control code Ctrl+[char] sends, or null if it has none.
int? chatShellCtrlCode(String char) {
if (char.length != 1) return null;
final code = char.toLowerCase().codeUnitAt(0);
if (code >= 0x61 && code <= 0x7a) return code - 0x60;
return _ctrlSymbols[char];
}
/// The bytes for [char] (as typed, Shift applied) with Ctrl and/or Meta
/// ([alt]): Ctrl maps it to its control code, Meta prefixes ESC. Null with
/// neither modifier, or Ctrl with a character that has no control code.
String? chatShellCharBytes(
String char, {
required bool alt,
required bool ctrl,
}) {
if (!alt && !ctrl) return null;
if (ctrl) {
final code = chatShellCtrlCode(char);
if (code == null) return null;
return '${alt ? _esc : ''}${String.fromCharCode(code)}';
}
return '$_esc$char';
}
@@ -0,0 +1,127 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:xterm/core.dart';
import 'chat_shell_terminal_input.dart';
import 'chat_shell_terminal_keymap.dart';
/// The terminal's input handler, chained before xterm.dart's defaults: it
/// encodes every key [Terminal.keyInput] receives (the key toolbar, the soft
/// keyboard's keys, hardware keys the view did not encode itself) as xterm
/// does. A printing key's character comes from the US layout here; the view
/// encodes hardware keys with their real character first
/// ([chatShellKeyEventBytes]).
class ChatShellInputHandler implements TerminalInputHandler {
const ChatShellInputHandler({required this.optionAsMeta});
/// Whether Option is Meta on Apple platforms (read at each key).
final bool Function() optionAsMeta;
@override
String? call(TerminalKeyboardEvent event) {
final alt = event.alt && chatShellAltIsMeta(optionAsMeta: optionAsMeta());
final special = chatShellSpecialKeyBytes(
event.key,
shift: event.shift,
alt: event.alt,
meta: alt,
ctrl: event.ctrl,
state: event.state,
);
if (special != null) return special;
final char = chatShellTerminalKeyChar(event.key);
if (char == null) return null;
return chatShellCharBytes(
event.shift ? chatShellUsShifted(char) : char,
alt: alt,
ctrl: event.ctrl,
);
}
}
bool _printable(String? text) {
if (text == null || text.runes.length != 1) return false;
final code = text.runes.single;
return code >= 0x20 && code != 0x7f;
}
bool _ascii(String text) {
final code = text.codeUnitAt(0);
return code >= 0x20 && code < 0x7f;
}
/// The character a key types with Shift but without Ctrl or Alt: the event's
/// own character where it is plain ASCII (so the layout counts), else the
/// logical key's, else the physical key's on a US layout. On Apple platforms
/// Option's own symbol (Option+B types ∫) is never the character.
String? _baseChar(KeyEvent event, {required bool shift, required bool option}) {
final character = event.character;
if (_printable(character) && _ascii(character!) && !option) {
return character;
}
final id = event.logicalKey.keyId;
if (id >= 0x20 && id < 0x7f) {
final char = String.fromCharCode(id);
return shift ? chatShellUsShifted(char) : char;
}
final physical = chatShellPhysicalChar(event.physicalKey);
if (physical == null) return null;
return shift ? chatShellUsShifted(physical) : physical;
}
/// The bytes a hardware key event sends, or null to leave it to the
/// emulator's own handling (plain typing, Cmd chords, IME text).
///
/// Non-printing keys are encoded as xterm does, honouring application cursor
/// keys and keypad mode in [state]. Ctrl with a character sends its control
/// code; Alt (Meta, see [chatShellAltIsMeta]) sends ESC and the character it
/// types with Shift and the layout. AltGr (Ctrl+Alt typing a symbol outside
/// Apple platforms) types the symbol.
String? chatShellKeyEventBytes(
KeyEvent event,
HardwareKeyboard keyboard,
TerminalState state, {
required bool optionAsMeta,
}) {
if (event is KeyUpEvent || keyboard.isMetaPressed) return null;
final apple =
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
final shift = keyboard.isShiftPressed;
final ctrl = keyboard.isControlPressed;
final alt =
keyboard.isAltPressed && chatShellAltIsMeta(optionAsMeta: optionAsMeta);
final special = chatShellSpecialKeys[event.logicalKey];
if (special != null) {
final bytes = chatShellSpecialKeyBytes(
special,
shift: shift,
alt: keyboard.isAltPressed,
meta: alt,
ctrl: ctrl,
state: state,
);
if (bytes != null) return bytes;
}
if (!alt && !ctrl) return null;
final base = _baseChar(
event,
shift: shift,
option: apple && keyboard.isAltPressed,
);
if (base == null) return null;
if (!apple && ctrl && keyboard.isAltPressed) {
// AltGr arrives as Ctrl+Alt: a symbol the layout composes is typed.
final character = event.character;
final id = event.logicalKey.keyId;
final plain = id >= 0x20 && id < 0x7f
? String.fromCharCode(id)
: chatShellPhysicalChar(event.physicalKey);
if (_printable(character) &&
character!.toLowerCase() != plain &&
chatShellUsShifted(plain ?? '') != character) {
return null;
}
}
return chatShellCharBytes(base, alt: alt, ctrl: ctrl);
}
@@ -0,0 +1,139 @@
import 'package:flutter/services.dart';
import 'package:xterm/core.dart';
/// Key tables for terminal input: the non-printing keys by their Flutter
/// logical key, and the US layout's characters, used when a key event
/// carries no usable character (Option's symbol on a Mac, a control code).
/// The non-printing keys the terminal encodes itself.
final Map<LogicalKeyboardKey, TerminalKey> chatShellSpecialKeys = {
LogicalKeyboardKey.arrowUp: TerminalKey.arrowUp,
LogicalKeyboardKey.arrowDown: TerminalKey.arrowDown,
LogicalKeyboardKey.arrowLeft: TerminalKey.arrowLeft,
LogicalKeyboardKey.arrowRight: TerminalKey.arrowRight,
LogicalKeyboardKey.home: TerminalKey.home,
LogicalKeyboardKey.end: TerminalKey.end,
LogicalKeyboardKey.insert: TerminalKey.insert,
LogicalKeyboardKey.delete: TerminalKey.delete,
LogicalKeyboardKey.pageUp: TerminalKey.pageUp,
LogicalKeyboardKey.pageDown: TerminalKey.pageDown,
LogicalKeyboardKey.f1: TerminalKey.f1,
LogicalKeyboardKey.f2: TerminalKey.f2,
LogicalKeyboardKey.f3: TerminalKey.f3,
LogicalKeyboardKey.f4: TerminalKey.f4,
LogicalKeyboardKey.f5: TerminalKey.f5,
LogicalKeyboardKey.f6: TerminalKey.f6,
LogicalKeyboardKey.f7: TerminalKey.f7,
LogicalKeyboardKey.f8: TerminalKey.f8,
LogicalKeyboardKey.f9: TerminalKey.f9,
LogicalKeyboardKey.f10: TerminalKey.f10,
LogicalKeyboardKey.f11: TerminalKey.f11,
LogicalKeyboardKey.f12: TerminalKey.f12,
LogicalKeyboardKey.enter: TerminalKey.enter,
LogicalKeyboardKey.numpadEnter: TerminalKey.numpadEnter,
LogicalKeyboardKey.tab: TerminalKey.tab,
LogicalKeyboardKey.escape: TerminalKey.escape,
LogicalKeyboardKey.backspace: TerminalKey.backspace,
LogicalKeyboardKey.space: TerminalKey.space,
LogicalKeyboardKey.numpadMultiply: TerminalKey.numpadMultiply,
LogicalKeyboardKey.numpadAdd: TerminalKey.numpadAdd,
LogicalKeyboardKey.numpadSubtract: TerminalKey.numpadSubtract,
LogicalKeyboardKey.numpadDivide: TerminalKey.numpadDivide,
LogicalKeyboardKey.numpadEqual: TerminalKey.numpadEqual,
};
/// US layout: each unshifted symbol and its shifted one.
const Map<String, String> _usShifted = {
'1': '!',
'2': '@',
'3': '#',
'4': r'$',
'5': '%',
'6': '^',
'7': '&',
'8': '*',
'9': '(',
'0': ')',
'-': '_',
'=': '+',
'[': '{',
']': '}',
'\\': '|',
';': ':',
"'": '"',
'`': '~',
',': '<',
'.': '>',
'/': '?',
};
/// [char] as Shift types it on a US layout.
String chatShellUsShifted(String char) =>
_usShifted[char] ?? char.toUpperCase();
/// The unshifted character of a printing [TerminalKey] on a US layout.
String? chatShellTerminalKeyChar(TerminalKey key) {
final index = key.index;
if (index >= TerminalKey.keyA.index && index <= TerminalKey.keyZ.index) {
return String.fromCharCode(0x61 + index - TerminalKey.keyA.index);
}
if (index >= TerminalKey.digit1.index && index <= TerminalKey.digit9.index) {
return String.fromCharCode(0x31 + index - TerminalKey.digit1.index);
}
if (index >= TerminalKey.numpad1.index &&
index <= TerminalKey.numpad9.index) {
return String.fromCharCode(0x31 + index - TerminalKey.numpad1.index);
}
return _terminalKeySymbols[key];
}
const Map<TerminalKey, String> _terminalKeySymbols = {
TerminalKey.digit0: '0',
TerminalKey.numpad0: '0',
TerminalKey.minus: '-',
TerminalKey.equal: '=',
TerminalKey.bracketLeft: '[',
TerminalKey.bracketRight: ']',
TerminalKey.backslash: '\\',
TerminalKey.semicolon: ';',
TerminalKey.quote: "'",
TerminalKey.backquote: '`',
TerminalKey.comma: ',',
TerminalKey.period: '.',
TerminalKey.slash: '/',
TerminalKey.numpadDecimal: '.',
TerminalKey.numpadDivide: '/',
TerminalKey.numpadMultiply: '*',
TerminalKey.numpadSubtract: '-',
TerminalKey.numpadAdd: '+',
TerminalKey.numpadEqual: '=',
};
/// The unshifted character a physical key types on a US layout.
String? chatShellPhysicalChar(PhysicalKeyboardKey key) {
final usb = key.usbHidUsage;
// USB HID: keyA (0x70004) … keyZ, digit1 … digit9, digit0.
if (usb >= 0x70004 && usb <= 0x7001d) {
return String.fromCharCode(0x61 + usb - 0x70004);
}
if (usb >= 0x7001e && usb <= 0x70026) {
return String.fromCharCode(0x31 + usb - 0x7001e);
}
return _physicalSymbols[key];
}
final Map<PhysicalKeyboardKey, String> _physicalSymbols = {
PhysicalKeyboardKey.digit0: '0',
PhysicalKeyboardKey.minus: '-',
PhysicalKeyboardKey.equal: '=',
PhysicalKeyboardKey.bracketLeft: '[',
PhysicalKeyboardKey.bracketRight: ']',
PhysicalKeyboardKey.backslash: '\\',
PhysicalKeyboardKey.semicolon: ';',
PhysicalKeyboardKey.quote: "'",
PhysicalKeyboardKey.backquote: '`',
PhysicalKeyboardKey.comma: ',',
PhysicalKeyboardKey.period: '.',
PhysicalKeyboardKey.slash: '/',
PhysicalKeyboardKey.space: ' ',
};
@@ -1,6 +1,9 @@
import 'package:flutter/foundation.dart';
import 'package:xterm/core.dart';
import '../../terminal/terminal_layout.dart';
import 'chat_shell_run.dart';
import 'chat_shell_terminal_key_input.dart';
/// Lines of scrollback one card's terminal keeps.
const int chatShellTerminalScrollback = 5000;
@@ -16,7 +19,14 @@ class ChatShellTerminalSession {
ChatShellRun run, {
required this.onInput,
required this.onResize,
}) : terminal = _ChatShellTerminal() {
bool Function()? optionAsMeta,
}) : optionAsMeta =
optionAsMeta ?? (() => TerminalLayout.instance.optionAsMeta),
terminal = _ChatShellTerminal() {
terminal.inputHandler = CascadeInputHandler([
ChatShellInputHandler(optionAsMeta: this.optionAsMeta),
defaultInputHandler,
]);
// Drawn at the process's own size until a view lays it out at its own.
if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows);
terminal.onOutput = _output;
@@ -26,6 +36,9 @@ class ChatShellTerminalSession {
final Terminal terminal;
/// Whether a Mac's Option key is Meta (Settings → Appearance → Terminal).
final bool Function() optionAsMeta;
/// Receives input for the process; only called while the run is live.
final void Function(String data) onInput;
@@ -47,6 +60,7 @@ class ChatShellTerminalSession {
/// queries in that output are not sent: the process asked them long ago.
void replay(ChatShellRun run) {
_live = run.running && run.terminal;
terminal.reflowEnabled = !_live;
_replaying = true;
try {
terminal.useMainBuffer();
@@ -86,6 +100,7 @@ class ChatShellTerminalSession {
void finish(ChatShellRun run) {
if (!_live) return;
_live = false;
terminal.reflowEnabled = true;
terminal.setCursorVisibleMode(false);
}
@@ -125,21 +140,48 @@ class ChatShellTerminalSession {
/// The emulator with the scrollback the cards keep. It answers a cursor
/// position query (DSR 6) with the one-based row and column the protocol
/// specifies; xterm.dart 4.0.0 itself answers zero-based.
///
/// A live terminal does not reflow on resize: xterm.dart 4.0.0's reflow
/// leaves the cursor on a row other than its line's, so the shell's redraw
/// lands on old output. Without it a resize behaves as xterm's: narrowing
/// cuts rows at the new width, fewer rows scroll the top into scrollback
/// (keeping the cursor's row at the bottom), more rows bring it back.
/// Finished output, which nothing writes to any more, reflows to fit.
class _ChatShellTerminal extends Terminal {
_ChatShellTerminal() : super(maxLines: chatShellTerminalScrollback);
_ChatShellTerminal()
: super(maxLines: chatShellTerminalScrollback, platform: _platform());
/// The package's own Alt handler (a fallback after the app's) leaves
/// Option alone only when it knows it is on a Mac.
static TerminalTargetPlatform _platform() =>
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS
? TerminalTargetPlatform.macos
: TerminalTargetPlatform.unknown;
@override
void sendCursorPosition() {
onOutput?.call('\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}R');
}
/// Narrowing rewraps long lines, and xterm.dart 4.0.0 keeps every blank
/// row below the cursor while doing so: the extra rows push the top of
/// the output into scrollback. Blank rows below the cursor are dropped
/// instead, keeping the cursor on its line.
@override
void resize(int width, int height, [int? pixelWidth, int? pixelHeight]) {
final oldWidth = viewWidth;
if (!reflowEnabled && width >= 1 && width < oldWidth) {
// A cut row keeps its cells past the new width, which a later widening
// would show again beside what was written since: they are erased.
for (final buffer in [mainBuffer, altBuffer]) {
buffer.lines.forEach((line) {
if (line.length > width) {
line.eraseRange(width, line.length, CursorStyle.empty);
}
});
}
}
super.resize(width, height, pixelWidth, pixelHeight);
if (!reflowEnabled) return;
// Rewrapping keeps every blank row below the cursor, and the extra rows
// push the top of finished output into scrollback: they are dropped.
final lines = buffer.lines;
while (buffer.height > viewHeight &&
buffer.height - 1 > buffer.absoluteCursorY &&
@@ -6,6 +6,7 @@ import 'package:xterm/xterm.dart';
import '../conversation/chat_composer_paste_focus.dart';
import '../ui/transcript/chat_link_launcher.dart';
import 'chat_shell_metrics.dart';
import 'chat_shell_terminal_key_input.dart';
import 'chat_shell_terminal_links.dart';
import 'chat_shell_terminal_session.dart';
import 'chat_shell_terminal_theme.dart';
@@ -94,6 +95,9 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
final TerminalController _controller = TerminalController();
final FocusNode _focus = FocusNode(debugLabel: 'chat-shell-terminal');
final FocusNode _outputFocus = FocusNode(debugLabel: 'chat-shell-output');
final ScrollController _scroll = ScrollController();
final Map<ShortcutActivator, Intent> _shortcuts =
chatShellTerminalShortcuts();
@override
void initState() {
@@ -109,6 +113,7 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
_controller.dispose();
_focus.dispose();
_outputFocus.dispose();
_scroll.dispose();
super.dispose();
}
@@ -123,11 +128,30 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
return true;
}
/// Ctrl-C with a selection copies; anything else is the terminal's.
KeyEventResult _key(FocusNode node, KeyEvent event) =>
chatShellCopyKey(event, HardwareKeyboard.instance) && _copySelection()
? KeyEventResult.handled
: KeyEventResult.ignored;
/// Ctrl-C with a selection copies; the terminal's own shortcuts (copy,
/// paste) are left to it; any other key xterm encodes differently from
/// xterm.dart (Alt as Meta, Ctrl symbols, modified special keys) is sent
/// here with its real character. The rest is the emulator's.
KeyEventResult _key(FocusNode node, KeyEvent event) {
final keyboard = HardwareKeyboard.instance;
if (chatShellCopyKey(event, keyboard) && _copySelection()) {
return KeyEventResult.handled;
}
if (_shortcuts.keys.any((key) => key.accepts(event, keyboard))) {
return KeyEventResult.ignored;
}
final session = widget.session;
final bytes = chatShellKeyEventBytes(
event,
keyboard,
session.terminal,
optionAsMeta: session.optionAsMeta(),
);
if (bytes == null) return KeyEventResult.ignored;
session.terminal.textInput(bytes);
if (_scroll.hasClients) _scroll.jumpTo(_scroll.position.maxScrollExtent);
return KeyEventResult.handled;
}
/// A finished run's output takes no keys of its own, so the copy keys are
/// answered here while it has the keyboard.
@@ -163,6 +187,7 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
child: TerminalView(
session.terminal,
controller: _controller,
scrollController: _scroll,
focusNode: _focus,
autofocus: widget.autofocus && live,
autoResize: widget.autoResize,
@@ -177,7 +202,7 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
hardwareKeyboardOnly: !chatShellTouchFirst(),
// No autocorrect or suggestions rewriting what is sent to a shell.
keyboardType: TextInputType.visiblePassword,
shortcuts: chatShellTerminalShortcuts(),
shortcuts: _shortcuts,
cursorType: TerminalCursorType.block,
onTapUp: _tapped,
onKeyEvent: _key,
@@ -208,9 +208,11 @@ class KeyboardShortcutRegistry {
web: web,
platform: platform,
).toggle.join(', '),
caveat: web
? 'Browser tab shortcuts such as Cmd+T are not available to the app.'
: null,
caveat: [
TerminalShortcutLabels(web: web, platform: platform).inTerminalNote,
if (web)
'Browser tab shortcuts such as Cmd+T are not available to the app.',
].join(' '),
),
if (!web)
const KeyboardShortcutEntry(
@@ -1,3 +1,4 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../terminal/terminal_layout.dart';
@@ -63,6 +64,20 @@ class SettingsTerminalSection extends StatelessWidget {
),
),
),
// Alt is always Meta elsewhere; only a Mac's Option types symbols.
if (defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS)
SwitchListTile(
key: const ValueKey('settings-terminal-option-as-meta'),
title: const Text('Use Option as Meta key'),
subtitle: const Text(
'Option+B, Option+F and Option+D move and delete by word in '
'the shell (ESC b, ESC f, ESC d). Off, Option types its '
'symbol (∫, ƒ, ∂).',
),
value: layout.optionAsMeta,
onChanged: layout.setOptionAsMeta,
),
],
);
},
@@ -75,6 +75,11 @@ class TerminalLayout extends ChangeNotifier {
Rect floatRect = terminalFloatDefaultRect;
bool maximized = false;
/// Whether a Mac's Option key is Meta in the terminal (Option+B sends
/// ESC b, readline's word back) rather than typing its symbol (∫). Other
/// platforms' Alt is always Meta.
bool optionAsMeta = true;
/// Whether the last change could not be saved.
bool saveFailed = false;
@@ -100,6 +105,7 @@ class TerminalLayout extends ChangeNotifier {
}
}
maximized = json['maximized'] == true;
optionAsMeta = json['option_as_meta'] != false;
} catch (_) {
return;
}
@@ -107,6 +113,7 @@ class TerminalLayout extends ChangeNotifier {
}
void setMode(TerminalMode value) => _change(() => mode = value);
void setOptionAsMeta(bool value) => _change(() => optionAsMeta = value);
void toggle() => _change(() => visible = !visible);
void show() => _change(() => visible = true);
void hide() => _change(() => visible = false);
@@ -128,6 +135,7 @@ class TerminalLayout extends ChangeNotifier {
floatRect.height,
],
'maximized': maximized,
'option_as_meta': optionAsMeta,
}),
);
if (revision != _revision || saved != saveFailed) return;
@@ -3,13 +3,18 @@ import 'package:flutter/services.dart';
/// Whether [event] shows or hides the terminal: Alt+T, Ctrl+T, Cmd+T
/// (Meta+T) or Ctrl+` (Shift allowed only with Ctrl+`). They are global key
/// handlers, so inside the terminal they toggle rather than reaching the
/// shell (whose Ctrl+T, transpose-chars, is then not available) and inside
/// text fields they toggle rather than type.
/// handlers, so inside text fields they toggle rather than type. While a
/// terminal has the keyboard ([inTerminal]) only Cmd+T and Ctrl+` toggle:
/// Ctrl+T (transpose-chars) and Alt+T (ESC t, transpose-words) reach the
/// shell.
///
/// A held chord's repeats match too (and are swallowed); only its first
/// press toggles.
bool terminalToggleShortcut(KeyEvent event, HardwareKeyboard keyboard) {
bool terminalToggleShortcut(
KeyEvent event,
HardwareKeyboard keyboard, {
bool inTerminal = false,
}) {
if (event is KeyUpEvent) return false;
final control = keyboard.isControlPressed;
final meta = keyboard.isMetaPressed;
@@ -24,6 +29,7 @@ bool terminalToggleShortcut(KeyEvent event, HardwareKeyboard keyboard) {
event.logicalKey == LogicalKeyboardKey.keyT ||
alt && event.physicalKey == PhysicalKeyboardKey.keyT;
if (!t || keyboard.isShiftPressed) return false;
if (inTerminal) return meta && !control && !alt;
return [control, meta, alt].where((pressed) => pressed).length == 1;
}
@@ -66,6 +72,15 @@ class TerminalShortcutLabels {
'Ctrl+`',
];
/// The keys that still hide the terminal while it has the keyboard: its
/// Ctrl+T and Alt+T are the shell's.
List<String> get toggleInTerminal => [if (!web && _apple) 'Cmd+T', 'Ctrl+`'];
/// How the in-terminal exception reads in the menu and the cheatsheet.
String get inTerminalNote =>
'Inside the terminal, ${_apple ? 'Option+T' : 'Alt+T'} and Ctrl+T '
'reach the shell; ${toggleInTerminal.join(' or ')} hides it.';
/// The keys that move between tabs, or none where the browser keeps them.
List<String> get tabs =>
web ? const [] : const ['Ctrl+Tab', 'Ctrl+Shift+Tab'];
@@ -76,6 +91,7 @@ class TerminalShortcutLabels {
/// Every shortcut, one per line, for the terminal's menu.
String get summary => [
'Show or hide: ${toggle.join(', ')}',
inTerminalNote,
if (tabs.isNotEmpty) 'Next or previous tab: ${tabs.join(' / ')}',
'Copy selected text: $copy',
].join('\n');
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../core/api_gateway.dart';
import '../../ui/input/keyboard_owner.dart';
import '../../ui/motion/motion.dart';
import 'terminal_focus.dart';
import 'terminal_hub.dart';
@@ -81,6 +82,9 @@ class _TerminalSurfaceState extends State<TerminalSurface>
bool _panelShown = false;
String? _selected;
/// The key of the toggle chord held down, if any.
PhysicalKeyboardKey? _toggleKey;
@override
void initState() {
super.initState();
@@ -150,8 +154,21 @@ class _TerminalSurfaceState extends State<TerminalSurface>
KeyEventResult _key(KeyEvent event) {
if (!mounted) return KeyEventResult.ignored;
final keyboard = HardwareKeyboard.instance;
if (terminalToggleShortcut(event, keyboard)) {
if (event is KeyDownEvent) toggle();
// A held toggle chord's repeats stay swallowed after the terminal it
// showed takes the keyboard (where Alt+T and Ctrl+T are the shell's).
if (event.physicalKey == _toggleKey) {
if (event is KeyUpEvent) _toggleKey = null;
if (event is KeyRepeatEvent) return KeyEventResult.handled;
}
if (terminalToggleShortcut(
event,
keyboard,
inTerminal: primaryFocusIsTypingSurface(),
)) {
if (event is KeyDownEvent) {
_toggleKey = event.physicalKey;
toggle();
}
return KeyEventResult.handled;
}
final step = terminalTabShortcut(event, keyboard);
+35 -4
View File
@@ -28,7 +28,30 @@ emulator. Auth flows that print a link, wait for a pasted token and continue
Android/iOS the toolbar also has a text field ("Type input, then Enter")
for the soft keyboard, with a Hide typing toggle; it is emptied when sent.
- The terminal is resized to its layout (debounced 150 ms); the process gets
SIGWINCH. New runs start at the last laid-out size.
SIGWINCH. New runs start at the last laid-out size. A live terminal does
not reflow (xterm.dart's reflow left the cursor on another line's row, so
prompts landed on old output and rows merged): narrowing cuts rows at the
new width (the cut cells are erased, so widening never brings stale text
back), fewer rows drop blank rows below the cursor and then scroll the top
into scrollback with the cursor's row at the bottom, more rows bring
scrollback back above it. Finished output still reflows to its card.
- **Keys** (`chat_shell_terminal_{input,key_input,keymap}.dart`): the view
encodes hardware keys before xterm.dart does, with the event's real
character, and a `TerminalInputHandler` chained before the package's
defaults encodes `keyInput` calls (key toolbar, soft keyboard) the same
way. Alt is Meta (ESC + the character, Shift and layout included; Macs:
the Option as Meta setting, the key's own character instead of Option's
symbol). Ctrl maps letters and `@ 2 Space`→NUL, `[ 3`→ESC, `\ 4`→0x1c,
`] 5`→0x1d, `^ 6`→0x1e, `_ / - 7`→0x1f, `? 8`→DEL. Arrows, Home/End,
Insert/Delete, PgUp/PgDn and F1–F12 carry xterm's modifier parameter
(1 + Shift 1 + Alt 2 + Ctrl 4: Shift+Up `CSI 1;2A`, Alt+Left `CSI 1;3D`,
Ctrl+Shift+Right `CSI 1;6C`, Ctrl+PgDn `CSI 6;5~`, Shift+F1 `CSI 1;2P`);
unmodified arrows and Home/End are SS3 under DECCKM. With DECKPAM the
keypad's Enter and operators send SS3 (`ESC O M`, `k`, `m`, `j`, `o`);
keypad digits keep typing (NumLock on). Alt+Backspace is `ESC DEL`,
Ctrl+Backspace `^H`, Shift+Tab `CSI Z`, Alt+Enter `ESC CR`. Ctrl+Alt
typing a composed symbol outside Apple platforms (AltGr) types it.
Cmd (Meta key) chords and plain typing are left to the emulator.
- Printed `http(s)` links open in the browser on tap (wrapped links are
joined). Other schemes are ignored.
- Finished runs are drawn read-only, shrunk to the rows their output takes
@@ -92,8 +115,16 @@ emulator. Auth flows that print a link, wait for a pasted token and continue
position) for a live run, so two open clients send two answers.
xterm.dart 4.0.0 answers DSR 6 zero-based; the app overrides it to the
correct one-based answer.
- xterm.dart 4.0.0 keeps blank rows when it rewraps; the app drops blank rows
below the cursor after a resize so the top of the output stays in view.
- xterm.dart 4.0.0 keeps blank rows when it rewraps; for finished output
(the only output that reflows) the app drops blank rows below the cursor
after a resize so the top of the output stays in view.
- A live terminal's long lines are cut, not rewrapped, when it narrows, and
stay cut when it widens again (as xterm without reflow).
- Key encoding gaps: no modifyOtherKeys / CSI u (Ctrl+Shift+letter sends the
plain control code, Ctrl+1/9/0 type the digit); Alt as Meta on Linux
assumes AltGr arrives as Ctrl+Alt or its own key; a Mac's Option as Meta
takes the character from the logical key, else the US position of the
physical key, so a non-US Mac layout's Option+key may send the US letter.
- Desktop typing uses key events (no IME composition for CJK input). Touch
platforms use the field.
- A descendant that keeps the PTY open after the command exits is read for
@@ -110,7 +141,7 @@ emulator. Auth flows that print a link, wait for a pasted token and continue
`chat_shell_plain.go`, `chat_shell_runner.go`, `chat_shell_supervise.go`,
`chat_shell_run_handlers.go`, `chat_shell_share.go`, `chat.go`,
`websocket.go`; `internal/pipeline/chat_shell_runs.go`; `go.mod`, `go.sum`.
- App: `lib/features/chat/shell/chat_shell_terminal_{session,view,keys,theme,links,page}.dart`,
- App: `lib/features/chat/shell/chat_shell_terminal_{session,view,keys,theme,links,page,input,key_input,keymap}.dart`,
`chat_shell_terminals.dart`, `chat_shell_output_view.dart`,
`chat_shell_run{,_card}.dart`, `chat_shell_card_actions.dart`,
`chat_shell_runs_{controller,repository}.dart`, `chat_shell_metrics.dart`;
+42 -6
View File
@@ -25,14 +25,20 @@ tmux inside it for work that must survive that).
own login and asks for the password again.
- **Shortcuts** (`terminal_shortcuts.dart`, handled by the surface as a
`FocusManager` early key handler, so they work wherever focus is, including
inside the terminal and in the chat composer, and neither receives the key):
in the chat composer, which does not receive the key):
- **Alt+T** (Option+T), **Ctrl+T**, **Cmd+T** (Meta+T) and **Ctrl+`**
show or hide the terminal in the selected mode; on a narrow window they
open and close the full-screen page. Only the one modifier counts
(Ctrl+Shift+T, Ctrl+Alt+T pass through); Option+T, which types † on a
Mac, is also matched by key position. Cmd+` stays the macOS window
switcher. **The shell's own Ctrl+T (transpose-chars) no longer reaches
it** while this binding is on.
switcher.
- **Inside a focused terminal** (any `TypingSurface`, i.e. a terminal
view) only **Cmd+T** and **Ctrl+`** toggle: **Ctrl+T** reaches the shell
as `^T` (transpose-chars) and **Alt+T** as `ESC t` (transpose-words).
A held chord that opened the terminal from outside keeps its repeats
swallowed after the terminal takes the keyboard, so nothing is typed.
The ⋮ menu and the shortcut cheatsheet say so
(`TerminalShortcutLabels.inTerminalNote`).
- **Ctrl+Tab / Ctrl+Shift+Tab**, while the terminal is shown (panel,
window or narrow page), select the next / previous terminal tab, wrapping,
and focus it. This deliberately overrides the chat's Ctrl+Tab pane
@@ -89,9 +95,16 @@ tmux inside it for work that must survive that).
from its retained output. A dropped connection resumes after the last
byte held. A restarted server lists the terminals as ended, with why.
- **Keyboard:** a focused terminal gets every key (Ctrl-C, Esc, Tab, arrows,
Ctrl-letters) except the shortcuts above (Ctrl+T, Alt+T, Cmd+T, Ctrl+`,
and Ctrl+Tab while shown); paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking
elsewhere moves focus away normally.
Ctrl-letters, Ctrl+T, Alt+T) except Cmd+T, Ctrl+` and Ctrl+Tab while
shown; paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking elsewhere
moves focus away normally. Keys are encoded as xterm does; see
`chat-interactive-terminal.md` (Keys). **Option as Meta** (Settings →
Appearance → Terminal, Macs only, saved with the layout, default on): a
Mac's Option sends `ESC` + the key's character (Option+B = `ESC b`)
instead of typing its symbol (∫). On by default because the shell's
Meta bindings (word motion, transpose, yank-last-arg) are used far more
in a terminal than Option's symbols; turn it off to type them. Other
platforms' Alt is always Meta.
- No terminal request is sent until the terminal is first shown (or a
terminal is opened): each connection sends one request at a time, so the
first screen's read is never queued behind `terminal_list`.
@@ -391,3 +404,26 @@ The tmux results above (restart survival, client replacement, the
service outlived it and was killed by hand.
- Not verified: logging in for real (needs the operator's password), Linux
su, and the app against a live server in a browser (widget tests only).
### Terminal input and resize fixes, round 1 (2026-11-25)
- Resize: live terminals run with `reflowEnabled: false`; the old
blank-row-trimming `resize` override now applies only to finished
(reflowing) output, and narrowing erases cells past the new width.
Tests: `test/features/chat/shell/chat_shell_terminal_resize_test.dart`
(long lines shrink/grow with the prompt on the cursor row, shell redraw
and command output after shrinking, no stale text after widening, cleared
screen and scrollback stay cleared, a view whose box shrinks and grows).
- Keys: xterm encoding for Alt/Meta, Ctrl symbols, modified special keys,
DECCKM and DECKPAM (`chat-interactive-terminal.md`, Keys); Option as Meta
setting. Tests: `chat_shell_terminal_input_test.dart` (key event to
bytes, Linux and macOS variants, setting on and off, toolbar `keyInput`),
`chat_shell_terminal_test.dart` (keys through the real view, Ctrl-V paste
intact), `terminal_surface_test.dart` (setting saved and restored, hidden
off Apple platforms).
- Shortcuts: inside a terminal Alt+T and Ctrl+T reach the shell; Cmd+T
and Ctrl+` still toggle (`terminal_shortcuts_test.dart`).
- Not verified: bytes against a real PTY in a browser or native build after
the change (widget tests only), real macOS Option events (native and
browser logical-key shapes are assumed as the tests model them), AltGr on
a real non-US Linux/Windows layout.
@@ -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));
});
}
@@ -85,7 +85,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 +96,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: ');
+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',