Merge branch 'worktree-agent-ad4dacaa0da379451'

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 02:44:31 +00:00
36 changed files with 1730 additions and 173 deletions
@@ -58,7 +58,7 @@ class ChatShellOutputView extends StatelessWidget {
padding: const EdgeInsets.only(top: 8),
child: ChatShellTerminalKeys(
session: session,
field: chatShellTouchFirst(),
touch: chatShellTouchFirst(),
),
),
],
@@ -3,16 +3,26 @@ import 'package:flutter/material.dart';
import '../ui/transcript/chat_link_browser_menu.dart';
/// What the terminal's right-click menu offers.
enum ChatShellTerminalMenuItem { copy, paste, selectAll, clear, find }
enum ChatShellTerminalMenuItem {
copy,
paste,
selectAll,
clear,
find,
browserKeys,
}
/// Shows the terminal's context menu at [position] (global): Copy (with a
/// selection), Paste (into a live terminal), Select all, Clear scrollback
/// and Find…. Resolves with the chosen item, or null when dismissed.
/// and Find…, and on a browser that can lock its keys, Capture (or
/// Release) browser keys ([browserKeys] is its label, null for none).
/// Resolves with the chosen item, or null when dismissed.
Future<ChatShellTerminalMenuItem?> showChatShellTerminalMenu(
BuildContext context, {
required Offset position,
required bool canCopy,
required bool canPaste,
String? browserKeys,
}) {
final overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
final local = overlay.globalToLocal(position);
@@ -55,6 +65,12 @@ Future<ChatShellTerminalMenuItem?> showChatShellTerminalMenu(
Icons.clear_all,
),
item(ChatShellTerminalMenuItem.find, 'Find…', Icons.search),
if (browserKeys != null)
item(
ChatShellTerminalMenuItem.browserKeys,
browserKeys,
Icons.keyboard,
),
],
);
}
@@ -0,0 +1,28 @@
import 'package:flutter/material.dart';
/// One compact key of the terminal's key toolbar: an outlined icon button
/// with [label] as its tooltip, or an outlined text button without [icon].
/// Its key is `chat-shell-key-[id]`.
Widget chatShellKeyButton(
String id,
String label,
IconData? icon,
VoidCallback onPressed,
) {
final key = Key('chat-shell-key-$id');
if (icon == null) {
return OutlinedButton(
key: key,
style: OutlinedButton.styleFrom(visualDensity: VisualDensity.compact),
onPressed: onPressed,
child: Text(label),
);
}
return IconButton.outlined(
key: key,
visualDensity: VisualDensity.compact,
tooltip: label,
onPressed: onPressed,
icon: Icon(icon),
);
}
@@ -0,0 +1,217 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xterm/core.dart';
import 'chat_shell_terminal_key_button.dart';
import 'chat_shell_terminal_line_field.dart';
import 'chat_shell_terminal_session.dart';
import 'chat_shell_terminal_sticky.dart';
/// A key of the touch row that a phone keyboard lacks, encoded as the
/// hardware key is.
typedef _RowKey = ({String id, String label, IconData? icon, TerminalKey key});
const List<_RowKey> _rowKeys = [
(id: 'esc', label: 'Esc', icon: null, key: TerminalKey.escape),
(id: 'tab', label: 'Tab', icon: Icons.keyboard_tab, key: TerminalKey.tab),
(
id: 'left',
label: 'Left',
icon: Icons.keyboard_arrow_left,
key: TerminalKey.arrowLeft,
),
(
id: 'up',
label: 'Up',
icon: Icons.keyboard_arrow_up,
key: TerminalKey.arrowUp,
),
(
id: 'down',
label: 'Down',
icon: Icons.keyboard_arrow_down,
key: TerminalKey.arrowDown,
),
(
id: 'right',
label: 'Right',
icon: Icons.keyboard_arrow_right,
key: TerminalKey.arrowRight,
),
(id: 'home', label: 'Home', icon: null, key: TerminalKey.home),
(id: 'end', label: 'End', icon: null, key: TerminalKey.end),
(id: 'pgup', label: 'PgUp', icon: null, key: TerminalKey.pageUp),
(id: 'pgdn', label: 'PgDn', icon: null, key: TerminalKey.pageDown),
];
/// Symbols that are a long press or a page away on a phone keyboard.
const List<String> _symbols = ['|', '~', '-', '/', r'\'];
/// The touch key row under a running terminal: sticky Ctrl and Alt (a tap
/// holds one for the next key or typed character, a double tap locks it),
/// Esc, Tab, the arrows, Home/End, PgUp/PgDn, awkward symbols, Enter,
/// Ctrl-C and Paste, scrolled sideways when the screen is narrow. Keys go
/// through the hardware key encoder (application cursor keys included).
/// Typing goes to the terminal itself, key by key; Line opens a text field
/// for typing a whole line first (it can hide a token or password).
class ChatShellTerminalKeyRow extends StatefulWidget {
const ChatShellTerminalKeyRow({super.key, required this.session});
final ChatShellTerminalSession session;
@override
State<ChatShellTerminalKeyRow> createState() =>
_ChatShellTerminalKeyRowState();
}
class _ChatShellTerminalKeyRowState extends State<ChatShellTerminalKeyRow> {
bool _line = false;
Terminal get _terminal => widget.session.terminal;
ChatShellStickyModifiers get _sticky => widget.session.modifiers;
void _key(TerminalKey key) {
final held = _sticky.take();
final bytes = chatShellStickyKeyBytes(
key,
ctrl: held.ctrl,
alt: held.alt,
state: _terminal,
);
if (bytes != null) _terminal.textInput(bytes);
}
void _symbol(String symbol) {
final held = _sticky.take();
_terminal.textInput(
chatShellStickyText(symbol, ctrl: held.ctrl, alt: held.alt),
);
}
Future<void> _paste() async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text;
if (text != null && text.isNotEmpty && widget.session.live) {
_terminal.paste(text);
}
}
@override
Widget build(BuildContext context) {
final row = ListenableBuilder(
listenable: _sticky,
builder: (context, _) => SingleChildScrollView(
key: const Key('chat-shell-key-row'),
scrollDirection: Axis.horizontal,
child: Row(
children: [
_modifier('ctrl', 'Ctrl', _sticky.ctrl, _sticky.tapCtrl),
_modifier('alt', 'Alt', _sticky.alt, _sticky.tapAlt),
for (final key in _rowKeys)
chatShellKeyButton(
key.id,
key.label,
key.icon,
() => _key(key.key),
),
for (final symbol in _symbols)
chatShellKeyButton(
'sym-${symbol.codeUnitAt(0)}',
symbol,
null,
() => _symbol(symbol),
),
chatShellKeyButton(
'enter',
'Enter',
Icons.keyboard_return,
() => _key(TerminalKey.enter),
),
chatShellKeyButton(
'ctrl-c',
'Ctrl-C',
null,
() => _terminal.textInput('\x03'),
),
chatShellKeyButton('paste', 'Paste', Icons.content_paste, _paste),
_lineToggle(),
].map(_spaced).toList(),
),
),
);
if (!_line) return row;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: ChatShellTerminalLineField(terminal: _terminal),
),
row,
],
);
}
Widget _spaced(Widget child) =>
Padding(padding: const EdgeInsetsDirectional.only(end: 4), child: child);
Widget _lineToggle() {
final label = _line ? 'Close line field' : 'Type a line';
return IconButton.outlined(
key: const Key('chat-shell-key-line'),
visualDensity: VisualDensity.compact,
tooltip: label,
isSelected: _line,
onPressed: () => setState(() => _line = !_line),
icon: const Icon(Icons.short_text),
);
}
/// A sticky modifier: outlined while off, tonal while held for the next
/// key, filled with a lock while locked.
Widget _modifier(
String id,
String label,
ChatShellStickyState state,
VoidCallback onPressed,
) {
final key = Key('chat-shell-key-$id');
final description = switch (state) {
ChatShellStickyState.off =>
'$label: tap for the next key, '
'double-tap to lock',
ChatShellStickyState.once => '$label held for the next key',
ChatShellStickyState.locked => '$label locked; tap to release',
};
const density = VisualDensity.compact;
final Widget button = switch (state) {
ChatShellStickyState.off => OutlinedButton(
key: key,
style: OutlinedButton.styleFrom(visualDensity: density),
onPressed: onPressed,
child: Text(label),
),
ChatShellStickyState.once => FilledButton.tonal(
key: key,
style: FilledButton.styleFrom(visualDensity: density),
onPressed: onPressed,
child: Text(label),
),
ChatShellStickyState.locked => FilledButton.icon(
key: key,
style: FilledButton.styleFrom(visualDensity: density),
onPressed: onPressed,
icon: const Icon(Icons.lock),
label: Text(label),
),
};
return Tooltip(
message: description,
child: Semantics(
toggled: state != ChatShellStickyState.off,
child: button,
),
);
}
}
@@ -2,9 +2,12 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xterm/core.dart';
import 'chat_shell_terminal_key_button.dart';
import 'chat_shell_terminal_key_row.dart';
import 'chat_shell_terminal_session.dart';
/// One key of the terminal toolbar: its label, icon and what it sends.
/// One key of the desktop terminal toolbar: its label, icon and what it
/// sends.
typedef _Key = ({
String id,
String label,
@@ -63,117 +66,45 @@ final List<_Key> _keys = [
),
];
/// The keys a touch keyboard lacks, and Paste, for a running terminal; with
/// [field], also a text line whose text is typed into the process on Enter
/// (the soft keyboard's own way in). The field is emptied as soon as its
/// text is sent and can hide what is typed, for a token or password.
class ChatShellTerminalKeys extends StatefulWidget {
/// The keys a running terminal's toolbar offers. With [touch] it is the
/// touch key row ([ChatShellTerminalKeyRow]: sticky Ctrl and Alt and the
/// keys a phone keyboard lacks); otherwise Paste and a few keys for a mouse.
class ChatShellTerminalKeys extends StatelessWidget {
const ChatShellTerminalKeys({
super.key,
required this.session,
required this.field,
required this.touch,
});
final ChatShellTerminalSession session;
final bool field;
final bool touch;
@override
State<ChatShellTerminalKeys> createState() => _ChatShellTerminalKeysState();
}
class _ChatShellTerminalKeysState extends State<ChatShellTerminalKeys> {
final TextEditingController _text = TextEditingController();
bool _hidden = false;
@override
void dispose() {
_text.dispose();
super.dispose();
}
Terminal get _terminal => widget.session.terminal;
Terminal get _terminal => session.terminal;
Future<void> _paste() async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text;
if (text != null && text.isNotEmpty && widget.session.live) {
if (text != null && text.isNotEmpty && session.live) {
_terminal.paste(text);
}
}
/// Types the field's text and Enter, then forgets it.
void _submit() {
final text = _text.text;
_text.clear();
if (text.isNotEmpty) _terminal.textInput(text);
_terminal.keyInput(TerminalKey.enter);
}
@override
Widget build(BuildContext context) {
final keys = Wrap(
if (touch) return ChatShellTerminalKeyRow(session: session);
return Wrap(
spacing: 4,
runSpacing: 4,
children: [
_button('paste', 'Paste', Icons.content_paste, _paste),
chatShellKeyButton('paste', 'Paste', Icons.content_paste, _paste),
for (final key in _keys)
_button(key.id, key.label, key.material, () => key.send(_terminal)),
chatShellKeyButton(
key.id,
key.label,
key.material,
() => key.send(_terminal),
),
],
);
if (!widget.field) return keys;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Padding(padding: const EdgeInsets.only(bottom: 8), child: _field()),
keys,
],
);
}
Widget _field() {
final toggle = _hidden ? 'Show typing' : 'Hide typing';
return TextField(
key: const Key('chat-shell-terminal-field'),
controller: _text,
obscureText: _hidden,
autocorrect: false,
enableSuggestions: false,
textInputAction: TextInputAction.send,
onSubmitted: (_) => _submit(),
decoration: InputDecoration(
labelText: 'Type input, then Enter',
suffixIcon: IconButton(
key: const Key('chat-shell-terminal-hide'),
tooltip: toggle,
onPressed: () => setState(() => _hidden = !_hidden),
icon: Icon(_hidden ? Icons.visibility : Icons.visibility_off),
),
),
);
}
Widget _button(
String id,
String label,
IconData? material,
VoidCallback onPressed,
) {
final key = Key('chat-shell-key-$id');
if (material == null) {
return OutlinedButton(
key: key,
style: OutlinedButton.styleFrom(visualDensity: VisualDensity.compact),
onPressed: onPressed,
child: Text(label),
);
}
return IconButton.outlined(
key: key,
visualDensity: VisualDensity.compact,
tooltip: label,
onPressed: onPressed,
icon: Icon(material),
);
}
}
@@ -0,0 +1,59 @@
import 'package:flutter/material.dart';
import 'package:xterm/core.dart';
/// A text line whose text is typed into the process with Enter, for typing
/// a whole line (or a token) before sending it. The field is emptied as
/// soon as its text is sent and can hide what is typed.
class ChatShellTerminalLineField extends StatefulWidget {
const ChatShellTerminalLineField({super.key, required this.terminal});
final Terminal terminal;
@override
State<ChatShellTerminalLineField> createState() =>
_ChatShellTerminalLineFieldState();
}
class _ChatShellTerminalLineFieldState
extends State<ChatShellTerminalLineField> {
final TextEditingController _text = TextEditingController();
bool _hidden = false;
@override
void dispose() {
_text.dispose();
super.dispose();
}
/// Types the field's text and Enter, then forgets it.
void _submit() {
final text = _text.text;
_text.clear();
if (text.isNotEmpty) widget.terminal.textInput(text);
widget.terminal.keyInput(TerminalKey.enter);
}
@override
Widget build(BuildContext context) {
final toggle = _hidden ? 'Show typing' : 'Hide typing';
return TextField(
key: const Key('chat-shell-terminal-field'),
controller: _text,
autofocus: true,
obscureText: _hidden,
autocorrect: false,
enableSuggestions: false,
textInputAction: TextInputAction.send,
onSubmitted: (_) => _submit(),
decoration: InputDecoration(
labelText: 'Type input, then Enter',
suffixIcon: IconButton(
key: const Key('chat-shell-terminal-hide'),
tooltip: toggle,
onPressed: () => setState(() => _hidden = !_hidden),
icon: Icon(_hidden ? Icons.visibility : Icons.visibility_off),
),
),
);
}
}
@@ -61,7 +61,7 @@ class ChatShellTerminalPage extends StatelessWidget {
padding: const EdgeInsets.only(top: 8),
child: ChatShellTerminalKeys(
session: session,
field: chatShellTouchFirst(),
touch: chatShellTouchFirst(),
),
),
],
@@ -6,6 +6,7 @@ import 'chat_shell_terminal_emulator.dart';
import 'chat_shell_terminal_events.dart';
import 'chat_shell_terminal_feed.dart';
import 'chat_shell_terminal_key_input.dart';
import 'chat_shell_terminal_sticky.dart';
/// Lines a terminal keeps unless the setting says otherwise.
const int chatShellTerminalScrollback = terminalScrollbackDefault;
@@ -69,6 +70,11 @@ class ChatShellTerminalSession {
/// Whether a Mac's Option key is Meta (Settings → Appearance → Terminal).
final bool Function() optionAsMeta;
/// The touch key row's held Ctrl and Alt, shared by every view of this
/// terminal so a soft keyboard's next character takes them. It holds
/// no resources, so it outlives the session's views undisposed.
final ChatShellStickyModifiers modifiers = ChatShellStickyModifiers();
/// Receives what the operator types for the process; only called while
/// the run is live.
final void Function(String data) onInput;
@@ -0,0 +1,124 @@
import 'package:flutter/foundation.dart';
import 'package:xterm/core.dart';
import 'chat_shell_terminal_input.dart';
/// How a sticky modifier of the touch key row is held.
enum ChatShellStickyState {
off,
/// Applies to the next key or typed character, then turns off.
once,
/// Applies to every key until tapped again.
locked,
}
/// The touch key row's Ctrl and Alt, which a phone keyboard lacks: a tap
/// holds one for the next key (one-shot), a second tap soon after locks it,
/// a tap on a held one releases it. The key row's keys and what the soft
/// keyboard types both use them.
class ChatShellStickyModifiers extends ChangeNotifier {
ChatShellStickyModifiers({DateTime Function()? clock})
: _clock = clock ?? DateTime.now;
/// A second tap within this long of the first locks the modifier.
static const Duration doubleTap = Duration(milliseconds: 400);
final DateTime Function() _clock;
ChatShellStickyState _ctrl = ChatShellStickyState.off;
ChatShellStickyState _alt = ChatShellStickyState.off;
DateTime? _ctrlTapped;
DateTime? _altTapped;
ChatShellStickyState get ctrl => _ctrl;
ChatShellStickyState get alt => _alt;
/// Whether either modifier applies to the next key.
bool get active =>
_ctrl != ChatShellStickyState.off || _alt != ChatShellStickyState.off;
void tapCtrl() {
final now = _clock();
_ctrl = _next(_ctrl, _ctrlTapped, now);
_ctrlTapped = now;
notifyListeners();
}
void tapAlt() {
final now = _clock();
_alt = _next(_alt, _altTapped, now);
_altTapped = now;
notifyListeners();
}
ChatShellStickyState _next(
ChatShellStickyState state,
DateTime? tapped,
DateTime now,
) {
switch (state) {
case ChatShellStickyState.off:
return ChatShellStickyState.once;
case ChatShellStickyState.once:
final quick = tapped != null && now.difference(tapped) <= doubleTap;
return quick ? ChatShellStickyState.locked : ChatShellStickyState.off;
case ChatShellStickyState.locked:
return ChatShellStickyState.off;
}
}
/// The held modifiers for one key, releasing the one-shot ones.
({bool ctrl, bool alt}) take() {
final held = (
ctrl: _ctrl != ChatShellStickyState.off,
alt: _alt != ChatShellStickyState.off,
);
var changed = false;
if (_ctrl == ChatShellStickyState.once) {
_ctrl = ChatShellStickyState.off;
changed = true;
}
if (_alt == ChatShellStickyState.once) {
_alt = ChatShellStickyState.off;
changed = true;
}
if (changed) notifyListeners();
return held;
}
}
/// The bytes a non-printing [key] sends with the held modifiers, encoded as
/// a hardware key is (modifier parameter, DECCKM and keypad mode from
/// [state]). Alt is always Meta here: the key row has no Option symbols.
String? chatShellStickyKeyBytes(
TerminalKey key, {
required bool ctrl,
required bool alt,
required TerminalState state,
}) => chatShellSpecialKeyBytes(
key,
shift: false,
alt: alt,
meta: alt,
ctrl: ctrl,
state: state,
);
/// [text] as typed with the held modifiers: Ctrl maps its first character
/// to its control code (left as typed when it has none), Alt prefixes ESC;
/// the rest follows unmodified.
String chatShellStickyText(
String text, {
required bool ctrl,
required bool alt,
}) {
if (text.isEmpty || !ctrl && !alt) return text;
final first = String.fromCharCode(text.runes.first);
final rest = text.substring(first.length);
final bytes =
chatShellCharBytes(first, alt: alt, ctrl: ctrl) ??
chatShellCharBytes(first, alt: alt, ctrl: false) ??
first;
return '$bytes$rest';
}
@@ -0,0 +1,102 @@
import 'package:flutter/services.dart';
import 'package:xterm/core.dart';
import 'chat_shell_terminal_key_input.dart';
import 'chat_shell_terminal_keymap.dart';
import 'chat_shell_terminal_session.dart';
import 'chat_shell_terminal_sticky.dart';
/// What committed text from the text input sends: an IME's or dead key's
/// composed character, the emoji picker's, dictation's, a soft keyboard's.
/// A line break (a soft keyboard's Return types one) is Enter, as the
/// terminal's line feed mode sends it; the touch key row's held Ctrl or Alt
/// applies to the first character. Null for nothing to send (a cancelled
/// composition commits empty text).
String? chatShellTextInputBytes(
String text, {
required TerminalState state,
ChatShellStickyModifiers? sticky,
}) {
if (text.isEmpty) return null;
final enter = state.lineFeedMode ? '\r\n' : '\r';
final typed = text.replaceAll('\r\n', '\n').replaceAll('\n', enter);
if (sticky == null || !sticky.active) return typed;
final held = sticky.take();
if (text == '\n') {
return chatShellStickyKeyBytes(
TerminalKey.enter,
ctrl: held.ctrl,
alt: held.alt,
state: state,
);
}
return chatShellStickyText(typed, ctrl: held.ctrl, alt: held.alt);
}
bool _printable(String? text) {
if (text == null || text.isEmpty) return false;
final code = text.runes.first;
return code >= 0x20 && code != 0x7f;
}
/// The bytes a key event sends with the touch key row's held modifiers (a
/// soft keyboard's Backspace or Enter, a Bluetooth keyboard's keys), or null
/// when none is held, a real modifier is down, or the key types nothing.
/// The held one-shot modifiers are used up only when bytes are returned.
String? chatShellStickyKeyEventBytes(
KeyEvent event,
HardwareKeyboard keyboard,
ChatShellStickyModifiers sticky,
TerminalState state,
) {
if (!sticky.active || event is KeyUpEvent) return null;
if (keyboard.isControlPressed ||
keyboard.isAltPressed ||
keyboard.isMetaPressed) {
return null;
}
final special = chatShellSpecialKeys[event.logicalKey];
if (special != null) {
final held = (
ctrl: sticky.ctrl != ChatShellStickyState.off,
alt: sticky.alt != ChatShellStickyState.off,
);
final bytes = chatShellStickyKeyBytes(
special,
ctrl: held.ctrl,
alt: held.alt,
state: state,
);
// Space types a character when its modifiers give it no code.
if (bytes != null) {
sticky.take();
return bytes;
}
}
final character = event.character;
if (!_printable(character)) return null;
final held = sticky.take();
return chatShellStickyText(character!, ctrl: held.ctrl, alt: held.alt);
}
/// The bytes a hardware key event sends to [session]'s process: with the
/// touch key row's held modifiers, else as xterm encodes it
/// ([chatShellKeyEventBytes]); null to leave it to the emulator and the
/// text input.
String? chatShellSessionKeyBytes(
KeyEvent event,
HardwareKeyboard keyboard,
ChatShellTerminalSession session,
) =>
chatShellStickyKeyEventBytes(
event,
keyboard,
session.modifiers,
session.terminal,
) ??
chatShellKeyEventBytes(
event,
keyboard,
session.terminal,
optionAsMeta: session.optionAsMeta(),
);
@@ -7,10 +7,10 @@ import '../conversation/chat_composer_paste_focus.dart';
import '../ui/transcript/chat_link_launcher.dart';
import 'chat_shell_metrics.dart';
import 'chat_shell_terminal_bell.dart';
import 'chat_shell_terminal_key_input.dart';
import 'chat_shell_terminal_links.dart';
import 'chat_shell_terminal_session.dart';
import 'chat_shell_terminal_shortcuts.dart';
import 'chat_shell_terminal_text_input.dart';
import 'chat_shell_terminal_theme.dart';
import 'chat_shell_terminal_find_host.dart';
import 'chat_shell_terminal_view_features.dart';
@@ -35,7 +35,8 @@ int chatShellCardRows(
}
/// Whether the soft keyboard is the main way to type here, so the key
/// toolbar offers a text field: the terminal itself takes hardware keys only.
/// toolbar is the touch key row (sticky Ctrl and Alt, the keys a phone
/// keyboard lacks, an optional line field).
bool chatShellTouchFirst() =>
defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS;
@@ -140,19 +141,28 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView>
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(),
);
final bytes = chatShellSessionKeyBytes(event, keyboard, widget.session);
if (bytes == null) return KeyEventResult.ignored;
session.terminal.textInput(bytes);
if (scroll.hasClients) scroll.jumpTo(scroll.position.maxScrollExtent);
_send(bytes);
return KeyEventResult.handled;
}
/// Committed text from the text input (see [chatShellTextInputBytes]).
void _typed(String text) {
final session = widget.session;
final bytes = chatShellTextInputBytes(
text,
state: session.terminal,
sticky: session.modifiers,
);
if (bytes != null) _send(bytes);
}
void _send(String bytes) {
widget.session.terminal.textInput(bytes);
if (scroll.hasClients) scroll.jumpTo(scroll.position.maxScrollExtent);
}
void _tapped(TapUpDetails details, CellOffset offset) {
final link = chatShellTerminalLinkAt(widget.session.terminal, offset);
if (link != null) openChatLink(context, link.uri);
@@ -187,11 +197,16 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView>
textStyle: style,
padding: padding,
readOnly: !live,
// Desktop keys go straight to the process as key events (a focused
// text input stays closed in desktop browsers). On phones and
// tablets a tap opens the on-screen keyboard and typing goes to the
// terminal; the key toolbar's field stays as an alternative.
hardwareKeyboardOnly: !chatShellTouchFirst(),
// Typing goes through the text input everywhere, so IMEs, dead
// keys, the emoji picker and dictation work: [_key] encodes the
// special keys and chords first (a key it sends is never typed
// again), and the text input types the characters, composing text
// drawn at the cursor until committed. On phones and tablets a tap
// opens the on-screen keyboard. A finished run attaches none.
hardwareKeyboardOnly: !live,
onTextInput: _typed,
// A soft keyboard's Backspace on an empty field may send nothing.
deleteDetection: chatShellTouchFirst(),
// No autocorrect or suggestions rewriting what is sent to a shell.
keyboardType: TextInputType.visiblePassword,
shortcuts: _shortcuts,
@@ -3,6 +3,7 @@ import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
import '../../terminal/terminal_browser_keys.dart';
import 'chat_shell_terminal_actions.dart';
import 'chat_shell_terminal_context_menu.dart';
import 'chat_shell_terminal_cursor_blink.dart';
@@ -165,11 +166,13 @@ mixin ChatShellTerminalFeatures<T extends StatefulWidget>
/// The right-click menu at [position] (global).
Future<void> openMenu(Offset position) async {
final keys = TerminalBrowserKeys.instance;
final choice = await showChatShellTerminalMenu(
context,
position: position,
canCopy: controller.selection != null,
canPaste: session.live,
browserKeys: keys.supported ? terminalBrowserKeysLabel(keys) : null,
);
if (!mounted || choice == null) return;
switch (choice) {
@@ -184,6 +187,9 @@ mixin ChatShellTerminalFeatures<T extends StatefulWidget>
case ChatShellTerminalMenuItem.find:
openFind();
return;
case ChatShellTerminalMenuItem.browserKeys:
await toggleTerminalBrowserKeys(context, keys);
if (!mounted) return;
}
if (mounted && session.live) focus.requestFocus();
}
@@ -239,6 +239,17 @@ class KeyboardShortcutRegistry {
action: 'Select all terminal text',
keys: 'Cmd+A',
),
if (TerminalShortcutLabels(web: web, platform: platform).browserKeysNote
case final note?)
KeyboardShortcutEntry(
group: KeyboardShortcutGroup.terminal,
action: 'Send browser keys to the terminal',
keys: 'Terminal menu: Capture browser keys',
caveat:
'$note Firefox and Safari cannot capture them; readline '
'alternatives that reach the page: Ctrl+U deletes to the line '
'start, Alt+B and Alt+F move by word.',
),
const KeyboardShortcutEntry(
group: KeyboardShortcutGroup.terminal,
action: 'Resize the terminal panel',
+1 -1
View File
@@ -65,7 +65,7 @@ class TerminalBody extends StatelessWidget {
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
child: ChatShellTerminalKeys(
session: tab.session,
field: chatShellTouchFirst(),
touch: chatShellTouchFirst(),
),
),
if (!tab.info.running && tab.connected) _closeEnded(tab),
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
import 'terminal_browser_keys_stub.dart'
if (dart.library.js_interop) 'terminal_browser_keys_web.dart'
as impl;
/// What captures the browser's own keys: the Keyboard Lock API in full
/// screen on the web ([impl]); nothing elsewhere.
abstract class TerminalBrowserKeysBackend {
/// Whether this browser can lock its keys (Chrome and Edge can; Firefox,
/// Safari and native builds cannot).
bool get supported;
/// Enters full screen and locks the keys; false if the browser refused.
Future<bool> lock();
/// Unlocks the keys and leaves full screen.
Future<void> unlock();
/// Called when the browser ends the capture itself (Esc held, full screen
/// left another way).
set onReleased(void Function() callback);
}
/// "Capture browser keys": while on, the page is full screen with the
/// keyboard locked, so Ctrl+W, Ctrl+T, Ctrl+N, Ctrl+Tab and the like reach
/// the terminal instead of closing or opening browser tabs. Holding Esc
/// ends it, as the browser requires. A no-op where [supported] is false.
class TerminalBrowserKeys extends ChangeNotifier {
TerminalBrowserKeys({TerminalBrowserKeysBackend? backend})
: _backend = backend ?? impl.TerminalBrowserKeysPlatform() {
_backend.onReleased = _released;
}
/// The app's one capture (the page is full screen once at most).
static TerminalBrowserKeys instance = TerminalBrowserKeys();
final TerminalBrowserKeysBackend _backend;
bool _active = false;
bool get supported => _backend.supported;
bool get active => _active;
/// Starts the capture; false where unsupported or refused.
Future<bool> capture() async {
if (!supported) return false;
if (_active) return true;
final locked = await _backend.lock();
if (locked != _active) {
_active = locked;
notifyListeners();
}
return locked;
}
/// Ends the capture.
Future<void> release() async {
if (!_active) return;
_active = false;
notifyListeners();
await _backend.unlock();
}
void _released() {
if (!_active) return;
_active = false;
notifyListeners();
}
}
/// The menu label for [keys]' toggle.
String terminalBrowserKeysLabel(TerminalBrowserKeys keys) =>
keys.active ? 'Release browser keys' : 'Capture browser keys';
/// Turns the capture on or off from a menu, saying what happened.
Future<void> toggleTerminalBrowserKeys(
BuildContext context, [
TerminalBrowserKeys? keys,
]) async {
final capture = keys ?? TerminalBrowserKeys.instance;
final messenger = ScaffoldMessenger.maybeOf(context);
if (capture.active) {
await capture.release();
return;
}
final captured = await capture.capture();
messenger
?..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(
captured
? 'Browser keys such as Ctrl+W go to the terminal. '
'Hold Esc to leave full screen.'
: 'This browser did not let the page capture its keys.',
),
),
);
}
@@ -0,0 +1,16 @@
import 'terminal_browser_keys.dart';
/// Native builds get every key already; there is nothing to capture.
class TerminalBrowserKeysPlatform implements TerminalBrowserKeysBackend {
@override
bool get supported => false;
@override
Future<bool> lock() async => false;
@override
Future<void> unlock() async {}
@override
set onReleased(void Function() callback) {}
}
@@ -0,0 +1,73 @@
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:web/web.dart' as web;
import 'terminal_browser_keys.dart';
/// The Keyboard Lock API (`navigator.keyboard.lock()`), which Chrome and
/// Edge honour only in full screen: the page enters full screen, then locks
/// every key. The browser keeps holding Esc as the way out; leaving full
/// screen ends the lock.
class TerminalBrowserKeysPlatform implements TerminalBrowserKeysBackend {
TerminalBrowserKeysPlatform() {
web.document.addEventListener(
'fullscreenchange',
((web.Event _) {
if (web.document.fullscreenElement == null) _onReleased?.call();
}).toJS,
);
}
void Function()? _onReleased;
JSObject? get _keyboard {
final keyboard = (web.window.navigator as JSObject)['keyboard'];
return keyboard.isUndefinedOrNull ? null : keyboard as JSObject;
}
@override
bool get supported {
final keyboard = _keyboard;
return keyboard != null &&
keyboard.has('lock') &&
web.document.fullscreenEnabled;
}
@override
Future<bool> lock() async {
final keyboard = _keyboard;
final root = web.document.documentElement;
if (keyboard == null || root == null) return false;
try {
if (web.document.fullscreenElement == null) {
await root.requestFullscreen().toDart;
}
await keyboard.callMethod<JSPromise<JSAny?>>('lock'.toJS).toDart;
return true;
} catch (_) {
// Refused (no user gesture, a policy, an iframe): back out of full
// screen so the page is as it was.
await _exitFullscreen();
return false;
}
}
@override
Future<void> unlock() async {
_keyboard?.callMethod<JSAny?>('unlock'.toJS);
await _exitFullscreen();
}
Future<void> _exitFullscreen() async {
if (web.document.fullscreenElement == null) return;
try {
await web.document.exitFullscreen().toDart;
} catch (_) {
// Already leaving full screen.
}
}
@override
set onReleased(void Function() callback) => _onReleased = callback;
}
@@ -94,8 +94,19 @@ class TerminalShortcutLabels {
inTerminalNote,
if (tabs.isNotEmpty) 'Next or previous tab: ${tabs.join(' / ')}',
'Copy selected text: $copy',
?browserKeysNote,
].join('\n');
/// A browser outside macOS keeps Ctrl+W, Ctrl+T and Ctrl+N (close and
/// open tabs and windows) from the page: how to send them anyway, or
/// what to press instead. Null where the terminal receives them (native
/// builds; Safari and Chrome on a Mac use Cmd for those).
String? get browserKeysNote => web && !_apple
? 'The browser keeps Ctrl+W, Ctrl+T and Ctrl+N: choose Capture '
'browser keys (Chrome, Edge; hold Esc to leave), or press '
'Alt+Backspace instead of Ctrl+W to delete a word.'
: null;
/// The keys that copy the terminal's selected text. A browser keeps
/// Ctrl+Shift+C for its developer tools.
String get copy => _apple
@@ -2,6 +2,7 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'terminal_browser_keys.dart';
import 'terminal_hub.dart';
import 'terminal_layout.dart';
import 'terminal_menu.dart';
@@ -29,6 +30,9 @@ class TerminalTabStrip extends StatelessWidget {
/// False on the narrow page, which has no panel or window to choose.
final bool showModes;
/// The browser keys capture the menu offers (tests replace the instance).
TerminalBrowserKeys get browserKeys => TerminalBrowserKeys.instance;
@override
Widget build(BuildContext context) {
final selected = hub.selected;
@@ -54,33 +58,53 @@ class TerminalTabStrip extends StatelessWidget {
),
_newTerminal(),
if (showModes)
TerminalMenuButton<_Option>(
label: 'Terminal options',
info: TerminalShortcutLabels.current().summary,
icon: Icons.more_vert,
choices: [
for (final mode in TerminalMode.values)
TerminalChoice(
_Option(mode),
mode.label,
checked: layout.mode == mode,
key: ValueKey('terminal-mode-${mode.name}'),
),
const TerminalChoice(
_Option(null),
'Hide terminal',
key: ValueKey('terminal-hide'),
),
],
onSelected: (option) => option.mode == null
? layout.hide()
: layout.setMode(option.mode!),
ListenableBuilder(
listenable: browserKeys,
builder: (context, _) => _options(context),
),
...trailing,
],
);
}
/// The options menu: the modes, the browser keys capture (on a browser
/// that can) and Hide terminal, with the shortcuts under them.
Widget _options(BuildContext context) => TerminalMenuButton<_Option>(
label: 'Terminal options',
info: TerminalShortcutLabels.current().summary,
icon: Icons.more_vert,
choices: [
for (final mode in TerminalMode.values)
TerminalChoice(
_Option(mode),
mode.label,
checked: layout.mode == mode,
key: ValueKey('terminal-mode-${mode.name}'),
),
if (browserKeys.supported)
TerminalChoice(
const _Option(null, browserKeys: true),
'Capture browser keys',
checked: browserKeys.active,
key: const ValueKey('terminal-browser-keys'),
),
const TerminalChoice(
_Option(null),
'Hide terminal',
key: ValueKey('terminal-hide'),
),
],
onSelected: (option) {
if (option.browserKeys) {
unawaited(toggleTerminalBrowserKeys(context, browserKeys));
} else if (option.mode == null) {
layout.hide();
} else {
layout.setMode(option.mode!);
}
},
);
String _label(TerminalTab tab) =>
hub.multiMachine ? '${tab.title} · ${tab.machineName}' : tab.title;
@@ -125,8 +149,10 @@ class TerminalTabStrip extends StatelessWidget {
}
}
/// A mode to switch to, or (null) hiding the terminal.
/// A mode to switch to, (null) hiding the terminal, or the browser keys
/// capture.
class _Option {
const _Option(this.mode);
const _Option(this.mode, {this.browserKeys = false});
final TerminalMode? mode;
final bool browserKeys;
}