From c5af000453475e722856c9249bd6f7336f587e91 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 26 Nov 2026 02:43:57 +0000 Subject: [PATCH] Terminal: text input for IMEs, Capture browser keys, touch key row - Desktop and web terminals use the text-input path too, so IMEs, dead keys, the emoji picker and dictation work; the key handler still encodes special keys and chords first (handled keys are never typed again), composing text is drawn at the cursor and sent on commit, the platform editable sits at the cursor, and a closed input reopens on the next key. The editable terminal is a semantics text field so web typing also works with semantics on. - Web: "Capture browser keys" (terminal menu and right-click menu) goes full screen and calls navigator.keyboard.lock(); hold Esc to leave. No-op where unsupported; cheatsheet and menu note give alternatives. - Touch: scrollable key row with sticky Ctrl/Alt (tap once, double-tap lock), Esc, Tab, arrows, Home/End, PgUp/PgDn and symbols through the hardware encoder; soft keyboard types per key (delete detection, Return as Enter); the line field moves behind the row's Line button. - Capture kit: compose=, --semantics false, --user-agent. Co-Authored-By: Claude Opus 5.5 --- .../chat/shell/chat_shell_output_view.dart | 2 +- .../chat_shell_terminal_context_menu.dart | 20 +- .../shell/chat_shell_terminal_key_button.dart | 28 +++ .../shell/chat_shell_terminal_key_row.dart | 217 ++++++++++++++++++ .../chat/shell/chat_shell_terminal_keys.dart | 111 ++------- .../shell/chat_shell_terminal_line_field.dart | 59 +++++ .../chat/shell/chat_shell_terminal_page.dart | 2 +- .../shell/chat_shell_terminal_session.dart | 6 + .../shell/chat_shell_terminal_sticky.dart | 124 ++++++++++ .../shell/chat_shell_terminal_text_input.dart | 102 ++++++++ .../chat/shell/chat_shell_terminal_view.dart | 47 ++-- .../chat_shell_terminal_view_features.dart | 6 + .../settings/keyboard_shortcuts_registry.dart | 11 + app/lib/features/terminal/terminal_body.dart | 2 +- .../terminal/terminal_browser_keys.dart | 99 ++++++++ .../terminal/terminal_browser_keys_stub.dart | 16 ++ .../terminal/terminal_browser_keys_web.dart | 73 ++++++ .../features/terminal/terminal_shortcuts.dart | 11 + .../features/terminal/terminal_tab_strip.dart | 72 ++++-- app/notes/chat-interactive-terminal.md | 12 +- app/notes/terminal-panel.md | 114 ++++++++- .../shell/chat_shell_terminal_find_test.dart | 3 +- .../chat_shell_terminal_key_row_test.dart | 203 ++++++++++++++++ .../chat/shell/chat_shell_terminal_test.dart | 25 +- .../chat_shell_terminal_text_input_test.dart | 166 ++++++++++++++ .../features/chat/shell/terminal_typing.dart | 59 +++++ .../keyboard_shortcuts_cheatsheet_test.dart | 20 ++ .../terminal/terminal_browser_keys_test.dart | 154 +++++++++++++ .../terminal/terminal_shortcuts_test.dart | 25 +- .../terminal/terminal_surface_test.dart | 4 +- .../xterm/lib/src/terminal_view.dart | 13 ++ .../xterm/lib/src/ui/custom_text_edit.dart | 54 ++++- app/third_party/xterm/lib/src/ui/render.dart | 11 +- app/tool/capture/README.md | 12 +- app/tool/capture/capture.mjs | 5 +- app/tool/capture/page.mjs | 15 +- 36 files changed, 1730 insertions(+), 173 deletions(-) create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_key_button.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_key_row.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_line_field.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_sticky.dart create mode 100644 app/lib/features/chat/shell/chat_shell_terminal_text_input.dart create mode 100644 app/lib/features/terminal/terminal_browser_keys.dart create mode 100644 app/lib/features/terminal/terminal_browser_keys_stub.dart create mode 100644 app/lib/features/terminal/terminal_browser_keys_web.dart create mode 100644 app/test/features/chat/shell/chat_shell_terminal_key_row_test.dart create mode 100644 app/test/features/chat/shell/chat_shell_terminal_text_input_test.dart create mode 100644 app/test/features/chat/shell/terminal_typing.dart create mode 100644 app/test/features/terminal/terminal_browser_keys_test.dart diff --git a/app/lib/features/chat/shell/chat_shell_output_view.dart b/app/lib/features/chat/shell/chat_shell_output_view.dart index 5fbd597d..b35ae49d 100644 --- a/app/lib/features/chat/shell/chat_shell_output_view.dart +++ b/app/lib/features/chat/shell/chat_shell_output_view.dart @@ -52,7 +52,7 @@ class ChatShellOutputView extends StatelessWidget { padding: const EdgeInsets.only(top: 8), child: ChatShellTerminalKeys( session: session, - field: chatShellTouchFirst(), + touch: chatShellTouchFirst(), ), ), ], diff --git a/app/lib/features/chat/shell/chat_shell_terminal_context_menu.dart b/app/lib/features/chat/shell/chat_shell_terminal_context_menu.dart index 750474b7..2cfcc4af 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_context_menu.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_context_menu.dart @@ -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 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 showChatShellTerminalMenu( Icons.clear_all, ), item(ChatShellTerminalMenuItem.find, 'Find…', Icons.search), + if (browserKeys != null) + item( + ChatShellTerminalMenuItem.browserKeys, + browserKeys, + Icons.keyboard, + ), ], ); } diff --git a/app/lib/features/chat/shell/chat_shell_terminal_key_button.dart b/app/lib/features/chat/shell/chat_shell_terminal_key_button.dart new file mode 100644 index 00000000..f5a6f158 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_key_button.dart @@ -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), + ); +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_key_row.dart b/app/lib/features/chat/shell/chat_shell_terminal_key_row.dart new file mode 100644 index 00000000..83bc2a0b --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_key_row.dart @@ -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 _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 createState() => + _ChatShellTerminalKeyRowState(); +} + +class _ChatShellTerminalKeyRowState extends State { + 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 _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, + ), + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_keys.dart b/app/lib/features/chat/shell/chat_shell_terminal_keys.dart index fdd3e9fa..32a7c23d 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_keys.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_keys.dart @@ -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 createState() => _ChatShellTerminalKeysState(); -} - -class _ChatShellTerminalKeysState extends State { - 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 _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), - ); } } diff --git a/app/lib/features/chat/shell/chat_shell_terminal_line_field.dart b/app/lib/features/chat/shell/chat_shell_terminal_line_field.dart new file mode 100644 index 00000000..69b0c55f --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_line_field.dart @@ -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 createState() => + _ChatShellTerminalLineFieldState(); +} + +class _ChatShellTerminalLineFieldState + extends State { + 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), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_page.dart b/app/lib/features/chat/shell/chat_shell_terminal_page.dart index 1f1a9023..b2d3fd75 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_page.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_page.dart @@ -61,7 +61,7 @@ class ChatShellTerminalPage extends StatelessWidget { padding: const EdgeInsets.only(top: 8), child: ChatShellTerminalKeys( session: session, - field: chatShellTouchFirst(), + touch: chatShellTouchFirst(), ), ), ], diff --git a/app/lib/features/chat/shell/chat_shell_terminal_session.dart b/app/lib/features/chat/shell/chat_shell_terminal_session.dart index 06553eaf..3227a6ef 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_session.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_session.dart @@ -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; diff --git a/app/lib/features/chat/shell/chat_shell_terminal_sticky.dart b/app/lib/features/chat/shell/chat_shell_terminal_sticky.dart new file mode 100644 index 00000000..8ee86071 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_sticky.dart @@ -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'; +} diff --git a/app/lib/features/chat/shell/chat_shell_terminal_text_input.dart b/app/lib/features/chat/shell/chat_shell_terminal_text_input.dart new file mode 100644 index 00000000..253d0ba8 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_terminal_text_input.dart @@ -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(), + ); diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view.dart b/app/lib/features/chat/shell/chat_shell_terminal_view.dart index 0355ccf5..b84dc375 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view.dart @@ -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'; @@ -20,7 +20,8 @@ export 'chat_shell_terminal_shortcuts.dart' show chatShellTerminalShortcuts, chatShellCopyKey; /// 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; @@ -121,19 +122,28 @@ class _ChatShellTerminalViewState extends State 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); @@ -168,11 +178,16 @@ class _ChatShellTerminalViewState extends State 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, diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart b/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart index 0afb8404..a50679aa 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart @@ -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 /// The right-click menu at [position] (global). Future 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 case ChatShellTerminalMenuItem.find: openFind(); return; + case ChatShellTerminalMenuItem.browserKeys: + await toggleTerminalBrowserKeys(context, keys); + if (!mounted) return; } if (mounted && session.live) focus.requestFocus(); } diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 4cf60f8f..22fdcc3b 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -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', diff --git a/app/lib/features/terminal/terminal_body.dart b/app/lib/features/terminal/terminal_body.dart index 661e7af5..a193cc68 100644 --- a/app/lib/features/terminal/terminal_body.dart +++ b/app/lib/features/terminal/terminal_body.dart @@ -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), diff --git a/app/lib/features/terminal/terminal_browser_keys.dart b/app/lib/features/terminal/terminal_browser_keys.dart new file mode 100644 index 00000000..aa475cfb --- /dev/null +++ b/app/lib/features/terminal/terminal_browser_keys.dart @@ -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 lock(); + + /// Unlocks the keys and leaves full screen. + Future 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 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 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 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.', + ), + ), + ); +} diff --git a/app/lib/features/terminal/terminal_browser_keys_stub.dart b/app/lib/features/terminal/terminal_browser_keys_stub.dart new file mode 100644 index 00000000..32b114b4 --- /dev/null +++ b/app/lib/features/terminal/terminal_browser_keys_stub.dart @@ -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 lock() async => false; + + @override + Future unlock() async {} + + @override + set onReleased(void Function() callback) {} +} diff --git a/app/lib/features/terminal/terminal_browser_keys_web.dart b/app/lib/features/terminal/terminal_browser_keys_web.dart new file mode 100644 index 00000000..3fdfa421 --- /dev/null +++ b/app/lib/features/terminal/terminal_browser_keys_web.dart @@ -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 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>('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 unlock() async { + _keyboard?.callMethod('unlock'.toJS); + await _exitFullscreen(); + } + + Future _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; +} diff --git a/app/lib/features/terminal/terminal_shortcuts.dart b/app/lib/features/terminal/terminal_shortcuts.dart index 677ee3bf..be478884 100644 --- a/app/lib/features/terminal/terminal_shortcuts.dart +++ b/app/lib/features/terminal/terminal_shortcuts.dart @@ -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 diff --git a/app/lib/features/terminal/terminal_tab_strip.dart b/app/lib/features/terminal/terminal_tab_strip.dart index cd663d1a..00d91739 100644 --- a/app/lib/features/terminal/terminal_tab_strip.dart +++ b/app/lib/features/terminal/terminal_tab_strip.dart @@ -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'; @@ -28,6 +29,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; @@ -53,33 +57,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; @@ -147,8 +171,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; } diff --git a/app/notes/chat-interactive-terminal.md b/app/notes/chat-interactive-terminal.md index 53a31290..1c356268 100644 --- a/app/notes/chat-interactive-terminal.md +++ b/app/notes/chat-interactive-terminal.md @@ -25,8 +25,10 @@ emulator. Auth flows that print a link, wait for a pasted token and continue Cmd-V on Apple platforms, Ctrl-V or Ctrl-Shift-V elsewhere, plus the toolbar's Paste button. Ctrl-A and other Ctrl keys reach the process. A key toolbar under the terminal: Paste, Enter, Ctrl-C, Tab, Esc, arrows. On - 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. + Android/iOS it is the touch key row (sticky Ctrl/Alt, Esc, Tab, arrows, + Home/End, PgUp/PgDn, symbols) and typing goes to the terminal key by + key; its Line button opens a text field ("Type input, then Enter") with + a Hide typing toggle, 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. A live terminal does not reflow (xterm.dart's reflow left the cursor on another line's row, so @@ -125,8 +127,10 @@ emulator. Auth flows that print a link, wait for a pasted token and continue 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. +- Desktop typing uses the text input as well as key events (2026-11-26, + see `terminal-panel.md` "Text input"): IMEs, dead keys, the emoji picker + and dictation work; touch platforms type key by key into the terminal, + with a touch key row and the line field behind its Line button. - A descendant that keeps the PTY open after the command exits is read for 1 s; on macOS the PTY has no read deadline, so its reader goroutine ends only when that descendant closes it (the run itself is finished and the diff --git a/app/notes/terminal-panel.md b/app/notes/terminal-panel.md index a511f932..ba270fed 100644 --- a/app/notes/terminal-panel.md +++ b/app/notes/terminal-panel.md @@ -172,6 +172,112 @@ context menu, Ctrl+= zoom, OSC 8 link hover underline; a synthetic `contextmenu` event over the terminal is default-prevented, elsewhere not. The capture kit gained `rightclick=`. +## Text input (round 3, 2026-11-26) + +Shared by the permanent terminal and chat terminal cards; client-side only. + +- **IME, dead keys, emoji picker, dictation (desktop and web):** the view + now uses the emulator's text-input path on every platform + (`hardwareKeyboardOnly` only for a finished, read-only run), instead of + hardware key events alone, which dropped `insertText`. The key handler + still runs first: special keys and chords it encodes (arrows, Enter, + Backspace, Tab, Ctrl/Alt chords, the view's own keys) are *handled*, so + the browser's default (inserting text) is prevented and the OS IME never + sees them; a plain printing key is left to the text input, which types + it. So no key is sent twice. Committed text goes through + `TerminalView.onTextInput` (`chat_shell_terminal_text_input.dart`): a + line break is Enter (`\r`, or `\r\n` in line-feed mode), empty commits + (a cancelled composition) send nothing. Composing text (CJK, a dead + key's accent) is drawn underlined at the cursor, over the cursor, and + sent only when committed; while composing, the IME keeps Enter and + Backspace. The platform's editable is placed at the cursor + (`setEditableSizeAndTransform` with the cursor's offset), so IME + candidate windows open there. If the platform closes the text input (a + browser window losing focus), the next printing key is typed from the + key event and the input reopened. +- **Web with semantics on** (assistive technology, the capture kit): the + browser's text input is the terminal's semantics text field + (`CustomTextEdit` now exposes `Semantics(textField, focused)` as a leaf, + like `EditableText`; the scroll view's semantics are excluded so the + engine keeps that field focused). Typing, dictation and emoji work + there, but Flutter's web engine does not report IME composition for a + semantics text field, so a CJK IME's intermediate text is sent as typed + in that mode only. +- **Capture browser keys (web):** terminal ⋮ menu (panel/window) and the + terminal's right-click menu offer "Capture browser keys" + (`terminal_browser_keys{,_web,_stub}.dart`): the page goes full screen + and calls `navigator.keyboard.lock()`, so Ctrl+W, Ctrl+T, Ctrl+N, + Ctrl+Tab and the like reach the terminal. Holding Esc leaves full + screen (the browser's rule; a short Esc still reaches the terminal), + which ends the capture; the menu item is checked while it is on and + releases it. Only where the API exists (Chrome, Edge); Firefox, Safari + and native builds do not show the item. A refused lock says so in a + snack bar. Alternatives documented in the menu note and the shortcut + cheatsheet (web outside macOS): Alt+Backspace instead of Ctrl+W + (delete a word), Ctrl+U, Alt+B / Alt+F. +- **Touch key row** (narrow terminal page, chat terminal cards on a phone + or tablet; `chat_shell_terminal_key_row.dart`): horizontally scrollable + Ctrl and Alt (sticky: a tap holds one for the next key or typed + character, tonal; a second tap within 400 ms locks it, filled with a + lock icon; a tap on a held one releases it), Esc, Tab, arrows, + Home/End, PgUp/PgDn, `| ~ - / \`, Enter, Ctrl-C, Paste and Line. Keys + use the hardware encoder (`chatShellSpecialKeyBytes`: xterm modifier + parameter, DECCKM/SS3, keypad mode); a held Ctrl maps the next typed + character to its control code, Alt prefixes ESC; a held modifier also + applies to a soft keyboard's key events (Backspace, Enter). The + modifiers live on the session (`ChatShellStickyModifiers`), shared by + its views. +- **Soft keyboard per key:** tapping the terminal opens the soft keyboard + and each character, Backspace and Return reaches the process at once + (no line to submit): `deleteDetection` keeps two placeholder spaces in + the editing state on touch platforms, so a Backspace with nothing typed + is still seen; Return's line break is Enter. The old line field is now + behind the row's Line button (still with Hide typing) for typing a whole + line or a token first. + +Evidence: tests `test/features/chat/shell/chat_shell_terminal_text_input_test.dart` +(commits from IME/dead key/emoji/dictation on macOS, Linux, Windows; +composing drawn not sent, IME keeps Enter/Backspace while composing; +handled keys report handled and printing keys do not; reopen after the +platform closes the input; editable at the cursor; read-only attaches +none; Android per-key typing, Backspace via delete detection, Return as +Enter), `chat_shell_terminal_key_row_test.dart` (sticky state machine, +row bytes incl. DECCKM, one-shot/locked Ctrl and Alt on keys, typed +text and soft-keyboard key events, Line field), +`test/features/terminal/terminal_browser_keys_test.dart` (capture, +release, browser-ended, refused, unsupported, ⋮ and right-click menus), +`terminal_shortcuts_test.dart`, `keyboard_shortcuts_cheatsheet_test.dart`. +Existing desktop typing tests now type printing keys as a platform does +(`test/features/chat/shell/terminal_typing.dart`: key event first, its +character through the text input only if unhandled). + +Chromium (headless, CanvasKit, capture kit, probe `?terminals=1 +&terminal=panel`, 1200x800), `/tmp/r3-capture/`: +- `ime-nosem/` (`--semantics false`): key presses `echo`, CDP + `Input.imeSetComposition` "にほ" drawn underlined at the cursor and not + sent, commit "日本" via `Input.insertText`, dead key "´" composing then + "é", emoji and `:q!` via `insertText`, Enter one new prompt; the hidden + input sits at the cursor (x 143→183 as text is typed, y of the cursor + row). Result line `echo 日本 é 👍 :q!`. +- `sem/` (semantics on): the focused element is the terminal's text field + `INPUT` ("Terminal, type to send input"); key presses and `insertText` + type `echo é 👍 日本 xyz`; Ctrl+W and Alt+B add no text (sent as + control bytes). `ime/` shows the semantics-mode composition gap. +- `lock/`: Chromium has `navigator.keyboard.lock`; ⋮ → Capture browser + keys enters full screen (`document.fullscreenElement` set) with the + snack bar; the item is then checked; choosing it again leaves full + screen; the right-click menu lists it. +- `touch/` (`--touch true`, Android user agent, 560x1000, Alt+T opens the + narrow page): key row under the terminal, per-key `insertText` typing, + Ctrl tonal while held and released after one character, Alt locked + with the lock icon after a double tap, the row scrolled sideways to + Home/End/PgUp/PgDn. +Not verified: a real OS IME (macOS/Windows/Linux), real dictation, Safari +and Firefox, a real Ctrl+W in a non-headless browser while captured, and +any phone or tablet (no device test ran). +The capture kit gained `compose=`, `--semantics false` and +`--user-agent`. + ## Protocol (server) `internal/protocol/terminal.go`; documented in `docs/cli.md` ("Machine @@ -472,8 +578,12 @@ software) costs about 2 ms more raster. Runs on this machine vary by about shell input already does). - Opening a terminal elsewhere (another device) adds its tab here too: the tabs are the machine's terminals. -- Mobile (narrow page, soft-keyboard field) is verified by widget tests and - a narrow Chrome capture only; no device test ran. Android/Linux builds +- Mobile (narrow page, touch key row, per-key soft keyboard typing) is + verified by widget tests and narrow Chromium captures with an Android + user agent only; no device test ran. +- On the web with semantics on, IME composition is not reported to the + app (Flutter web engine limitation for semantics text fields), so a CJK + IME's intermediate text is sent; without semantics it is a preedit. Android/Linux builds were not run. - `test/application` and `test/features/settings` have 51 failures that are identical on the base commit 8f06f12d (pending `LaunchUpdateChecker` diff --git a/app/test/features/chat/shell/chat_shell_terminal_find_test.dart b/app/test/features/chat/shell/chat_shell_terminal_find_test.dart index d3282745..846eda31 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_find_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_find_test.dart @@ -5,6 +5,7 @@ import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_search.dar import 'package:xterm/xterm.dart'; import 'terminal_view_harness.dart'; +import 'terminal_typing.dart'; const _field = ValueKey('terminal-find-field'); @@ -108,7 +109,7 @@ void main() { expect(find.byKey(_field), findsNothing); expect(harness.controller(tester).highlights, isEmpty); expect(harness.view(tester).focusNode!.hasFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.keyX); + await typeKey(tester, LogicalKeyboardKey.keyX); await tester.pump(); expect(harness.typed, 'x'); }, variant: desktops); diff --git a/app/test/features/chat/shell/chat_shell_terminal_key_row_test.dart b/app/test/features/chat/shell/chat_shell_terminal_key_row_test.dart new file mode 100644 index 00000000..c6647f5a --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_key_row_test.dart @@ -0,0 +1,203 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_keys.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_sticky.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_view.dart'; + +import 'terminal_typing.dart'; +import 'terminal_view_harness.dart'; + +final _touch = TargetPlatformVariant({ + TargetPlatform.android, + TargetPlatform.iOS, +}); + +/// A phone-sized live terminal with the touch key row under it. +Future _pumpRow(WidgetTester tester) async { + final harness = TerminalViewHarness(); + tester.view.physicalSize = const Size(400, 700); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + addTearDown(harness.session.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Column( + children: [ + Expanded( + child: ChatShellTerminalView( + session: harness.session, + fill: true, + autofocus: true, + ), + ), + ChatShellTerminalKeys(session: harness.session, touch: true), + ], + ), + ), + ), + ); + await tester.pump(); + return harness; +} + +Widget _key(WidgetTester tester, String id) => + tester.widget(find.byKey(Key('chat-shell-key-$id'))); + +void main() { + group('sticky modifiers', () { + var now = DateTime(2026); + ChatShellStickyModifiers sticky() => + ChatShellStickyModifiers(clock: () => now); + + test('a tap holds one for one key; a quick second tap locks it', () { + final mods = sticky(); + mods.tapCtrl(); + expect(mods.ctrl, ChatShellStickyState.once); + expect(mods.take(), (ctrl: true, alt: false)); + expect(mods.ctrl, ChatShellStickyState.off); + expect(mods.take(), (ctrl: false, alt: false)); + + mods.tapAlt(); + now = now.add(const Duration(milliseconds: 200)); + mods.tapAlt(); + expect(mods.alt, ChatShellStickyState.locked); + expect(mods.take(), (ctrl: false, alt: true)); + expect(mods.take(), (ctrl: false, alt: true)); + mods.tapAlt(); + expect(mods.alt, ChatShellStickyState.off); + }); + + test('a slow second tap releases a held one instead of locking it', () { + final mods = sticky(); + mods.tapCtrl(); + now = now.add(const Duration(seconds: 2)); + mods.tapCtrl(); + expect(mods.ctrl, ChatShellStickyState.off); + }); + + test('held text: Ctrl maps the first character, Alt prefixes ESC', () { + expect(chatShellStickyText('c', ctrl: true, alt: false), '\x03'); + expect(chatShellStickyText('b', ctrl: false, alt: true), '\x1bb'); + expect(chatShellStickyText('cd', ctrl: true, alt: true), '\x1b\x03d'); + expect(chatShellStickyText('é', ctrl: true, alt: false), 'é'); + }); + }); + + testWidgets('the row sends the keys a phone lacks, as hardware keys do', ( + tester, + ) async { + final harness = await _pumpRow(tester); + for (final id in [ + 'esc', + 'tab', + 'left', + 'up', + 'home', + 'end', + 'pgup', + 'pgdn', + 'sym-124', + 'sym-126', + 'sym-45', + 'sym-47', + 'sym-92', + 'enter', + ]) { + await tapKey(tester, id); + } + expect( + harness.typed, + '\x1b\t\x1b[D\x1b[A\x1b[H\x1b[F\x1b[5~\x1b[6~|~-/\\\r', + ); + // Application cursor keys (DECCKM) from the program's own mode. + harness.sent.clear(); + await harness.write(tester, '\x1b[?1h'); + await tapKey(tester, 'up'); + await tapKey(tester, 'home'); + expect(harness.typed, '\x1bOA\x1bOH'); + }, variant: _touch); + + testWidgets('a tapped Ctrl or Alt applies to the next key or typed ' + 'character once; a double tap locks it until tapped again', ( + tester, + ) async { + final harness = await _pumpRow(tester); + final sticky = harness.session.modifiers; + expect(_key(tester, 'ctrl'), isA()); + await tapKey(tester, 'ctrl'); + expect(sticky.ctrl, ChatShellStickyState.once); + expect(_key(tester, 'ctrl'), isA()); + // The soft keyboard's next character takes it. + await commitText(tester, 'c'); + expect(harness.typed, '\x03'); + expect(sticky.ctrl, ChatShellStickyState.off); + await commitText(tester, 'c'); + expect(harness.typed, '\x03c'); + + // A row key takes it too, with xterm's modifier parameter. + harness.sent.clear(); + await tapKey(tester, 'ctrl'); + await tapKey(tester, 'right'); + expect(harness.typed, '\x1b[1;5C'); + await tapKey(tester, 'ctrl'); + await tapKey(tester, 'sym-47'); + expect(harness.typed, '\x1b[1;5C\x1f'); + + // Double tap: locked for every key until released. + harness.sent.clear(); + await tester.ensureVisible(find.byKey(const Key('chat-shell-key-alt'))); + await tester.pump(); + await tester.tap(find.byKey(const Key('chat-shell-key-alt'))); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.byKey(const Key('chat-shell-key-alt'))); + await tester.pump(); + expect(sticky.alt, ChatShellStickyState.locked); + expect( + find.descendant( + of: find.byKey(const Key('chat-shell-key-alt')), + matching: find.byIcon(Icons.lock), + ), + findsOneWidget, + ); + await commitText(tester, 'b'); + await commitText(tester, 'f'); + await tapKey(tester, 'left'); + expect(harness.typed, '\x1bb\x1bf\x1b[1;3D'); + expect(sticky.alt, ChatShellStickyState.locked); + await tapKey(tester, 'alt'); + expect(sticky.alt, ChatShellStickyState.off); + await commitText(tester, 'b'); + expect(harness.typed, '\x1bb\x1bf\x1b[1;3Db'); + }, variant: _touch); + + testWidgets('a held modifier applies to a soft keyboard key event', ( + tester, + ) async { + final harness = await _pumpRow(tester); + await tapKey(tester, 'ctrl'); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + expect(harness.typed, '\b'); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + expect(harness.typed, '\b\x7f'); + }, variant: _touch); + + testWidgets( + 'Line opens a field for a whole line, sent with Enter', + (tester) async { + final harness = await _pumpRow(tester); + final field = find.byKey(const Key('chat-shell-terminal-field')); + expect(field, findsNothing); + await tapKey(tester, 'line'); + expect(field, findsOneWidget); + await tester.enterText(field, 'echo hi'); + await tester.testTextInput.receiveAction(TextInputAction.send); + await tester.pump(); + expect(harness.typed, 'echo hi\r'); + await tapKey(tester, 'line'); + expect(field, findsNothing); + }, + variant: TargetPlatformVariant.only(TargetPlatform.android), + ); +} diff --git a/app/test/features/chat/shell/chat_shell_terminal_test.dart b/app/test/features/chat/shell/chat_shell_terminal_test.dart index b6e6fd1c..6851df42 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_test.dart @@ -5,6 +5,7 @@ import 'package:pipelines_app/features/chat/shell/chat_shell_runs_controller.dar import 'package:xterm/xterm.dart'; import 'chat_shell_fixtures.dart'; +import 'terminal_typing.dart'; void main() { late ShellGateway gateway; @@ -43,8 +44,8 @@ void main() { expect(find.byKey(const Key('chat-shell-terminal-field')), findsNothing); await tester.tap(find.byType(TerminalView)); await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.keyG); - await tester.sendKeyEvent(LogicalKeyboardKey.digit7); + await typeKey(tester, LogicalKeyboardKey.keyG); + await typeKey(tester, LogicalKeyboardKey.digit7); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyEvent(LogicalKeyboardKey.keyC); @@ -156,7 +157,7 @@ void main() { 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); + await typeKey(tester, LogicalKeyboardKey.keyX); expect( typed(), '\x1bb\x1bf\x1b.\x1bB\x1b\x7f\x1f\x1d' @@ -289,10 +290,8 @@ void main() { ), ); await openRunning(tester); - await tester.tap(find.byKey(const Key('chat-shell-key-paste'))); - await tester.pump(); - await tester.tap(find.byKey(const Key('chat-shell-key-enter'))); - await tester.pump(); + await tapKey(tester, 'paste'); + await tapKey(tester, 'enter'); expect(typed(), 'gho_pasted-token\r'); }); @@ -301,13 +300,16 @@ void main() { ) async { await openRunning(tester, output: 'Password: '); for (final key in ['ctrl-c', 'tab', 'esc', 'left', 'down', 'right']) { - await tester.tap(find.byKey(Key('chat-shell-key-$key'))); - await tester.pump(); + await tapKey(tester, key); } expect(typed(), '\x03\t\x1b\x1b[D\x1b[B\x1b[C'); gateway.calls.clear(); + // Typing goes to the terminal key by key; Line opens a field for a + // whole line. final field = find.byKey(const Key('chat-shell-terminal-field')); + expect(field, findsNothing); + await tapKey(tester, 'line'); expect(field, findsOneWidget); await tester.tap(find.byKey(const Key('chat-shell-terminal-hide'))); await tester.pump(); @@ -331,8 +333,7 @@ void main() { expect(tester.testTextInput.isVisible, isTrue); expect(tester.testTextInput.hasAnyClients, isTrue); gateway.calls.clear(); - tester.testTextInput.enterText('tok'); - await tester.pump(); + await commitText(tester, 'tok'); await tester.testTextInput.receiveAction(TextInputAction.newline); await tester.pump(); expect(typed(), startsWith('tok')); @@ -390,7 +391,7 @@ void main() { expect(claim['activate'], isTrue); expect((claim['cols'], claim['rows']), (laidOut['cols'], laidOut['rows'])); // Typing carries this client's size. - await tester.sendKeyEvent(LogicalKeyboardKey.keyG); + await typeKey(tester, LogicalKeyboardKey.keyG); await tester.pump(); var inputs = gateway.bodies('chat_shell_input'); expect(inputs.single['data'], 'g'); diff --git a/app/test/features/chat/shell/chat_shell_terminal_text_input_test.dart b/app/test/features/chat/shell/chat_shell_terminal_text_input_test.dart new file mode 100644 index 00000000..6a4d10be --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_terminal_text_input_test.dart @@ -0,0 +1,166 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:xterm/xterm.dart'; + +import 'terminal_typing.dart'; +import 'terminal_view_harness.dart'; + +/// Desktops whose IMEs, dead keys, emoji pickers and dictation commit text +/// through the text input (the web runs on these too). +final _desktops = TargetPlatformVariant({ + TargetPlatform.macOS, + TargetPlatform.linux, + TargetPlatform.windows, +}); + +void main() { + testWidgets('a desktop terminal takes committed text from the text input: ' + 'IME, dead keys, emoji and dictation', (tester) async { + final harness = TerminalViewHarness(); + await harness.pump(tester); + expect(tester.testTextInput.hasAnyClients, isTrue); + // A dead key's composed character, a CJK commit, an emoji, a phrase. + await commitText(tester, 'é'); + await commitText(tester, '日本'); + await commitText(tester, '\u{1F44D}'); + await commitText(tester, ':q!'); + expect(harness.typed, 'é日本\u{1F44D}:q!'); + }, variant: _desktops); + + testWidgets('composing text is drawn at the cursor and sent only when ' + 'committed; the IME keeps its keys meanwhile', (tester) async { + final harness = TerminalViewHarness(); + await harness.pump(tester); + final render = harness.viewState(tester).renderTerminal; + await composeText(tester, 'にほ'); + expect(render.composingText, 'にほ'); + // Enter picks the IME's candidate, not the shell's line. + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + expect(harness.typed, isEmpty); + await commitText(tester, '日本'); + expect(render.composingText, isNull); + expect(harness.typed, '日本'); + // A dead key: ´ is shown, é is sent. + await composeText(tester, '´'); + expect(harness.typed, '日本'); + await commitText(tester, 'é'); + expect(harness.typed, '日本é'); + // A cancelled composition sends nothing. + await composeText(tester, 'x'); + await commitText(tester, ''); + expect(harness.typed, '日本é'); + }, variant: _desktops); + + testWidgets('a key the terminal encodes is taken, so the platform never ' + 'types it again; a printing key is left to the text input', ( + tester, + ) async { + final harness = TerminalViewHarness(); + await harness.pump(tester); + // Handled: the browser's default (inserting text) is prevented. + expect(await tester.sendKeyEvent(LogicalKeyboardKey.enter), isTrue); + expect(await tester.sendKeyEvent(LogicalKeyboardKey.backspace), isTrue); + expect(await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft), isTrue); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + expect(await tester.sendKeyEvent(LogicalKeyboardKey.keyC), isTrue); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + expect(harness.typed, '\r\x7f\x1b[D\x03'); + // Not handled: the platform types it through the text input, once. + expect(await tester.sendKeyEvent(LogicalKeyboardKey.keyA), isFalse); + expect(harness.typed, '\r\x7f\x1b[D\x03'); + await typeKey(tester, LogicalKeyboardKey.keyA); + expect(harness.typed, '\r\x7f\x1b[D\x03a'); + }, variant: _desktops); + + testWidgets('after the platform closes the text input (a browser window ' + 'losing focus), a printing key is typed and the input reopened', ( + tester, + ) async { + final harness = TerminalViewHarness(); + await harness.pump(tester); + tester.testTextInput.closeConnection(); + await tester.pump(); + tester.testTextInput.log.clear(); + expect(await tester.sendKeyEvent(LogicalKeyboardKey.keyQ), isTrue); + expect(harness.typed, 'q'); + expect( + tester.testTextInput.log.map((call) => call.method), + contains('TextInput.setClient'), + ); + await commitText(tester, 'w'); + expect(harness.typed, 'qw'); + }, variant: _desktops); + + testWidgets('the text input sits at the cursor, so an IME opens its ' + 'candidates there', (tester) async { + final harness = TerminalViewHarness(); + await harness.pump(tester); + await harness.write(tester, r'$ echo '); + tester.testTextInput.log.clear(); + await tester.pump(); + // The editable follows the cursor once painted. + harness.terminal.write('x'); + await tester.pump(); + final calls = tester.testTextInput.log.where( + (call) => call.method == 'TextInput.setEditableSizeAndTransform', + ); + expect(calls, isNotEmpty); + final transform = List.from( + (calls.last.arguments as Map)['transform'] as List, + ); + final cursor = harness.viewState(tester).globalCursorRect; + expect(transform[12], moreOrLessEquals(cursor.left)); + expect(transform[13], moreOrLessEquals(cursor.top)); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + + testWidgets('a live terminal is a focused text field to assistive ' + 'technology (the web text input under semantics)', (tester) async { + final semantics = tester.ensureSemantics(); + final harness = TerminalViewHarness(); + await harness.pump(tester); + expect( + tester.getSemantics(find.byType(TerminalView)), + isSemantics(isTextField: true, isFocused: true, isEnabled: true), + ); + semantics.dispose(); + }, variant: TargetPlatformVariant.only(TargetPlatform.linux)); + + testWidgets('a finished run attaches no text input', (tester) async { + final harness = TerminalViewHarness(live: false); + await harness.pump(tester); + await tester.tap(find.byType(TerminalView)); + await tester.pump(const Duration(seconds: 1)); + expect(tester.testTextInput.hasAnyClients, isFalse); + }, variant: _desktops); + + testWidgets('a soft keyboard types key by key: characters, Backspace and ' + 'Return reach the process without submitting a line', (tester) async { + final harness = TerminalViewHarness(); + await harness.pump(tester); + expect(defaultTargetPlatform, TargetPlatform.android); + await commitText(tester, 'l'); + expect(harness.typed, 'l'); + await commitText(tester, 's'); + expect(harness.typed, 'ls'); + // Backspace on the (otherwise empty) field deletes one of its two + // placeholder spaces, which is read as Backspace. + final before = '${tester.testTextInput.editingState!['text']}'; + expect(before, ' '); + tester.testTextInput.updateEditingValue( + const TextEditingValue( + text: ' ', + selection: TextSelection.collapsed(offset: 1), + ), + ); + await tester.pump(); + expect(harness.typed, 'ls\x7f'); + // Return types a line break, which is Enter. + await commitText(tester, '\n'); + expect(harness.typed, 'ls\x7f\r'); + // Close the keyboard connection before the tree goes away. + await tester.pumpWidget(const SizedBox.shrink()); + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); +} diff --git a/app/test/features/chat/shell/terminal_typing.dart b/app/test/features/chat/shell/terminal_typing.dart new file mode 100644 index 00000000..b70b8b1f --- /dev/null +++ b/app/test/features/chat/shell/terminal_typing.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// Commits [text] through the platform text input, as an IME, dead key, +/// the emoji picker, dictation or a soft keyboard does: appended to what +/// the focused client last told the platform, the caret at its end. +Future commitText(WidgetTester tester, String text) async { + final before = '${tester.testTextInput.editingState?['text'] ?? ''}'; + final value = '$before$text'; + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: value, + selection: TextSelection.collapsed(offset: value.length), + ), + ); + await tester.pump(); +} + +/// Sends [text] as composing (marked) text: drawn, not yet committed. +Future composeText(WidgetTester tester, String text) async { + final before = '${tester.testTextInput.editingState?['text'] ?? ''}'; + final value = '$before$text'; + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: value, + selection: TextSelection.collapsed(offset: value.length), + composing: TextRange(start: before.length, end: value.length), + ), + ); + await tester.pump(); +} + +/// Presses [key] as a desktop platform does: the key event first, and only +/// if no handler took it, its [character] (default: the key's label in +/// lower case) through the text input. A key the terminal encoded is never +/// typed a second time. +Future typeKey( + WidgetTester tester, + LogicalKeyboardKey key, { + String? character, +}) async { + final handled = await tester.sendKeyEvent(key, character: character); + if (!handled) { + final text = character ?? key.keyLabel.toLowerCase(); + if (text.isNotEmpty) await commitText(tester, text); + } + await tester.pump(); +} + +/// Taps the key toolbar's key [id] (`chat-shell-key-`), scrolling the +/// touch key row to it first. +Future tapKey(WidgetTester tester, String id) async { + final key = find.byKey(Key('chat-shell-key-$id')); + await tester.ensureVisible(key); + await tester.pump(); + await tester.tap(key); + await tester.pump(); +} diff --git a/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart b/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart index a207bd55..a7f95f8a 100644 --- a/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart +++ b/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart @@ -131,6 +131,26 @@ void main() { expect(actions, isNot(contains('Move between terminal tabs'))); }); + test('a browser outside macOS documents capturing its keys', () { + List actions(TargetPlatform platform, {required bool web}) => [ + for (final entry in KeyboardShortcutRegistry( + platform: platform, + web: web, + ).entries) + entry.action, + ]; + const action = 'Send browser keys to the terminal'; + final entry = _entry( + const KeyboardShortcutRegistry(platform: TargetPlatform.linux, web: true), + action, + ); + expect(entry.group, KeyboardShortcutGroup.terminal); + expect(entry.caveat, contains('Alt+Backspace')); + expect(entry.caveat, contains('hold Esc')); + expect(actions(TargetPlatform.macOS, web: true), isNot(contains(action))); + expect(actions(TargetPlatform.linux, web: false), isNot(contains(action))); + }); + test('Search documents field-scoped Control navigation', () { final registry = KeyboardShortcutRegistry( platform: TargetPlatform.macOS, diff --git a/app/test/features/terminal/terminal_browser_keys_test.dart b/app/test/features/terminal/terminal_browser_keys_test.dart new file mode 100644 index 00000000..def9e0ab --- /dev/null +++ b/app/test/features/terminal/terminal_browser_keys_test.dart @@ -0,0 +1,154 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/terminal/terminal_browser_keys.dart'; +import 'package:pipelines_app/features/terminal/terminal_hub.dart'; +import 'package:pipelines_app/features/terminal/terminal_layout.dart'; +import 'package:pipelines_app/features/terminal/terminal_tab_strip.dart'; + +import '../chat/shell/terminal_view_harness.dart'; +import 'terminal_fixtures.dart'; + +/// A browser's Keyboard Lock, recorded. +class FakeBrowserKeys implements TerminalBrowserKeysBackend { + FakeBrowserKeys({this.supported = true, this.grant = true}); + + @override + final bool supported; + final bool grant; + int locks = 0; + int unlocks = 0; + void Function()? released; + + @override + Future lock() async { + locks++; + return grant; + } + + @override + Future unlock() async => unlocks++; + + @override + set onReleased(void Function() callback) => released = callback; +} + +void main() { + final original = TerminalBrowserKeys.instance; + tearDown(() => TerminalBrowserKeys.instance = original); + + test('capture locks the keys until released by the app or the browser ' + '(Esc held)', () async { + final backend = FakeBrowserKeys(); + final keys = TerminalBrowserKeys(backend: backend); + expect(keys.supported, isTrue); + expect(await keys.capture(), isTrue); + expect(keys.active, isTrue); + expect(terminalBrowserKeysLabel(keys), 'Release browser keys'); + await keys.release(); + expect((keys.active, backend.unlocks), (false, 1)); + await keys.capture(); + backend.released!(); + expect(keys.active, isFalse); + expect(terminalBrowserKeysLabel(keys), 'Capture browser keys'); + }); + + test('a refused lock or an unsupported browser leaves it off', () async { + final refused = TerminalBrowserKeys(backend: FakeBrowserKeys(grant: false)); + expect(await refused.capture(), isFalse); + expect(refused.active, isFalse); + final none = FakeBrowserKeys(supported: false); + final unsupported = TerminalBrowserKeys(backend: none); + expect(await unsupported.capture(), isFalse); + expect(none.locks, 0); + }); + + test('native builds (and tests) have nothing to capture', () { + expect(TerminalBrowserKeys().supported, isFalse); + }); + + Future pumpStrip(WidgetTester tester) async { + final hub = TerminalHub(TestMachines([])); + addTearDown(hub.dispose); + final layout = TerminalLayout(store: MemoryLayoutStore()); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: TerminalTabStrip(hub: hub, layout: layout), + ), + ), + ); + } + + const item = ValueKey('terminal-browser-keys'); + + testWidgets('the terminal menu offers Capture browser keys where the ' + 'browser can, checked while on', (tester) async { + final backend = FakeBrowserKeys(); + TerminalBrowserKeys.instance = TerminalBrowserKeys(backend: backend); + await pumpStrip(tester); + await tester.tap(find.byTooltip('Terminal options')); + await tester.pumpAndSettle(); + expect(find.byKey(item), findsOneWidget); + expect( + tester.widget>(find.byKey(item)).checked, + isFalse, + ); + await tester.tap(find.byKey(item)); + await tester.pumpAndSettle(); + expect(backend.locks, 1); + expect(find.textContaining('Hold Esc'), findsOneWidget); + await tester.tap(find.byTooltip('Terminal options')); + await tester.pumpAndSettle(); + expect( + tester.widget>(find.byKey(item)).checked, + isTrue, + ); + await tester.tap(find.byKey(item)); + await tester.pumpAndSettle(); + expect(backend.unlocks, 1); + expect(TerminalBrowserKeys.instance.active, isFalse); + }); + + testWidgets('no such item where the browser cannot capture its keys', ( + tester, + ) async { + TerminalBrowserKeys.instance = TerminalBrowserKeys( + backend: FakeBrowserKeys(supported: false), + ); + await pumpStrip(tester); + await tester.tap(find.byTooltip('Terminal options')); + await tester.pumpAndSettle(); + expect(find.byKey(item), findsNothing); + expect(find.byKey(const ValueKey('terminal-hide')), findsOneWidget); + }); + + testWidgets('a refused capture says so', (tester) async { + TerminalBrowserKeys.instance = TerminalBrowserKeys( + backend: FakeBrowserKeys(grant: false), + ); + await pumpStrip(tester); + await tester.tap(find.byTooltip('Terminal options')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(item)); + await tester.pumpAndSettle(); + expect(find.textContaining('did not let the page'), findsOneWidget); + }); + + testWidgets("the chat terminal's right-click menu has it too", ( + tester, + ) async { + final backend = FakeBrowserKeys(); + TerminalBrowserKeys.instance = TerminalBrowserKeys(backend: backend); + final harness = TerminalViewHarness(); + await harness.pump(tester); + await harness.rightClick(tester, 1, 0); + final menuItem = find.byKey(const ValueKey('terminal-menu-browserKeys')); + expect(menuItem, findsOneWidget); + expect(find.text('Capture browser keys'), findsOneWidget); + await tester.tap(menuItem); + await tester.pumpAndSettle(); + expect(backend.locks, 1); + await harness.rightClick(tester, 1, 0); + expect(find.text('Release browser keys'), findsOneWidget); + }, variant: desktops); +} diff --git a/app/test/features/terminal/terminal_shortcuts_test.dart b/app/test/features/terminal/terminal_shortcuts_test.dart index f7eaf1b0..0cce56d7 100644 --- a/app/test/features/terminal/terminal_shortcuts_test.dart +++ b/app/test/features/terminal/terminal_shortcuts_test.dart @@ -10,6 +10,7 @@ import 'package:xterm/xterm.dart'; import 'terminal_app.dart'; import 'terminal_fixtures.dart'; +import '../chat/shell/terminal_typing.dart'; void main() { late TerminalGateway mac; @@ -160,6 +161,24 @@ void main() { expect(linuxWeb.summary, contains(linuxWeb.inTerminalNote)); }); + test('a browser outside macOS keeps Ctrl+W: the menu says how to send ' + 'it anyway and what to press instead', () { + const linuxWeb = TerminalShortcutLabels( + web: true, + platform: TargetPlatform.linux, + ); + expect(linuxWeb.browserKeysNote, contains('Capture browser keys')); + expect(linuxWeb.browserKeysNote, contains('Alt+Backspace')); + expect(linuxWeb.summary, contains(linuxWeb.browserKeysNote)); + for (final labels in const [ + TerminalShortcutLabels(web: true, platform: TargetPlatform.macOS), + TerminalShortcutLabels(web: false, platform: TargetPlatform.linux), + ]) { + expect(labels.browserKeysNote, isNull); + expect(labels.summary, isNot(contains('Ctrl+W'))); + } + }); + desktopTestWidgets('holding the chord toggles once and types nothing', ( tester, ) async { @@ -203,8 +222,7 @@ void main() { expect(terminalFocused(key('term_a')), isTrue); expect(appFieldFocused(tester), isFalse); // Typing goes straight to the shell. - await tester.sendKeyEvent(LogicalKeyboardKey.keyX); - await tester.pump(); + await typeKey(tester, LogicalKeyboardKey.keyX); expect(mac.bodies('terminal_input').last['data'], 'x'); await toggleTerminal(tester); expect(appFieldFocused(tester), isTrue); @@ -348,8 +366,7 @@ void main() { // App-wide shortcuts see a typing surface and leave the key alone. expect(primaryFocusIsTypingSurface(), isTrue); expect(primaryFocusTakesTyping(), isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.slash, character: '/'); - await tester.pump(); + await typeKey(tester, LogicalKeyboardKey.slash, character: '/'); expect(terminalFocused(key('term_a')), isTrue); expect( mac.bodies('terminal_input').map((b) => b['data']).join(), diff --git a/app/test/features/terminal/terminal_surface_test.dart b/app/test/features/terminal/terminal_surface_test.dart index 5638cadd..1fa069c0 100644 --- a/app/test/features/terminal/terminal_surface_test.dart +++ b/app/test/features/terminal/terminal_surface_test.dart @@ -12,6 +12,7 @@ import 'package:xterm/xterm.dart'; import 'terminal_app.dart'; import 'terminal_fixtures.dart'; +import '../chat/shell/terminal_typing.dart'; void main() { late TerminalGateway mac; @@ -72,8 +73,7 @@ void main() { // The terminal has the keyboard, yet the shortcut still hides it. await tester.tap(find.byType(TerminalView)); await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.keyX); - await tester.pump(); + await typeKey(tester, LogicalKeyboardKey.keyX); expect(mac.bodies('terminal_input').last['data'], 'x'); await ctrlBacktick(tester); expect(find.byKey(const ValueKey('terminal-panel')), findsNothing); diff --git a/app/third_party/xterm/lib/src/terminal_view.dart b/app/third_party/xterm/lib/src/terminal_view.dart index 98699926..173c9bb2 100644 --- a/app/third_party/xterm/lib/src/terminal_view.dart +++ b/app/third_party/xterm/lib/src/terminal_view.dart @@ -52,6 +52,7 @@ class TerminalView extends StatefulWidget { this.readOnly = false, this.hardwareKeyboardOnly = false, this.simulateScroll = true, + this.onTextInput, }); /// The underlying terminal that this widget renders. @@ -143,6 +144,12 @@ class TerminalView extends StatefulWidget { /// also prevent any on-screen keyboard to be shown. final bool hardwareKeyboardOnly; + /// Receives committed text from the text input (an IME, dead keys, the + /// emoji picker, dictation, a soft keyboard) instead of the default, which + /// types it as a key where one matches and as text otherwise. Composing + /// text is never passed here: it is drawn at the cursor until committed. + final void Function(String text)? onTextInput; + /// If true, when the terminal is in alternate buffer (for example running /// vim, man, etc), if the application does not declare that it can handle /// scrolling, the terminal will simulate scrolling by sending up/down arrow @@ -412,6 +419,12 @@ class TerminalViewState extends State { } void _onInsert(String text) { + final onTextInput = widget.onTextInput; + if (onTextInput != null) { + onTextInput(text); + _scrollToBottom(); + return; + } final key = charToTerminalKey(text.trim()); // On mobile platforms there is no guarantee that virtual keyboard will diff --git a/app/third_party/xterm/lib/src/ui/custom_text_edit.dart b/app/third_party/xterm/lib/src/ui/custom_text_edit.dart index 1d33c7a2..bdb239e6 100644 --- a/app/third_party/xterm/lib/src/ui/custom_text_edit.dart +++ b/app/third_party/xterm/lib/src/ui/custom_text_edit.dart @@ -87,12 +87,27 @@ class CustomTextEditState extends State with TextInputClient { @override Widget build(BuildContext context) { - return Focus( + final child = Focus( focusNode: widget.focusNode, autofocus: widget.autofocus, onKeyEvent: _onKeyEvent, + includeSemantics: widget.readOnly, child: widget.child, ); + if (widget.readOnly) return child; + // An editable terminal is a focusable text field to assistive + // technology, as EditableText is. On the web with semantics on, the + // browser's text input is this node's own element, so typing needs it + // focused: the node is a leaf (the scroll view's semantics left out), + // which the engine keeps focused instead of moving the focus away. + return Semantics( + textField: true, + enabled: true, + focusable: true, + focused: widget.focusNode.hasFocus, + onFocus: requestKeyboard, + child: ExcludeSemantics(child: child), + ); } bool get hasInputConnection => _connection != null && _connection!.attached; @@ -121,24 +136,43 @@ class CustomTextEditState extends State with TextInputClient { return; } + // The editable sits at the cursor, so an IME's candidate window (and + // the web's hidden input) opens there; the caret is in its own space. _connection?.setEditableSizeAndTransform( rect.size, - Matrix4.translationValues(0, 0, 0), + Matrix4.translationValues(rect.left, rect.top, 0), ); - _connection?.setCaretRect(caretRect); + _connection?.setCaretRect(caretRect.shift(-rect.topLeft)); } void _onFocusChange() { _openOrCloseInputConnectionIfNeeded(); + // The semantics' focused flag follows. + if (mounted) setState(() {}); } KeyEventResult _onKeyEvent(FocusNode focusNode, KeyEvent event) { - if (_currentEditingState.composing.isCollapsed) { - return widget.onKeyEvent(focusNode, event); + if (!_currentEditingState.composing.isCollapsed) { + return KeyEventResult.skipRemainingHandlers; } + final result = widget.onKeyEvent(focusNode, event); + if (result != KeyEventResult.ignored || widget.readOnly) return result; + // A printing key the handlers left alone is typed by the text input. If + // the platform closed it (a browser window that lost focus, say), the + // key's own character is typed and the input reopened for what follows. + if (hasInputConnection || event is KeyUpEvent) return result; + final character = event.character; + if (character == null || !_printable(character)) return result; + if (widget.focusNode.hasFocus) _openInputConnection(); + widget.onInsert(character); + return KeyEventResult.handled; + } - return KeyEventResult.skipRemainingHandlers; + static bool _printable(String text) { + if (text.isEmpty) return false; + final code = text.runes.first; + return code >= 0x20 && code != 0x7f; } void _openOrCloseInputConnectionIfNeeded() { @@ -254,9 +288,15 @@ class CustomTextEditState extends State with TextInputClient { // print('showAutocorrectionPromptRect'); } + /// The platform ended the connection (a browser closes it when its window + /// loses focus): it is forgotten, with any unfinished composition, so the + /// next key or focus opens a new one. @override void connectionClosed() { - // print('connectionClosed'); + _connection?.connectionClosedReceived(); + _connection = null; + if (!_currentEditingState.composing.isCollapsed) widget.onComposing(null); + _currentEditingState = _initEditingState.copyWith(); } @override diff --git a/app/third_party/xterm/lib/src/ui/render.dart b/app/third_party/xterm/lib/src/ui/render.dart index 96c20bb8..5c88fdfc 100644 --- a/app/third_party/xterm/lib/src/ui/render.dart +++ b/app/third_party/xterm/lib/src/ui/render.dart @@ -166,6 +166,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { markNeedsLayout(); } + /// The IME's composing (preedit) text drawn at the cursor, if any. + String? get composingText => _composingText; String? _composingText; set composingText(String? value) { if (value == _composingText) return; @@ -497,10 +499,6 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { if (_terminal.buffer.absoluteCursorY >= effectFirstLine && _terminal.buffer.absoluteCursorY <= effectLastLine) { - if (_isComposingText) { - _paintComposingText(canvas, offset + cursorOffset); - } - if (_shouldShowCursor) { final buffer = _terminal.buffer; final cell = CellData.empty(); @@ -514,6 +512,11 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin { cell: _isComposingText ? null : cell, ); } + // The IME's preedit is drawn over the cursor, so a block cursor does + // not hide its first character. + if (_isComposingText) { + _paintComposingText(canvas, offset + cursorOffset); + } } _paintHighlights( diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index 19b648cf..d547866b 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -40,6 +40,15 @@ voice list can then be captured. Without `theme`, the app follows the browser's colour scheme. `--theme` also sets that colour scheme through Chrome emulation. +`--semantics false` leaves Flutter's semantics tree off, as for a user without +assistive technology: only point targets (`x,y`) work, and the web's text input +is Flutter's own hidden field, which reports IME composition (with semantics on, +a text field's input is its semantics element, which does not). + +`--user-agent ''` overrides the browser's user agent before loading, so an +Android phone's (with `--touch true`) makes Flutter's `defaultTargetPlatform` +Android, for touch-only UI such as the terminal's key row. + ## Steps You can pass steps on the command line as `verb=value`. With `--script`, they @@ -52,7 +61,8 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`. | `shot=name` | take a screenshot | | `click=` | click the centre of the target, then wait `--wait` ms (default 1000) | | `waitfor=` | wait up to 10 s for the target to appear | -| `type=text` | type into the focused field (or the first visible one) | +| `type=text` | type into the focused field (or the first visible one) through CDP `Input.insertText`, which commits text as an IME, the emoji picker or dictation does | +| `compose=text` | set IME composing text (CDP `Input.imeSetComposition`) in the focused field, as a CJK IME or a dead key does; a following `type=` commits it | | `press=Enter` | press a key: Enter, Escape, Tab, Backspace, ArrowUp, ArrowDown, a letter or a digit, optionally after `Control+`, `Shift+`, `Alt+` or `Meta+` (`press=Control+2`) | | `scroll=600` | scroll with the mouse wheel at the centre (JSON `at` sets a target, `dx` a horizontal delta, `repeat` and `gap` a run of ticks) | | `rightclick=` | click the secondary mouse button on the target (context menus), then wait | diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index 29ebcaf4..37a615bd 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -21,6 +21,8 @@ options: --script --size WxH (880x1000) --film-ms --cdp http://127.0.0.1: --probe true|false --params --touch true (emulate a touch screen: mobile metrics, touch input) + --semantics false (leave Flutter semantics off; point targets only) + --user-agent (e.g. an Android phone's, for defaultTargetPlatform) steps: open=[@WxH] wait= shot= click= waitfor= type= press= scroll= size=WxH files=[,] (answers the next file chooser) @@ -90,7 +92,7 @@ let exitCode = 0; try { const base = opts.build ? (server = await serveBuild(opts.build)).origin : opts.url; browser = await openBrowser({ cdp: opts.cdp }); - page = flutterPage(browser, log, { touch: opts.touch === 'true' }); + page = flutterPage(browser, log, { touch: opts.touch === 'true', semantics: opts.semantics !== 'false', userAgent: opts['user-agent'] }); for (const step of steps) { const [verb] = Object.keys(step); const value = step[verb]; @@ -123,6 +125,7 @@ try { case 'waitfor': await page.waitFor(value, step.timeout ?? 10000); break; case 'files': await page.armFiles(String(value).split(',').map((p) => resolve(p))); break; case 'type': await page.type(String(value)); await delay(step.wait ?? settle); break; + case 'compose': await page.compose(String(value)); await delay(step.wait ?? settle); break; case 'press': await page.press(String(value)); await delay(step.wait ?? settle); break; case 'scroll': { const at = await page.scroll(Number(value), step.at, { dx: Number(step.dx ?? 0), repeat: Number(step.repeat ?? 1), gap: Number(step.gap ?? 16) }); diff --git a/app/tool/capture/page.mjs b/app/tool/capture/page.mjs index 9a9fe893..beed4d6d 100644 --- a/app/tool/capture/page.mjs +++ b/app/tool/capture/page.mjs @@ -46,7 +46,7 @@ const LABELS = `(() => [...document.querySelectorAll('flt-semantics, [aria-label rect: [r.left, r.top, r.width, r.height].map(Math.round) }; }) .filter((n) => (n.label || n.key) && n.rect[2] > 0 && n.rect[3] > 0))()`; -export function flutterPage(browser, log, { touch = false } = {}) { +export function flutterPage(browser, log, { touch = false, semantics = true, userAgent } = {}) { const { send } = browser; let viewport = { width: 880, height: 1000 }; const errors = []; @@ -107,8 +107,17 @@ export function flutterPage(browser, log, { touch = false } = {}) { await send('Page.bringToFront'); await resize(width, height); await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: theme ?? '' }] }); + // A phone's user agent makes Flutter's defaultTargetPlatform Android. + if (userAgent) await send('Emulation.setUserAgentOverride', { userAgent, platform: /Android/.test(userAgent) ? 'Linux armv8l' : undefined }); await send('Page.navigate', { url }); await until(() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), 'Flutter to start', 30000); + if (!semantics) { + // As a user without assistive technology sees it: no semantics tree, + // so only point targets work (the web's text input then is Flutter's + // own hidden field, with IME composition events). + await delay(1500); + return; + } await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); await until(() => evaluate("document.querySelectorAll('flt-semantics').length > 0"), 'the semantics tree', 15000); // Touch starts once semantics is on: the placeholder's click does not @@ -150,6 +159,10 @@ export function flutterPage(browser, log, { touch = false } = {}) { if (!focused) throw new Error('No text field to type into; click the field first'); await send('Input.insertText', { text }); }, + /** Sets IME composing (marked) text in the focused field, as a CJK IME or a dead key does; a following `type` commits. */ + async compose(text) { + await send('Input.imeSetComposition', { text, selectionStart: text.length, selectionEnd: text.length }); + }, /** Presses [chord]: a key, optionally after `Control+`, `Shift+`, `Alt+` or `Meta+` (e.g. `Control+2`). */ async press(chord) { const parts = String(chord).split('+');