Merge main into the terminal flow-control branch
Conflicts resolved keeping both sides: main's active-client rules, input lane, reply marking and key input, and this branch's flow control, acknowledgements, subscriptions and sliced emulator feed. terminal_ack joins the terminal lane; the feed marks each live slice it writes as drawing, so the emulator's answers still go to onReply. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -127,11 +127,28 @@ class PipelinesClient implements ApiGateway {
|
||||
if (!_states.isClosed) _states.add(value);
|
||||
}
|
||||
|
||||
/// Requests sent at once rather than after the previous request's reply:
|
||||
/// a terminal's keystrokes and sizes. They are written to the socket in
|
||||
/// call order, and the server handles them in arrival order on a lane of
|
||||
/// their own, so they never wait behind a slow request (a terminal_open
|
||||
/// waiting for its login prompt, a chat backend call) and stay in order
|
||||
/// among themselves. An older server handles them in order with the rest.
|
||||
static const pipelined = {
|
||||
'terminal_input',
|
||||
'terminal_resize',
|
||||
'chat_shell_input',
|
||||
'chat_shell_resize',
|
||||
};
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||
final completer = Completer<JsonMap>();
|
||||
final generation = _generation;
|
||||
final snapshot = Map<String, dynamic>.of(fields);
|
||||
if (pipelined.contains(type)) {
|
||||
_send(type, snapshot, completer, generation);
|
||||
return completer.future;
|
||||
}
|
||||
final run = _queue.then(
|
||||
(_) => _sendCall(type, snapshot, completer, generation),
|
||||
);
|
||||
@@ -145,6 +162,22 @@ class PipelinesClient implements ApiGateway {
|
||||
Completer<JsonMap> result,
|
||||
int generation,
|
||||
) async {
|
||||
_send(type, fields, result, generation);
|
||||
// Match the existing client's serialized request semantics, even on errors.
|
||||
try {
|
||||
await result.future;
|
||||
} catch (_) {
|
||||
/* The caller receives the error. */
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes one request now; [result] completes with its reply.
|
||||
void _send(
|
||||
String type,
|
||||
JsonMap fields,
|
||||
Completer<JsonMap> result,
|
||||
int generation,
|
||||
) {
|
||||
if (generation != _generation) {
|
||||
result.completeError(StateError('Connection replaced'));
|
||||
return;
|
||||
@@ -175,12 +208,6 @@ class PipelinesClient implements ApiGateway {
|
||||
timer.cancel();
|
||||
if (_pending.remove(id) != null) result.completeError(error);
|
||||
}
|
||||
// Match the existing client's serialized request semantics, even on errors.
|
||||
try {
|
||||
await result.future;
|
||||
} catch (_) {
|
||||
/* The caller receives the error. */
|
||||
}
|
||||
}
|
||||
|
||||
String sendOnly(String type, [JsonMap fields = const {}]) {
|
||||
|
||||
@@ -15,6 +15,8 @@ class ChatShellRunsRepository {
|
||||
String? data,
|
||||
int? after,
|
||||
List<String>? runIds,
|
||||
bool reply = false,
|
||||
bool activate = false,
|
||||
}) => {
|
||||
'chat_shell_run_request': {
|
||||
'session_id': sessionId,
|
||||
@@ -25,6 +27,8 @@ class ChatShellRunsRepository {
|
||||
'data': ?data,
|
||||
'after': ?after,
|
||||
'run_ids': ?runIds,
|
||||
if (reply) 'reply': true,
|
||||
if (activate) 'activate': true,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -43,16 +47,40 @@ class ChatShellRunsRepository {
|
||||
);
|
||||
|
||||
/// Writes typed text (control characters and escape sequences included)
|
||||
/// to a running command's terminal.
|
||||
Future<void> input(String sessionId, String runId, String data) => gateway
|
||||
.call('chat_shell_input', _body(sessionId, runId: runId, data: data));
|
||||
/// to a running command's terminal. [reply] marks the emulator's automatic
|
||||
/// answer to a query, which the server passes on only from the terminal's
|
||||
/// active client; typing carries the [size] this client draws it at.
|
||||
Future<void> input(
|
||||
String sessionId,
|
||||
String runId,
|
||||
String data, {
|
||||
bool reply = false,
|
||||
(int, int)? size,
|
||||
}) => gateway.call(
|
||||
'chat_shell_input',
|
||||
_body(
|
||||
sessionId,
|
||||
runId: runId,
|
||||
data: data,
|
||||
reply: reply,
|
||||
cols: size?.$1,
|
||||
rows: size?.$2,
|
||||
),
|
||||
);
|
||||
|
||||
/// Sets a running command's terminal size.
|
||||
Future<void> resize(String sessionId, String runId, int cols, int rows) =>
|
||||
gateway.call(
|
||||
'chat_shell_resize',
|
||||
_body(sessionId, runId: runId, cols: cols, rows: rows),
|
||||
);
|
||||
/// Reports the size this client draws a running command's terminal at;
|
||||
/// [activate] makes it the active client (it focused the terminal), whose
|
||||
/// size the process takes.
|
||||
Future<void> resize(
|
||||
String sessionId,
|
||||
String runId,
|
||||
int cols,
|
||||
int rows, {
|
||||
bool activate = false,
|
||||
}) => gateway.call(
|
||||
'chat_shell_resize',
|
||||
_body(sessionId, runId: runId, cols: cols, rows: rows, activate: activate),
|
||||
);
|
||||
|
||||
Future<void> stop(String sessionId, String runId) =>
|
||||
gateway.call('chat_shell_stop', _body(sessionId, runId: runId));
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:xterm/core.dart';
|
||||
|
||||
/// The bytes xterm sends for keys, where xterm.dart 4.0.0's own handlers
|
||||
/// differ (Alt+letter upper-cased, no Ctrl symbols, the wrong modifier codes,
|
||||
/// application cursor keys read from the keypad mode).
|
||||
///
|
||||
/// Modified special keys use xterm's parameter: 1 + Shift(1) + Alt(2) +
|
||||
/// Ctrl(4), so Shift+Up is `CSI 1;2A`, Alt+Left `CSI 1;3D`, Ctrl+Right
|
||||
/// `CSI 1;5C`, Ctrl+Shift+Home `CSI 1;6H`, Shift+PgUp `CSI 5;2~`.
|
||||
|
||||
const String _esc = '\x1b';
|
||||
|
||||
/// Whether Alt is Meta here: always outside Apple platforms; on them the
|
||||
/// Option key is Meta only while [optionAsMeta] (else it types its symbol).
|
||||
bool chatShellAltIsMeta({required bool optionAsMeta}) {
|
||||
final apple =
|
||||
defaultTargetPlatform == TargetPlatform.macOS ||
|
||||
defaultTargetPlatform == TargetPlatform.iOS;
|
||||
return !apple || optionAsMeta;
|
||||
}
|
||||
|
||||
int _modifier({required bool shift, required bool alt, required bool ctrl}) =>
|
||||
1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0);
|
||||
|
||||
/// Cursor keys and Home/End: their final letter. DECCKM (application cursor
|
||||
/// keys) sends them unmodified as SS3.
|
||||
const Map<TerminalKey, String> _cursorKeys = {
|
||||
TerminalKey.arrowUp: 'A',
|
||||
TerminalKey.arrowDown: 'B',
|
||||
TerminalKey.arrowRight: 'C',
|
||||
TerminalKey.arrowLeft: 'D',
|
||||
TerminalKey.home: 'H',
|
||||
TerminalKey.end: 'F',
|
||||
};
|
||||
|
||||
/// F1–F4: SS3 unmodified, `CSI 1;m P` modified.
|
||||
const Map<TerminalKey, String> _pfKeys = {
|
||||
TerminalKey.f1: 'P',
|
||||
TerminalKey.f2: 'Q',
|
||||
TerminalKey.f3: 'R',
|
||||
TerminalKey.f4: 'S',
|
||||
};
|
||||
|
||||
/// Keys sent as `CSI n ~` (`CSI n;m ~` modified).
|
||||
const Map<TerminalKey, int> _tildeKeys = {
|
||||
TerminalKey.insert: 2,
|
||||
TerminalKey.delete: 3,
|
||||
TerminalKey.pageUp: 5,
|
||||
TerminalKey.pageDown: 6,
|
||||
TerminalKey.f5: 15,
|
||||
TerminalKey.f6: 17,
|
||||
TerminalKey.f7: 18,
|
||||
TerminalKey.f8: 19,
|
||||
TerminalKey.f9: 20,
|
||||
TerminalKey.f10: 21,
|
||||
TerminalKey.f11: 23,
|
||||
TerminalKey.f12: 24,
|
||||
};
|
||||
|
||||
/// Keypad keys in application keypad mode (DECKPAM). The digits and the
|
||||
/// decimal point keep typing their characters, as xterm does while NumLock
|
||||
/// is on (a keypad digit only arrives with NumLock on).
|
||||
const Map<TerminalKey, String> _keypadKeys = {
|
||||
TerminalKey.numpadEnter: 'M',
|
||||
TerminalKey.numpadMultiply: 'j',
|
||||
TerminalKey.numpadAdd: 'k',
|
||||
TerminalKey.numpadSubtract: 'm',
|
||||
TerminalKey.numpadDivide: 'o',
|
||||
TerminalKey.numpadEqual: 'X',
|
||||
};
|
||||
|
||||
/// The bytes for a non-printing key, or null for a key that types a
|
||||
/// character (letters, digits, symbols, Space, the keypad outside its
|
||||
/// application mode). [alt] counts in the modifier parameter; [meta] (Alt
|
||||
/// as Meta) prefixes ESC to the keys that have no parameter.
|
||||
String? chatShellSpecialKeyBytes(
|
||||
TerminalKey key, {
|
||||
required bool shift,
|
||||
required bool alt,
|
||||
required bool meta,
|
||||
required bool ctrl,
|
||||
required TerminalState state,
|
||||
}) {
|
||||
final m = _modifier(shift: shift, alt: alt, ctrl: ctrl);
|
||||
final prefix = meta ? _esc : '';
|
||||
final cursor = _cursorKeys[key];
|
||||
if (cursor != null) {
|
||||
if (m > 1) return '$_esc[1;$m$cursor';
|
||||
return state.cursorKeysMode ? '${_esc}O$cursor' : '$_esc[$cursor';
|
||||
}
|
||||
final pf = _pfKeys[key];
|
||||
if (pf != null) return m > 1 ? '$_esc[1;$m$pf' : '${_esc}O$pf';
|
||||
final tilde = _tildeKeys[key];
|
||||
if (tilde != null) return m > 1 ? '$_esc[$tilde;$m~' : '$_esc[$tilde~';
|
||||
if (state.appKeypadMode) {
|
||||
final keypad = _keypadKeys[key];
|
||||
if (keypad != null) return '${_esc}O$keypad';
|
||||
}
|
||||
switch (key) {
|
||||
case TerminalKey.enter || TerminalKey.numpadEnter || TerminalKey.returnKey:
|
||||
return '$prefix${state.lineFeedMode ? '\r\n' : '\r'}';
|
||||
case TerminalKey.tab:
|
||||
return shift ? '$prefix$_esc[Z' : '$prefix\t';
|
||||
case TerminalKey.backtab:
|
||||
return '$prefix$_esc[Z';
|
||||
case TerminalKey.escape:
|
||||
return '$prefix$_esc';
|
||||
case TerminalKey.backspace:
|
||||
return '$prefix${ctrl ? '\b' : '\x7f'}';
|
||||
case TerminalKey.space:
|
||||
if (ctrl) return '$prefix\x00';
|
||||
return meta ? '$_esc ' : null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ctrl with a character: the C0 code xterm sends for it.
|
||||
const Map<String, int> _ctrlSymbols = {
|
||||
' ': 0x00,
|
||||
'@': 0x00,
|
||||
'2': 0x00,
|
||||
'[': 0x1b,
|
||||
'3': 0x1b,
|
||||
'\\': 0x1c,
|
||||
'4': 0x1c,
|
||||
']': 0x1d,
|
||||
'5': 0x1d,
|
||||
'^': 0x1e,
|
||||
'6': 0x1e,
|
||||
'_': 0x1f,
|
||||
'/': 0x1f,
|
||||
'-': 0x1f,
|
||||
'7': 0x1f,
|
||||
'?': 0x7f,
|
||||
'8': 0x7f,
|
||||
};
|
||||
|
||||
/// The control code Ctrl+[char] sends, or null if it has none.
|
||||
int? chatShellCtrlCode(String char) {
|
||||
if (char.length != 1) return null;
|
||||
final code = char.toLowerCase().codeUnitAt(0);
|
||||
if (code >= 0x61 && code <= 0x7a) return code - 0x60;
|
||||
return _ctrlSymbols[char];
|
||||
}
|
||||
|
||||
/// The bytes for [char] (as typed, Shift applied) with Ctrl and/or Meta
|
||||
/// ([alt]): Ctrl maps it to its control code, Meta prefixes ESC. Null with
|
||||
/// neither modifier, or Ctrl with a character that has no control code.
|
||||
String? chatShellCharBytes(
|
||||
String char, {
|
||||
required bool alt,
|
||||
required bool ctrl,
|
||||
}) {
|
||||
if (!alt && !ctrl) return null;
|
||||
if (ctrl) {
|
||||
final code = chatShellCtrlCode(char);
|
||||
if (code == null) return null;
|
||||
return '${alt ? _esc : ''}${String.fromCharCode(code)}';
|
||||
}
|
||||
return '$_esc$char';
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:xterm/core.dart';
|
||||
|
||||
import 'chat_shell_terminal_input.dart';
|
||||
import 'chat_shell_terminal_keymap.dart';
|
||||
|
||||
/// The terminal's input handler, chained before xterm.dart's defaults: it
|
||||
/// encodes every key [Terminal.keyInput] receives (the key toolbar, the soft
|
||||
/// keyboard's keys, hardware keys the view did not encode itself) as xterm
|
||||
/// does. A printing key's character comes from the US layout here; the view
|
||||
/// encodes hardware keys with their real character first
|
||||
/// ([chatShellKeyEventBytes]).
|
||||
class ChatShellInputHandler implements TerminalInputHandler {
|
||||
const ChatShellInputHandler({required this.optionAsMeta});
|
||||
|
||||
/// Whether Option is Meta on Apple platforms (read at each key).
|
||||
final bool Function() optionAsMeta;
|
||||
|
||||
@override
|
||||
String? call(TerminalKeyboardEvent event) {
|
||||
final alt = event.alt && chatShellAltIsMeta(optionAsMeta: optionAsMeta());
|
||||
final special = chatShellSpecialKeyBytes(
|
||||
event.key,
|
||||
shift: event.shift,
|
||||
alt: event.alt,
|
||||
meta: alt,
|
||||
ctrl: event.ctrl,
|
||||
state: event.state,
|
||||
);
|
||||
if (special != null) return special;
|
||||
final char = chatShellTerminalKeyChar(event.key);
|
||||
if (char == null) return null;
|
||||
return chatShellCharBytes(
|
||||
event.shift ? chatShellUsShifted(char) : char,
|
||||
alt: alt,
|
||||
ctrl: event.ctrl,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bool _printable(String? text) {
|
||||
if (text == null || text.runes.length != 1) return false;
|
||||
final code = text.runes.single;
|
||||
return code >= 0x20 && code != 0x7f;
|
||||
}
|
||||
|
||||
bool _ascii(String text) {
|
||||
final code = text.codeUnitAt(0);
|
||||
return code >= 0x20 && code < 0x7f;
|
||||
}
|
||||
|
||||
/// The character a key types with Shift but without Ctrl or Alt: the event's
|
||||
/// own character where it is plain ASCII (so the layout counts), else the
|
||||
/// logical key's, else the physical key's on a US layout. On Apple platforms
|
||||
/// Option's own symbol (Option+B types ∫) is never the character.
|
||||
String? _baseChar(KeyEvent event, {required bool shift, required bool option}) {
|
||||
final character = event.character;
|
||||
if (_printable(character) && _ascii(character!) && !option) {
|
||||
return character;
|
||||
}
|
||||
final id = event.logicalKey.keyId;
|
||||
if (id >= 0x20 && id < 0x7f) {
|
||||
final char = String.fromCharCode(id);
|
||||
return shift ? chatShellUsShifted(char) : char;
|
||||
}
|
||||
final physical = chatShellPhysicalChar(event.physicalKey);
|
||||
if (physical == null) return null;
|
||||
return shift ? chatShellUsShifted(physical) : physical;
|
||||
}
|
||||
|
||||
/// The bytes a hardware key event sends, or null to leave it to the
|
||||
/// emulator's own handling (plain typing, Cmd chords, IME text).
|
||||
///
|
||||
/// Non-printing keys are encoded as xterm does, honouring application cursor
|
||||
/// keys and keypad mode in [state]. Ctrl with a character sends its control
|
||||
/// code; Alt (Meta, see [chatShellAltIsMeta]) sends ESC and the character it
|
||||
/// types with Shift and the layout. AltGr (Ctrl+Alt typing a symbol outside
|
||||
/// Apple platforms) types the symbol.
|
||||
String? chatShellKeyEventBytes(
|
||||
KeyEvent event,
|
||||
HardwareKeyboard keyboard,
|
||||
TerminalState state, {
|
||||
required bool optionAsMeta,
|
||||
}) {
|
||||
if (event is KeyUpEvent || keyboard.isMetaPressed) return null;
|
||||
final apple =
|
||||
defaultTargetPlatform == TargetPlatform.macOS ||
|
||||
defaultTargetPlatform == TargetPlatform.iOS;
|
||||
final shift = keyboard.isShiftPressed;
|
||||
final ctrl = keyboard.isControlPressed;
|
||||
final alt =
|
||||
keyboard.isAltPressed && chatShellAltIsMeta(optionAsMeta: optionAsMeta);
|
||||
final special = chatShellSpecialKeys[event.logicalKey];
|
||||
if (special != null) {
|
||||
final bytes = chatShellSpecialKeyBytes(
|
||||
special,
|
||||
shift: shift,
|
||||
alt: keyboard.isAltPressed,
|
||||
meta: alt,
|
||||
ctrl: ctrl,
|
||||
state: state,
|
||||
);
|
||||
if (bytes != null) return bytes;
|
||||
}
|
||||
if (!alt && !ctrl) return null;
|
||||
final base = _baseChar(
|
||||
event,
|
||||
shift: shift,
|
||||
option: apple && keyboard.isAltPressed,
|
||||
);
|
||||
if (base == null) return null;
|
||||
if (!apple && ctrl && keyboard.isAltPressed) {
|
||||
// AltGr arrives as Ctrl+Alt: a symbol the layout composes is typed.
|
||||
final character = event.character;
|
||||
final id = event.logicalKey.keyId;
|
||||
final plain = id >= 0x20 && id < 0x7f
|
||||
? String.fromCharCode(id)
|
||||
: chatShellPhysicalChar(event.physicalKey);
|
||||
if (_printable(character) &&
|
||||
character!.toLowerCase() != plain &&
|
||||
chatShellUsShifted(plain ?? '') != character) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return chatShellCharBytes(base, alt: alt, ctrl: ctrl);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:xterm/core.dart';
|
||||
|
||||
/// Key tables for terminal input: the non-printing keys by their Flutter
|
||||
/// logical key, and the US layout's characters, used when a key event
|
||||
/// carries no usable character (Option's symbol on a Mac, a control code).
|
||||
|
||||
/// The non-printing keys the terminal encodes itself.
|
||||
final Map<LogicalKeyboardKey, TerminalKey> chatShellSpecialKeys = {
|
||||
LogicalKeyboardKey.arrowUp: TerminalKey.arrowUp,
|
||||
LogicalKeyboardKey.arrowDown: TerminalKey.arrowDown,
|
||||
LogicalKeyboardKey.arrowLeft: TerminalKey.arrowLeft,
|
||||
LogicalKeyboardKey.arrowRight: TerminalKey.arrowRight,
|
||||
LogicalKeyboardKey.home: TerminalKey.home,
|
||||
LogicalKeyboardKey.end: TerminalKey.end,
|
||||
LogicalKeyboardKey.insert: TerminalKey.insert,
|
||||
LogicalKeyboardKey.delete: TerminalKey.delete,
|
||||
LogicalKeyboardKey.pageUp: TerminalKey.pageUp,
|
||||
LogicalKeyboardKey.pageDown: TerminalKey.pageDown,
|
||||
LogicalKeyboardKey.f1: TerminalKey.f1,
|
||||
LogicalKeyboardKey.f2: TerminalKey.f2,
|
||||
LogicalKeyboardKey.f3: TerminalKey.f3,
|
||||
LogicalKeyboardKey.f4: TerminalKey.f4,
|
||||
LogicalKeyboardKey.f5: TerminalKey.f5,
|
||||
LogicalKeyboardKey.f6: TerminalKey.f6,
|
||||
LogicalKeyboardKey.f7: TerminalKey.f7,
|
||||
LogicalKeyboardKey.f8: TerminalKey.f8,
|
||||
LogicalKeyboardKey.f9: TerminalKey.f9,
|
||||
LogicalKeyboardKey.f10: TerminalKey.f10,
|
||||
LogicalKeyboardKey.f11: TerminalKey.f11,
|
||||
LogicalKeyboardKey.f12: TerminalKey.f12,
|
||||
LogicalKeyboardKey.enter: TerminalKey.enter,
|
||||
LogicalKeyboardKey.numpadEnter: TerminalKey.numpadEnter,
|
||||
LogicalKeyboardKey.tab: TerminalKey.tab,
|
||||
LogicalKeyboardKey.escape: TerminalKey.escape,
|
||||
LogicalKeyboardKey.backspace: TerminalKey.backspace,
|
||||
LogicalKeyboardKey.space: TerminalKey.space,
|
||||
LogicalKeyboardKey.numpadMultiply: TerminalKey.numpadMultiply,
|
||||
LogicalKeyboardKey.numpadAdd: TerminalKey.numpadAdd,
|
||||
LogicalKeyboardKey.numpadSubtract: TerminalKey.numpadSubtract,
|
||||
LogicalKeyboardKey.numpadDivide: TerminalKey.numpadDivide,
|
||||
LogicalKeyboardKey.numpadEqual: TerminalKey.numpadEqual,
|
||||
};
|
||||
|
||||
/// US layout: each unshifted symbol and its shifted one.
|
||||
const Map<String, String> _usShifted = {
|
||||
'1': '!',
|
||||
'2': '@',
|
||||
'3': '#',
|
||||
'4': r'$',
|
||||
'5': '%',
|
||||
'6': '^',
|
||||
'7': '&',
|
||||
'8': '*',
|
||||
'9': '(',
|
||||
'0': ')',
|
||||
'-': '_',
|
||||
'=': '+',
|
||||
'[': '{',
|
||||
']': '}',
|
||||
'\\': '|',
|
||||
';': ':',
|
||||
"'": '"',
|
||||
'`': '~',
|
||||
',': '<',
|
||||
'.': '>',
|
||||
'/': '?',
|
||||
};
|
||||
|
||||
/// [char] as Shift types it on a US layout.
|
||||
String chatShellUsShifted(String char) =>
|
||||
_usShifted[char] ?? char.toUpperCase();
|
||||
|
||||
/// The unshifted character of a printing [TerminalKey] on a US layout.
|
||||
String? chatShellTerminalKeyChar(TerminalKey key) {
|
||||
final index = key.index;
|
||||
if (index >= TerminalKey.keyA.index && index <= TerminalKey.keyZ.index) {
|
||||
return String.fromCharCode(0x61 + index - TerminalKey.keyA.index);
|
||||
}
|
||||
if (index >= TerminalKey.digit1.index && index <= TerminalKey.digit9.index) {
|
||||
return String.fromCharCode(0x31 + index - TerminalKey.digit1.index);
|
||||
}
|
||||
if (index >= TerminalKey.numpad1.index &&
|
||||
index <= TerminalKey.numpad9.index) {
|
||||
return String.fromCharCode(0x31 + index - TerminalKey.numpad1.index);
|
||||
}
|
||||
return _terminalKeySymbols[key];
|
||||
}
|
||||
|
||||
const Map<TerminalKey, String> _terminalKeySymbols = {
|
||||
TerminalKey.digit0: '0',
|
||||
TerminalKey.numpad0: '0',
|
||||
TerminalKey.minus: '-',
|
||||
TerminalKey.equal: '=',
|
||||
TerminalKey.bracketLeft: '[',
|
||||
TerminalKey.bracketRight: ']',
|
||||
TerminalKey.backslash: '\\',
|
||||
TerminalKey.semicolon: ';',
|
||||
TerminalKey.quote: "'",
|
||||
TerminalKey.backquote: '`',
|
||||
TerminalKey.comma: ',',
|
||||
TerminalKey.period: '.',
|
||||
TerminalKey.slash: '/',
|
||||
TerminalKey.numpadDecimal: '.',
|
||||
TerminalKey.numpadDivide: '/',
|
||||
TerminalKey.numpadMultiply: '*',
|
||||
TerminalKey.numpadSubtract: '-',
|
||||
TerminalKey.numpadAdd: '+',
|
||||
TerminalKey.numpadEqual: '=',
|
||||
};
|
||||
|
||||
/// The unshifted character a physical key types on a US layout.
|
||||
String? chatShellPhysicalChar(PhysicalKeyboardKey key) {
|
||||
final usb = key.usbHidUsage;
|
||||
// USB HID: keyA (0x70004) … keyZ, digit1 … digit9, digit0.
|
||||
if (usb >= 0x70004 && usb <= 0x7001d) {
|
||||
return String.fromCharCode(0x61 + usb - 0x70004);
|
||||
}
|
||||
if (usb >= 0x7001e && usb <= 0x70026) {
|
||||
return String.fromCharCode(0x31 + usb - 0x7001e);
|
||||
}
|
||||
return _physicalSymbols[key];
|
||||
}
|
||||
|
||||
final Map<PhysicalKeyboardKey, String> _physicalSymbols = {
|
||||
PhysicalKeyboardKey.digit0: '0',
|
||||
PhysicalKeyboardKey.minus: '-',
|
||||
PhysicalKeyboardKey.equal: '=',
|
||||
PhysicalKeyboardKey.bracketLeft: '[',
|
||||
PhysicalKeyboardKey.bracketRight: ']',
|
||||
PhysicalKeyboardKey.backslash: '\\',
|
||||
PhysicalKeyboardKey.semicolon: ';',
|
||||
PhysicalKeyboardKey.quote: "'",
|
||||
PhysicalKeyboardKey.backquote: '`',
|
||||
PhysicalKeyboardKey.comma: ',',
|
||||
PhysicalKeyboardKey.period: '.',
|
||||
PhysicalKeyboardKey.slash: '/',
|
||||
PhysicalKeyboardKey.space: ' ',
|
||||
};
|
||||
@@ -1,7 +1,10 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:xterm/core.dart';
|
||||
|
||||
import '../../terminal/terminal_layout.dart';
|
||||
import 'chat_shell_run.dart';
|
||||
import 'chat_shell_terminal_feed.dart';
|
||||
import 'chat_shell_terminal_key_input.dart';
|
||||
|
||||
/// Lines of scrollback one card's terminal keeps.
|
||||
const int chatShellTerminalScrollback = 5000;
|
||||
@@ -12,31 +15,62 @@ const int chatShellTerminalScrollback = 5000;
|
||||
///
|
||||
/// It keeps no copy of typed input: [Terminal.onOutput] hands each key or
|
||||
/// paste straight to [onInput], which sends it.
|
||||
///
|
||||
/// Several clients may draw one terminal. The emulator's automatic answers
|
||||
/// to queries in the output (cursor position, device attributes) go to
|
||||
/// [onReply] instead, so the server can let only the active client's
|
||||
/// answers through; a view gaining focus calls [activate], which makes this
|
||||
/// client the active one at its size ([onActivate]).
|
||||
class ChatShellTerminalSession {
|
||||
ChatShellTerminalSession(
|
||||
ChatShellRun run, {
|
||||
required this.onInput,
|
||||
required this.onResize,
|
||||
}) : terminal = _ChatShellTerminal() {
|
||||
this.onReply,
|
||||
this.onActivate,
|
||||
bool Function()? optionAsMeta,
|
||||
}) : optionAsMeta =
|
||||
optionAsMeta ?? (() => TerminalLayout.instance.optionAsMeta),
|
||||
terminal = _ChatShellTerminal() {
|
||||
terminal.inputHandler = CascadeInputHandler([
|
||||
ChatShellInputHandler(optionAsMeta: this.optionAsMeta),
|
||||
defaultInputHandler,
|
||||
]);
|
||||
_feed = ChatShellTerminalFeed(_write);
|
||||
// Drawn at the process's own size until a view lays it out at its own.
|
||||
if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows);
|
||||
terminal.onOutput = _output;
|
||||
terminal.onResize = (cols, rows, _, _) => onResize(cols, rows);
|
||||
terminal.onResize = (cols, rows, _, _) {
|
||||
_viewSize = (cols, rows);
|
||||
onResize(cols, rows);
|
||||
};
|
||||
replay(run);
|
||||
}
|
||||
|
||||
final Terminal terminal;
|
||||
|
||||
/// Receives input for the process; only called while the run is live.
|
||||
/// Whether a Mac's Option key is Meta (Settings → Appearance → Terminal).
|
||||
final bool Function() optionAsMeta;
|
||||
|
||||
/// Receives what the operator types for the process; only called while
|
||||
/// the run is live.
|
||||
final void Function(String data) onInput;
|
||||
|
||||
/// Receives the size the view laid the terminal out at.
|
||||
final void Function(int cols, int rows) onResize;
|
||||
|
||||
/// Receives the emulator's automatic answers to queries in the live
|
||||
/// output; [onInput] receives them when this is null.
|
||||
final void Function(String data)? onReply;
|
||||
|
||||
/// Receives this client's size when a view of it gains focus.
|
||||
final void Function(int cols, int rows)? onActivate;
|
||||
|
||||
late final ChatShellTerminalFeed _feed;
|
||||
bool _live = false;
|
||||
bool _replaying = false;
|
||||
bool _drawing = false;
|
||||
(int, int)? _viewSize;
|
||||
|
||||
/// The absolute output byte this terminal has drawn up to, or will once
|
||||
/// the output waiting in its feed is written.
|
||||
@@ -51,6 +85,16 @@ class ChatShellTerminalSession {
|
||||
/// Whether typing reaches a running process.
|
||||
bool get live => _live;
|
||||
|
||||
/// The size a view last laid the terminal out at; null before any did.
|
||||
(int, int)? get viewSize => _viewSize;
|
||||
|
||||
/// A view of this terminal gained focus: this client becomes the one the
|
||||
/// process is sized for and whose answers it receives.
|
||||
void activate() {
|
||||
final size = _viewSize;
|
||||
if (_live && size != null) onActivate?.call(size.$1, size.$2);
|
||||
}
|
||||
|
||||
/// Draws [run]'s held output from scratch: on open, after a gap and after
|
||||
/// a readback replaced the card's copy. Answers the emulator gives to old
|
||||
/// queries in that output are not sent: the process asked them long ago.
|
||||
@@ -58,6 +102,7 @@ class ChatShellTerminalSession {
|
||||
/// (ChatShellTerminalFeed), so it never stalls the UI.
|
||||
void replay(ChatShellRun run) {
|
||||
_live = run.running && run.terminal;
|
||||
terminal.reflowEnabled = !_live;
|
||||
_feed.restart(run.outputStart);
|
||||
_replaying = true;
|
||||
try {
|
||||
@@ -96,18 +141,23 @@ class ChatShellTerminalSession {
|
||||
void finish(ChatShellRun run) {
|
||||
if (!_live) return;
|
||||
_live = false;
|
||||
terminal.reflowEnabled = true;
|
||||
_feed.then(() => terminal.setCursorVisibleMode(false));
|
||||
}
|
||||
|
||||
/// Stops drawing what still waits (the emulator is going away).
|
||||
void dispose() => _feed.dispose();
|
||||
|
||||
/// Writes one slice. What the emulator sends while drawing live output
|
||||
/// answers that output (onReply); during a replay it is not sent at all.
|
||||
void _write(String text, bool replay) {
|
||||
_replaying = replay;
|
||||
_drawing = !replay;
|
||||
try {
|
||||
terminal.write(text);
|
||||
} finally {
|
||||
_replaying = false;
|
||||
_drawing = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,7 +185,13 @@ class ChatShellTerminalSession {
|
||||
}
|
||||
|
||||
void _output(String data) {
|
||||
if (_live && !_replaying) onInput(data);
|
||||
if (!_live || _replaying) return;
|
||||
final reply = onReply;
|
||||
if (_drawing && reply != null) {
|
||||
reply(data);
|
||||
} else {
|
||||
onInput(data);
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain-pipe output has bare newlines, which a terminal draws as a line
|
||||
@@ -147,21 +203,48 @@ class ChatShellTerminalSession {
|
||||
/// The emulator with the scrollback the cards keep. It answers a cursor
|
||||
/// position query (DSR 6) with the one-based row and column the protocol
|
||||
/// specifies; xterm.dart 4.0.0 itself answers zero-based.
|
||||
///
|
||||
/// A live terminal does not reflow on resize: xterm.dart 4.0.0's reflow
|
||||
/// leaves the cursor on a row other than its line's, so the shell's redraw
|
||||
/// lands on old output. Without it a resize behaves as xterm's: narrowing
|
||||
/// cuts rows at the new width, fewer rows scroll the top into scrollback
|
||||
/// (keeping the cursor's row at the bottom), more rows bring it back.
|
||||
/// Finished output, which nothing writes to any more, reflows to fit.
|
||||
class _ChatShellTerminal extends Terminal {
|
||||
_ChatShellTerminal() : super(maxLines: chatShellTerminalScrollback);
|
||||
_ChatShellTerminal()
|
||||
: super(maxLines: chatShellTerminalScrollback, platform: _platform());
|
||||
|
||||
/// The package's own Alt handler (a fallback after the app's) leaves
|
||||
/// Option alone only when it knows it is on a Mac.
|
||||
static TerminalTargetPlatform _platform() =>
|
||||
defaultTargetPlatform == TargetPlatform.macOS ||
|
||||
defaultTargetPlatform == TargetPlatform.iOS
|
||||
? TerminalTargetPlatform.macos
|
||||
: TerminalTargetPlatform.unknown;
|
||||
|
||||
@override
|
||||
void sendCursorPosition() {
|
||||
onOutput?.call('\x1b[${buffer.cursorY + 1};${buffer.cursorX + 1}R');
|
||||
}
|
||||
|
||||
/// Narrowing rewraps long lines, and xterm.dart 4.0.0 keeps every blank
|
||||
/// row below the cursor while doing so: the extra rows push the top of
|
||||
/// the output into scrollback. Blank rows below the cursor are dropped
|
||||
/// instead, keeping the cursor on its line.
|
||||
@override
|
||||
void resize(int width, int height, [int? pixelWidth, int? pixelHeight]) {
|
||||
final oldWidth = viewWidth;
|
||||
if (!reflowEnabled && width >= 1 && width < oldWidth) {
|
||||
// A cut row keeps its cells past the new width, which a later widening
|
||||
// would show again beside what was written since: they are erased.
|
||||
for (final buffer in [mainBuffer, altBuffer]) {
|
||||
buffer.lines.forEach((line) {
|
||||
if (line.length > width) {
|
||||
line.eraseRange(width, line.length, CursorStyle.empty);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
super.resize(width, height, pixelWidth, pixelHeight);
|
||||
if (!reflowEnabled) return;
|
||||
// Rewrapping keeps every blank row below the cursor, and the extra rows
|
||||
// push the top of finished output into scrollback: they are dropped.
|
||||
final lines = buffer.lines;
|
||||
while (buffer.height > viewHeight &&
|
||||
buffer.height - 1 > buffer.absoluteCursorY &&
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:xterm/xterm.dart';
|
||||
import '../conversation/chat_composer_paste_focus.dart';
|
||||
import '../ui/transcript/chat_link_launcher.dart';
|
||||
import 'chat_shell_metrics.dart';
|
||||
import 'chat_shell_terminal_key_input.dart';
|
||||
import 'chat_shell_terminal_links.dart';
|
||||
import 'chat_shell_terminal_session.dart';
|
||||
import 'chat_shell_terminal_theme.dart';
|
||||
@@ -94,6 +95,10 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
|
||||
final TerminalController _controller = TerminalController();
|
||||
final FocusNode _focus = FocusNode(debugLabel: 'chat-shell-terminal');
|
||||
final FocusNode _outputFocus = FocusNode(debugLabel: 'chat-shell-output');
|
||||
final ScrollController _scroll = ScrollController();
|
||||
final Map<ShortcutActivator, Intent> _shortcuts =
|
||||
chatShellTerminalShortcuts();
|
||||
bool _focused = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -101,14 +106,25 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
|
||||
// A paste while the terminal has focus goes to the process, not to the
|
||||
// chat composer.
|
||||
ChatComposerPasteFocus.registerInput(_focus);
|
||||
_focus.addListener(_focusChanged);
|
||||
}
|
||||
|
||||
/// Focusing a terminal makes this client the one it is sized for, the
|
||||
/// way typing in it does.
|
||||
void _focusChanged() {
|
||||
final focused = _focus.hasFocus;
|
||||
if (focused && !_focused) widget.session.activate();
|
||||
_focused = focused;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focus.removeListener(_focusChanged);
|
||||
ChatComposerPasteFocus.unregisterInput(_focus);
|
||||
_controller.dispose();
|
||||
_focus.dispose();
|
||||
_outputFocus.dispose();
|
||||
_scroll.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -123,11 +139,30 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Ctrl-C with a selection copies; anything else is the terminal's.
|
||||
KeyEventResult _key(FocusNode node, KeyEvent event) =>
|
||||
chatShellCopyKey(event, HardwareKeyboard.instance) && _copySelection()
|
||||
? KeyEventResult.handled
|
||||
: KeyEventResult.ignored;
|
||||
/// Ctrl-C with a selection copies; the terminal's own shortcuts (copy,
|
||||
/// paste) are left to it; any other key xterm encodes differently from
|
||||
/// xterm.dart (Alt as Meta, Ctrl symbols, modified special keys) is sent
|
||||
/// here with its real character. The rest is the emulator's.
|
||||
KeyEventResult _key(FocusNode node, KeyEvent event) {
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
if (chatShellCopyKey(event, keyboard) && _copySelection()) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (_shortcuts.keys.any((key) => key.accepts(event, keyboard))) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
final session = widget.session;
|
||||
final bytes = chatShellKeyEventBytes(
|
||||
event,
|
||||
keyboard,
|
||||
session.terminal,
|
||||
optionAsMeta: session.optionAsMeta(),
|
||||
);
|
||||
if (bytes == null) return KeyEventResult.ignored;
|
||||
session.terminal.textInput(bytes);
|
||||
if (_scroll.hasClients) _scroll.jumpTo(_scroll.position.maxScrollExtent);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
/// A finished run's output takes no keys of its own, so the copy keys are
|
||||
/// answered here while it has the keyboard.
|
||||
@@ -163,6 +198,7 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
|
||||
child: TerminalView(
|
||||
session.terminal,
|
||||
controller: _controller,
|
||||
scrollController: _scroll,
|
||||
focusNode: _focus,
|
||||
autofocus: widget.autofocus && live,
|
||||
autoResize: widget.autoResize,
|
||||
@@ -177,7 +213,7 @@ class _ChatShellTerminalViewState extends State<ChatShellTerminalView> {
|
||||
hardwareKeyboardOnly: !chatShellTouchFirst(),
|
||||
// No autocorrect or suggestions rewriting what is sent to a shell.
|
||||
keyboardType: TextInputType.visiblePassword,
|
||||
shortcuts: chatShellTerminalShortcuts(),
|
||||
shortcuts: _shortcuts,
|
||||
cursorType: TerminalCursorType.block,
|
||||
onTapUp: _tapped,
|
||||
onKeyEvent: _key,
|
||||
|
||||
@@ -43,7 +43,9 @@ class ChatShellTerminals {
|
||||
() => ChatShellTerminalSession(
|
||||
run,
|
||||
onInput: (data) => _input(run.id, data),
|
||||
onReply: (data) => _input(run.id, data, reply: true),
|
||||
onResize: (cols, rows) => _resized(run.id, cols, rows),
|
||||
onActivate: (cols, rows) => _activated(run.id, cols, rows),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -69,17 +71,35 @@ class ChatShellTerminals {
|
||||
_sessions[run.id]?.replay(run);
|
||||
}
|
||||
|
||||
void _input(String runId, String data) {
|
||||
void _input(String runId, String data, {bool reply = false}) {
|
||||
if (_disposed) return;
|
||||
_inputs
|
||||
.putIfAbsent(
|
||||
runId,
|
||||
() => ChatShellInputPipe(
|
||||
(data) => _repository.input(_sessionId, runId, data),
|
||||
(data, reply) => _repository.input(
|
||||
_sessionId,
|
||||
runId,
|
||||
data,
|
||||
reply: reply,
|
||||
// Typing makes this client the active one at its size.
|
||||
size: reply ? null : _sessions[runId]?.viewSize,
|
||||
),
|
||||
(error) => onError(runId, error),
|
||||
),
|
||||
)
|
||||
.add(data);
|
||||
.add(data, reply: reply);
|
||||
}
|
||||
|
||||
/// A view of [runId] gained focus: it becomes the active client and the
|
||||
/// process takes its size at once.
|
||||
void _activated(String runId, int cols, int rows) {
|
||||
if (_disposed || !(_sessions[runId]?.live ?? false)) return;
|
||||
_resizes.remove(runId)?.cancel();
|
||||
_sentSizes[runId] = (cols, rows);
|
||||
_repository
|
||||
.resize(_sessionId, runId, cols, rows, activate: true)
|
||||
.catchError((Object error) => onError(runId, error));
|
||||
}
|
||||
|
||||
void _resized(String runId, int cols, int rows) {
|
||||
@@ -113,16 +133,25 @@ class ChatShellTerminals {
|
||||
/// machine terminal's), in order: what arrives
|
||||
/// while a request is in flight goes in the next one. Nothing is kept once
|
||||
/// sent, and a refusal discards what was waiting rather than retyping it.
|
||||
///
|
||||
/// The emulator's automatic answers ([add] with reply) travel in requests
|
||||
/// of their own, marked so, never merged with typing on either side.
|
||||
class ChatShellInputPipe {
|
||||
ChatShellInputPipe(this._send, this._failed);
|
||||
|
||||
final Future<void> Function(String data) _send;
|
||||
final Future<void> Function(String data, bool reply) _send;
|
||||
final void Function(Object error) _failed;
|
||||
final StringBuffer _pending = StringBuffer();
|
||||
|
||||
/// Waiting text in order, each run of typing or of answers in one buffer.
|
||||
final List<(StringBuffer, bool)> _pending = [];
|
||||
bool _busy = false;
|
||||
|
||||
void add(String data) {
|
||||
_pending.write(data);
|
||||
void add(String data, {bool reply = false}) {
|
||||
if (data.isEmpty) return;
|
||||
if (_pending.isEmpty || _pending.last.$2 != reply) {
|
||||
_pending.add((StringBuffer(), reply));
|
||||
}
|
||||
_pending.last.$1.write(data);
|
||||
if (!_busy) unawaited(_pump());
|
||||
}
|
||||
|
||||
@@ -130,19 +159,22 @@ class ChatShellInputPipe {
|
||||
_busy = true;
|
||||
try {
|
||||
while (_pending.isNotEmpty) {
|
||||
var waiting = _pending.toString();
|
||||
_pending.clear();
|
||||
final (buffer, reply) = _pending.first;
|
||||
var waiting = buffer.toString();
|
||||
buffer.clear();
|
||||
var cut = waiting.length;
|
||||
if (cut > chatShellInputChunk) {
|
||||
cut = chatShellInputChunk;
|
||||
// Never split a surrogate pair across two requests.
|
||||
final unit = waiting.codeUnitAt(cut - 1);
|
||||
if (unit >= 0xD800 && unit <= 0xDBFF) cut--;
|
||||
_pending.write(waiting.substring(cut));
|
||||
buffer.write(waiting.substring(cut));
|
||||
} else {
|
||||
_pending.removeAt(0);
|
||||
}
|
||||
final chunk = waiting.substring(0, cut);
|
||||
waiting = '';
|
||||
await _send(chunk);
|
||||
await _send(chunk, reply);
|
||||
}
|
||||
} catch (error) {
|
||||
_pending.clear();
|
||||
|
||||
@@ -208,9 +208,11 @@ class KeyboardShortcutRegistry {
|
||||
web: web,
|
||||
platform: platform,
|
||||
).toggle.join(', '),
|
||||
caveat: web
|
||||
? 'Browser tab shortcuts such as Cmd+T are not available to the app.'
|
||||
: null,
|
||||
caveat: [
|
||||
TerminalShortcutLabels(web: web, platform: platform).inTerminalNote,
|
||||
if (web)
|
||||
'Browser tab shortcuts such as Cmd+T are not available to the app.',
|
||||
].join(' '),
|
||||
),
|
||||
if (!web)
|
||||
const KeyboardShortcutEntry(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../terminal/terminal_layout.dart';
|
||||
@@ -63,6 +64,20 @@ class SettingsTerminalSection extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
// Alt is always Meta elsewhere; only a Mac's Option types symbols.
|
||||
if (defaultTargetPlatform == TargetPlatform.macOS ||
|
||||
defaultTargetPlatform == TargetPlatform.iOS)
|
||||
SwitchListTile(
|
||||
key: const ValueKey('settings-terminal-option-as-meta'),
|
||||
title: const Text('Use Option as Meta key'),
|
||||
subtitle: const Text(
|
||||
'Option+B, Option+F and Option+D move and delete by word in '
|
||||
'the shell (ESC b, ESC f, ESC d). Off, Option types its '
|
||||
'symbol (∫, ƒ, ∂).',
|
||||
),
|
||||
value: layout.optionAsMeta,
|
||||
onChanged: layout.setOptionAsMeta,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
|
||||
@@ -75,6 +75,11 @@ class TerminalLayout extends ChangeNotifier {
|
||||
Rect floatRect = terminalFloatDefaultRect;
|
||||
bool maximized = false;
|
||||
|
||||
/// Whether a Mac's Option key is Meta in the terminal (Option+B sends
|
||||
/// ESC b, readline's word back) rather than typing its symbol (∫). Other
|
||||
/// platforms' Alt is always Meta.
|
||||
bool optionAsMeta = true;
|
||||
|
||||
/// Whether the last change could not be saved.
|
||||
bool saveFailed = false;
|
||||
|
||||
@@ -100,6 +105,7 @@ class TerminalLayout extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
maximized = json['maximized'] == true;
|
||||
optionAsMeta = json['option_as_meta'] != false;
|
||||
} catch (_) {
|
||||
return;
|
||||
}
|
||||
@@ -107,6 +113,7 @@ class TerminalLayout extends ChangeNotifier {
|
||||
}
|
||||
|
||||
void setMode(TerminalMode value) => _change(() => mode = value);
|
||||
void setOptionAsMeta(bool value) => _change(() => optionAsMeta = value);
|
||||
void toggle() => _change(() => visible = !visible);
|
||||
void show() => _change(() => visible = true);
|
||||
void hide() => _change(() => visible = false);
|
||||
@@ -128,6 +135,7 @@ class TerminalLayout extends ChangeNotifier {
|
||||
floatRect.height,
|
||||
],
|
||||
'maximized': maximized,
|
||||
'option_as_meta': optionAsMeta,
|
||||
}),
|
||||
);
|
||||
if (revision != _revision || saved != saveFailed) return;
|
||||
|
||||
@@ -3,13 +3,18 @@ import 'package:flutter/services.dart';
|
||||
|
||||
/// Whether [event] shows or hides the terminal: Alt+T, Ctrl+T, Cmd+T
|
||||
/// (Meta+T) or Ctrl+` (Shift allowed only with Ctrl+`). They are global key
|
||||
/// handlers, so inside the terminal they toggle rather than reaching the
|
||||
/// shell (whose Ctrl+T, transpose-chars, is then not available) and inside
|
||||
/// text fields they toggle rather than type.
|
||||
/// handlers, so inside text fields they toggle rather than type. While a
|
||||
/// terminal has the keyboard ([inTerminal]) only Cmd+T and Ctrl+` toggle:
|
||||
/// Ctrl+T (transpose-chars) and Alt+T (ESC t, transpose-words) reach the
|
||||
/// shell.
|
||||
///
|
||||
/// A held chord's repeats match too (and are swallowed); only its first
|
||||
/// press toggles.
|
||||
bool terminalToggleShortcut(KeyEvent event, HardwareKeyboard keyboard) {
|
||||
bool terminalToggleShortcut(
|
||||
KeyEvent event,
|
||||
HardwareKeyboard keyboard, {
|
||||
bool inTerminal = false,
|
||||
}) {
|
||||
if (event is KeyUpEvent) return false;
|
||||
final control = keyboard.isControlPressed;
|
||||
final meta = keyboard.isMetaPressed;
|
||||
@@ -24,6 +29,7 @@ bool terminalToggleShortcut(KeyEvent event, HardwareKeyboard keyboard) {
|
||||
event.logicalKey == LogicalKeyboardKey.keyT ||
|
||||
alt && event.physicalKey == PhysicalKeyboardKey.keyT;
|
||||
if (!t || keyboard.isShiftPressed) return false;
|
||||
if (inTerminal) return meta && !control && !alt;
|
||||
return [control, meta, alt].where((pressed) => pressed).length == 1;
|
||||
}
|
||||
|
||||
@@ -66,6 +72,15 @@ class TerminalShortcutLabels {
|
||||
'Ctrl+`',
|
||||
];
|
||||
|
||||
/// The keys that still hide the terminal while it has the keyboard: its
|
||||
/// Ctrl+T and Alt+T are the shell's.
|
||||
List<String> get toggleInTerminal => [if (!web && _apple) 'Cmd+T', 'Ctrl+`'];
|
||||
|
||||
/// How the in-terminal exception reads in the menu and the cheatsheet.
|
||||
String get inTerminalNote =>
|
||||
'Inside the terminal, ${_apple ? 'Option+T' : 'Alt+T'} and Ctrl+T '
|
||||
'reach the shell; ${toggleInTerminal.join(' or ')} hides it.';
|
||||
|
||||
/// The keys that move between tabs, or none where the browser keeps them.
|
||||
List<String> get tabs =>
|
||||
web ? const [] : const ['Ctrl+Tab', 'Ctrl+Shift+Tab'];
|
||||
@@ -76,6 +91,7 @@ class TerminalShortcutLabels {
|
||||
/// Every shortcut, one per line, for the terminal's menu.
|
||||
String get summary => [
|
||||
'Show or hide: ${toggle.join(', ')}',
|
||||
inTerminalNote,
|
||||
if (tabs.isNotEmpty) 'Next or previous tab: ${tabs.join(' / ')}',
|
||||
'Copy selected text: $copy',
|
||||
].join('\n');
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../../ui/input/keyboard_owner.dart';
|
||||
import '../../ui/motion/motion.dart';
|
||||
import 'terminal_focus.dart';
|
||||
import 'terminal_hub.dart';
|
||||
@@ -81,6 +82,9 @@ class _TerminalSurfaceState extends State<TerminalSurface>
|
||||
bool _panelShown = false;
|
||||
String? _selected;
|
||||
|
||||
/// The key of the toggle chord held down, if any.
|
||||
PhysicalKeyboardKey? _toggleKey;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -150,8 +154,21 @@ class _TerminalSurfaceState extends State<TerminalSurface>
|
||||
KeyEventResult _key(KeyEvent event) {
|
||||
if (!mounted) return KeyEventResult.ignored;
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
if (terminalToggleShortcut(event, keyboard)) {
|
||||
if (event is KeyDownEvent) toggle();
|
||||
// A held toggle chord's repeats stay swallowed after the terminal it
|
||||
// showed takes the keyboard (where Alt+T and Ctrl+T are the shell's).
|
||||
if (event.physicalKey == _toggleKey) {
|
||||
if (event is KeyUpEvent) _toggleKey = null;
|
||||
if (event is KeyRepeatEvent) return KeyEventResult.handled;
|
||||
}
|
||||
if (terminalToggleShortcut(
|
||||
event,
|
||||
keyboard,
|
||||
inTerminal: primaryFocusIsTypingSurface(),
|
||||
)) {
|
||||
if (event is KeyDownEvent) {
|
||||
_toggleKey = event.physicalKey;
|
||||
toggle();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
final step = terminalTabShortcut(event, keyboard);
|
||||
|
||||
@@ -26,7 +26,9 @@ class TerminalTab extends ChangeNotifier {
|
||||
session = ChatShellTerminalSession(
|
||||
_run(),
|
||||
onInput: _input,
|
||||
onReply: (data) => _input(data, reply: true),
|
||||
onResize: _resized,
|
||||
onActivate: _activated,
|
||||
);
|
||||
session.terminal.onTitleChange = _titled;
|
||||
session.onDrawn = _drawn;
|
||||
@@ -93,6 +95,10 @@ class TerminalTab extends ChangeNotifier {
|
||||
_window = 0;
|
||||
_update(info);
|
||||
unawaited(resume());
|
||||
// The new connection reports the size it draws at; the server applies
|
||||
// it while no other client is the active one.
|
||||
final size = session.viewSize;
|
||||
if (size != null) _resized(size.$1, size.$2);
|
||||
}
|
||||
|
||||
void disconnected() {
|
||||
@@ -217,19 +223,25 @@ class TerminalTab extends ChangeNotifier {
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _input(String data) {
|
||||
/// Sends typed text, or with [reply] the emulator's automatic answer to a
|
||||
/// query, which the server passes on only from the active client. Typing
|
||||
/// carries the size this client draws at: it becomes the active client.
|
||||
void _input(String data, {bool reply = false}) {
|
||||
if (_disposed || !connected) return;
|
||||
final id = _info.id;
|
||||
final gateway = _gateway;
|
||||
(_pipe ??= ChatShellInputPipe(
|
||||
(data) => gateway.call('terminal_input', {
|
||||
'terminal_request': {'terminal_id': id, 'data': data},
|
||||
}),
|
||||
(failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
},
|
||||
)).add(data);
|
||||
(_pipe ??= ChatShellInputPipe((data, reply) {
|
||||
final size = reply ? null : session.viewSize;
|
||||
return gateway.call('terminal_input', {
|
||||
'terminal_request': {
|
||||
'terminal_id': id,
|
||||
'data': data,
|
||||
if (reply) 'reply': true,
|
||||
'cols': ?size?.$1,
|
||||
'rows': ?size?.$2,
|
||||
},
|
||||
});
|
||||
}, _failed)).add(data, reply: reply);
|
||||
}
|
||||
|
||||
void _resized(int cols, int rows) {
|
||||
@@ -237,23 +249,40 @@ class TerminalTab extends ChangeNotifier {
|
||||
_resize?.cancel();
|
||||
_resize = Timer(chatShellResizeDelay, () {
|
||||
if (_sentSize == (cols, rows) || !connected) return;
|
||||
_sentSize = (cols, rows);
|
||||
_gateway
|
||||
.call('terminal_resize', {
|
||||
'terminal_request': {
|
||||
'terminal_id': _info.id,
|
||||
'cols': cols,
|
||||
'rows': rows,
|
||||
},
|
||||
})
|
||||
.catchError((Object failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
return <String, dynamic>{};
|
||||
});
|
||||
_sendSize(cols, rows, activate: false);
|
||||
});
|
||||
}
|
||||
|
||||
/// A view gained focus: this client becomes the active one and the
|
||||
/// terminal takes its size at once.
|
||||
void _activated(int cols, int rows) {
|
||||
if (_disposed || !_info.running || !connected) return;
|
||||
_resize?.cancel();
|
||||
_sendSize(cols, rows, activate: true);
|
||||
}
|
||||
|
||||
void _sendSize(int cols, int rows, {required bool activate}) {
|
||||
_sentSize = (cols, rows);
|
||||
_gateway
|
||||
.call('terminal_resize', {
|
||||
'terminal_request': {
|
||||
'terminal_id': _info.id,
|
||||
'cols': cols,
|
||||
'rows': rows,
|
||||
if (activate) 'activate': true,
|
||||
},
|
||||
})
|
||||
.catchError((Object failure) {
|
||||
_failed(failure);
|
||||
return <String, dynamic>{};
|
||||
});
|
||||
}
|
||||
|
||||
void _failed(Object failure) {
|
||||
error = '$failure';
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user