Merge main into the terminal flow-control branch

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 00:03:20 +00:00
148 changed files with 18443 additions and 153 deletions
+5
View File
@@ -9,6 +9,11 @@
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
analyzer:
exclude:
# Vendored upstream package (path dependency) with its own style.
- third_party/**
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
+33 -6
View File
@@ -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);
+53 -24
View File
@@ -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();
}
+35 -4
View File
@@ -28,7 +28,30 @@ emulator. Auth flows that print a link, wait for a pasted token and continue
Android/iOS the toolbar also has a text field ("Type input, then Enter")
for the soft keyboard, with a Hide typing toggle; it is emptied when sent.
- The terminal is resized to its layout (debounced 150 ms); the process gets
SIGWINCH. New runs start at the last laid-out size.
SIGWINCH. New runs start at the last laid-out size. A live terminal does
not reflow (xterm.dart's reflow left the cursor on another line's row, so
prompts landed on old output and rows merged): narrowing cuts rows at the
new width (the cut cells are erased, so widening never brings stale text
back), fewer rows drop blank rows below the cursor and then scroll the top
into scrollback with the cursor's row at the bottom, more rows bring
scrollback back above it. Finished output still reflows to its card.
- **Keys** (`chat_shell_terminal_{input,key_input,keymap}.dart`): the view
encodes hardware keys before xterm.dart does, with the event's real
character, and a `TerminalInputHandler` chained before the package's
defaults encodes `keyInput` calls (key toolbar, soft keyboard) the same
way. Alt is Meta (ESC + the character, Shift and layout included; Macs:
the Option as Meta setting, the key's own character instead of Option's
symbol). Ctrl maps letters and `@ 2 Space`→NUL, `[ 3`→ESC, `\ 4`→0x1c,
`] 5`→0x1d, `^ 6`→0x1e, `_ / - 7`→0x1f, `? 8`→DEL. Arrows, Home/End,
Insert/Delete, PgUp/PgDn and F1–F12 carry xterm's modifier parameter
(1 + Shift 1 + Alt 2 + Ctrl 4: Shift+Up `CSI 1;2A`, Alt+Left `CSI 1;3D`,
Ctrl+Shift+Right `CSI 1;6C`, Ctrl+PgDn `CSI 6;5~`, Shift+F1 `CSI 1;2P`);
unmodified arrows and Home/End are SS3 under DECCKM. With DECKPAM the
keypad's Enter and operators send SS3 (`ESC O M`, `k`, `m`, `j`, `o`);
keypad digits keep typing (NumLock on). Alt+Backspace is `ESC DEL`,
Ctrl+Backspace `^H`, Shift+Tab `CSI Z`, Alt+Enter `ESC CR`. Ctrl+Alt
typing a composed symbol outside Apple platforms (AltGr) types it.
Cmd (Meta key) chords and plain typing are left to the emulator.
- Printed `http(s)` links open in the browser on tap (wrapped links are
joined). Other schemes are ignored.
- Finished runs are drawn read-only, shrunk to the rows their output takes
@@ -92,8 +115,16 @@ emulator. Auth flows that print a link, wait for a pasted token and continue
position) for a live run, so two open clients send two answers.
xterm.dart 4.0.0 answers DSR 6 zero-based; the app overrides it to the
correct one-based answer.
- xterm.dart 4.0.0 keeps blank rows when it rewraps; the app drops blank rows
below the cursor after a resize so the top of the output stays in view.
- xterm.dart 4.0.0 keeps blank rows when it rewraps; for finished output
(the only output that reflows) the app drops blank rows below the cursor
after a resize so the top of the output stays in view.
- A live terminal's long lines are cut, not rewrapped, when it narrows, and
stay cut when it widens again (as xterm without reflow).
- Key encoding gaps: no modifyOtherKeys / CSI u (Ctrl+Shift+letter sends the
plain control code, Ctrl+1/9/0 type the digit); Alt as Meta on Linux
assumes AltGr arrives as Ctrl+Alt or its own key; a Mac's Option as Meta
takes the character from the logical key, else the US position of the
physical key, so a non-US Mac layout's Option+key may send the US letter.
- Desktop typing uses key events (no IME composition for CJK input). Touch
platforms use the field.
- A descendant that keeps the PTY open after the command exits is read for
@@ -110,7 +141,7 @@ emulator. Auth flows that print a link, wait for a pasted token and continue
`chat_shell_plain.go`, `chat_shell_runner.go`, `chat_shell_supervise.go`,
`chat_shell_run_handlers.go`, `chat_shell_share.go`, `chat.go`,
`websocket.go`; `internal/pipeline/chat_shell_runs.go`; `go.mod`, `go.sum`.
- App: `lib/features/chat/shell/chat_shell_terminal_{session,view,keys,theme,links,page}.dart`,
- App: `lib/features/chat/shell/chat_shell_terminal_{session,view,keys,theme,links,page,input,key_input,keymap}.dart`,
`chat_shell_terminals.dart`, `chat_shell_output_view.dart`,
`chat_shell_run{,_card}.dart`, `chat_shell_card_actions.dart`,
`chat_shell_runs_{controller,repository}.dart`, `chat_shell_metrics.dart`;
+64 -8
View File
@@ -25,14 +25,20 @@ tmux inside it for work that must survive that).
own login and asks for the password again.
- **Shortcuts** (`terminal_shortcuts.dart`, handled by the surface as a
`FocusManager` early key handler, so they work wherever focus is, including
inside the terminal and in the chat composer, and neither receives the key):
in the chat composer, which does not receive the key):
- **Alt+T** (Option+T), **Ctrl+T**, **Cmd+T** (Meta+T) and **Ctrl+`**
show or hide the terminal in the selected mode; on a narrow window they
open and close the full-screen page. Only the one modifier counts
(Ctrl+Shift+T, Ctrl+Alt+T pass through); Option+T, which types † on a
Mac, is also matched by key position. Cmd+` stays the macOS window
switcher. **The shell's own Ctrl+T (transpose-chars) no longer reaches
it** while this binding is on.
switcher.
- **Inside a focused terminal** (any `TypingSurface`, i.e. a terminal
view) only **Cmd+T** and **Ctrl+`** toggle: **Ctrl+T** reaches the shell
as `^T` (transpose-chars) and **Alt+T** as `ESC t` (transpose-words).
A held chord that opened the terminal from outside keeps its repeats
swallowed after the terminal takes the keyboard, so nothing is typed.
The ⋮ menu and the shortcut cheatsheet say so
(`TerminalShortcutLabels.inTerminalNote`).
- **Ctrl+Tab / Ctrl+Shift+Tab**, while the terminal is shown (panel,
window or narrow page), select the next / previous terminal tab, wrapping,
and focus it. This deliberately overrides the chat's Ctrl+Tab pane
@@ -89,9 +95,16 @@ tmux inside it for work that must survive that).
from its retained output. A dropped connection resumes after the last
byte held. A restarted server lists the terminals as ended, with why.
- **Keyboard:** a focused terminal gets every key (Ctrl-C, Esc, Tab, arrows,
Ctrl-letters) except the shortcuts above (Ctrl+T, Alt+T, Cmd+T, Ctrl+`,
and Ctrl+Tab while shown); paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking
elsewhere moves focus away normally.
Ctrl-letters, Ctrl+T, Alt+T) except Cmd+T, Ctrl+` and Ctrl+Tab while
shown; paste is Cmd-V (Apple) or Ctrl-V/Ctrl-Shift-V. Clicking elsewhere
moves focus away normally. Keys are encoded as xterm does; see
`chat-interactive-terminal.md` (Keys). **Option as Meta** (Settings →
Appearance → Terminal, Macs only, saved with the layout, default on): a
Mac's Option sends `ESC` + the key's character (Option+B = `ESC b`)
instead of typing its symbol (∫). On by default because the shell's
Meta bindings (word motion, transpose, yank-last-arg) are used far more
in a terminal than Option's symbols; turn it off to type them. Other
platforms' Alt is always Meta.
- No terminal request is sent until the terminal is first shown (or a
terminal is opened): each connection sends one request at a time, so the
first screen's read is never queued behind `terminal_list`.
@@ -107,8 +120,28 @@ data?, after?}`.
when the login cannot ask for a password (below).
- `terminal_list` → `terminals` (running and ended, oldest first; live
records carry their current title, size and `stream`).
- `terminal_input {terminal_id, data}` (UTF-8, ≤ 16 KiB, 64-request queue),
`terminal_resize {terminal_id, cols, rows}` (clamped 20–500 × 4–200).
- `terminal_input {terminal_id, data, reply?, cols?, rows?}` (UTF-8,
≤ 16 KiB, 64-request queue), `terminal_resize {terminal_id, cols, rows,
activate?}` (clamped 20–500 × 4–200).
- **Several clients on one terminal** (`terminal_viewers.go`,
`terminal_active.go`; chat terminal commands too): one *active* client
owns the PTY size and is the only one whose emulator's automatic answers
(`reply: true`: cursor position, device attributes) reach the shell, so
a query gets one answer, not one per client. The opener starts active;
typing (carrying the typist's `cols`/`rows`, applied before the input)
or focusing a terminal view (`terminal_resize` with `activate`) makes a
client active. Others' sizes are kept, not applied; when the active
connection closes the next most recent client's size is applied. The
client marks answers by what the emulator emits while drawing output
(`ChatShellTerminalSession.onReply`).
- **Input latency**: `PipelinesClient.call` sends `terminal_input`,
`terminal_resize`, `chat_shell_input` and `chat_shell_resize` at once
instead of behind the previous request's reply; the server reads them
onto a per-connection terminal lane (`terminal_lane.go`) handled in
order beside the ordinary loop, and `terminal_open` runs off the read
loop. `ChatShellInputPipe` still keeps one request in flight per
terminal (typing during it is coalesced; answers go in their own
requests).
- `terminal_output {terminal_id, after}` → `terminal` with `output`,
`output_start`, `output_end`, `stream`; subscribes the connection.
- `terminal_close {terminal_id}` → the closed record (runs off the read
@@ -438,3 +471,26 @@ The tmux results above (restart survival, client replacement, the
service outlived it and was killed by hand.
- Not verified: logging in for real (needs the operator's password), Linux
su, and the app against a live server in a browser (widget tests only).
### Terminal input and resize fixes, round 1 (2026-11-25)
- Resize: live terminals run with `reflowEnabled: false`; the old
blank-row-trimming `resize` override now applies only to finished
(reflowing) output, and narrowing erases cells past the new width.
Tests: `test/features/chat/shell/chat_shell_terminal_resize_test.dart`
(long lines shrink/grow with the prompt on the cursor row, shell redraw
and command output after shrinking, no stale text after widening, cleared
screen and scrollback stay cleared, a view whose box shrinks and grows).
- Keys: xterm encoding for Alt/Meta, Ctrl symbols, modified special keys,
DECCKM and DECKPAM (`chat-interactive-terminal.md`, Keys); Option as Meta
setting. Tests: `chat_shell_terminal_input_test.dart` (key event to
bytes, Linux and macOS variants, setting on and off, toolbar `keyInput`),
`chat_shell_terminal_test.dart` (keys through the real view, Ctrl-V paste
intact), `terminal_surface_test.dart` (setting saved and restored, hidden
off Apple platforms).
- Shortcuts: inside a terminal Alt+T and Ctrl+T reach the shell; Cmd+T
and Ctrl+` still toggle (`terminal_shortcuts_test.dart`).
- Not verified: bytes against a real PTY in a browser or native build after
the change (widget tests only), real macOS Option events (native and
browser logical-key shapes are assumed as the tests model them), AltGr on
a real non-US Linux/Windows layout.
+3 -4
View File
@@ -983,10 +983,9 @@ packages:
xterm:
dependency: "direct main"
description:
name: xterm
sha256: "168dfedca77cba33fdb6f52e2cd001e9fde216e398e89335c19b524bb22da3a2"
url: "https://pub.dev"
source: hosted
path: "third_party/xterm"
relative: true
source: path
version: "4.0.0"
yaml:
dependency: transitive
+3 -1
View File
@@ -47,7 +47,9 @@ dependencies:
file_picker: ^13.3.0
url_launcher: ^6.3.3
bonsoir: ^7.1.5
xterm: ^4.0.0
# Vendored, patched xterm.dart 4.0.0; see third_party/xterm/README.md.
xterm:
path: third_party/xterm
flutter_tts: ^4.2.3
dev_dependencies:
@@ -72,6 +72,76 @@ void main() {
await client.dispose();
});
test('terminal keystrokes do not wait behind a slow request', () async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
final connecting = client.connect(Uri.parse('ws://example.test'));
channel.readyCompleter.complete();
await connecting;
Map<String, dynamic> sent(int i) =>
jsonDecode(channel.outgoing[i] as String) as Map<String, dynamic>;
// A terminal_open waiting for its login prompt.
final open = client.call('terminal_open');
final later = client.call('terminal_list');
await Future<void>.delayed(Duration.zero);
final keys = [
for (final data in ['l', 's', '\r'])
client.call('terminal_input', {
'terminal_request': {'terminal_id': 't', 'data': data},
}),
];
final size = client.call('chat_shell_resize', {
'chat_shell_run_request': {'cols': 80, 'rows': 24},
});
await Future<void>.delayed(Duration.zero);
// The keystrokes and the size went out at once, in order; the ordinary
// request behind the slow one still waits for it.
expect(channel.outgoing, hasLength(5));
expect(
[for (var i = 0; i < 5; i++) sent(i)['type']],
[
'terminal_open',
'terminal_input',
'terminal_input',
'terminal_input',
'chat_shell_resize',
],
);
expect(
[for (var i = 1; i < 4; i++) sent(i)['terminal_request']['data']],
['l', 's', '\r'],
);
for (var i = 1; i < 5; i++) {
channel.incoming.add(
jsonEncode({'id': sent(i)['id'], 'type': sent(i)['type']}),
);
}
for (final key in keys) {
expect((await key)['type'], 'terminal_input');
}
expect((await size)['type'], 'chat_shell_resize');
channel.incoming.add(
jsonEncode({'id': sent(0)['id'], 'type': 'terminal_open'}),
);
expect((await open)['type'], 'terminal_open');
await Future<void>.delayed(Duration.zero);
expect(sent(5)['type'], 'terminal_list');
channel.incoming.add(
jsonEncode({'id': sent(5)['id'], 'type': 'terminal_list'}),
);
expect((await later)['type'], 'terminal_list');
await client.dispose();
});
test('a keystroke while disconnected fails at once', () async {
final client = PipelinesClient(channelFactory: (_) => FakeChannel());
await expectLater(
client.call('terminal_input', {'terminal_request': {}}),
throwsA(isA<NotConnectedError>()),
);
await client.dispose();
});
test('disconnect fails pending requests', () async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
@@ -0,0 +1,309 @@
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_key_input.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart';
import 'package:xterm/core.dart';
/// Modifiers held, as [chatShellKeyEventBytes] reads them.
class _Held extends HardwareKeyboard {
_Held(String mods)
: shift = mods.contains('S'),
alt = mods.contains('A'),
ctrl = mods.contains('C'),
meta = mods.contains('M');
final bool shift, alt, ctrl, meta;
@override
bool get isShiftPressed => shift;
@override
bool get isAltPressed => alt;
@override
bool get isControlPressed => ctrl;
@override
bool get isMetaPressed => meta;
}
KeyDownEvent _down(
LogicalKeyboardKey logical, {
PhysicalKeyboardKey? physical,
String? character,
}) => KeyDownEvent(
physicalKey: physical ?? PhysicalKeyboardKey.keyA,
logicalKey: logical,
character: character,
timeStamp: Duration.zero,
);
/// The bytes a key sends with [mods] (S Shift, A Alt, C Ctrl, M Meta).
String? _bytes(
LogicalKeyboardKey logical, {
String mods = '',
String? character,
PhysicalKeyboardKey? physical,
Terminal? terminal,
bool optionAsMeta = true,
}) => chatShellKeyEventBytes(
_down(logical, physical: physical, character: character),
_Held(mods),
terminal ?? Terminal(),
optionAsMeta: optionAsMeta,
);
const _l = LogicalKeyboardKey.new;
void main() {
final linux = TargetPlatformVariant.only(TargetPlatform.linux);
final mac = TargetPlatformVariant.only(TargetPlatform.macOS);
testWidgets('Alt is Meta: ESC and the character typed, Shift and layout '
'included', (tester) async {
expect(_bytes(LogicalKeyboardKey.keyB, mods: 'A', character: 'b'), '\x1bb');
expect(_bytes(LogicalKeyboardKey.keyF, mods: 'A', character: 'f'), '\x1bf');
expect(_bytes(LogicalKeyboardKey.keyD, mods: 'A', character: 'd'), '\x1bd');
expect(
_bytes(LogicalKeyboardKey.keyB, mods: 'AS', character: 'B'),
'\x1bB',
);
expect(
_bytes(LogicalKeyboardKey.period, mods: 'A', character: '.'),
'\x1b.',
);
expect(
_bytes(LogicalKeyboardKey.digit1, mods: 'A', character: '1'),
'\x1b1',
);
// Without a character (some platforms send none with Alt): the key's.
expect(_bytes(LogicalKeyboardKey.keyT, mods: 'A'), '\x1bt');
expect(_bytes(LogicalKeyboardKey.period, mods: 'AS'), '\x1b>');
// A non-US layout's own character (AZERTY's A key types "q").
expect(_bytes(LogicalKeyboardKey.keyQ, mods: 'A', character: 'q'), '\x1bq');
expect(_bytes(LogicalKeyboardKey.backspace, mods: 'A'), '\x1b\x7f');
expect(_bytes(LogicalKeyboardKey.enter, mods: 'A'), '\x1b\r');
expect(
_bytes(LogicalKeyboardKey.space, mods: 'A', character: ' '),
'\x1b ',
);
}, variant: linux);
testWidgets('Ctrl sends the control code of letters and symbols', (
tester,
) async {
final table = <(LogicalKeyboardKey, String, String), String>{
(LogicalKeyboardKey.keyA, '', 'a'): '\x01',
(LogicalKeyboardKey.keyT, '', 't'): '\x14',
(LogicalKeyboardKey.keyT, 'S', 'T'): '\x14',
(LogicalKeyboardKey.slash, '', '/'): '\x1f',
(LogicalKeyboardKey.bracketRight, '', ']'): '\x1d',
(LogicalKeyboardKey.backslash, '', '\\'): '\x1c',
(LogicalKeyboardKey.bracketLeft, '', '['): '\x1b',
(LogicalKeyboardKey.minus, 'S', '_'): '\x1f',
(LogicalKeyboardKey.digit2, '', '2'): '\x00',
(LogicalKeyboardKey.digit2, 'S', '@'): '\x00',
(LogicalKeyboardKey.digit6, 'S', '^'): '\x1e',
(LogicalKeyboardKey.digit8, '', '8'): '\x7f',
(LogicalKeyboardKey.space, '', ' '): '\x00',
(LogicalKeyboardKey.keyB, 'A', 'b'): '\x1b\x02',
};
for (final MapEntry(key: (key, mods, character), value: bytes)
in table.entries) {
expect(
_bytes(key, mods: 'C$mods', character: character),
bytes,
reason: 'Ctrl+$mods $character',
);
}
// A control character as the event's character still maps by key.
expect(
_bytes(LogicalKeyboardKey.slash, mods: 'C', character: '\x1f'),
'\x1f',
);
expect(_bytes(LogicalKeyboardKey.backspace, mods: 'C'), '\b');
// Ctrl+1 has no control code: the emulator types it.
expect(
_bytes(LogicalKeyboardKey.digit1, mods: 'C', character: '1'),
isNull,
);
}, variant: linux);
testWidgets('modified special keys use the xterm modifier parameter', (
tester,
) async {
const up = LogicalKeyboardKey.arrowUp;
expect(_bytes(up), '\x1b[A');
expect(_bytes(up, mods: 'S'), '\x1b[1;2A');
expect(_bytes(LogicalKeyboardKey.arrowLeft, mods: 'A'), '\x1b[1;3D');
expect(_bytes(LogicalKeyboardKey.arrowDown, mods: 'AS'), '\x1b[1;4B');
expect(_bytes(LogicalKeyboardKey.arrowRight, mods: 'C'), '\x1b[1;5C');
expect(_bytes(up, mods: 'CS'), '\x1b[1;6A');
expect(_bytes(up, mods: 'CA'), '\x1b[1;7A');
expect(_bytes(up, mods: 'CAS'), '\x1b[1;8A');
expect(_bytes(LogicalKeyboardKey.home), '\x1b[H');
expect(_bytes(LogicalKeyboardKey.end, mods: 'S'), '\x1b[1;2F');
expect(_bytes(LogicalKeyboardKey.home, mods: 'C'), '\x1b[1;5H');
expect(_bytes(LogicalKeyboardKey.pageUp), '\x1b[5~');
expect(_bytes(LogicalKeyboardKey.pageUp, mods: 'S'), '\x1b[5;2~');
expect(_bytes(LogicalKeyboardKey.pageDown, mods: 'C'), '\x1b[6;5~');
expect(_bytes(LogicalKeyboardKey.insert), '\x1b[2~');
expect(_bytes(LogicalKeyboardKey.delete), '\x1b[3~');
expect(_bytes(LogicalKeyboardKey.delete, mods: 'A'), '\x1b[3;3~');
expect(_bytes(LogicalKeyboardKey.f1), '\x1bOP');
expect(_bytes(LogicalKeyboardKey.f1, mods: 'S'), '\x1b[1;2P');
expect(_bytes(LogicalKeyboardKey.f4, mods: 'C'), '\x1b[1;5S');
expect(_bytes(LogicalKeyboardKey.f5), '\x1b[15~');
expect(_bytes(LogicalKeyboardKey.f12, mods: 'C'), '\x1b[24;5~');
expect(_bytes(LogicalKeyboardKey.tab, mods: 'S'), '\x1b[Z');
expect(_bytes(LogicalKeyboardKey.tab), '\t');
expect(_bytes(LogicalKeyboardKey.enter), '\r');
expect(_bytes(LogicalKeyboardKey.escape), '\x1b');
expect(_bytes(LogicalKeyboardKey.backspace), '\x7f');
}, variant: linux);
testWidgets('application cursor keys and keypad mode', (tester) async {
final terminal = Terminal()..write('\x1b[?1h');
String? bytes(LogicalKeyboardKey key, [String mods = '']) =>
_bytes(key, mods: mods, terminal: terminal);
expect(bytes(LogicalKeyboardKey.arrowUp), '\x1bOA');
expect(bytes(LogicalKeyboardKey.arrowLeft), '\x1bOD');
expect(bytes(LogicalKeyboardKey.home), '\x1bOH');
expect(bytes(LogicalKeyboardKey.end), '\x1bOF');
// Modified keys are the same in either mode.
expect(bytes(LogicalKeyboardKey.arrowUp, 'C'), '\x1b[1;5A');
// The keypad's operators and Enter follow DECKPAM; digits keep typing.
expect(bytes(LogicalKeyboardKey.numpadAdd), isNull);
expect(bytes(LogicalKeyboardKey.numpadEnter), '\r');
terminal.write('\x1b=');
expect(bytes(LogicalKeyboardKey.numpadAdd), '\x1bOk');
expect(bytes(LogicalKeyboardKey.numpadEnter), '\x1bOM');
expect(bytes(LogicalKeyboardKey.numpadDivide), '\x1bOo');
expect(bytes(LogicalKeyboardKey.numpad1), isNull);
terminal.write('\x1b>\x1b[?1l');
expect(bytes(LogicalKeyboardKey.arrowUp), '\x1b[A');
expect(bytes(LogicalKeyboardKey.numpadAdd), isNull);
// Enter in line feed mode (LNM).
terminal.write('\x1b[20h');
expect(bytes(LogicalKeyboardKey.enter), '\r\n');
}, variant: linux);
testWidgets('plain typing, Cmd chords and AltGr are left to the emulator', (
tester,
) async {
expect(_bytes(LogicalKeyboardKey.keyA, character: 'a'), isNull);
expect(_bytes(LogicalKeyboardKey.keyA, mods: 'S', character: 'A'), isNull);
expect(_bytes(LogicalKeyboardKey.space, character: ' '), isNull);
expect(_bytes(LogicalKeyboardKey.keyK, mods: 'M', character: 'k'), isNull);
// German AltGr+Q types @.
expect(
_bytes(
LogicalKeyboardKey.keyQ,
mods: 'CA',
character: '@',
physical: PhysicalKeyboardKey.keyQ,
),
isNull,
);
}, variant: linux);
testWidgets('a Mac\'s Option is Meta while the setting is on', (
tester,
) async {
// Option+B types ∫; its logical key is B (natively) or ∫ (browsers).
expect(_bytes(LogicalKeyboardKey.keyB, mods: 'A', character: '∫'), '\x1bb');
expect(
_bytes(
_l(0x222b),
mods: 'A',
character: '∫',
physical: PhysicalKeyboardKey.keyB,
),
'\x1bb',
);
expect(
_bytes(
_l(0x0131),
mods: 'AS',
character: 'ı',
physical: PhysicalKeyboardKey.keyB,
),
'\x1bB',
);
expect(
_bytes(
_l(0x2265),
mods: 'A',
character: '≥',
physical: PhysicalKeyboardKey.period,
),
'\x1b.',
);
expect(_bytes(LogicalKeyboardKey.backspace, mods: 'A'), '\x1b\x7f');
expect(_bytes(LogicalKeyboardKey.slash, mods: 'C', character: '/'), '\x1f');
// Off, Option types its symbol; special keys keep the Alt parameter.
expect(
_bytes(
LogicalKeyboardKey.keyB,
mods: 'A',
character: '∫',
optionAsMeta: false,
),
isNull,
);
expect(
_bytes(LogicalKeyboardKey.backspace, mods: 'A', optionAsMeta: false),
'\x7f',
);
expect(
_bytes(LogicalKeyboardKey.arrowLeft, mods: 'A', optionAsMeta: false),
'\x1b[1;3D',
);
expect(
_bytes(LogicalKeyboardKey.arrowLeft, mods: 'A', optionAsMeta: true),
'\x1b[1;3D',
);
}, variant: mac);
ChatShellTerminalSession session(List<String> sent, bool Function() meta) =>
ChatShellTerminalSession(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': 'running',
'started_at': 1,
'output': '',
'output_bytes': 0,
'terminal': true,
'cols': 40,
'rows': 10,
})!,
onInput: sent.add,
onResize: (_, _) {},
optionAsMeta: meta,
);
testWidgets('the toolbar and soft keyboard keys go through the same '
'encoding', (tester) async {
final sent = <String>[];
final terminal = session(sent, () => true).terminal;
terminal.keyInput(TerminalKey.arrowUp);
terminal.write('\x1b[?1h');
terminal.keyInput(TerminalKey.arrowUp);
terminal.keyInput(TerminalKey.keyB, alt: true);
terminal.keyInput(TerminalKey.keyB, alt: true, shift: true);
terminal.keyInput(TerminalKey.slash, ctrl: true);
terminal.keyInput(TerminalKey.arrowLeft, alt: true);
// A plain letter is typed as its text instead.
expect(terminal.keyInput(TerminalKey.keyB), isFalse);
expect(sent, ['\x1b[A', '\x1bOA', '\x1bb', '\x1bB', '\x1f', '\x1b[1;3D']);
}, variant: linux);
testWidgets('on a Mac with Option as Meta off, the package does not '
'send its own Alt sequence', (tester) async {
final sent = <String>[];
var meta = false;
final terminal = session(sent, () => meta).terminal;
expect(terminal.keyInput(TerminalKey.keyB, alt: true), isFalse);
meta = true;
expect(terminal.keyInput(TerminalKey.keyB, alt: true), isTrue);
expect(sent, ['\x1bb']);
}, variant: mac);
}
@@ -0,0 +1,165 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_session.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_view.dart';
import 'package:xterm/core.dart';
ChatShellTerminalSession _session({int cols = 40, int rows = 10}) =>
ChatShellTerminalSession(
ChatShellRun.fromJson({
'id': 'run_1',
'command': 'sh',
'directory': '/w',
'status': 'running',
'started_at': 1,
'output': '',
'output_bytes': 0,
'terminal': true,
'cols': cols,
'rows': rows,
})!,
onInput: (_) {},
onResize: (_, _) {},
);
/// The rows on screen, trimmed.
List<String> _screen(Terminal terminal) {
final buffer = terminal.buffer;
final top = buffer.height - terminal.viewHeight;
return [
for (var y = 0; y < terminal.viewHeight; y++)
buffer.lines[top + y].getText().trimRight(),
];
}
String _cursorRow(Terminal terminal) => terminal
.buffer
.lines[terminal.buffer.absoluteCursorY]
.getText()
.trimRight();
/// Twelve output lines of 58 characters (two rows each at 40 columns), then
/// a prompt.
String _longLines() => [
for (var i = 0; i < 12; i++)
'line ${i.toString().padLeft(2, '0')} ${'x' * 50}',
r'$ ',
].join('\r\n');
void main() {
test('shrinking keeps the prompt on the cursor row at the bottom, and '
'growing brings the rows above back in order', () {
final terminal = _session().terminal..write(_longLines());
expect(terminal.buffer.cursorY, 9);
expect(_cursorRow(terminal), r'$');
terminal.resize(20, 5);
expect(terminal.buffer.cursorY, 4);
expect(_cursorRow(terminal), r'$');
// Line 11's second row (cut at 20 columns), then the prompt.
expect(_screen(terminal), [
'line 10 ${'x' * 12}',
'x' * 18,
'line 11 ${'x' * 12}',
'x' * 18,
r'$',
]);
// The shell redraws its prompt and runs a command: nothing lands on
// old rows and no rows merge.
terminal.write('\r\x1b[K\$ ls\r\nout\r\n\$ ');
expect(_screen(terminal).sublist(2), [r'$ ls', 'out', r'$']);
terminal.resize(40, 10);
expect(terminal.buffer.cursorY, 9);
expect(_cursorRow(terminal), r'$');
final screen = _screen(terminal);
expect(screen.sublist(7), [r'$ ls', 'out', r'$']);
// Rows cut while narrow stay cut: no stale text past column 20.
for (final row in screen) {
expect(row.length, lessThanOrEqualTo(20), reason: row);
}
});
test('a prompt redrawn while narrow does not grow stale text when the '
'terminal widens again', () {
final terminal = _session().terminal..write('\$ ${'abcdefghij' * 3}');
terminal.resize(10, 10);
terminal.write('\r\x1b[K\$ ');
terminal.resize(40, 10);
expect(_cursorRow(terminal), r'$');
expect(terminal.buffer.cursorX, 2);
});
test('a cleared screen and scrollback stay cleared across resizes', () {
final terminal = _session().terminal..write(_longLines());
terminal.write('\x1b[H\x1b[2J\x1b[3J\$ ');
terminal.resize(20, 5);
terminal.resize(40, 12);
expect(_screen(terminal), [r'$', for (var i = 0; i < 11; i++) '']);
expect(terminal.buffer.height, 12);
expect(terminal.buffer.absoluteCursorY, 0);
});
test('fewer rows than the output drop blank rows below the cursor first', () {
final terminal = _session().terminal..write('a\r\nb\r\n\$ ');
terminal.resize(40, 4);
expect(_screen(terminal), ['a', 'b', r'$', '']);
expect(terminal.buffer.absoluteCursorY, 2);
terminal.resize(40, 10);
expect(_screen(terminal).take(3), ['a', 'b', r'$']);
expect(terminal.buffer.absoluteCursorY, 2);
});
testWidgets('the view resizes the live terminal as its box changes, '
'keeping the prompt on the cursor row', (tester) async {
final session = _session(cols: 80, rows: 24);
final sizes = <(int, int)>[];
session.terminal.onResize = (cols, rows, _, _) => sizes.add((cols, rows));
session.terminal.write(_longLines());
var size = const Size(600, 300);
late StateSetter setSize;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: StatefulBuilder(
builder: (context, setState) {
setSize = setState;
return SizedBox.fromSize(
size: size,
child: ChatShellTerminalView(session: session, fill: true),
);
},
),
),
),
),
);
await tester.pump();
final wide = session.terminal.viewWidth;
// The prompt is the 13th line; the screen has room below it.
final row = session.terminal.buffer.cursorY;
expect(row, 12);
expect(_cursorRow(session.terminal), r'$');
setSize(() => size = const Size(250, 120));
await tester.pump();
final terminal = session.terminal;
expect(terminal.viewWidth, lessThan(wide));
expect(terminal.buffer.cursorY, terminal.viewHeight - 1);
expect(_cursorRow(terminal), r'$');
setSize(() => size = const Size(600, 300));
await tester.pump();
expect(terminal.viewWidth, wide);
// The rows that scrolled off come back above the prompt.
expect(terminal.buffer.cursorY, row);
expect(_cursorRow(terminal), r'$');
expect(_screen(terminal)[row - 1], startsWith('line 11'));
expect(_screen(terminal)[0], startsWith('line 00'));
expect(sizes.length, greaterThanOrEqualTo(3));
});
}
@@ -67,6 +67,35 @@ void main() {
expect(sent, hasLength(2));
});
test('query answers go to onReply; focus reports the laid out size', () {
final typed = <String>[];
final replies = <String>[];
final activations = <(int, int)>[];
final session = ChatShellTerminalSession(
_run('prompt'),
onInput: typed.add,
onReply: replies.add,
onResize: (_, _) {},
onActivate: (cols, rows) => activations.add((cols, rows)),
);
session.append(_run('prompt\x1b[6n'), '\x1b[6n', 6, 10);
session.terminal.textInput('y');
expect(replies, ['\x1b[1;7R']);
expect(typed, ['y']);
// Drawn at the run's own size until a view lays it out.
expect(session.viewSize, isNull);
session.activate();
expect(activations, isEmpty);
session.terminal.resize(90, 20);
expect(session.viewSize, (90, 20));
session.activate();
expect(activations, [(90, 20)]);
// A finished run claims nothing.
session.finish(_run('prompt', status: 'exited'));
session.activate();
expect(activations, hasLength(1));
});
test('a chunk after a hole redraws the held copy', () {
final session = ChatShellTerminalSession(
_run('a\r\n'),
@@ -85,7 +114,8 @@ void main() {
);
});
test('narrowing rewraps without pushing the first line out of view', () {
test('narrowing a live terminal cuts rows instead of rewrapping, keeping '
'the first line and the cursor on its own', () {
final session = ChatShellTerminalSession(
_run('first\r\n${'u' * 30}\r\nprompt: '),
onInput: (_) {},
@@ -95,11 +125,26 @@ void main() {
final buffer = session.terminal.buffer;
expect(buffer.height, 6);
expect(buffer.lines[0].getText().trim(), 'first');
expect(buffer.lines[3].getText().trim(), 'prompt:');
expect(buffer.absoluteCursorY, 3);
expect(buffer.lines[1].getText().trim(), 'u' * 20);
expect(buffer.lines[2].getText().trim(), 'prompt:');
expect(buffer.absoluteCursorY, 2);
expect(buffer.cursorX, 8);
});
test('finished output still rewraps to the width it is shown at', () {
final session = ChatShellTerminalSession(
_run('first\r\n${'u' * 30}\r\nend', status: 'exited'),
onInput: (_) {},
onResize: (_, _) {},
);
session.terminal.resize(20, 6);
final buffer = session.terminal.buffer;
expect(buffer.lines[0].getText().trim(), 'first');
expect(buffer.lines[1].getText().trim(), 'u' * 20);
expect(buffer.lines[2].getText().trim(), 'u' * 10);
expect(buffer.lines[3].getText().trim(), 'end');
});
test('a finished run counts the rows its output takes at a width', () {
final session = ChatShellTerminalSession(
_run('a\r\n${'x' * 50}\r\nend\r\n', status: 'exited'),
@@ -110,6 +110,109 @@ void main() {
);
}
Future<void> press(
WidgetTester tester,
LogicalKeyboardKey key, {
List<LogicalKeyboardKey> modifiers = const [],
String? character,
PhysicalKeyboardKey? physical,
}) async {
for (final modifier in modifiers) {
await tester.sendKeyDownEvent(modifier);
}
await tester.sendKeyDownEvent(
key,
character: character,
physicalKey: physical,
);
await tester.sendKeyUpEvent(key, physicalKey: physical);
for (final modifier in modifiers.reversed) {
await tester.sendKeyUpEvent(modifier);
}
await tester.pump();
}
testWidgets('the focused terminal sends xterm bytes for Alt, Ctrl and '
'modified keys, and the copy and paste keys still work', (tester) async {
await openRunning(tester, output: r'$ ');
await tester.tap(find.byType(TerminalView));
await tester.pump();
const alt = [LogicalKeyboardKey.altLeft];
const ctrl = [LogicalKeyboardKey.controlLeft];
const shift = [LogicalKeyboardKey.shiftLeft];
await press(tester, LogicalKeyboardKey.keyB, modifiers: alt);
await press(tester, LogicalKeyboardKey.keyF, modifiers: alt);
await press(tester, LogicalKeyboardKey.period, modifiers: alt);
await press(
tester,
LogicalKeyboardKey.keyB,
modifiers: [...alt, ...shift],
character: 'B',
);
await press(tester, LogicalKeyboardKey.backspace, modifiers: alt);
await press(tester, LogicalKeyboardKey.slash, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.bracketRight, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.arrowUp, modifiers: shift);
await press(tester, LogicalKeyboardKey.arrowLeft, modifiers: alt);
await press(tester, LogicalKeyboardKey.arrowRight, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.keyT, modifiers: ctrl);
await press(tester, LogicalKeyboardKey.keyX);
expect(
typed(),
'\x1bb\x1bf\x1b.\x1bB\x1b\x7f\x1f\x1d'
'\x1b[1;2A\x1b[1;3D\x1b[1;5C\x14x',
);
// Application cursor keys from the process's own mode switch.
gateway.emitOutput('run_t', '\x1b[?1h', 2);
await tester.pump();
gateway.calls.clear();
await press(tester, LogicalKeyboardKey.arrowUp);
expect(typed(), '\x1bOA');
// Ctrl-V is still paste, not ^V.
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async =>
call.method == 'Clipboard.getData' ? {'text': 'tok'} : null,
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
await press(tester, LogicalKeyboardKey.keyV, modifiers: ctrl);
for (var i = 0; i < 5; i++) {
await tester.pump(const Duration(milliseconds: 20));
}
expect(typed(), '\x1bOAtok');
await tester.pump(const Duration(milliseconds: 400));
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets(
'on a Mac, Option is Meta in the terminal',
(tester) async {
await openRunning(tester, output: r'$ ');
await tester.tap(find.byType(TerminalView));
await tester.pump();
await press(
tester,
LogicalKeyboardKey.keyB,
modifiers: [LogicalKeyboardKey.altLeft],
character: '∫',
);
await press(
tester,
const LogicalKeyboardKey(0x2202),
modifiers: [LogicalKeyboardKey.altLeft],
character: '∂',
physical: PhysicalKeyboardKey.keyD,
);
expect(typed(), '\x1bb\x1bd');
await tester.pump(const Duration(milliseconds: 400));
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
testWidgets('on Linux, Ctrl-C copies a selection and interrupts without one; '
'Ctrl-Insert copies too', (tester) async {
await openRunning(tester, output: 'Paste your token: ');
@@ -274,6 +377,47 @@ void main() {
expect(gateway.bodies('chat_shell_input'), isEmpty);
});
testWidgets('focusing the terminal claims it at its size; typing carries '
'the size and query answers are marked', (tester) async {
await openRunning(tester, output: 'size? \x1b[6n');
await tester.pump(const Duration(milliseconds: 200));
final laidOut = gateway.bodies('chat_shell_resize').single;
// The replayed query is not answered; nothing was claimed yet.
expect(gateway.bodies('chat_shell_input'), isEmpty);
await tester.tap(find.byType(TerminalView));
await tester.pump();
final claim = gateway.bodies('chat_shell_resize').last;
expect(claim['activate'], isTrue);
expect((claim['cols'], claim['rows']), (laidOut['cols'], laidOut['rows']));
// Typing carries this client's size.
await tester.sendKeyEvent(LogicalKeyboardKey.keyG);
await tester.pump();
var inputs = gateway.bodies('chat_shell_input');
expect(inputs.single['data'], 'g');
expect(inputs.single['reply'], isNull);
expect(
(inputs.single['cols'], inputs.single['rows']),
(laidOut['cols'], laidOut['rows']),
);
// A live query is answered with the answer marked, without a size.
gateway.emitOutput('run_t', '\x1b[6n', 'size? \x1b[6n'.length);
await tester.pump();
await tester.pump();
inputs = gateway.bodies('chat_shell_input');
expect(inputs.last['data'], '\x1b[1;7R');
expect(inputs.last['reply'], isTrue);
expect(inputs.last['cols'], isNull);
// Focusing again after the focus left claims again.
FocusManager.instance.primaryFocus?.unfocus();
await tester.pump();
await tester.tap(find.byType(TerminalView));
await tester.pump();
expect(
gateway.bodies('chat_shell_resize').where((b) => b['activate'] == true),
hasLength(2),
);
}, variant: TargetPlatformVariant.only(TargetPlatform.linux));
testWidgets('coloured output is drawn without its escape codes', (
tester,
) async {
@@ -0,0 +1,101 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/shell/chat_shell_terminals.dart';
import 'package:pipelines_app/features/terminal/terminal_info.dart';
import 'package:pipelines_app/features/terminal/terminal_tab.dart';
import 'terminal_fixtures.dart';
void main() {
testWidgets('answers are marked, typing carries the size, focus activates', (
tester,
) async {
final gateway = TerminalGateway();
final tab = TerminalTab(
machineId: 'm',
machineName: 'm',
gateway: gateway,
info: TerminalInfo.fromJson(gateway.add('t1')),
);
// Before a view lays it out, focus has no size to claim.
tab.session.activate();
await tester.pump();
expect(gateway.bodies('terminal_resize'), isEmpty);
tab.session.terminal.resize(100, 30);
await tester.pump(chatShellResizeDelay);
expect(gateway.bodies('terminal_resize'), [
{'terminal_id': 't1', 'cols': 100, 'rows': 30},
]);
// A cursor position query in the output: the answer is marked.
tab.frame({'output': '\x1b[6n', 'offset': 0, 'end': 4});
await tester.pump();
// Typing carries the size this client draws at.
tab.session.terminal.textInput('ls');
await tester.pump();
expect(gateway.bodies('terminal_input'), [
{'terminal_id': 't1', 'data': '\x1b[1;1R', 'reply': true},
{'terminal_id': 't1', 'data': 'ls', 'cols': 100, 'rows': 30},
]);
// A view gaining focus claims the terminal at once, at its size.
tab.session.activate();
await tester.pump();
expect(gateway.bodies('terminal_resize').last, {
'terminal_id': 't1',
'cols': 100,
'rows': 30,
'activate': true,
});
// A new connection reports its size again.
tab.attach(gateway, TerminalInfo.fromJson(gateway.terminals['t1']!));
await tester.pump(chatShellResizeDelay);
expect(gateway.bodies('terminal_resize'), hasLength(3));
expect(gateway.bodies('terminal_resize').last, {
'terminal_id': 't1',
'cols': 100,
'rows': 30,
});
tab.dispose();
});
test('the input pipe keeps answers and typing apart, in order', () async {
final sent = <(String, bool)>[];
final pipe = ChatShellInputPipe((data, reply) async {
sent.add((data, reply));
await Future<void>.delayed(Duration.zero);
}, (_) {});
pipe.add('a');
// While the first is in flight, typing, an answer and typing wait.
pipe.add('b');
pipe.add('c');
pipe.add('\x1b[1;1R', reply: true);
pipe.add('d');
pipe.add('${'x' * chatShellInputChunk}y');
await pumpEventQueue();
expect(sent, [
('a', false),
('bc', false),
('\x1b[1;1R', true),
('d${'x' * (chatShellInputChunk - 1)}', false),
('xy', false),
]);
});
test('a refusal drops what was waiting and reports once', () async {
final failures = <Object>[];
final sent = <String>[];
final pipe = ChatShellInputPipe((data, reply) async {
sent.add(data);
await Future<void>.delayed(Duration.zero);
throw StateError('not running');
}, failures.add);
pipe.add('a');
pipe.add('b');
pipe.add('?', reply: true);
await pumpEventQueue();
expect(sent, ['a']);
expect(failures, hasLength(1));
});
}
+11 -3
View File
@@ -90,9 +90,7 @@ class TerminalTestAppState extends State<TerminalTestApp> {
child: Scaffold(
appBar: AppBar(
title: const Text('App'),
actions: [
TerminalToggleButton(layout: widget.layout),
],
actions: [TerminalToggleButton(layout: widget.layout)],
),
body: const TextField(key: appField),
),
@@ -125,6 +123,8 @@ Future<void> chord(
}
}
/// Alt+T: shows or hides the terminal from outside it (inside, it is the
/// shell's ESC t).
Future<void> altT(WidgetTester tester, {bool settle = true}) => chord(
tester,
LogicalKeyboardKey.keyT,
@@ -132,6 +132,14 @@ Future<void> altT(WidgetTester tester, {bool settle = true}) => chord(
settle: settle,
);
/// Ctrl+`: shows or hides the terminal wherever the keyboard is.
Future<void> toggleTerminal(WidgetTester tester, {bool settle = true}) => chord(
tester,
LogicalKeyboardKey.backquote,
[LogicalKeyboardKey.controlLeft],
settle: settle,
);
Future<void> ctrlTab(WidgetTester tester, {bool reverse = false}) => chord(
tester,
LogicalKeyboardKey.tab,
@@ -57,9 +57,7 @@ Future<Widget?> _pumpBar(
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: actions == null
? bar
: TerminalScope(actions: actions, child: bar),
home: actions == null ? bar : TerminalScope(actions: actions, child: bar),
),
);
await tester.pump();
@@ -106,7 +106,7 @@ void main() {
// Hidden again: the composer that had the keyboard gets it back, and
// Ctrl+Tab is the chat's once more.
await altT(tester);
await toggleTerminal(tester);
expect(_composer(tester, 'a').focusNode.hasPrimaryFocus, isTrue);
await ctrlTab(tester);
expect(workspace.activePane?.sessionId, 'b');
@@ -48,7 +48,7 @@ void main() {
await pumpTerminalApp(tester, hub: hub, layout: layout);
await tester.tap(find.byKey(appField));
await tester.pump();
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump(const Duration(milliseconds: 100));
expect(panelFinder, findsOneWidget);
// Midway: the app has given up part of the panel's height, and the
@@ -61,7 +61,7 @@ void main() {
expect(appBottom(tester), shown);
expect(panelOpacity(tester), 1);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
// The keyboard is back in the field at once; the panel leaves after.
expect(appFieldFocused(tester), isTrue);
await tester.pump(const Duration(milliseconds: 100));
@@ -77,7 +77,7 @@ void main() {
'shrinks away', (tester) async {
layout.setMode(TerminalMode.float);
await pumpTerminalApp(tester, hub: hub, layout: layout);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
// The window is built, then its motion starts.
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
@@ -87,7 +87,7 @@ void main() {
expect(appBottom(tester), 800);
await tester.pumpAndSettle();
expect(floatScale(tester).scale.value, 1);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump(const Duration(milliseconds: 100));
// Hiding: no longer shown, still painted while it shrinks away.
expect(floatFinder, findsNothing);
@@ -100,7 +100,7 @@ void main() {
// AnimationSpeedController plays animations at half speed this way.
timeDilation = 2;
await pumpTerminalApp(tester, hub: hub, layout: layout);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump(const Duration(milliseconds: 300));
expect(appBottom(tester), inExclusiveRange(shown, 800));
await tester.pumpAndSettle();
@@ -112,16 +112,16 @@ void main() {
tester,
) async {
await pumpTerminalApp(tester, hub: hub, layout: layout, reduceMotion: true);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump();
expect(appBottom(tester), shown);
expect(panelOpacity(tester), 1);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump();
expect(panelFinder, findsNothing);
expect(appBottom(tester), 800);
layout.setMode(TerminalMode.float);
await altT(tester, settle: false);
await toggleTerminal(tester, settle: false);
await tester.pump();
expect(floatScale(tester).scale.value, 1);
// The emulator's size reaches the server after its debounce.
@@ -31,16 +31,48 @@ void main() {
String key(String id) => terminalKey('mac', id);
/// Each toggle chord, and what it sends to the shell from inside the
/// terminal (null: it hides the terminal there too).
const toggles = {
'Alt+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.altLeft),
'Ctrl+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.controlLeft),
'Cmd+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.metaLeft),
'Ctrl+`': (LogicalKeyboardKey.backquote, LogicalKeyboardKey.controlLeft),
'Alt+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.altLeft, '\x1bt'),
'Ctrl+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.controlLeft, '\x14'),
'Cmd+T': (LogicalKeyboardKey.keyT, LogicalKeyboardKey.metaLeft, null),
'Ctrl+`': (
LogicalKeyboardKey.backquote,
LogicalKeyboardKey.controlLeft,
null,
),
};
for (final mode in TerminalMode.values) {
for (final MapEntry(key: name, value: (letter, modifier))
for (final MapEntry(key: name, value: (letter, modifier, sent))
in toggles.entries) {
if (sent != null) {
desktopTestWidgets(
'$name shows the ${mode.label.toLowerCase()} from a text field; '
'inside the terminal it reaches the shell',
(tester) async {
layout.setMode(mode);
await pumpTerminalApp(tester, hub: hub, layout: layout);
await tester.tap(find.byKey(appField));
await tester.pump();
await chord(tester, letter, [modifier]);
expect(layout.visible, isTrue);
expect(find.text('t'), findsNothing);
expect(terminalFocused(key('term_a')), isTrue);
await chord(tester, letter, [modifier]);
expect(layout.visible, isTrue);
expect(mac.bodies('terminal_input').last['data'], sent);
// Cmd+T and Ctrl+` still hide it from inside.
await chord(tester, LogicalKeyboardKey.backquote, [
LogicalKeyboardKey.controlLeft,
]);
expect(layout.visible, isFalse);
await tester.pump(const Duration(milliseconds: 300));
},
);
continue;
}
desktopTestWidgets(
'$name toggles the ${mode.label.toLowerCase()} from a text '
'field and from inside the terminal',
@@ -58,8 +90,7 @@ void main() {
// The shortcut never types into the field it was pressed in.
expect(find.text('t'), findsNothing);
expect(terminalFocused(key('term_a')), isTrue);
// Inside the terminal the same keys hide it instead of reaching the
// shell (Ctrl+T would be transpose-chars there).
// Inside the terminal the same keys hide it.
final typed = mac.bodies('terminal_input').length;
await chord(tester, letter, [modifier]);
expect(surface, findsNothing);
@@ -79,6 +110,54 @@ void main() {
timeStamp: Duration.zero,
);
expect(terminalToggleShortcut(event, _AltHeld()), isTrue);
// Inside the terminal Option+T is the shell's (ESC t, or † when Option
// is not Meta).
expect(
terminalToggleShortcut(event, _AltHeld(), inTerminal: true),
isFalse,
);
});
test('inside the terminal only Cmd+T and Ctrl+` toggle', () {
KeyDownEvent down(LogicalKeyboardKey key, PhysicalKeyboardKey physical) =>
KeyDownEvent(
physicalKey: physical,
logicalKey: key,
timeStamp: Duration.zero,
);
final t = down(LogicalKeyboardKey.keyT, PhysicalKeyboardKey.keyT);
final tick = down(
LogicalKeyboardKey.backquote,
PhysicalKeyboardKey.backquote,
);
bool inside(KeyDownEvent event, HardwareKeyboard keyboard) =>
terminalToggleShortcut(event, keyboard, inTerminal: true);
expect(inside(t, _AltHeld()), isFalse);
expect(inside(t, _Held(control: true)), isFalse);
expect(inside(t, _Held(meta: true)), isTrue);
expect(inside(tick, _Held(control: true)), isTrue);
expect(terminalToggleShortcut(t, _Held(control: true)), isTrue);
});
test('the menu and cheatsheet say which keys reach the shell', () {
expect(
const TerminalShortcutLabels(
web: false,
platform: TargetPlatform.macOS,
).inTerminalNote,
'Inside the terminal, Option+T and Ctrl+T reach the shell; Cmd+T or '
'Ctrl+` hides it.',
);
const linuxWeb = TerminalShortcutLabels(
web: true,
platform: TargetPlatform.linux,
);
expect(
linuxWeb.inTerminalNote,
'Inside the terminal, Alt+T and Ctrl+T reach the shell; Ctrl+` hides '
'it.',
);
expect(linuxWeb.summary, contains(linuxWeb.inTerminalNote));
});
desktopTestWidgets('holding the chord toggles once and types nothing', (
@@ -127,7 +206,7 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.keyX);
await tester.pump();
expect(mac.bodies('terminal_input').last['data'], 'x');
await altT(tester);
await toggleTerminal(tester);
expect(appFieldFocused(tester), isTrue);
// The bar button focuses it as well.
await tester.tap(find.byIcon(Icons.terminal));
@@ -170,7 +249,7 @@ void main() {
await ctrlTab(tester);
expect(hub.selected!.info.id, 'term_a');
expect(terminalFocused(key('term_a')), isTrue);
await altT(tester);
await toggleTerminal(tester);
await ctrlTab(tester);
expect(hub.selected!.info.id, 'term_a');
});
@@ -195,8 +274,8 @@ void main() {
expect(empty.bodies('terminal_open'), hasLength(1));
expect(bare.tabs, hasLength(1));
expect(terminalFocused(bare.tabs.single.key), isTrue);
await altT(tester);
await altT(tester);
await toggleTerminal(tester);
await toggleTerminal(tester);
expect(empty.bodies('terminal_open'), hasLength(1));
});
@@ -220,7 +299,7 @@ void main() {
await ctrlTab(tester, reverse: true);
expect(hub.selected!.info.id, 'term_c');
expect(terminalFocused(key('term_c')), isTrue);
await chord(tester, LogicalKeyboardKey.keyT, [
await chord(tester, LogicalKeyboardKey.backquote, [
LogicalKeyboardKey.controlLeft,
]);
expect(find.widgetWithText(AppBar, 'Terminal'), findsNothing);
@@ -284,6 +363,21 @@ void main() {
});
}
/// A keyboard with the given modifiers held.
class _Held extends HardwareKeyboard {
_Held({this.control = false, this.meta = false});
final bool control;
final bool meta;
@override
bool get isAltPressed => false;
@override
bool get isControlPressed => control;
@override
bool get isMetaPressed => meta;
@override
bool get isShiftPressed => false;
}
/// A keyboard on which only Alt (Option) is held.
class _AltHeld extends HardwareKeyboard {
@override
@@ -265,6 +265,39 @@ void main() {
expect(layout.mode, TerminalMode.panel);
});
Future<void> pumpSettings(WidgetTester tester) => tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: SettingsTerminalSection(layout: layout),
),
),
),
);
const optionAsMeta = ValueKey('settings-terminal-option-as-meta');
desktopTestWidgets('on a Mac, Settings chooses whether Option is Meta, '
'saved with the layout', (tester) async {
await pumpSettings(tester);
expect(layout.optionAsMeta, isTrue);
await tester.tap(find.byKey(optionAsMeta));
await tester.pumpAndSettle();
expect(layout.optionAsMeta, isFalse);
expect(saved()['option_as_meta'], isFalse);
final restored = TerminalLayout(store: store);
await restored.restore();
expect(restored.optionAsMeta, isFalse);
});
testWidgets(
'elsewhere Alt is always Meta and there is no Option switch',
(tester) async {
await pumpSettings(tester);
expect(find.byKey(optionAsMeta), findsNothing);
},
variant: TargetPlatformVariant.only(TargetPlatform.linux),
);
desktopTestWidgets(
'a narrow window opens the terminal full screen with the key '
'toolbar',
@@ -0,0 +1,75 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'paint_fixture.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final size = fixturePainter().cellSize;
final w = size.width.ceil();
final h = size.height.ceil();
Future<Pixels> cell(CellData data) => Pixels.paint(
w,
h * 2, // room for decorations drawn below the cell
(canvas) => fixturePainter().paintCell(canvas, Offset.zero, data),
);
/// The rows of the cell that contain painted pixels.
Future<List<int>> inkRows(CellData data) async {
final pixels = await cell(data);
return [
for (var y = 0; y < h * 2; y++)
if (pixels.rowHasInk(y)) y,
];
}
test('a plain space draws nothing', () async {
expect(await inkRows(cellOf(' ')), isEmpty);
});
test('strikethrough (SGR 9) draws a line through the middle', () async {
final rows = await inkRows(cellOf(' ', flags: CellAttr.strikethrough));
expect(rows, isNotEmpty);
expect(rows.every((y) => y > h * 0.2 && y < h * 0.8), isTrue);
});
test('overline (SGR 53) draws at the top, underline at the bottom', () async {
final over = await inkRows(cellOf(' ', flags: CellAttr.overline));
expect(over, isNotEmpty);
expect(over.first, lessThan(h * 0.3));
final under = await inkRows(cellOf(' ', flags: CellAttr.underline));
expect(under, isNotEmpty);
expect(under.last, greaterThan(h * 0.6));
});
test('double underline (SGR 21) draws two lines', () async {
const doubled = CellAttr.underline | (2 << CellAttr.underlineStyleShift);
final single = await inkRows(cellOf(' ', flags: CellAttr.underline));
final two = await inkRows(cellOf(' ', flags: doubled));
expect(two.length, greaterThan(single.length));
});
test(
'concealed text (SGR 8) keeps its background, hides the glyph',
() async {
final shown = await cell(cellOf('M'));
expect(shown.count(foregroundColor), greaterThan(0));
final hidden = await cell(cellOf('M', flags: CellAttr.invisible));
expect(hidden.count(foregroundColor), 0);
final inverse = await cell(
cellOf('M', flags: CellAttr.invisible | CellAttr.inverse),
);
expect(
inverse.count(foregroundColor),
greaterThan(0),
reason: 'background',
);
expect(inverse.count(backgroundColor), 0, reason: 'no glyph');
},
);
}
@@ -0,0 +1,61 @@
import 'package:flutter_test/flutter_test.dart';
import 'xterm_fixture.dart';
void main() {
test('DCS, APC, PM and SOS bodies are swallowed, not printed', () {
final t = FixtureTerminal()
..feed('a\x1bP+q544e\x1b\\b')
..feed('\x1b_Gf=24;AAAA\x1b\\c')
..feed('\x1b^private\x1b\\d')
..feed('\x1bXstring\x1b\\e');
expect(t.row(0), 'abcde');
});
test('a control string split across writes is still swallowed', () {
final t = FixtureTerminal()
..feed('x\x1bPtmux;')
..feed('\x1b')
..feed('\x1b[31mhidden')
..feed('\x1b')
..feed('\\y');
// An ESC that is not ST aborts the string, as on a VT; the next ESC
// starts a CSI, so the output after it is ordinary text again.
expect(t.row(0), 'xhiddeny');
expect(t.cell(1, 0).foreground, named(1));
});
test('ST split between writes ends the string', () {
final t = FixtureTerminal()
..feed('1\x1bPq#0;2;0;0;0#0~~@@')
..feed('\x1b')
..feed('\\2');
expect(t.row(0), '12');
});
test('CAN aborts a control string', () {
final t = FixtureTerminal()..feed('\x1bPjunk\x18ok');
expect(t.row(0), 'ok');
});
test('DECRQSS m reports the current SGR', () {
final t = FixtureTerminal()..feed('\x1b[1;4:3;38;5;196;48;2;1;2;3m');
t.takeReplies();
t.feed('\x1bP\$qm\x1b\\');
expect(t.takeReplies(), '\x1bP1\$r0;1;4:3;38;5;196;48;2;1;2;3m\x1b\\');
expect(t.row(0), '');
});
test('DECRQSS r reports margins; unknown requests are refused', () {
final t = FixtureTerminal()..feed('\x1b[2;4r');
t.feed('\x1bP\$qr\x1b\\');
expect(t.takeReplies(), '\x1bP1\$r2;4r\x1b\\');
t.feed('\x1bP\$qbogus\x1b\\');
expect(t.takeReplies(), '\x1bP0\$r\x1b\\');
});
test('a DCS other than DECRQSS sends nothing', () {
final t = FixtureTerminal()..feed('\x1bP+q544e\x1b\\');
expect(t.takeReplies(), '');
});
}
@@ -0,0 +1,65 @@
import 'package:flutter_test/flutter_test.dart';
import 'xterm_fixture.dart';
void main() {
test('CSI s / CSI u save and restore the cursor (SCOSC / SCORC)', () {
final t = FixtureTerminal()..feed('\x1b[2;3H\x1b[s\x1b[5;9Hx\x1b[uy');
expect(t.charAt(2, 1), 'y');
expect(t.charAt(8, 4), 'x');
expect(t.buffer.cursorX, 3);
expect(t.buffer.cursorY, 1);
});
test('CSI ? u (kitty keyboard query) does not restore the cursor', () {
final t = FixtureTerminal()..feed('\x1b[s\x1b[3;3H\x1b[?u');
expect(t.buffer.cursorX, 2);
expect(t.buffer.cursorY, 2);
expect(t.takeReplies(), '');
});
test('CHT moves forward by tab stops and stops at the last column', () {
final t = FixtureTerminal()..feed('\x1b[I');
expect(t.buffer.cursorX, 8);
t.feed('\x1b[2I');
expect(t.buffer.cursorX, 19);
});
test('CBT moves back by tab stops and stops at column 0', () {
final t = FixtureTerminal()..feed('\x1b[1;19H\x1b[Z');
expect(t.buffer.cursorX, 16);
t.feed('\x1b[5Z');
expect(t.buffer.cursorX, 0);
});
test('HTS sets a tab stop that HT and CBT use', () {
final t = FixtureTerminal()..feed('\x1b[1;4H\x1bH\r\t');
expect(t.buffer.cursorX, 3);
t.feed('\x1b[1;7H\x1b[Z');
expect(t.buffer.cursorX, 3);
});
test('HPA, HPR and VPR', () {
final t = FixtureTerminal()..feed('\x1b[7`');
expect(t.buffer.cursorX, 6);
t.feed('\x1b[3a');
expect(t.buffer.cursorX, 9);
t.feed('\x1b[a');
expect(t.buffer.cursorX, 10);
t.feed('\x1b[2e');
expect(t.buffer.cursorY, 2);
t.feed('\x1b[e');
expect(t.buffer.cursorY, 3);
});
test('DSR 6 reports the one-based cursor position', () {
final t = FixtureTerminal()..feed('\x1b[3;7H\x1b[6n');
expect(t.takeReplies(), '\x1b[3;7R');
});
test('zero counts mean one', () {
final t = FixtureTerminal()..feed('\x1b[0C\x1b[0B');
expect(t.buffer.cursorX, 1);
expect(t.buffer.cursorY, 1);
});
}
@@ -0,0 +1,97 @@
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'paint_fixture.dart';
import 'xterm_fixture.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('DECSCUSR', () {
test('stores the requested shape and blinking', () {
final t = FixtureTerminal();
expect(t.terminal.cursorShape, isNull);
const expected = {
1: (TerminalCursorType.block, true),
2: (TerminalCursorType.block, false),
3: (TerminalCursorType.underline, true),
4: (TerminalCursorType.underline, false),
5: (TerminalCursorType.verticalBar, true),
6: (TerminalCursorType.verticalBar, false),
};
for (final MapEntry(key: ps, value: (shape, blinks))
in expected.entries) {
t.feed('\x1b[$ps q');
expect(t.terminal.cursorShape, shape, reason: 'Ps $ps');
expect(t.terminal.cursorShapeBlinks, blinks, reason: 'Ps $ps');
}
t.feed('\x1b[0 q');
expect(t.terminal.cursorShape, isNull);
t.feed('\x1b[6 q\x1bc');
expect(t.terminal.cursorShape, isNull);
});
test('does not print and is reported by DECRQSS', () {
final t = FixtureTerminal()..feed('\x1b[5 qa');
expect(t.row(0), 'a');
t.feed('\x1bP\$q q\x1b\\');
expect(t.takeReplies(), '\x1bP1\$r5 q\x1b\\');
});
});
group('cursor painting', () {
final cell = fixturePainter().cellSize;
final w = cell.width.ceil();
final h = cell.height.ceil();
final area = Rect.fromLTWH(0, 0, cell.width, cell.height);
Future<Pixels> cursor(TerminalCursorType type, {CellData? under}) =>
Pixels.paint(
w * 2,
h,
(canvas) => fixturePainter().paintCursor(
canvas,
Offset.zero,
cursorType: type,
cell: under,
),
);
test('a block cursor draws the character under it inverted', () async {
final empty = await cursor(TerminalCursorType.block);
expect(empty.count(backgroundColor, area), 0);
expect(empty.count(cursorColor, area), greaterThan(0));
final withChar = await cursor(
TerminalCursorType.block,
under: cellOf('M'),
);
// The test font's glyphs fill the whole cell; before the fix the
// block hid them and every pixel was the cursor colour.
expect(
withChar.count(backgroundColor, area),
greaterThan(0),
reason: 'the glyph is drawn in the background colour',
);
});
test('a block cursor over a wide character spans two cells', () async {
final pixels = await cursor(
TerminalCursorType.block,
under: cellOf('中', width: 2),
);
expect(pixels.at(w + w ~/ 2, 0), cursorColor);
});
test('underline and bar cursors sit in the cell, not at the top', () async {
final underline = await cursor(TerminalCursorType.underline);
expect(underline.at(w ~/ 2, h - 1), cursorColor);
expect(underline.at(w ~/ 2, 0), isNot(cursorColor));
final bar = await cursor(TerminalCursorType.verticalBar);
expect(bar.at(0, h ~/ 2), cursorColor);
expect(bar.at(w - 1, h ~/ 2), isNot(cursorColor));
});
});
}
@@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
test('focusInput sends CSI I / CSI O only with ?1004 set', () {
final t = FixtureTerminal();
expect(t.terminal.focusInput(true), isFalse);
expect(t.takeReplies(), '');
t.feed('\x1b[?1004h');
expect(t.terminal.focusInput(true), isTrue);
t.terminal.focusInput(false);
expect(t.takeReplies(), '\x1b[I\x1b[O');
t.feed('\x1b[?1004l');
t.terminal.focusInput(true);
expect(t.takeReplies(), '');
});
testWidgets('TerminalView reports its focus changes', (tester) async {
final terminal = Terminal();
final replies = <String>[];
terminal.onOutput = replies.add;
final focus = FocusNode();
addTearDown(focus.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: TerminalView(
terminal,
focusNode: focus,
hardwareKeyboardOnly: true,
),
),
),
);
terminal.write('\x1b[?1004h');
focus.requestFocus();
await tester.pump();
focus.unfocus();
await tester.pump();
expect(replies.join(), '\x1b[I\x1b[O');
});
}
@@ -0,0 +1,45 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
test('leaving the 1049 alternate screen restores the saved cursor', () {
final t = FixtureTerminal()..feed('main\x1b[3;5H\x1b[31m');
t.feed('\x1b[?1049h');
expect(t.terminal.isUsingAltBuffer, isTrue);
t.feed('\x1b[1;1H\x1b[0malt screen');
t.feed('\x1b[?1049l');
expect(t.terminal.isUsingAltBuffer, isFalse);
expect(t.buffer.cursorX, 4);
expect(t.buffer.cursorY, 2);
expect(t.row(0), 'main');
t.feed('z');
expect(t.cell(4, 2).foreground, named(NamedColor.red));
});
test('DECCKM (CSI ? 1 h/l) is its own mode, not the keypad mode', () {
final t = FixtureTerminal();
expect(t.terminal.cursorKeysMode, isFalse);
t.feed('\x1b[?1h');
expect(t.terminal.cursorKeysMode, isTrue);
expect(t.terminal.appKeypadMode, isFalse);
t.feed('\x1b[?1l\x1b=');
expect(t.terminal.cursorKeysMode, isFalse);
expect(t.terminal.appKeypadMode, isTrue);
});
test('arrow keys follow DECCKM, not DECKPAM', () {
final t = FixtureTerminal();
t.terminal.keyInput(TerminalKey.arrowUp);
expect(t.takeReplies(), '\x1b[A');
t.feed('\x1b=');
t.terminal.keyInput(TerminalKey.arrowUp);
expect(t.takeReplies(), '\x1b[A');
t.feed('\x1b>\x1b[?1h');
t.terminal.keyInput(TerminalKey.arrowUp);
expect(t.takeReplies(), '\x1bOA');
});
}
@@ -0,0 +1,105 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
const down = TerminalMouseButtonState.down;
const up = TerminalMouseButtonState.up;
const at = CellOffset(4, 2); // column 5, row 3 one-based
String report(
String modes,
TerminalMouseButton button,
TerminalMouseButtonState state, {
bool motion = false,
bool ctrl = false,
}) {
final t = FixtureTerminal()..feed(modes);
t.terminal.mouseInput(button, state, at, motion: motion, ctrl: ctrl);
return t.takeReplies();
}
test('SGR wheel is 64 up and 65 down', () {
const sgr = '\x1b[?1000h\x1b[?1006h';
expect(report(sgr, TerminalMouseButton.wheelUp, down), '\x1b[<64;5;3M');
expect(report(sgr, TerminalMouseButton.wheelDown, down), '\x1b[<65;5;3M');
expect(report(sgr, TerminalMouseButton.wheelUp, up), '');
});
test('default encoding: 32 + code, 32 + column, 32 + row', () {
const normal = '\x1b[?1000h';
expect(
report(normal, TerminalMouseButton.left, down),
'\x1b[M\x20\x25\x23',
);
expect(report(normal, TerminalMouseButton.left, up), '\x1b[M\x23\x25\x23');
expect(
report(normal, TerminalMouseButton.wheelDown, down),
'\x1b[M\x61\x25\x23',
);
});
test('SGR reports which button was released', () {
const sgr = '\x1b[?1000h\x1b[?1006h';
expect(report(sgr, TerminalMouseButton.middle, down), '\x1b[<1;5;3M');
expect(report(sgr, TerminalMouseButton.middle, up), '\x1b[<1;5;3m');
expect(report(sgr, TerminalMouseButton.right, up), '\x1b[<2;5;3m');
});
test('modifiers add 4/8/16', () {
const sgr = '\x1b[?1000h\x1b[?1006h';
expect(
report(sgr, TerminalMouseButton.left, down, ctrl: true),
'\x1b[<16;5;3M',
);
});
group('motion', () {
test('1000 reports no motion', () {
expect(
report(
'\x1b[?1000h\x1b[?1006h',
TerminalMouseButton.left,
down,
motion: true,
),
'',
);
});
test('1002 reports drags with the button held, plus 32', () {
const drag = '\x1b[?1002h\x1b[?1006h';
expect(
report(drag, TerminalMouseButton.left, down, motion: true),
'\x1b[<32;5;3M',
);
expect(report(drag, TerminalMouseButton.none, down, motion: true), '');
});
test('1003 reports motion without a button as 35', () {
expect(
report(
'\x1b[?1003h\x1b[?1006h',
TerminalMouseButton.none,
down,
motion: true,
),
'\x1b[<35;5;3M',
);
expect(
report('\x1b[?1003h', TerminalMouseButton.none, down, motion: true),
'\x1b[M\x43\x25\x23',
);
});
});
test('X10 mode (9) reports presses only', () {
expect(
report('\x1b[?9h', TerminalMouseButton.left, down),
'\x1b[M\x20\x25\x23',
);
expect(report('\x1b[?9h', TerminalMouseButton.left, up), '');
expect(report('\x1b[?9h', TerminalMouseButton.wheelUp, down), '');
});
}
@@ -0,0 +1,159 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
/// A TerminalView placed away from the window's origin, so a report that
/// used window coordinates instead of the view's own would be wrong.
class _Harness {
_Harness(this.tester);
final WidgetTester tester;
final terminal = Terminal();
final controller = TerminalController();
final replies = <String>[];
Future<void> pump() async {
terminal.onOutput = replies.add;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Padding(
padding: const EdgeInsets.only(left: 100, top: 60),
child: SizedBox(
width: 400,
height: 200,
child: TerminalView(
terminal,
controller: controller,
hardwareKeyboardOnly: true,
),
),
),
),
),
);
}
TerminalViewState get _view =>
tester.state<TerminalViewState>(find.byType(TerminalView));
/// The global centre of zero-based screen cell ([x], [y]).
Offset cell(int x, int y) {
final render = _view.renderTerminal;
final size = render.cellSize;
return render.localToGlobal(
Offset((x + 0.5) * size.width, (y + 0.5) * size.height),
);
}
double get lineHeight => _view.renderTerminal.lineHeight;
String take() {
final all = replies.join();
replies.clear();
return all;
}
}
void main() {
testWidgets('a left drag with 1002 is reported, not selected', (
tester,
) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('\x1b[?1002h\x1b[?1006h');
await tester.pump();
final gesture = await tester.startGesture(
h.cell(1, 1),
kind: PointerDeviceKind.mouse,
);
await gesture.moveTo(h.cell(4, 1));
await gesture.moveTo(h.cell(6, 2));
await gesture.up();
await tester.pumpAndSettle();
expect(h.take(), '\x1b[<0;2;2M\x1b[<32;5;2M\x1b[<32;7;3M\x1b[<0;7;3m');
expect(h.controller.selection, isNull);
});
testWidgets('1003 reports plain motion; 1000 does not', (tester) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('\x1b[?1003h\x1b[?1006h');
final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: h.cell(0, 0));
await gesture.moveTo(h.cell(3, 2));
expect(h.take(), '\x1b[<35;4;3M');
h.terminal.write('\x1b[?1003l\x1b[?1000h');
await gesture.moveTo(h.cell(5, 2));
expect(h.take(), '');
await gesture.removePointer();
});
testWidgets('a middle click is reported as middle press and release', (
tester,
) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('\x1b[?1000h\x1b[?1006h');
final gesture = await tester.startGesture(
h.cell(2, 0),
kind: PointerDeviceKind.mouse,
buttons: kMiddleMouseButton,
);
await gesture.up();
await tester.pumpAndSettle();
expect(h.take(), '\x1b[<1;3;1M\x1b[<1;3;1m');
});
testWidgets('Shift+drag selects text even while the program has the mouse', (
tester,
) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('hello world\x1b[?1002h\x1b[?1006h');
await tester.pump();
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
final gesture = await tester.startGesture(
h.cell(0, 0),
kind: PointerDeviceKind.mouse,
);
await gesture.moveTo(h.cell(2, 0));
await gesture.moveTo(h.cell(4, 0));
await gesture.up();
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
await tester.pumpAndSettle();
expect(h.take(), '');
final selection = h.controller.selection;
expect(selection, isNotNull);
expect(h.terminal.buffer.getText(selection), startsWith('hell'));
});
testWidgets('the wheel reports 65 down / 64 up at the view cell', (
tester,
) async {
final h = _Harness(tester);
await h.pump();
h.terminal.write('\x1b[?1049h\x1b[?1000h\x1b[?1006h');
await tester.pump();
final pointer = TestPointer(1, PointerDeviceKind.mouse);
final at = h.cell(3, 1);
await tester.sendEventToBinding(pointer.hover(at));
await tester.sendEventToBinding(
pointer.scroll(Offset(0, h.lineHeight * 2)),
);
await tester.pump();
expect(h.take(), '\x1b[<65;4;2M\x1b[<65;4;2M');
await tester.sendEventToBinding(pointer.scroll(Offset(0, -h.lineHeight)));
await tester.pump();
expect(h.take(), '\x1b[<64;4;2M');
});
}
+105
View File
@@ -0,0 +1,105 @@
import 'package:flutter_test/flutter_test.dart';
import 'xterm_fixture.dart';
void main() {
group('OSC 10/11/12 colour queries', () {
FixtureTerminal themed() {
final t = FixtureTerminal();
t.terminal.setReportedColors(
foreground: 0xFFC0C0C0,
background: 0xFF102030,
cursor: 0xFFFF8000,
);
return t;
}
test('answer with the theme colours and the query terminator', () {
final t = themed()..feed('\x1b]11;?\x1b\\');
expect(t.takeReplies(), '\x1b]11;rgb:1010/2020/3030\x1b\\');
t.feed('\x1b]10;?\x07');
expect(t.takeReplies(), '\x1b]10;rgb:c0c0/c0c0/c0c0\x07');
t.feed('\x1b]12;?\x07');
expect(t.takeReplies(), '\x1b]12;rgb:ffff/8080/0000\x07');
});
test('a multi-colour query answers each colour in turn', () {
final t = themed()..feed('\x1b]10;?;?\x07');
expect(
t.takeReplies(),
'\x1b]10;rgb:c0c0/c0c0/c0c0\x07\x1b]11;rgb:1010/2020/3030\x07',
);
});
test('setting a colour sends nothing and prints nothing', () {
final t = themed()..feed('\x1b]11;#000000\x07x');
expect(t.takeReplies(), '');
expect(t.row(0), 'x');
});
});
group('OSC 8 hyperlinks', () {
test('link cells without printing the sequence', () {
final t = FixtureTerminal()
..feed('a\x1b]8;id=1;https://example.com/a;b\x1b\\link\x1b]8;;\x1b\\z');
expect(t.row(0), 'alinkz');
final line = t.buffer.lines[0];
expect(t.terminal.hyperlinkAt(line, 0), isNull);
for (var x = 1; x <= 4; x++) {
expect(t.terminal.hyperlinkAt(line, x), 'https://example.com/a;b');
}
expect(t.terminal.hyperlinkAt(line, 5), isNull);
});
test('a link survives SGR changes and ends with an empty URI', () {
final t = FixtureTerminal()
..feed('\x1b]8;;https://x.test\x07\x1b[1ma\x1b[0mb\x1b]8;;\x07c');
final line = t.buffer.lines[0];
expect(t.terminal.hyperlinkAt(line, 0), 'https://x.test');
expect(t.terminal.hyperlinkAt(line, 1), 'https://x.test');
expect(t.terminal.hyperlinkAt(line, 2), isNull);
expect(t.cell(1, 0).flags & 0xFFFF, 0, reason: 'no SGR attributes');
});
});
group('OSC 52 clipboard', () {
test('a set reaches the callback decoded', () {
final t = FixtureTerminal();
final sets = <(String, String)>[];
t.terminal.onClipboardSet = (text, selection) =>
sets.add((text, selection));
t.feed('\x1b]52;c;aGVsbG8gd8O2cmxk\x07x');
expect(sets, [('hello wörld', 'c')]);
expect(t.row(0), 'x');
});
test('a read request and invalid data are ignored', () {
final t = FixtureTerminal();
var calls = 0;
t.terminal.onClipboardSet = (_, _) => calls++;
t.feed('\x1b]52;c;?\x07\x1b]52;c;not base64!\x07');
expect(calls, 0);
expect(t.takeReplies(), '');
});
});
test('OSC 7 reports the working directory', () {
final t = FixtureTerminal();
final dirs = <String>[];
t.terminal.onWorkingDirectoryChange = dirs.add;
t.feed('\x1b]7;file://host/home/me/a;b\x1b\\');
expect(dirs, ['file://host/home/me/a;b']);
expect(t.row(0), '');
});
test('titles keep their semicolons; an aborted OSC prints nothing', () {
final t = FixtureTerminal();
final titles = <String>[];
t.terminal.onTitleChange = titles.add;
t.feed('\x1b]2;vim; a.txt\x07');
t.feed('\x1b]2;cut\x1b[1mB');
expect(titles, ['vim; a.txt']);
expect(t.row(0), 'B');
expect(t.cell(0, 0).flags, isNot(0));
});
}
@@ -0,0 +1,107 @@
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/painting.dart';
import 'package:xterm/src/ui/painter.dart';
import 'package:xterm/xterm.dart';
const cursorColor = Color(0xFFFF0000);
const backgroundColor = Color(0xFF0000FF);
const foregroundColor = Color(0xFF00FF00);
/// A theme whose cursor, background and foreground are pure red, blue and
/// green, so painted pixels say which of them they are.
const fixtureTheme = TerminalTheme(
cursor: cursorColor,
selection: Color(0x80FFFFFF),
foreground: foregroundColor,
background: backgroundColor,
black: Color(0xFF000000),
red: Color(0xFF800000),
green: Color(0xFF008000),
yellow: Color(0xFF808000),
blue: Color(0xFF000080),
magenta: Color(0xFF800080),
cyan: Color(0xFF008080),
white: Color(0xFFC0C0C0),
brightBlack: Color(0xFF808080),
brightRed: Color(0xFFFF8080),
brightGreen: Color(0xFF80FF80),
brightYellow: Color(0xFFFFFF80),
brightBlue: Color(0xFF8080FF),
brightMagenta: Color(0xFFFF80FF),
brightCyan: Color(0xFF80FFFF),
brightWhite: Color(0xFFFFFFFF),
searchHitBackground: Color(0xFFFFFF00),
searchHitBackgroundCurrent: Color(0xFFFF8000),
searchHitForeground: Color(0xFF000000),
);
TerminalPainter fixturePainter() => TerminalPainter(
theme: fixtureTheme,
textStyle: const TerminalStyle(fontSize: 20, height: 1),
textScaler: TextScaler.noScaling,
);
/// The pixels [paint] draws on a transparent canvas of [width] x [height].
class Pixels {
Pixels._(this.width, this.height, this._rgba);
final int width;
final int height;
final ByteData _rgba;
static Future<Pixels> paint(
int width,
int height,
void Function(Canvas canvas) paint,
) async {
final recorder = ui.PictureRecorder();
paint(Canvas(recorder));
final image = await recorder.endRecording().toImage(width, height);
final data = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
image.dispose();
return Pixels._(width, height, data!);
}
/// The colour at ([x], [y]), opaque or transparent.
Color at(int x, int y) {
final i = (y * width + x) * 4;
return Color.fromARGB(
_rgba.getUint8(i + 3),
_rgba.getUint8(i),
_rgba.getUint8(i + 1),
_rgba.getUint8(i + 2),
);
}
/// Whether row [y] has any painted (non-transparent) pixel; decorations
/// are antialiased, so their exact colour varies.
bool rowHasInk(int y) {
for (var x = 0; x < width; x++) {
if (_rgba.getUint8((y * width + x) * 4 + 3) != 0) return true;
}
return false;
}
/// How many pixels in [rect] are exactly [color].
int count(Color color, [Rect? rect]) {
final area =
rect ?? Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble());
var n = 0;
for (var y = area.top.floor(); y < area.bottom.ceil(); y++) {
for (var x = area.left.floor(); x < area.right.ceil(); x++) {
if (at(x, y) == color) n++;
}
}
return n;
}
}
/// A cell holding [char] with [flags] and default colours.
CellData cellOf(String char, {int flags = 0, int width = 1}) => CellData(
foreground: 0,
background: 0,
flags: flags,
content: char.codeUnitAt(0) | (width << CellContent.widthShift),
);
@@ -0,0 +1,75 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
/// Puts the terminal in the state a crashed full-screen program leaves.
FixtureTerminal messedUp() {
return FixtureTerminal()..feed(
'shell\r\n'
'\x1b[?1049h' // alternate screen
'\x1b[2;4r' // scroll region
'\x1b[?25l' // cursor hidden
'\x1b[?1h\x1b=' // application cursor keys and keypad
'\x1b[?7l\x1b[4h\x1b[?6h' // no autowrap, insert, origin
'\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[?1004h' // mouse, paste, focus
'\x1b(0' // DEC graphics in G0
'\x1b[1;7;38;5;9m' // attributes
'\x1b[3;3Hjunk',
);
}
test('RIS (ESC c) recovers every mode, the screen and the cursor', () {
final t = messedUp()..feed('\x1bc');
final term = t.terminal;
expect(term.isUsingAltBuffer, isFalse);
expect(term.cursorVisibleMode, isTrue);
expect(term.cursorKeysMode, isFalse);
expect(term.appKeypadMode, isFalse);
expect(term.autoWrapMode, isTrue);
expect(term.insertMode, isFalse);
expect(term.originMode, isFalse);
expect(term.mouseMode, MouseMode.none);
expect(term.mouseReportMode, MouseReportMode.normal);
expect(term.bracketedPasteMode, isFalse);
expect(term.reportFocusMode, isFalse);
expect(t.buffer.marginTop, 0);
expect(t.buffer.marginBottom, 4);
expect(t.buffer.cursorX, 0);
expect(t.buffer.cursorY, 0);
for (var y = 0; y < 5; y++) {
expect(t.row(y), '', reason: 'row $y is cleared');
}
// Plain ASCII and plain attributes again.
t.feed('q');
expect(t.charAt(0, 0), 'q');
expect(t.cell(0, 0).flags, 0);
expect(t.cell(0, 0).foreground, 0);
});
test('RIS keeps the main screen scrollback', () {
final t = FixtureTerminal();
for (var i = 0; i < 8; i++) {
t.feed('line $i\r\n');
}
final scrollBack = t.buffer.scrollBack;
t.feed('\x1bc');
expect(t.buffer.scrollBack, scrollBack);
expect(t.buffer.lines[0].getText().trimRight(), 'line 0');
});
test('DECSTR (CSI ! p) resets modes and attributes but keeps the text', () {
final t = FixtureTerminal()
..feed('keep\x1b[?25l\x1b[?1h\x1b[2;4r\x1b[4h\x1b[1m\x1b[!p');
expect(t.row(0), 'keep');
expect(t.terminal.cursorVisibleMode, isTrue);
expect(t.terminal.cursorKeysMode, isFalse);
expect(t.terminal.insertMode, isFalse);
expect(t.terminal.cursor.attrs, 0);
expect(t.buffer.marginTop, 0);
expect(t.buffer.marginBottom, 4);
});
}
+98
View File
@@ -0,0 +1,98 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
import 'xterm_fixture.dart';
void main() {
CellData styled(String sgr) {
final t = FixtureTerminal()..feed('\x1b[${sgr}mX');
return t.cell(0, 0);
}
int underlineStyle(CellData cell) => cell.flags & CellAttr.underline == 0
? 0
: (cell.flags & CellAttr.underlineStyleMask) >>
CellAttr.underlineStyleShift;
test('4:3 is a curly underline, not a yellow background', () {
final cell = styled('4:3');
expect(underlineStyle(cell), 3);
expect(cell.background, 0);
expect(cell.flags & CellAttr.italic, 0);
});
test('underline styles 4:0 to 4:5 and plain 4 / 24 / 21', () {
expect(underlineStyle(styled('4')), 1);
expect(underlineStyle(styled('4:0')), 0);
expect(underlineStyle(styled('4:1')), 1);
expect(underlineStyle(styled('4:2')), 2);
expect(underlineStyle(styled('4:4')), 4);
expect(underlineStyle(styled('4:5')), 5);
expect(underlineStyle(styled('4:3;24')), 0);
expect(underlineStyle(styled('4:3;4:0')), 0);
expect(underlineStyle(styled('21')), 2);
expect(styled('21').flags & CellAttr.bold, 0);
});
test('colon direct colours with and without a colour space id', () {
expect(styled('38:2::10:20:30').foreground, rgb(10, 20, 30));
expect(styled('38:2:1:10:20:30').foreground, rgb(10, 20, 30));
expect(styled('38:2:10:20:30').foreground, rgb(10, 20, 30));
expect(styled('48:2::1:2:3').background, rgb(1, 2, 3));
});
test('colon and semicolon indexed colours', () {
expect(styled('38:5:196').foreground, palette(196));
expect(styled('48:5:21').background, palette(21));
expect(styled('38;5;196').foreground, palette(196));
expect(styled('38;2;1;2;3;1').foreground, rgb(1, 2, 3));
expect(styled('38;2;1;2;3;1').flags & CellAttr.bold, isNot(0));
});
test('colon groups end at the next semicolon', () {
final cell = styled('38:5:2;41;1');
expect(cell.foreground, palette(2));
expect(cell.background, named(NamedColor.red));
expect(cell.flags & CellAttr.bold, isNot(0));
});
test('underline colour 58 / 59 is consumed, not applied elsewhere', () {
var cell = styled('58:2::255:0:0;4:3');
expect(cell.foreground, 0);
expect(cell.background, 0);
expect(underlineStyle(cell), 3);
cell = styled('58;5;9;1');
expect(cell.foreground, 0);
expect(cell.flags & CellAttr.bold, isNot(0));
cell = styled('58;2;1;2;3;59;7');
expect(cell.flags & CellAttr.inverse, isNot(0));
expect(cell.background, 0);
});
test('truncated extended colours do not throw or misapply', () {
expect(styled('38;5').foreground, 0);
expect(styled('38;2;1;2').foreground, 0);
expect(styled('48').background, 0);
});
test('22 clears bold and faint; 53/55 toggle overline', () {
expect(styled('1;2;22').flags & (CellAttr.bold | CellAttr.faint), 0);
expect(styled('53').flags & CellAttr.overline, isNot(0));
expect(styled('53;55').flags & CellAttr.overline, 0);
});
test('a private-prefixed m (modifyOtherKeys) is not SGR', () {
final t = FixtureTerminal()..feed('\x1b[>4;2mX');
expect(t.cell(0, 0).flags, 0);
expect(t.row(0), 'X');
});
test('empty parameters default: CSI ; 5 H and CSI 3 H', () {
final t = FixtureTerminal()..feed('\x1b[;5H');
expect(t.buffer.cursorX, 4);
expect(t.buffer.cursorY, 0);
t.feed('\x1b[3H');
expect(t.buffer.cursorX, 0);
expect(t.buffer.cursorY, 2);
});
}
@@ -0,0 +1,47 @@
import 'package:xterm/xterm.dart';
/// A terminal fed raw bytes in byte-fixture tests, with every reply it sends
/// to the program collected in [replies].
class FixtureTerminal {
FixtureTerminal({int width = 20, int height = 5}) {
terminal.onOutput = replies.add;
terminal.resize(width, height);
}
final terminal = Terminal(maxLines: 100);
final replies = <String>[];
Buffer get buffer => terminal.buffer;
void feed(String bytes) => terminal.write(bytes);
/// The text of screen row [y], trailing blanks trimmed.
String row(int y) =>
buffer.lines[buffer.scrollBack + y].getText().trimRight();
/// The cell at column [x] of screen row [y].
CellData cell(int x, int y) {
final data = CellData.empty();
buffer.lines[buffer.scrollBack + y].getCellData(x, data);
return data;
}
/// The character at column [x] of screen row [y], '' for an empty cell.
String charAt(int x, int y) {
final code = cell(x, y).content & CellContent.codepointMask;
return code == 0 ? '' : String.fromCharCode(code);
}
/// The replies sent so far, joined, and then forgotten.
String takeReplies() {
final all = replies.join();
replies.clear();
return all;
}
}
int rgb(int r, int g, int b) => CellColor.rgb | (r << 16) | (g << 8) | b;
int palette(int index) => CellColor.palette | index;
int named(int index) => CellColor.named | index;
+277
View File
@@ -0,0 +1,277 @@
## [4.0.0] - 2024-02-27
* Update for Flutter 3.19 [#190]. Thanks [@domesticmouse].
* Fix designate charset logic [#186]. Thanks [@djnalluri].
## [3.6.1-pre] - 2023-04-28
* Add Termianl.onPrivateOSC callback
* Copy shortcut on Windows default to Ctrl+Shift+V (#173)
## [3.6.0-pre] - 2023-04-27
* Basic ZMODEM support
## [3.5.0] - 2023-04-20
* Support customizing word separators for selection [#160]. Thanks [@itzhoujun].
* Fix incorrect tab stop handling [#161]. Thanks [@itzhoujun].
* Added support for Ctrl+Home, Ctrl+End etc [#169]. Thanks [@nuc134r].
## [3.4.1] - 2023-01-27
* Fix Flutter 3.7 incompatibilities [#151], thanks [@jpnurmi].
## [3.4.0] - 2022-11-4
* Mouse input is enabled by default.
* Support scrolling in alternate buffer.
* Fix `deleteLines` behavior.
* Fix `eraseDisplayFromCursor` removes characters before the cursor.
## [3.3.0] - 2022-10-30
* Sync ShortcutManager's shortcuts in didUpdateWidget [#140], thanks [@jpnurmi].
* fix: terminal font size not respecting system level font scale [#138], thanks [@LucasAschenbach].
* Fix selection color [#135], thanks [@jpnurmi].
* fix: dispose controllers of TerminalView [#132], thanks [@tauu].
* feat: add hardwareKeyboardOnly flag to TerminalView [#131], thanks [@tauu].
* feat: initial mouse support [#130], thanks [@tauu].
* feat: limited window manipulation support [#129], thanks [@tauu].
* fix: workaround to draw underlined spaces [#128], thanks [@tauu].
* feat: block selection [#127], thanks [@tauu].
* feat: enable changing the inputHandler of a terminal [#126], thanks [@tauu].
* fix: export TerminalTargetPlatform [#125], thanks [@tauu].
* fix: only dispose the FocusNodes which TerminalView creates [#124], thanks [@tauu].
* feat: expose readOnly flag of CustomTextEdit in TerminalView [#123], thanks [@tauu].
* fix: supports numpad enter key [#137].
* feat: expose `reflowEnabled` flag [#104].
* docs: add virtual keyboard example [#141].
## [3.2.7] - 2022-9-13
* Fix lint issues.
## [3.2.6] - 2022-9-13
* First stable release of xterm.dart v3.
## [3.2.6-alpha] - 2022-9-13
* Fix new line width in reflow.
## [3.2.5-alpha] - 2022-9-12
* Fix intent related issue.
## [3.2.4-alpha] - 2022-9-12
* Use flutter native shortcut intents.
## [3.2.3-alpha] - 2022-9-12
* Export shortcut related classes.
## [3.2.2-alpha] - 2022-9-12
* Implement default keyboard shortcuts.
## [3.2.1-alpha] - 2022-9-12
* Disable optional line scroll mode that is under development.
## [3.2.0-alpha] - 2022-9-12
* Enhanced selection handing.
* More tests.
## [3.1.0-alpha] - 2022-9-4
* Update dependencies & merge into master
## [3.0.6-alpha] - 2022-4-4
* Export `TerminalViewState`
* Added `onTap` callback to `TerminalView`
## [3.0.5-alpha] - 2022-4-4
* Avoid resize when `RenderBox.size` is zero.
* Added `charInput` and `textInput`method.
* Added `requestKeyboard`, `closeKeyboard` and `hasInputConnection`method.
* Export `KeyboardVisibilty`
## [3.0.4-alpha] - 2022-4-1
* Improved text editing
* Added composing state painting
* Adapt to `MediaQuery.padding`
## [3.0.3-alpha] - 2022-3-28
* Improved scroll handing
* Improved resize handing
* Fix focus repaint
* Fix OSC title update
## [3.0.2-alpha] - 2022-3-28
* Re-design `KeyboardVisibilty`
## [3.0.1-alpha] - 2022-3-27
* Add `KeyboardVisibilty`
## [3.0.0-alpha] - 2022-3-26
* Initial release of v3.
## [2.6.0] - 2021-12-28
* Add scrollBehavior field to the TerminalView class [#55].
* Feature: Search [#60]. Thanks [@devmil].
* Fixes for occasional unintended multi character input [#61]. Thanks [@devmil].
* Fixes ALT + L for a Mac (German Layout) [#62]. Thanks [@devmil].
* Fixes example build problem of flutter-windows for new version of flutter [#63]. Thanks [@linhanyu].
* Fixes inverse color text (when background == 0) [#66]. Thanks [@devmil].
* Fixes assert of scrollController.position [#67]. Thanks [@linhanyu].
* Change interface of ssh.dart example to satisfied new dartssh [#69]. Thanks [@linhanyu].
* add configuration options for keyboard [#74]. Thanks [@jda258].
* Adds check if the TerminalIsolate has already been started [#77]. Thanks [@devmil].
## [2.5.0-pre] - 2021-8-4
* Support select word / whole row via double tap [#40]. Thanks [@devmil].
* Adds "selectAll" to TerminalUiInteraction [#43]. Thanks [@devmil].
* Fixes sgr processing [#44],[#45]. Thanks [@devmil].
* Adds blinking Cursor support [#46]. Thanks [@devmil].
* Fixes Zoom adaptions on non active buffer [#47]. Thanks [@devmil].
* Adds Padding option to TerminalView [#48]. Thanks [@devmil].
* Removes no longer supported LogicalKeyboardKey [#49]. Thanks [@devmil].
* Adds the composing state [#50]. Thanks [@devmil].
* Fix scroll problem in mobile device [#51]. Thanks [@linhanyu].
## [2.4.0-pre] - 2021-6-13
* Update the signature of TerminalBackend.resize() to also receive dimensions in
pixels[(#39)](https://github.com/TerminalStudio/xterm.dart/pull/39). Thanks [@michaellee8](https://github.com/michaellee8).
## [2.3.1-pre] - 2021-6-1
* Export `theme/terminal_style.dart`
## [2.3.0-pre] - 2021-6-1
* Add `import 'package:xterm/isolate.dart';`
## [2.2.1-pre] - 2021-6-1
* Make BufferLine work on web.
## [2.2.0-pre] - 2021-4-12
## [2.1.0-pre] - 2021-3-20
* Better support for resizing and scrolling.
* Reflow support (in progress [#13](https://github.com/TerminalStudio/xterm.dart/pull/13)), thanks [@devmil](https://github.com/devmil).
## [2.0.0] - 2021-3-7
* Clean up for release
## [2.0.0-pre] - 2021-3-7
* Migrate to nnbd
## [1.3.0] - 2021-2-24
* Performance improvement.
## [1.2.0] - 2021-2-15
* Pass TerminalView's autofocus to the InputListener that it creates. [#10](https://github.com/TerminalStudio/xterm.dart/pull/10), thanks [@timburks](https://github.com/timburks)
## [1.2.0-pre] - 2021-1-20
* add the ability to use fonts from the google_fonts package [#9](https://github.com/TerminalStudio/xterm.dart/pull/9)
## [1.1.1+1] - 2020-10-4
* Update readme
## [1.1.1] - 2020-10-4
* Add brightWhite to TerminalTheme
## [1.1.0] - 2020-9-29
* Fix web support.
## [1.0.2] - 2020-9-29
* Update link.
## [1.0.1] - 2020-9-29
* Disable debug print.
## [1.0.0] - 2020-9-28
* Update readme.
## [1.0.0-dev] - 2020-9-28
* Major issues are fixed.
## [0.1.0] - 2020-8-9
* Bug fixes
## [0.0.4] - 2020-8-1
* Revert version constrain
## [0.0.3] - 2020-8-1
* Update version constrain
## [0.0.2] - 2020-8-1
* Update readme
## [0.0.1] - 2020-8-1
* First version
[@devmil]: https://github.com/devmil
[@michaellee8]: https://github.com/michaellee8
[@linhanyu]: https://github.com/linhanyu
[@jda258]: https://github.com/jda258
[@jpnurmi]: https://github.com/jpnurmi
[@LucasAschenbach]: https://github.com/LucasAschenbach
[@tauu]: https://github.com/tauu
[@itzhoujun]: https://github.com/itzhoujun
[@nuc134r]: https://github.com/nuc134r
[@djnalluri]: https://github.com/djnalluri
[@domesticmouse]: https://github.com/domesticmouse
[#40]: https://github.com/TerminalStudio/xterm.dart/pull/40
[#43]: https://github.com/TerminalStudio/xterm.dart/pull/43
[#44]: https://github.com/TerminalStudio/xterm.dart/pull/44
[#45]: https://github.com/TerminalStudio/xterm.dart/pull/45
[#46]: https://github.com/TerminalStudio/xterm.dart/pull/46
[#47]: https://github.com/TerminalStudio/xterm.dart/pull/47
[#48]: https://github.com/TerminalStudio/xterm.dart/pull/48
[#49]: https://github.com/TerminalStudio/xterm.dart/pull/49
[#50]: https://github.com/TerminalStudio/xterm.dart/pull/50
[#51]: https://github.com/TerminalStudio/xterm.dart/pull/51
[#55]: https://github.com/TerminalStudio/xterm.dart/pull/55
[#60]: https://github.com/TerminalStudio/xterm.dart/pull/60
[#61]: https://github.com/TerminalStudio/xterm.dart/pull/61
[#62]: https://github.com/TerminalStudio/xterm.dart/pull/62
[#63]: https://github.com/TerminalStudio/xterm.dart/pull/63
[#66]: https://github.com/TerminalStudio/xterm.dart/pull/66
[#67]: https://github.com/TerminalStudio/xterm.dart/pull/67
[#69]: https://github.com/TerminalStudio/xterm.dart/pull/69
[#74]: https://github.com/TerminalStudio/xterm.dart/pull/74
[#77]: https://github.com/TerminalStudio/xterm.dart/pull/77
[#104]: https://github.com/TerminalStudio/xterm.dart/issues/104
[#123]: https://github.com/TerminalStudio/xterm.dart/pull/123
[#124]: https://github.com/TerminalStudio/xterm.dart/pull/124
[#125]: https://github.com/TerminalStudio/xterm.dart/pull/125
[#126]: https://github.com/TerminalStudio/xterm.dart/pull/126
[#127]: https://github.com/TerminalStudio/xterm.dart/pull/127
[#128]: https://github.com/TerminalStudio/xterm.dart/pull/128
[#129]: https://github.com/TerminalStudio/xterm.dart/pull/129
[#130]: https://github.com/TerminalStudio/xterm.dart/pull/130
[#131]: https://github.com/TerminalStudio/xterm.dart/pull/131
[#132]: https://github.com/TerminalStudio/xterm.dart/pull/132
[#135]: https://github.com/TerminalStudio/xterm.dart/pull/135
[#137]: https://github.com/TerminalStudio/xterm.dart/issues/137
[#138]: https://github.com/TerminalStudio/xterm.dart/pull/138
[#140]: https://github.com/TerminalStudio/xterm.dart/pull/140
[#141]: https://github.com/TerminalStudio/xterm.dart/pull/141
[#151]: https://github.com/TerminalStudio/xterm.dart/pull/151
[#160]: https://github.com/TerminalStudio/xterm.dart/pull/160
[#161]: https://github.com/TerminalStudio/xterm.dart/pull/161
[#169]: https://github.com/TerminalStudio/xterm.dart/pull/169
[#186]: https://github.com/TerminalStudio/xterm.dart/pull/186
[#190]: https://github.com/TerminalStudio/xterm.dart/pull/190
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 xuty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+35
View File
@@ -0,0 +1,35 @@
# xterm (vendored)
This is our maintained copy of [xterm.dart](https://github.com/TerminalStudio/xterm.dart),
vendored from the pub.dev release **4.0.0** (MIT, see `LICENSE`; the upstream
README is kept as `UPSTREAM_README.md`). Upstream is unmaintained, so the app
depends on this directory through a path dependency and we patch it here.
The commit that added this directory is the pristine upstream copy; every later
change is a local patch. Review them with `git log -p -- app/third_party/xterm`.
Tests for the patches live in the app tree, `app/test/third_party_xterm/`, so they
run under the memory watchdog with the rest of the app tests. The app's
`analysis_options.yaml` excludes this directory from its strict lints; the code
still compiles as part of every app build.
Local patches (keep this list current):
- CSI parsing: colon subparameters (`4:3`, `38:2::r:g:b`, `58`/`59`),
intermediates and private prefixes (`CSI > 4;2 m` is not SGR), empty
parameters as defaults; SGR 21 is double underline, 53/55 overline
- DCS/APC/PM/SOS strings consumed rather than printed; DECRQSS (`m`, `r`,
` q`) answered
- RIS (`ESC c`) full reset and DECSTR (`CSI ! p`)
- DECSCUSR cursor shapes (blinking is stored, not animated); SCOSC/SCORC,
CHT, CBT, HPA, HPR, VPR; HTS sets tab stops; DSR 6 one-based
- OSC 10/11/12 colour queries from the view's theme; OSC 8 links on cells
(`Terminal.hyperlinkAt`); OSC 52 set (`onClipboardSet`, no reads); OSC 7
(`onWorkingDirectoryChange`)
- alternate screen 1049 restores the cursor; arrow keys follow DECCKM
- mouse: wheel 64/65, screen-cell coordinates, drag (1002) and motion
(1003) reporting, middle button, Shift+drag selects
(`ui/mouse_listener.dart`)
- rendering: block cursor shows the character inverted, underline/bar
cursor position, strikethrough, conceal, overline, underline styles
- focus reporting (`?1004`, `Terminal.focusInput`, called by `TerminalView`)
+125
View File
@@ -0,0 +1,125 @@
## xterm.dart
<p>
<a href="https://github.com/TerminalStudio/xterm.dart/actions/workflows/ci.yml">
<img alt="Actions" src="https://github.com/TerminalStudio/xterm.dart/actions/workflows/ci.yml/badge.svg">
</a>
<a href="https://pub.dev/packages/xterm">
<img alt="Package version" src="https://img.shields.io/pub/v/xterm?color=blue&include_prereleases">
</a>
<img alt="GitHub repo size" src="https://img.shields.io/github/repo-size/TerminalStudio/xterm.dart">
<img alt="GitHub issues" src="https://img.shields.io/github/issues-raw/TerminalStudio/xterm.dart">
<img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/TerminalStudio/xterm.dart">
</p>
**xterm.dart** is a fast and fully-featured terminal emulator for Flutter applications, with support for mobile and desktop platforms.
> This package requires Flutter version >=3.0.0
## Screenshots
<table>
<tr>
<td>
<img width="200px" src="https://raw.githubusercontent.com/TerminalStudio/xterm.dart/master/media/demo-shell.png">
</td>
<td>
<img width="200px" src="https://raw.githubusercontent.com/TerminalStudio/xterm.dart/master/media/demo-vim.png">
</td>
<tr>
</tr>
<td>
<img width="200px" src="https://raw.githubusercontent.com/TerminalStudio/xterm.dart/master/media/demo-htop.png">
</td>
<td>
<img width="200px" src="https://raw.githubusercontent.com/TerminalStudio/xterm.dart/master/media/demo-dialog.png">
</td>
</tr>
</table>
## Features
- 📦 **Works out of the box** No special configuration required.
- 🚀 **Fast** Renders at 60fps.
- 😀 **Wide character support** Supports CJK and emojis.
- ✂️ **Customizable**
- ✔ **Frontend independent**: The terminal core can work without flutter frontend.
**What's new in 3.0.0:**
- 📱 Enhanced support for **mobile** platforms.
- ⌨️ Integrates with Flutter's **shortcut** system.
- 🎨 Allows changing **theme** at runtime.
- 💪 Better **performance**. No tree rebuilds anymore.
- 🈂️ Works with **IMEs**.
## Getting Started
**1.** Add this to your package's pubspec.yaml file:
```yml
dependencies:
...
xterm: ^3.2.6
```
**2.** Create the terminal:
```dart
import 'package:xterm/xterm.dart';
...
terminal = Terminal();
```
Listen to user interaction with the terminal by simply adding a `onOutput` callback:
```dart
terminal = Terminal();
terminal.onOutput = (output) {
print('output: $output');
}
```
**3.** Create the view, attach the terminal to the view:
```dart
import 'package:xterm/flutter.dart';
...
child: TerminalView(terminal),
```
**4.** Write something to the terminal:
```dart
terminal.write('Hello, world!');
```
**Done!**
## More examples
- Write a simple terminal in ~100 lines of code:
https://github.com/TerminalStudio/xterm.dart/blob/master/example/lib/main.dart
- Write a SSH client in ~100 lines of code with [dartssh2]:
https://github.com/TerminalStudio/xterm.dart/blob/master/example/lib/ssh.dart
<img width="400px" src="https://raw.githubusercontent.com/TerminalStudio/xterm.dart/master/media/example-ssh.png">
For a complete project built with xterm.dart, check out [TerminalStudio].
## Features and bugs
Please file feature requests and bugs at the [issue tracker](https://github.com/TerminalStudio/xterm.dart/issues).
Contributions are always welcome!
## License
This project is licensed under an MIT license.
[dartssh2]: https://pub.dev/packages/dartssh2
[TerminalStudio]: https://github.com/TerminalStudio/studio
+22
View File
@@ -0,0 +1,22 @@
export 'src/core/buffer/buffer.dart';
export 'src/core/buffer/cell_flags.dart';
export 'src/core/buffer/cell_offset.dart';
export 'src/core/buffer/line.dart';
export 'src/core/buffer/range.dart';
export 'src/core/buffer/range_block.dart';
export 'src/core/buffer/range_line.dart';
export 'src/core/buffer/segment.dart';
export 'src/core/cell.dart';
export 'src/core/color.dart';
export 'src/core/cursor.dart';
export 'src/core/escape/handler.dart';
export 'src/core/escape/parser.dart';
export 'src/core/input/handler.dart';
export 'src/core/input/keys.dart';
export 'src/core/mouse/button.dart';
export 'src/core/mouse/button_state.dart';
export 'src/core/mouse/handler.dart';
export 'src/core/mouse/mode.dart';
export 'src/core/platform.dart';
export 'src/core/state.dart';
export 'src/terminal.dart';
+41
View File
@@ -0,0 +1,41 @@
import 'package:xterm/src/base/event.dart';
mixin Disposable {
final _disposables = <Disposable>[];
bool get disposed => _disposed;
bool _disposed = false;
Event get onDisposed => _onDisposed.event;
final _onDisposed = EventEmitter();
void register(Disposable disposable) {
assert(!_disposed);
_disposables.add(disposable);
}
void registerCallback(void Function() callback) {
assert(!_disposed);
_disposables.add(_DisposeCallback(callback));
}
void dispose() {
_disposed = true;
for (final disposable in _disposables) {
disposable.dispose();
}
_onDisposed.emit(null);
}
}
class _DisposeCallback with Disposable {
final void Function() callback;
_DisposeCallback(this.callback);
@override
void dispose() {
super.dispose();
callback();
}
}
+42
View File
@@ -0,0 +1,42 @@
import 'package:xterm/src/base/disposable.dart';
typedef EventListener<T> = void Function(T event);
class Event<T> {
final EventEmitter<T> emitter;
Event(this.emitter);
void call(EventListener<T> listener) {
emitter(listener);
}
}
class EventEmitter<T> {
final _listeners = <EventListener<T>>[];
EventSubscription<T> call(EventListener<T> listener) {
_listeners.add(listener);
return EventSubscription(this, listener);
}
void emit(T event) {
for (final listener in _listeners) {
listener(event);
}
}
Event<T> get event => Event(this);
}
class EventSubscription<T> with Disposable {
final EventEmitter<T> emitter;
final EventListener<T> listener;
EventSubscription(this.emitter, this.listener);
@override
void dispose() {
emitter._listeners.remove(listener);
}
}
+17
View File
@@ -0,0 +1,17 @@
mixin Observable {
final listeners = <void Function()>{};
void addListener(void Function() listener) {
listeners.add(listener);
}
void removeListener(void Function() listener) {
listeners.remove(listener);
}
void notifyListeners() {
for (var listener in listeners) {
listener();
}
}
}
+619
View File
@@ -0,0 +1,619 @@
import 'dart:math' show max, min;
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/buffer/line.dart';
import 'package:xterm/src/core/buffer/range_line.dart';
import 'package:xterm/src/core/buffer/range.dart';
import 'package:xterm/src/core/charset.dart';
import 'package:xterm/src/core/cursor.dart';
import 'package:xterm/src/core/reflow.dart';
import 'package:xterm/src/core/state.dart';
import 'package:xterm/src/utils/circular_buffer.dart';
import 'package:xterm/src/utils/unicode_v11.dart';
class Buffer {
final TerminalState terminal;
final int maxLines;
final bool isAltBuffer;
/// Characters that break selection when calling [getWordBoundary]. If null,
/// defaults to [defaultWordSeparators].
final Set<int>? wordSeparators;
Buffer(
this.terminal, {
required this.maxLines,
required this.isAltBuffer,
this.wordSeparators,
}) {
for (int i = 0; i < terminal.viewHeight; i++) {
lines.push(_newEmptyLine());
}
resetVerticalMargins();
}
int _cursorX = 0;
int _cursorY = 0;
late int _marginTop;
late int _marginBottom;
var _savedCursorX = 0;
var _savedCursorY = 0;
final _savedCursorStyle = CursorStyle();
final charset = Charset();
/// Width of the viewport in columns. Also the index of the last column.
int get viewWidth => terminal.viewWidth;
/// Height of the viewport in rows. Also the index of the last line.
int get viewHeight => terminal.viewHeight;
/// lines of the buffer. the length of [lines] should always be equal or
/// greater than [viewHeight].
late final lines = IndexAwareCircularBuffer<BufferLine>(maxLines);
/// Total number of lines in the buffer. Always equal or greater than
/// [viewHeight].
int get height => lines.length;
/// Horizontal position of the cursor relative to the top-left cornor of the
/// screen, starting from 0.
int get cursorX => _cursorX.clamp(0, terminal.viewWidth - 1);
/// Vertical position of the cursor relative to the top-left cornor of the
/// screen, starting from 0.
int get cursorY => _cursorY;
/// Index of the first line in the scroll region.
int get marginTop => _marginTop;
/// Index of the last line in the scroll region.
int get marginBottom => _marginBottom;
/// The number of lines above the viewport.
int get scrollBack => height - viewHeight;
/// Vertical position of the cursor relative to the top of the buffer,
/// starting from 0.
int get absoluteCursorY => _cursorY + scrollBack;
/// Absolute index of the first line in the scroll region.
int get absoluteMarginTop => _marginTop + scrollBack;
/// Absolute index of the last line in the scroll region.
int get absoluteMarginBottom => _marginBottom + scrollBack;
/// Writes data to the _terminal. Terminal sequences or special characters are
/// not interpreted and directly added to the buffer.
///
/// See also: [Terminal.write]
void write(String text) {
for (var char in text.runes) {
writeChar(char);
}
}
/// Writes a single character to the _terminal. Escape sequences or special
/// characters are not interpreted and directly added to the buffer.
///
/// See also: [Terminal.writeChar]
void writeChar(int codePoint) {
codePoint = charset.translate(codePoint);
final cellWidth = unicodeV11.wcwidth(codePoint);
if (_cursorX >= terminal.viewWidth) {
index();
setCursorX(0);
if (terminal.autoWrapMode) {
currentLine.isWrapped = true;
}
}
final line = currentLine;
line.setCell(_cursorX, codePoint, cellWidth, terminal.cursor);
if (_cursorX < viewWidth) {
_cursorX++;
}
if (cellWidth == 2) {
writeChar(0);
}
}
/// The line at the current cursor position.
BufferLine get currentLine {
return lines[absoluteCursorY];
}
void backspace() {
if (_cursorX == 0 && currentLine.isWrapped) {
currentLine.isWrapped = false;
moveCursor(viewWidth - 1, -1);
} else if (_cursorX == viewWidth) {
moveCursor(-2, 0);
} else {
moveCursor(-1, 0);
}
}
/// Erases the viewport from the cursor position to the end of the buffer,
/// including the cursor position.
void eraseDisplayFromCursor() {
eraseLineFromCursor();
for (var i = absoluteCursorY + 1; i < height; i++) {
final line = lines[i];
line.isWrapped = false;
line.eraseRange(0, viewWidth, terminal.cursor);
}
}
/// Erases the viewport from the top-left corner to the cursor, including the
/// cursor.
void eraseDisplayToCursor() {
eraseLineToCursor();
for (var i = 0; i < _cursorY; i++) {
final line = lines[i + scrollBack];
line.isWrapped = false;
line.eraseRange(0, viewWidth, terminal.cursor);
}
}
/// Erases the whole viewport.
void eraseDisplay() {
for (var i = 0; i < viewHeight; i++) {
final line = lines[i + scrollBack];
line.isWrapped = false;
line.eraseRange(0, viewWidth, terminal.cursor);
}
}
/// Erases the line from the cursor to the end of the line, including the
/// cursor position.
void eraseLineFromCursor() {
currentLine.isWrapped = false;
currentLine.eraseRange(_cursorX, viewWidth, terminal.cursor);
}
/// Erases the line from the start of the line to the cursor, including the
/// cursor.
void eraseLineToCursor() {
currentLine.isWrapped = false;
currentLine.eraseRange(0, _cursorX, terminal.cursor);
}
/// Erases the line at the current cursor position.
void eraseLine() {
currentLine.isWrapped = false;
currentLine.eraseRange(0, viewWidth, terminal.cursor);
}
/// Erases [count] cells starting at the cursor position.
void eraseChars(int count) {
final start = _cursorX;
currentLine.eraseRange(start, start + count, terminal.cursor);
}
void scrollDown(int lines) {
for (var i = absoluteMarginBottom; i >= absoluteMarginTop; i--) {
if (i >= absoluteMarginTop + lines) {
this.lines[i] = this.lines[i - lines];
} else {
this.lines[i] = _newEmptyLine();
}
}
}
void scrollUp(int lines) {
for (var i = absoluteMarginTop; i <= absoluteMarginBottom; i++) {
if (i <= absoluteMarginBottom - lines) {
this.lines[i] = this.lines[i + lines];
} else {
this.lines[i] = _newEmptyLine();
}
}
}
/// https://vt100.net/docs/vt100-ug/chapter3.html#IND IND – Index
///
/// ESC D
///
/// [index] causes the active position to move downward one line without
/// changing the column position. If the active position is at the bottom
/// margin, a scroll up is performed.
void index() {
if (isInVerticalMargin) {
if (_cursorY == _marginBottom) {
if (marginTop == 0 && !isAltBuffer) {
lines.insert(absoluteMarginBottom + 1, _newEmptyLine());
} else {
scrollUp(1);
}
} else {
moveCursorY(1);
}
return;
}
// the cursor is not in the scrollable region
if (_cursorY >= viewHeight - 1) {
// we are at the bottom
if (isAltBuffer) {
scrollUp(1);
} else {
lines.push(_newEmptyLine());
}
} else {
// there're still lines so we simply move cursor down.
moveCursorY(1);
}
}
void lineFeed() {
index();
if (terminal.lineFeedMode) {
setCursorX(0);
}
}
/// https://terminalguide.namepad.de/seq/a_esc_cm/
void reverseIndex() {
if (isInVerticalMargin) {
if (_cursorY == _marginTop) {
scrollDown(1);
} else {
moveCursorY(-1);
}
} else {
moveCursorY(-1);
}
}
void cursorGoForward() {
_cursorX = min(_cursorX + 1, viewWidth);
}
void setCursorX(int cursorX) {
_cursorX = cursorX.clamp(0, viewWidth - 1);
}
void setCursorY(int cursorY) {
_cursorY = cursorY.clamp(0, viewHeight - 1);
}
void moveCursorX(int offset) {
setCursorX(_cursorX + offset);
}
void moveCursorY(int offset) {
setCursorY(_cursorY + offset);
}
void setCursor(int cursorX, int cursorY) {
var maxCursorY = viewHeight - 1;
if (terminal.originMode) {
cursorY += _marginTop;
maxCursorY = _marginBottom;
}
_cursorX = cursorX.clamp(0, viewWidth - 1);
_cursorY = cursorY.clamp(0, maxCursorY);
}
void moveCursor(int offsetX, int offsetY) {
final cursorX = _cursorX + offsetX;
final cursorY = _cursorY + offsetY;
setCursor(cursorX, cursorY);
}
/// Save cursor position, charmap and text attributes.
void saveCursor() {
_savedCursorX = _cursorX;
_savedCursorY = _cursorY;
_savedCursorStyle.foreground = terminal.cursor.foreground;
_savedCursorStyle.background = terminal.cursor.background;
_savedCursorStyle.attrs = terminal.cursor.attrs;
charset.save();
}
/// Restore cursor position, charmap and text attributes.
void restoreCursor() {
_cursorX = _savedCursorX;
_cursorY = _savedCursorY;
terminal.cursor.foreground = _savedCursorStyle.foreground;
terminal.cursor.background = _savedCursorStyle.background;
terminal.cursor.attrs = _savedCursorStyle.attrs;
charset.restore();
}
/// Resets the cursor, the saved cursor, the character sets and the
/// margins to their power-on state (for RIS and DECSTR). The contents are
/// left alone.
void resetState() {
_cursorX = 0;
_cursorY = 0;
_savedCursorX = 0;
_savedCursorY = 0;
_savedCursorStyle
..reset()
..attrs = 0;
charset.reset();
resetVerticalMargins();
}
/// Sets the vertical scrolling margin to [top] and [bottom].
/// Both values must be between 0 and [viewHeight] - 1.
void setVerticalMargins(int top, int bottom) {
_marginTop = top.clamp(0, viewHeight - 1);
_marginBottom = bottom.clamp(0, viewHeight - 1);
_marginTop = min(_marginTop, _marginBottom);
_marginBottom = max(_marginTop, _marginBottom);
}
bool get isInVerticalMargin {
return _cursorY >= _marginTop && _cursorY <= _marginBottom;
}
void resetVerticalMargins() {
setVerticalMargins(0, viewHeight - 1);
}
void deleteChars(int count) {
final start = _cursorX.clamp(0, viewWidth);
count = min(count, viewWidth - start);
currentLine.removeCells(start, count, terminal.cursor);
}
/// Remove all lines above the top of the viewport.
void clearScrollback() {
if (height <= viewHeight) {
return;
}
lines.trimStart(scrollBack);
}
/// Clears the viewport and scrollback buffer. Then fill with empty lines.
void clear() {
lines.clear();
for (int i = 0; i < viewHeight; i++) {
lines.push(_newEmptyLine());
}
}
void insertBlankChars(int count) {
currentLine.insertCells(_cursorX, count, terminal.cursor);
}
void insertLines(int count) {
if (!isInVerticalMargin) {
return;
}
setCursorX(0);
// Number of lines from the cursor to the bottom of the scrollable region
// including the cursor itself.
final linesBelow = absoluteMarginBottom - absoluteCursorY + 1;
// Number of empty lines to insert.
final linesToInsert = min(count, linesBelow);
// Number of lines to move up.
final linesToMove = linesBelow - linesToInsert;
for (var i = 0; i < linesToMove; i++) {
final index = absoluteMarginBottom - i;
lines[index] = lines.swap(index - linesToInsert, _newEmptyLine());
}
for (var i = linesToMove; i < linesToInsert; i++) {
lines[absoluteCursorY + i] = _newEmptyLine();
}
}
/// Remove [count] lines starting at the current cursor position. Lines below
/// the removed lines are shifted up. This only affects the scrollable region.
/// Lines outside the scrollable region are not affected.
void deleteLines(int count) {
if (!isInVerticalMargin) {
return;
}
setCursorX(0);
count = min(count, absoluteMarginBottom - absoluteCursorY + 1);
final linesToMove = absoluteMarginBottom - absoluteCursorY + 1 - count;
for (var i = 0; i < linesToMove; i++) {
final index = absoluteCursorY + i;
lines[index] = lines[index + count];
}
for (var i = 0; i < count; i++) {
lines[absoluteMarginBottom - i] = _newEmptyLine();
}
}
void resize(int oldWidth, int oldHeight, int newWidth, int newHeight) {
// 1. Adjust the height.
if (newHeight > oldHeight) {
// Grow larger
for (var i = 0; i < newHeight - oldHeight; i++) {
if (newHeight > lines.length) {
lines.push(_newEmptyLine(newWidth));
} else {
_cursorY++;
}
}
} else {
// Shrink smaller
for (var i = 0; i < oldHeight - newHeight; i++) {
if (_cursorY > newHeight - 1) {
_cursorY--;
} else {
lines.pop();
}
}
}
// Ensure cursor is within the screen.
_cursorX = _cursorX.clamp(0, newWidth - 1);
_cursorY = _cursorY.clamp(0, newHeight - 1);
// 2. Adjust the width.
if (newWidth != oldWidth) {
if (terminal.reflowEnabled && !isAltBuffer) {
final reflowResult = reflow(lines, oldWidth, newWidth);
while (reflowResult.length < newHeight) {
reflowResult.add(_newEmptyLine(newWidth));
}
lines.replaceWith(reflowResult);
} else {
lines.forEach((item) => item.resize(newWidth));
}
}
}
/// Create a new [CellAnchor] at the specified [x] and [y] coordinates.
CellAnchor createAnchor(int x, int y) {
return lines[y].createAnchor(x);
}
/// Create a new [CellAnchor] at the specified [x] and [y] coordinates.
CellAnchor createAnchorFromOffset(CellOffset offset) {
return lines[offset.y].createAnchor(offset.x);
}
CellAnchor createAnchorFromCursor() {
return createAnchor(cursorX, absoluteCursorY);
}
/// Create a new empty [BufferLine] with the current [viewWidth] if [width]
/// is not specified.
BufferLine _newEmptyLine([int? width]) {
final line = BufferLine(width ?? viewWidth);
return line;
}
static final defaultWordSeparators = <int>{
0,
r' '.codeUnitAt(0),
r'.'.codeUnitAt(0),
r':'.codeUnitAt(0),
r'-'.codeUnitAt(0),
r'\'.codeUnitAt(0),
r'"'.codeUnitAt(0),
r'*'.codeUnitAt(0),
r'+'.codeUnitAt(0),
r'/'.codeUnitAt(0),
r'\'.codeUnitAt(0),
};
BufferRangeLine? getWordBoundary(CellOffset position) {
var separators = wordSeparators ?? defaultWordSeparators;
if (position.y >= lines.length) {
return null;
}
var line = lines[position.y];
var start = position.x;
var end = position.x;
do {
if (start == 0) {
break;
}
final char = line.getCodePoint(start - 1);
if (separators.contains(char)) {
break;
}
start--;
} while (true);
do {
if (end >= viewWidth) {
break;
}
final char = line.getCodePoint(end);
if (separators.contains(char)) {
break;
}
end++;
} while (true);
if (start == end) {
return null;
}
return BufferRangeLine(
CellOffset(start, position.y),
CellOffset(end, position.y),
);
}
/// Get the plain text content of the buffer including the scrollback.
/// Accepts an optional [range] to get a specific part of the buffer.
String getText([BufferRange? range]) {
range ??= BufferRangeLine(
CellOffset(0, 0),
CellOffset(viewWidth - 1, height - 1),
);
range = range.normalized;
final builder = StringBuffer();
for (var segment in range.toSegments()) {
if (segment.line < 0 || segment.line >= height) {
continue;
}
final line = lines[segment.line];
if (!(segment.line == range.begin.y ||
segment.line == 0 ||
line.isWrapped)) {
builder.write("\n");
}
builder.write(line.getText(segment.start, segment.end));
}
return builder.toString();
}
/// Returns a debug representation of the buffer.
@override
String toString() {
final builder = StringBuffer();
final lineNumberLength = lines.length.toString().length;
for (var i = 0; i < lines.length; i++) {
final line = lines[i];
builder.write('${i.toString().padLeft(lineNumberLength)}: |${lines[i]}|');
if (line.isWrapped) {
builder.write(' (⏎)');
}
builder.write('\n');
}
return builder.toString();
}
}
@@ -0,0 +1,11 @@
abstract class CellFlags {
static const bold = 1 << 0;
static const faint = 1 << 1;
static const italic = 1 << 2;
static const underline = 1 << 3;
static const blink = 1 << 4;
static const inverse = 1 << 5;
static const invisible = 1 << 6;
static const strikethrough = 1 << 7;
static const overline = 1 << 11;
}
@@ -0,0 +1,55 @@
import 'package:xterm/src/core/buffer/range.dart';
class CellOffset {
final int x;
final int y;
const CellOffset(this.x, this.y);
bool isEqual(CellOffset other) {
return other.x == x && other.y == y;
}
bool isBefore(CellOffset other) {
return y < other.y || (y == other.y && x < other.x);
}
bool isAfter(CellOffset other) {
return y > other.y || (y == other.y && x > other.x);
}
bool isBeforeOrSame(CellOffset other) {
return y < other.y || (y == other.y && x <= other.x);
}
bool isAfterOrSame(CellOffset other) {
return y > other.y || (y == other.y && x >= other.x);
}
bool isAtSameRow(CellOffset other) {
return y == other.y;
}
bool isAtSameColumn(CellOffset other) {
return x == other.x;
}
bool isWithin(BufferRange range) {
return range.contains(this);
}
@override
String toString() => 'CellOffset($x, $y)';
@override
int get hashCode => x.hashCode ^ y.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is CellOffset &&
runtimeType == other.runtimeType &&
x == other.x &&
y == other.y;
}
+418
View File
@@ -0,0 +1,418 @@
import 'dart:math' show min;
import 'dart:typed_data';
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/cell.dart';
import 'package:xterm/src/core/cursor.dart';
import 'package:xterm/src/utils/circular_buffer.dart';
import 'package:xterm/src/utils/unicode_v11.dart';
const _cellSize = 4;
const _cellForeground = 0;
const _cellBackground = 1;
const _cellAttributes = 2;
const _cellContent = 3;
class BufferLine with IndexedItem {
BufferLine(
this._length, {
this.isWrapped = false,
}) : _data = Uint32List(_calcCapacity(_length) * _cellSize);
int _length;
Uint32List _data;
Uint32List get data => _data;
var isWrapped = false;
int get length => _length;
final _anchors = <CellAnchor>[];
List<CellAnchor> get anchors => _anchors;
int getForeground(int index) {
return _data[index * _cellSize + _cellForeground];
}
int getBackground(int index) {
return _data[index * _cellSize + _cellBackground];
}
int getAttributes(int index) {
return _data[index * _cellSize + _cellAttributes];
}
int getContent(int index) {
return _data[index * _cellSize + _cellContent];
}
int getCodePoint(int index) {
return _data[index * _cellSize + _cellContent] & CellContent.codepointMask;
}
int getWidth(int index) {
return _data[index * _cellSize + _cellContent] >> CellContent.widthShift;
}
void getCellData(int index, CellData cellData) {
final offset = index * _cellSize;
cellData.foreground = _data[offset + _cellForeground];
cellData.background = _data[offset + _cellBackground];
cellData.flags = _data[offset + _cellAttributes];
cellData.content = _data[offset + _cellContent];
}
CellData createCellData(int index) {
final cellData = CellData.empty();
final offset = index * _cellSize;
_data[offset + _cellForeground] = cellData.foreground;
_data[offset + _cellBackground] = cellData.background;
_data[offset + _cellAttributes] = cellData.flags;
_data[offset + _cellContent] = cellData.content;
return cellData;
}
void setForeground(int index, int value) {
_data[index * _cellSize + _cellForeground] = value;
}
void setBackground(int index, int value) {
_data[index * _cellSize + _cellBackground] = value;
}
void setAttributes(int index, int value) {
_data[index * _cellSize + _cellAttributes] = value;
}
void setContent(int index, int value) {
_data[index * _cellSize + _cellContent] = value;
}
void setCodePoint(int index, int char) {
final width = unicodeV11.wcwidth(char);
setContent(index, char | (width << CellContent.widthShift));
}
void setCell(int index, int char, int witdh, CursorStyle style) {
final offset = index * _cellSize;
_data[offset + _cellForeground] = style.foreground;
_data[offset + _cellBackground] = style.background;
_data[offset + _cellAttributes] = style.attrs;
_data[offset + _cellContent] = char | (witdh << CellContent.widthShift);
}
void setCellData(int index, CellData cellData) {
final offset = index * _cellSize;
_data[offset + _cellForeground] = cellData.foreground;
_data[offset + _cellBackground] = cellData.background;
_data[offset + _cellAttributes] = cellData.flags;
_data[offset + _cellContent] = cellData.content;
}
void eraseCell(int index, CursorStyle style) {
final offset = index * _cellSize;
_data[offset + _cellForeground] = style.foreground;
_data[offset + _cellBackground] = style.background;
_data[offset + _cellAttributes] = style.attrs;
_data[offset + _cellContent] = 0;
}
void resetCell(int index) {
final offset = index * _cellSize;
_data[offset + _cellForeground] = 0;
_data[offset + _cellBackground] = 0;
_data[offset + _cellAttributes] = 0;
_data[offset + _cellContent] = 0;
}
/// Erase cells whose index satisfies [start] <= index < [end]. Erased cells
/// are filled with [style].
void eraseRange(int start, int end, CursorStyle style) {
// reset cell one to the left if start is second cell of a wide char
if (start > 0 && getWidth(start - 1) == 2) {
eraseCell(start - 1, style);
}
// reset cell one to the right if end is second cell of a wide char
if (end < _length && getWidth(end - 1) == 2) {
eraseCell(end - 1, style);
}
end = min(end, _length);
for (var i = start; i < end; i++) {
eraseCell(i, style);
}
}
/// Remove [count] cells starting at [start]. Cells that are empty after the
/// removal are filled with [style].
void removeCells(int start, int count, [CursorStyle? style]) {
assert(start >= 0 && start < _length);
assert(count >= 0 && start + count <= _length);
style ??= CursorStyle.empty;
if (start + count < _length) {
final moveStart = start * _cellSize;
final moveEnd = (_length - count) * _cellSize;
final moveOffset = count * _cellSize;
for (var i = moveStart; i < moveEnd; i++) {
_data[i] = _data[i + moveOffset];
}
}
for (var i = _length - count; i < _length; i++) {
eraseCell(i, style);
}
if (start > 0 && getWidth(start - 1) == 2) {
eraseCell(start - 1, style);
}
// Update anchors, remove anchors that are inside the removed range.
for (var i = 0; i < _anchors.length; i++) {
final anchor = _anchors[i];
if (anchor.x >= start) {
if (anchor.x < start + count) {
anchor.dispose();
} else {
anchor.reposition(anchor.x - count);
}
}
}
}
/// Inserts [count] cells at [start]. New cells are initialized with [style].
void insertCells(int start, int count, [CursorStyle? style]) {
style ??= CursorStyle.empty;
if (start > 0 && getWidth(start - 1) == 2) {
eraseCell(start - 1, style);
}
if (start + count < _length) {
final moveStart = start * _cellSize;
final moveEnd = (_length - count) * _cellSize;
final moveOffset = count * _cellSize;
for (var i = moveEnd - 1; i >= moveStart; i--) {
_data[i + moveOffset] = _data[i];
}
}
final end = min(start + count, _length);
for (var i = start; i < end; i++) {
eraseCell(i, style);
}
if (getWidth(_length - 1) == 2) {
eraseCell(_length - 1, style);
}
// Update anchors, move anchors that are after the inserted range.
for (var i = 0; i < _anchors.length; i++) {
final anchor = _anchors[i];
if (anchor.x >= start + count) {
anchor.reposition(anchor.x + count);
// Remove anchors that are now outside the buffer.
if (anchor.x >= _length) {
anchor.dispose();
}
}
}
}
void resize(int length) {
assert(length >= 0);
if (length == _length) {
return;
}
if (length > _length) {
final newBufferSize = _calcCapacity(length) * _cellSize;
if (newBufferSize > _data.length) {
final newBuffer = Uint32List(newBufferSize);
newBuffer.setRange(0, _data.length, _data);
_data = newBuffer;
}
}
_length = length;
for (var i = 0; i < _anchors.length; i++) {
final anchor = _anchors[i];
if (anchor.x > _length) {
anchor.reposition(_length);
}
}
}
/// Returns the offset of the last cell that has content from the start of
/// the line.
int getTrimmedLength([int? cols]) {
final maxCols = _data.length ~/ _cellSize;
if (cols == null || cols > maxCols) {
cols = maxCols;
}
if (cols <= 0) {
return 0;
}
for (var i = cols - 1; i >= 0; i--) {
var codePoint = getCodePoint(i);
if (codePoint != 0) {
// we are at the last cell in this line that has content.
// the length of this line is the index of this cell + 1
// the only exception is that if that last cell is wider
// than 1 then we have to add the diff
final lastCellWidth = getWidth(i);
return i + lastCellWidth;
}
}
return 0;
}
/// Copies [len] cells from [src] starting at [srcCol] to [dstCol] at this
/// line.
void copyFrom(BufferLine src, int srcCol, int dstCol, int len) {
resize(dstCol + len);
// data.setRange(
// dstCol * _cellSize,
// (dstCol + len) * _cellSize,
// Uint32List.sublistView(src.data, srcCol * _cellSize, len * _cellSize),
// );
var srcOffset = srcCol * _cellSize;
var dstOffset = dstCol * _cellSize;
for (var i = 0; i < len * _cellSize; i++) {
_data[dstOffset++] = src._data[srcOffset++];
}
}
static int _calcCapacity(int length) {
assert(length >= 0);
var capacity = 64;
if (length < 256) {
while (capacity < length) {
capacity *= 2;
}
} else {
capacity = 256;
while (capacity < length) {
capacity += 32;
}
}
return capacity;
}
String getText([int? from, int? to]) {
if (from == null || from < 0) {
from = 0;
}
if (to == null || to > _length) {
to = _length;
}
final builder = StringBuffer();
for (var i = from; i < to; i++) {
final codePoint = getCodePoint(i);
final width = getWidth(i);
if (codePoint != 0 && i + width <= to) {
builder.writeCharCode(codePoint);
}
}
return builder.toString();
}
CellAnchor createAnchor(int offset) {
final anchor = CellAnchor(offset, owner: this);
_anchors.add(anchor);
return anchor;
}
void dispose() {
for (final anchor in _anchors) {
anchor.dispose();
}
}
@override
String toString() {
return getText();
}
}
/// A handle to a cell in a [BufferLine] that can be used to track the location
/// of the cell. Anchors are guaranteed to be stable, retaining their relative
/// position to each other after mutations to the buffer.
class CellAnchor {
CellAnchor(int offset, {BufferLine? owner})
: _offset = offset,
_owner = owner;
int _offset;
int get x {
return _offset;
}
int get y {
assert(attached);
return _owner!.index;
}
CellOffset get offset {
assert(attached);
return CellOffset(_offset, _owner!.index);
}
BufferLine? _owner;
BufferLine? get line => _owner;
bool get attached => _owner?.attached ?? false;
void reparent(BufferLine owner, int offset) {
_owner?._anchors.remove(this);
_owner = owner;
_owner?._anchors.add(this);
_offset = offset;
}
void reposition(int offset) {
_offset = offset;
}
void dispose() {
_owner?._anchors.remove(this);
_owner = null;
}
@override
String toString() {
if (attached) {
return 'CellAnchor($x, $y)';
} else {
return 'CellAnchor($x, detached)';
}
}
}
+55
View File
@@ -0,0 +1,55 @@
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/buffer/segment.dart';
abstract class BufferRange {
final CellOffset begin;
final CellOffset end;
const BufferRange(this.begin, this.end);
BufferRange.collapsed(this.begin) : end = begin;
bool get isNormalized {
return begin.isBefore(end) || begin.isEqual(end);
}
bool get isCollapsed {
return begin.isEqual(end);
}
BufferRange get normalized;
/// Convert this range to segments of single lines.
Iterable<BufferSegment> toSegments();
/// Returns true if the given[position] is within this range.
bool contains(CellOffset position);
/// Returns the smallest range that contains both this range and the given
/// [range].
BufferRange merge(BufferRange range);
/// Returns the smallest range that contains both this range and the given
/// [position].
BufferRange extend(CellOffset position);
@override
operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! BufferRange) {
return false;
}
return begin == other.begin && end == other.end;
}
@override
int get hashCode => begin.hashCode ^ end.hashCode;
@override
String toString() => 'Range($begin, $end)';
}
@@ -0,0 +1,111 @@
import 'dart:math';
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/buffer/range.dart';
import 'package:xterm/src/core/buffer/segment.dart';
class BufferRangeBlock extends BufferRange {
BufferRangeBlock(super.begin, super.end);
BufferRangeBlock.collapsed(super.begin) : super.collapsed();
@override
bool get isNormalized {
// A block range is normalized if begin is the top left corner of the range
// and end the bottom right corner.
return (begin.isBefore(end) && begin.x <= end.x) || begin.isEqual(end);
}
@override
BufferRangeBlock get normalized {
if (isNormalized) {
return this;
}
// Determine new normalized begin and end offset, such that begin is the
// top left corner and end is the bottom right corner of the block.
final normalBegin = CellOffset(min(begin.x, end.x), min(begin.y, end.y));
final normalEnd = CellOffset(max(begin.x, end.x), max(begin.y, end.y));
return BufferRangeBlock(normalBegin, normalEnd);
}
@override
Iterable<BufferSegment> toSegments() sync* {
var begin = this.begin;
var end = this.end;
if (!isNormalized) {
end = this.begin;
begin = this.end;
}
final startX = min(begin.x, end.x);
final endX = max(begin.x, end.x);
for (var i = begin.y; i <= end.y; i++) {
yield BufferSegment(this, i, startX, endX);
}
}
@override
bool contains(CellOffset position) {
var begin = this.begin;
var end = this.end;
if (!isNormalized) {
end = this.begin;
begin = this.end;
}
if (!(begin.y <= position.y && position.y <= end.y)) {
return false;
}
final startX = min(begin.x, end.x);
final endX = max(begin.x, end.x);
return startX <= position.x && position.x <= endX;
}
@override
BufferRangeBlock merge(BufferRange range) {
// Enlarge the block such that both borders of the range
// are within the selected block.
return extend(range.begin).extend(range.end);
}
@override
BufferRangeBlock extend(CellOffset position) {
// If the position is within the block, there is nothing to do.
if (contains(position)) {
return this;
}
// Otherwise normalize the block and push the borders outside up to
// the position to which the block has to extended.
final normal = normalized;
final extendBegin = CellOffset(
min(normal.begin.x, position.x),
min(normal.begin.y, position.y),
);
final extendEnd = CellOffset(
max(normal.end.x, position.x),
max(normal.end.y, position.y),
);
return BufferRangeBlock(extendBegin, extendEnd);
}
@override
operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! BufferRangeBlock) {
return false;
}
return begin == other.begin && end == other.end;
}
@override
int get hashCode => begin.hashCode ^ end.hashCode;
@override
String toString() => 'Block Range($begin, $end)';
}
@@ -0,0 +1,66 @@
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/buffer/range.dart';
import 'package:xterm/src/core/buffer/segment.dart';
class BufferRangeLine extends BufferRange {
BufferRangeLine(super.begin, super.end);
BufferRangeLine.collapsed(super.begin) : super.collapsed();
@override
BufferRangeLine get normalized {
return isNormalized ? this : BufferRangeLine(end, begin);
}
@override
Iterable<BufferSegment> toSegments() sync* {
final self = normalized;
for (var i = self.begin.y; i <= self.end.y; i++) {
var startX = i == self.begin.y ? self.begin.x : null;
var endX = i == self.end.y ? self.end.x : null;
yield BufferSegment(this, i, startX, endX);
}
}
@override
bool contains(CellOffset position) {
final self = normalized;
return self.begin.isBeforeOrSame(position) &&
self.end.isAfterOrSame(position);
}
@override
BufferRangeLine merge(BufferRange range) {
final self = normalized;
final begin = self.begin.isBefore(range.begin) ? self.begin : range.begin;
final end = self.end.isAfter(range.end) ? self.end : range.end;
return BufferRangeLine(begin, end);
}
@override
BufferRangeLine extend(CellOffset position) {
final self = normalized;
final begin = self.begin.isAfter(position) ? position : self.begin;
final end = self.end.isBefore(position) ? position : self.end;
return BufferRangeLine(begin, end);
}
@override
operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! BufferRangeLine) {
return false;
}
return begin == other.begin && end == other.end;
}
@override
int get hashCode => begin.hashCode ^ end.hashCode;
@override
String toString() => 'Line Range($begin, $end)';
}
+58
View File
@@ -0,0 +1,58 @@
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/buffer/range.dart';
/// A BufferSegment represents a range within a line.
class BufferSegment {
/// The range that this segment belongs to.
final BufferRange range;
/// The line that this segment resides on.
final int line;
/// The start position of this segment. [null] means the start of the line.
final int? start;
/// The end position of this segment. [null] means the end of the line.
/// Should be greater than or equal to [start].
final int? end;
const BufferSegment(this.range, this.line, this.start, this.end)
: assert((start != null && end != null) ? start <= end : true);
bool isWithin(CellOffset position) {
if (position.y != line) {
return false;
}
if (start != null && position.x < start!) {
return false;
}
if (end != null && position.x > end!) {
return false;
}
return true;
}
@override
String toString() {
final start = this.start != null ? this.start.toString() : 'start';
final end = this.end != null ? this.end.toString() : 'end';
return 'Segment($line, $start -> $end)';
}
@override
int get hashCode =>
range.hashCode ^ line.hashCode ^ start.hashCode ^ end.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is BufferSegment &&
runtimeType == other.runtimeType &&
range == other.range &&
line == other.line &&
start == other.start &&
end == other.end;
}
+77
View File
@@ -0,0 +1,77 @@
import 'package:xterm/src/utils/hash_values.dart';
class CellData {
CellData({
required this.foreground,
required this.background,
required this.flags,
required this.content,
});
factory CellData.empty() {
return CellData(
foreground: 0,
background: 0,
flags: 0,
content: 0,
);
}
int foreground;
int background;
int flags;
int content;
int getHash() {
return hashValues(foreground, background, flags, content);
}
@override
String toString() {
return 'CellData{foreground: $foreground, background: $background, flags: $flags, content: $content}';
}
}
abstract class CellAttr {
static const bold = 1 << 0;
static const faint = 1 << 1;
static const italic = 1 << 2;
static const underline = 1 << 3;
static const blink = 1 << 4;
static const inverse = 1 << 5;
static const invisible = 1 << 6;
static const strikethrough = 1 << 7;
/// The underline style while [underline] is set: 1 single (also 0), 2
/// double, 3 curly, 4 dotted, 5 dashed.
static const underlineStyleShift = 8;
static const underlineStyleMask = 7 << underlineStyleShift;
static const overline = 1 << 11;
/// The OSC 8 hyperlink id (see `Terminal.hyperlinkOf`); 0 without a link.
static const linkShift = 16;
static const linkMask = 0xFFFF << linkShift;
}
abstract class CellColor {
static const valueMask = 0xFFFFFF;
static const typeShift = 25;
static const typeMask = 3 << typeShift;
static const normal = 0 << typeShift;
static const named = 1 << typeShift;
static const palette = 2 << typeShift;
static const rgb = 3 << typeShift;
}
abstract class CellContent {
static const codepointMask = 0x1fffff;
static const widthShift = 22;
// static const widthMask = 3 << widthShift;
}
+104
View File
@@ -0,0 +1,104 @@
typedef CharsetTranslator = int Function(int);
final _charsets = <int, CharsetTranslator>{
'0'.codeUnitAt(0): decSpecGraphicsTranslator,
'B'.codeUnitAt(0): asciiTranslator,
};
class Charset {
var _charsetMap = <int, CharsetTranslator>{};
var _currentIndex = 0;
var _savedCharsetMap = <int, CharsetTranslator>{};
var _savedIndex = 0;
var _cached = asciiTranslator;
void _updateCache() {
_cached = _charsetMap[_currentIndex] ?? asciiTranslator;
}
int translate(int codePoint) {
return _cached(codePoint);
}
void designate(int index, int name) {
final charset = _charsets[name];
if (charset != null) {
_charsetMap[index] = charset;
_updateCache();
}
}
void use(int index) {
_currentIndex = index;
_updateCache();
}
void save() {
_savedCharsetMap = Map.from(_charsetMap);
_savedIndex = _currentIndex;
}
/// Back to G0 selected and no designations (ASCII), as after power-on.
void reset() {
_charsetMap = {};
_currentIndex = 0;
_savedCharsetMap = {};
_savedIndex = 0;
_updateCache();
}
void restore() {
_charsetMap = _savedCharsetMap;
_currentIndex = _savedIndex;
_updateCache();
}
}
const decSpecGraphics = <int, int>{
0x5f: 0x00A0, // NO-BREAK SPACE
0x60: 0x25C6, // BLACK DIAMOND
0x61: 0x2592, // MEDIUM SHADE
0x62: 0x2409, // SYMBOL FOR HORIZONTAL TABULATION
0x63: 0x240C, // SYMBOL FOR FORM FEED
0x64: 0x240D, // SYMBOL FOR CARRIAGE RETURN
0x65: 0x240A, // SYMBOL FOR LINE FEED
0x66: 0x00B0, // DEGREE SIGN
0x67: 0x00B1, // PLUS-MINUS SIGN
0x68: 0x2424, // SYMBOL FOR NEWLINE
0x69: 0x240B, // SYMBOL FOR VERTICAL TABULATION
0x6a: 0x2518, // BOX DRAWINGS LIGHT UP AND LEFT
0x6b: 0x2510, // BOX DRAWINGS LIGHT DOWN AND LEFT
0x6c: 0x250C, // BOX DRAWINGS LIGHT DOWN AND RIGHT
0x6d: 0x2514, // BOX DRAWINGS LIGHT UP AND RIGHT
0x6e: 0x253C, // BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x6f: 0x23BA, // HORIZONTAL SCAN LINE-1
0x70: 0x23BB, // HORIZONTAL SCAN LINE-3
0x71: 0x2500, // BOX DRAWINGS LIGHT HORIZONTAL
0x72: 0x23BC, // HORIZONTAL SCAN LINE-7
0x73: 0x23BD, // HORIZONTAL SCAN LINE-9
0x74: 0x251C, // BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x75: 0x2524, // BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x76: 0x2534, // BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x77: 0x252C, // BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x78: 0x2502, // BOX DRAWINGS LIGHT VERTICAL
0x79: 0x2264, // LESS-THAN OR EQUAL TO
0x7a: 0x2265, // GREATER-THAN OR EQUAL TO
0x7b: 0x03C0, // GREEK SMALL LETTER PI
0x7c: 0x2260, // NOT EQUAL TO
0x7d: 0x00A3, // POUND SIGN
0x7e: 0x00B7, // MIDDLE DOT
};
int asciiTranslator(int codePoint) {
return codePoint;
}
int decSpecGraphicsTranslator(int codePoint) {
if (codePoint >= 127) {
return codePoint;
}
return decSpecGraphics[codePoint] ?? codePoint;
}
+19
View File
@@ -0,0 +1,19 @@
abstract class NamedColor {
static const black = 0;
static const red = 1;
static const green = 2;
static const yellow = 3;
static const blue = 4;
static const magenta = 5;
static const cyan = 6;
static const white = 7;
static const brightBlack = 8;
static const brightRed = 9;
static const brightGreen = 10;
static const brightYellow = 11;
static const brightBlue = 12;
static const brightMagenta = 13;
static const brightCyan = 14;
static const brightWhite = 15;
}
+166
View File
@@ -0,0 +1,166 @@
import 'package:xterm/src/core/cell.dart';
class CursorStyle {
int foreground;
int background;
int attrs;
CursorStyle({this.foreground = 0, this.background = 0, this.attrs = 0});
static final empty = CursorStyle();
void setBold() {
attrs |= CellAttr.bold;
}
void setFaint() {
attrs |= CellAttr.faint;
}
void setItalic() {
attrs |= CellAttr.italic;
}
/// Turns underline on in [style] (see [CellAttr.underlineStyleMask]).
void setUnderline([int style = 1]) {
attrs = (attrs & ~CellAttr.underlineStyleMask) |
CellAttr.underline |
((style & 7) << CellAttr.underlineStyleShift);
}
void setOverline() {
attrs |= CellAttr.overline;
}
void unsetOverline() {
attrs &= ~CellAttr.overline;
}
void setBlink() {
attrs |= CellAttr.blink;
}
void setInverse() {
attrs |= CellAttr.inverse;
}
void setInvisible() {
attrs |= CellAttr.invisible;
}
void setStrikethrough() {
attrs |= CellAttr.strikethrough;
}
void unsetBold() {
attrs &= ~CellAttr.bold;
}
void unsetFaint() {
attrs &= ~CellAttr.faint;
}
void unsetItalic() {
attrs &= ~CellAttr.italic;
}
void unsetUnderline() {
attrs &= ~(CellAttr.underline | CellAttr.underlineStyleMask);
}
void unsetBlink() {
attrs &= ~CellAttr.blink;
}
void unsetInverse() {
attrs &= ~CellAttr.inverse;
}
void unsetInvisible() {
attrs &= ~CellAttr.invisible;
}
void unsetStrikethrough() {
attrs &= ~CellAttr.strikethrough;
}
bool get isBold => (attrs & CellAttr.bold) != 0;
bool get isFaint => (attrs & CellAttr.faint) != 0;
bool get isItalis => (attrs & CellAttr.italic) != 0;
bool get isUnderline => (attrs & CellAttr.underline) != 0;
bool get isBlink => (attrs & CellAttr.blink) != 0;
bool get isInverse => (attrs & CellAttr.inverse) != 0;
bool get isInvisible => (attrs & CellAttr.invisible) != 0;
bool get isStrikethrough => (attrs & CellAttr.strikethrough) != 0;
bool get isOverline => (attrs & CellAttr.overline) != 0;
/// The underline style (1-5), or 0 without underline.
int get underlineStyle => isUnderline
? (attrs & CellAttr.underlineStyleMask) >> CellAttr.underlineStyleShift
: 0;
void setForegroundColor16(int color) {
foreground = color | CellColor.named;
}
void setForegroundColor256(int color) {
foreground = color | CellColor.palette;
}
void setForegroundColorRgb(int r, int g, int b) {
foreground = (r << 16) | (g << 8) | b | CellColor.rgb;
}
void resetForegroundColor() {
foreground = 0; // | CellColor.normal;
}
void setBackgroundColor16(int color) {
background = color | CellColor.named;
}
void setBackgroundColor256(int color) {
background = color | CellColor.palette;
}
void setBackgroundColorRgb(int r, int g, int b) {
background = (r << 16) | (g << 8) | b | CellColor.rgb;
}
void resetBackgroundColor() {
background = 0; // | CellColor.normal;
}
/// SGR 0: colours and attributes back to normal. An open OSC 8 hyperlink
/// is not an SGR attribute and stays open.
void reset() {
foreground = 0;
background = 0;
attrs &= CellAttr.linkMask;
}
/// The OSC 8 hyperlink id written with the text, 0 for none.
int get linkId => (attrs & CellAttr.linkMask) >> CellAttr.linkShift;
set linkId(int id) {
attrs = (attrs & ~CellAttr.linkMask) | ((id & 0xFFFF) << CellAttr.linkShift);
}
}
class CursorPosition {
int x;
int y;
CursorPosition(this.x, this.y);
}
+44
View File
@@ -0,0 +1,44 @@
class EscapeEmitter {
const EscapeEmitter();
String primaryDeviceAttributes() {
return '\x1b[?1;2c';
}
String secondaryDeviceAttributes() {
const model = 0;
const version = 0;
return '\x1b[>$model;$version;0c';
}
String tertiaryDeviceAttributes() {
return '\x1bP!|00000000\x1b\\';
}
String operatingStatus() {
return '\x1b[0n';
}
/// The CPR reply for the zero-based cursor ([x], [y]); the protocol is
/// one-based.
String cursorPosition(int x, int y) {
return '\x1b[${y + 1};${x + 1}R';
}
String bracketedPaste(String text) {
return '\x1b[200~$text\x1b[201~';
}
/// The reply to an OSC [which] (10, 11 or 12) colour query: `OSC Ps ;
/// rgb:rrrr/gggg/bbbb` with [terminator] (BEL or ST, as the query had).
String dynamicColor(int which, int rgb, String terminator) {
String channel(int shift) =>
(((rgb >> shift) & 0xFF) * 0x101).toRadixString(16).padLeft(4, '0');
return '\x1b]$which;rgb:${channel(16)}/${channel(8)}/${channel(0)}'
'$terminator';
}
String size(int rows, int cols) {
return '\x1b[8;$rows;${cols}t';
}
}
+262
View File
@@ -0,0 +1,262 @@
import 'package:xterm/src/core/mouse/mode.dart';
abstract class EscapeHandler {
void writeChar(int char);
/* SBC */
void bell();
void backspaceReturn();
void tab();
void lineFeed();
void carriageReturn();
void shiftOut();
void shiftIn();
void unknownSBC(int char);
/* ANSI sequence */
void saveCursor();
void restoreCursor();
void index();
void nextLine();
void setTapStop();
void reverseIndex();
void designateCharset(int charset, int name);
void unkownEscape(int char);
/// `ESC c` (RIS): everything back to the power-on state, screen cleared.
void resetTerminal();
/// `CSI ! p` (DECSTR): modes, attributes and margins reset; the screen
/// contents stay.
void softResetTerminal();
/* DCS */
/// `DCS $ q Pt ST` (DECRQSS): report the setting named by [setting], such
/// as `m` (SGR), `r` (margins) or ` q` (cursor style).
void requestStatusString(String setting);
/* CSI */
void repeatPreviousCharacter(int n);
void setCursor(int x, int y);
void setCursorX(int x);
void setCursorY(int y);
void sendPrimaryDeviceAttributes();
void clearTabStopUnderCursor();
void clearAllTabStops();
void moveCursorX(int offset);
void moveCursorY(int n);
void sendSecondaryDeviceAttributes();
void sendTertiaryDeviceAttributes();
void sendOperatingStatus();
void sendCursorPosition();
void setMargins(int i, [int? bottom]);
void cursorNextLine(int amount);
void cursorPrecedingLine(int amount);
/// Moves the cursor forward [amount] tab stops (CHT), stopping at the last
/// column.
void cursorForwardTab(int amount);
/// Moves the cursor back [amount] tab stops (CBT), stopping at column 0.
void cursorBackwardTab(int amount);
void eraseDisplayBelow();
void eraseDisplayAbove();
void eraseDisplay();
void eraseScrollbackOnly();
void eraseLineRight();
void eraseLineLeft();
void eraseLine();
void insertLines(int amount);
void deleteLines(int amount);
void deleteChars(int amount);
void scrollUp(int amount);
void scrollDown(int amount);
void eraseChars(int amount);
void insertBlankChars(int amount);
void unknownCSI(int finalByte);
/// `CSI Ps SP q` (DECSCUSR): 0 default, 1/2 blinking/steady block, 3/4
/// underline, 5/6 bar.
void setCursorShape(int shape);
/* Modes */
void setInsertMode(bool enabled);
void setLineFeedMode(bool enabled);
void setUnknownMode(int mode, bool enabled);
/* DEC Private modes */
void setCursorKeysMode(bool enabled);
void setReverseDisplayMode(bool enabled);
void setOriginMode(bool enabled);
void setColumnMode(bool enabled);
void setAutoWrapMode(bool enabled);
void setMouseMode(MouseMode mode);
void setCursorBlinkMode(bool enabled);
void setCursorVisibleMode(bool enabled);
void useAltBuffer();
void useMainBuffer();
void clearAltBuffer();
void setAppKeypadMode(bool enabled);
void setReportFocusMode(bool enabled);
void setMouseReportMode(MouseReportMode mode);
void setAltBufferMouseScrollMode(bool enabled);
void setBracketedPasteMode(bool enabled);
void setUnknownDecMode(int mode, bool enabled);
void resize(int cols, int rows);
void sendSize();
/* Select Graphic Rendition (SGR) */
void resetCursorStyle();
void setCursorBold();
void setCursorFaint();
void setCursorItalic();
void setCursorUnderline();
/// Underline in [style]: 1 single, 2 double, 3 curly, 4 dotted, 5 dashed.
void setCursorUnderlineStyle(int style);
void setCursorOverline();
void unsetCursorOverline();
void setCursorBlink();
void setCursorInverse();
void setCursorInvisible();
void setCursorStrikethrough();
void unsetCursorBold();
void unsetCursorFaint();
void unsetCursorItalic();
void unsetCursorUnderline();
void unsetCursorBlink();
void unsetCursorInverse();
void unsetCursorInvisible();
void unsetCursorStrikethrough();
void setForegroundColor16(int color);
void setForegroundColor256(int index);
void setForegroundColorRgb(int r, int g, int b);
void resetForeground();
void setBackgroundColor16(int color);
void setBackgroundColor256(int index);
void setBackgroundColorRgb(int r, int g, int b);
void resetBackground();
void unsupportedStyle(int param);
/* OSC */
void setTitle(String name);
void setIconName(String name);
/// `OSC 7 ; URI ST`: the program's working directory, as a `file:` URI.
void setWorkingDirectory(String uri);
/// `OSC 8 ; params ; URI ST`: text written from now on links to [uri];
/// an empty [uri] ends the link. [params] is `key=value` pairs separated
/// by `:`, such as `id=x`.
void setHyperlink(String params, String uri);
/// `OSC 10/11/12 ; ? ST`: report the foreground (10), background (11) or
/// cursor (12) colour, terminated with BEL when [bel] or ST otherwise.
void queryDynamicColor(int which, {required bool bel});
/// `OSC 52 ; Pc ; Pd ST`: set the clipboard selections [selection] (for
/// example `c`) to the base64 [data]. `?` asks to read the clipboard.
void setClipboard(String selection, String data);
void unknownOSC(String code, List<String> args);
}
File diff suppressed because it is too large Load Diff
+152
View File
@@ -0,0 +1,152 @@
import 'package:xterm/src/core/color.dart';
import 'package:xterm/src/core/escape/handler.dart';
/// Applies the parameters of `CSI Pm m` (SGR) to [handler].
///
/// [params] holds every parameter in order and [isSub] marks the ones that
/// were introduced by a colon, so a parameter followed by colon
/// subparameters forms one group: `4:3` is curly underline, not underline
/// followed by `3` (italic), and `38:2::r:g:b` is one direct colour.
///
/// The legacy semicolon forms `38;5;n` and `38;2;r;g;b` consume the
/// parameters that follow. A truncated sequence stops processing instead of
/// reading past the end.
///
/// https://terminalguide.namepad.de/seq/csi_sm/
void applySgr(EscapeHandler handler, List<int> params, List<bool> isSub) {
if (params.isEmpty) {
handler.resetCursorStyle();
return;
}
var i = 0;
while (i < params.length) {
final code = params[i++];
final subStart = i;
while (i < params.length && isSub[i]) {
i++;
}
final subCount = i - subStart;
switch (code) {
case 0:
handler.resetCursorStyle();
case 1:
handler.setCursorBold();
case 2:
handler.setCursorFaint();
case 3:
handler.setCursorItalic();
case 4:
final style = subCount > 0 ? params[subStart] : 1;
if (style == 0) {
handler.unsetCursorUnderline();
} else {
handler.setCursorUnderlineStyle(style > 5 ? 1 : style);
}
case 5:
case 6:
handler.setCursorBlink();
case 7:
handler.setCursorInverse();
case 8:
handler.setCursorInvisible();
case 9:
handler.setCursorStrikethrough();
case 21:
// ECMA-48 and xterm: doubly underlined (not "bold off").
handler.setCursorUnderlineStyle(2);
case 22:
handler.unsetCursorBold();
handler.unsetCursorFaint();
case 23:
handler.unsetCursorItalic();
case 24:
handler.unsetCursorUnderline();
case 25:
handler.unsetCursorBlink();
case 27:
handler.unsetCursorInverse();
case 28:
handler.unsetCursorInvisible();
case 29:
handler.unsetCursorStrikethrough();
case >= 30 && <= 37:
handler.setForegroundColor16(NamedColor.black + code - 30);
case 38:
case 48:
case 58:
if (subCount > 0) {
_extendedColor(handler, code, params, subStart, subCount);
} else {
final used = _semicolonColorLength(params, isSub, i);
if (used < 0) return; // truncated: nothing sensible follows
_extendedColor(handler, code, params, i, used);
i += used;
}
case 39:
handler.resetForeground();
case >= 40 && <= 47:
handler.setBackgroundColor16(NamedColor.black + code - 40);
case 49:
handler.resetBackground();
case 53:
handler.setCursorOverline();
case 55:
handler.unsetCursorOverline();
case 59:
// Default underline colour; underline colours are not rendered.
break;
case >= 90 && <= 97:
handler.setForegroundColor16(NamedColor.brightBlack + code - 90);
case >= 100 && <= 107:
handler.setBackgroundColor16(NamedColor.brightBlack + code - 100);
default:
handler.unsupportedStyle(code);
}
}
}
/// How many parameters after [at] the semicolon form of an extended colour
/// takes (`5;n` or `2;r;g;b`), or -1 when the sequence ends too early.
int _semicolonColorLength(List<int> params, List<bool> isSub, int at) {
if (at >= params.length) return -1;
final needed = switch (params[at]) {
5 => 2,
2 => 4,
_ => 1,
};
if (at + needed > params.length) return -1;
return needed;
}
/// Applies an extended colour whose mode is `params[at]` and whose values
/// follow it, [count] parameters in all. [target] is 38 (foreground), 48
/// (background) or 58 (underline colour, accepted and ignored).
void _extendedColor(
EscapeHandler handler,
int target,
List<int> params,
int at,
int count,
) {
final mode = params[at];
if (mode == 5 && count >= 2) {
final index = params[at + 1];
if (index > 255) return;
if (target == 38) handler.setForegroundColor256(index);
if (target == 48) handler.setBackgroundColor256(index);
return;
}
if (mode == 2 && count >= 4) {
// `2:Pi:r:g:b` carries a colour space id first; `2:r:g:b` and the
// semicolon form `2;r;g;b` do not.
final rgbAt = count >= 5 ? at + 2 : at + 1;
final r = params[rgbAt].clamp(0, 255);
final g = params[rgbAt + 1].clamp(0, 255);
final b = params[rgbAt + 2].clamp(0, 255);
if (target == 38) handler.setForegroundColorRgb(r, g, b);
if (target == 48) handler.setBackgroundColorRgb(r, g, b);
}
}
@@ -0,0 +1,40 @@
import 'package:xterm/src/core/cell.dart';
import 'package:xterm/src/core/cursor.dart';
/// The SGR parameters that recreate [style], for a DECRQSS `m` reply:
/// `0;1;38;5;196` and so on, always starting with a reset.
String sgrReport(CursorStyle style) {
final params = <String>['0'];
if (style.isBold) params.add('1');
if (style.isFaint) params.add('2');
if (style.isItalis) params.add('3');
switch (style.underlineStyle) {
case 0:
break;
case 1:
params.add('4');
default:
params.add('4:${style.underlineStyle}');
}
if (style.isBlink) params.add('5');
if (style.isInverse) params.add('7');
if (style.isInvisible) params.add('8');
if (style.isStrikethrough) params.add('9');
if (style.isOverline) params.add('53');
_color(params, style.foreground, 30, 90, 38);
_color(params, style.background, 40, 100, 48);
return params.join(';');
}
void _color(List<String> params, int color, int base, int bright, int ext) {
final value = color & CellColor.valueMask;
switch (color & CellColor.typeMask) {
case CellColor.named:
params.add('${value < 8 ? base + value : bright + value - 8}');
case CellColor.palette:
params.add('$ext;5;$value');
case CellColor.rgb:
params
.add('$ext;2;${value >> 16};${(value >> 8) & 0xFF};${value & 0xFF}');
}
}
+34
View File
@@ -0,0 +1,34 @@
/// The OSC 8 hyperlinks a terminal has seen. Cells store a 16-bit id (see
/// `CellAttr.linkMask`); this maps ids to their targets. Ids are never
/// reused, because cells in the scrollback may still refer to them; once
/// all ids are taken, new links are not recorded.
class HyperlinkTable {
static const maxLinks = 0xFFFF;
final _uris = <String>[''];
final _ids = <String, int>{};
/// The id for a link to [uri] with OSC 8 [params], 0 when [uri] is empty
/// (the link ends) or the table is full. The same `id=` parameter and URI
/// share an id; links without an `id=` share one per URI.
int idFor(String params, String uri) {
if (uri.isEmpty) return 0;
final key = '${_idParam(params)}\u0000$uri';
final known = _ids[key];
if (known != null) return known;
if (_uris.length > maxLinks) return 0;
_uris.add(uri);
return _ids[key] = _uris.length - 1;
}
/// The target of link [id], or null for 0 or an unknown id.
String? uriOf(int id) => id <= 0 || id >= _uris.length ? null : _uris[id];
static String _idParam(String params) {
for (final pair in params.split(':')) {
if (pair.startsWith('id=')) return pair.substring(3);
}
return '';
}
}
+210
View File
@@ -0,0 +1,210 @@
import 'package:xterm/src/core/input/keys.dart';
import 'package:xterm/src/core/input/keytab/keytab.dart';
import 'package:xterm/src/core/state.dart';
import 'package:xterm/src/core/platform.dart';
/// The key event received from the keyboard, along with the state of the
/// modifier keys and state of the terminal. Typically consumed by the
/// [TerminalInputHandler] to produce a escape sequence that can be recognized
/// by the terminal.
///
/// See also:
/// - [TerminalInputHandler]
class TerminalKeyboardEvent {
final TerminalKey key;
final bool shift;
final bool ctrl;
final bool alt;
final TerminalState state;
final bool altBuffer;
final TerminalTargetPlatform platform;
TerminalKeyboardEvent({
required this.key,
required this.shift,
required this.ctrl,
required this.alt,
required this.state,
required this.altBuffer,
required this.platform,
});
TerminalKeyboardEvent copyWith({
TerminalKey? key,
bool? shift,
bool? ctrl,
bool? alt,
TerminalState? state,
bool? altBuffer,
TerminalTargetPlatform? platform,
}) {
return TerminalKeyboardEvent(
key: key ?? this.key,
shift: shift ?? this.shift,
ctrl: ctrl ?? this.ctrl,
alt: alt ?? this.alt,
state: state ?? this.state,
altBuffer: altBuffer ?? this.altBuffer,
platform: platform ?? this.platform,
);
}
}
/// TerminalInputHandler contains the logic for translating a [TerminalKeyboardEvent]
/// into escape sequences that can be recognized by the terminal.
abstract class TerminalInputHandler {
/// Translates a [TerminalKeyboardEvent] into an escape sequence. If the event
/// cannot be translated, null is returned.
String? call(TerminalKeyboardEvent event);
}
/// A [TerminalInputHandler] that chains multiple handlers together. If any
/// handler returns a non-null value, it is returned. Otherwise, null is
/// returned.
class CascadeInputHandler implements TerminalInputHandler {
final List<TerminalInputHandler> _handlers;
const CascadeInputHandler(this._handlers);
@override
String? call(TerminalKeyboardEvent event) {
for (var handler in _handlers) {
final result = handler(event);
if (result != null) {
return result;
}
}
return null;
}
}
/// The default input handler for the terminal. That is composed of a
/// [KeytabInputHandler], a [CtrlInputHandler], and a [AltInputHandler].
///
/// It's possible to override the default input handler behavior by chaining
/// another input handler before or after the default input handler using
/// [CascadeInputHandler].
///
/// See also:
/// * [CascadeInputHandler]
const defaultInputHandler = CascadeInputHandler([
KeytabInputHandler(),
CtrlInputHandler(),
AltInputHandler(),
]);
/// A [TerminalInputHandler] that translates key events according to a keytab
/// file. If no keytab is provided, [Keytab.defaultKeytab] is used.
class KeytabInputHandler implements TerminalInputHandler {
const KeytabInputHandler([this.keytab]);
final Keytab? keytab;
@override
String? call(TerminalKeyboardEvent event) {
final keytab = this.keytab ?? Keytab.defaultKeytab;
final record = keytab.find(
event.key,
ctrl: event.ctrl,
alt: event.alt,
shift: event.shift,
newLineMode: event.state.lineFeedMode,
appCursorKeys: event.state.cursorKeysMode,
appKeyPad: event.state.appKeypadMode,
appScreen: event.altBuffer,
macos: event.platform == TerminalTargetPlatform.macos,
);
if (record == null) {
return null;
}
var result = record.action.unescapedValue();
result = insertModifiers(event, result);
return result;
}
String insertModifiers(TerminalKeyboardEvent event, String action) {
String? code;
if (event.shift && event.alt && event.ctrl) {
code = '8';
} else if (event.ctrl && event.alt) {
code = '7';
} else if (event.shift && event.ctrl) {
code = '6';
} else if (event.ctrl) {
code = '5';
} else if (event.shift && event.alt) {
code = '4';
} else if (event.alt) {
code = '3';
} else if (event.shift) {
code = '2';
}
if (code != null) {
return action.replaceAll('*', code);
}
return action;
}
}
/// A [TerminalInputHandler] that translates ctrl + key events into escape
/// sequences. For example, ctrl + a becomes ^A.
class CtrlInputHandler implements TerminalInputHandler {
const CtrlInputHandler();
@override
String? call(TerminalKeyboardEvent event) {
if (!event.ctrl || event.shift || event.alt) {
return null;
}
final key = event.key;
if (key.index >= TerminalKey.keyA.index &&
key.index <= TerminalKey.keyZ.index) {
final input = key.index - TerminalKey.keyA.index + 1;
return String.fromCharCode(input);
}
return null;
}
}
/// A [TerminalInputHandler] that translates alt + key events into escape
/// sequences. For example, alt + a becomes ^[a.
class AltInputHandler implements TerminalInputHandler {
const AltInputHandler();
@override
String? call(TerminalKeyboardEvent event) {
if (!event.alt || event.ctrl || event.shift) {
return null;
}
if (event.platform == TerminalTargetPlatform.macos) {
return null;
}
final key = event.key;
if (key.index >= TerminalKey.keyA.index &&
key.index <= TerminalKey.keyZ.index) {
final charCode = key.index - TerminalKey.keyA.index + 65;
final input = [0x1b, charCode];
return String.fromCharCodes(input);
}
return null;
}
}
+835
View File
@@ -0,0 +1,835 @@
enum TerminalKey {
/// Represents the logical "None" key on the keyboard.
none,
/// Represents the logical "Hyper" key on the keyboard.
hyper,
/// Represents the logical "Super Key" key on the keyboard.
superKey,
/// Represents the logical "Fn Lock" key on the keyboard.
fnLock,
/// Represents the logical "Suspend" key on the keyboard.
suspend,
/// Represents the logical "Resume" key on the keyboard.
resume,
/// Represents the logical "Turbo" key on the keyboard.
turbo,
/// Represents the logical "Privacy Screen Toggle" key on the keyboard.
privacyScreenToggle,
/// Represents the logical "Sleep" key on the keyboard.
sleep,
/// Represents the logical "Wake Up" key on the keyboard.
wakeUp,
/// Represents the logical "Display Toggle Int Ext" key on the keyboard.
displayToggleIntExt,
/// Represents the logical "Usb Reserved" key on the keyboard.
usbReserved,
/// Represents the logical "Usb Error Roll Over" key on the keyboard.
usbErrorRollOver,
/// Represents the logical "Usb Post Fail" key on the keyboard.
usbPostFail,
/// Represents the logical "Usb Error Undefined" key on the keyboard.
usbErrorUndefined,
/// Represents the logical "Key A" key on the keyboard.
keyA,
/// Represents the logical "Key B" key on the keyboard.
keyB,
/// Represents the logical "Key C" key on the keyboard.
keyC,
/// Represents the logical "Key D" key on the keyboard.
keyD,
/// Represents the logical "Key E" key on the keyboard.
keyE,
/// Represents the logical "Key F" key on the keyboard.
keyF,
/// Represents the logical "Key G" key on the keyboard.
keyG,
/// Represents the logical "Key H" key on the keyboard.
keyH,
/// Represents the logical "Key I" key on the keyboard.
keyI,
/// Represents the logical "Key J" key on the keyboard.
keyJ,
/// Represents the logical "Key K" key on the keyboard.
keyK,
/// Represents the logical "Key L" key on the keyboard.
keyL,
/// Represents the logical "Key M" key on the keyboard.
keyM,
/// Represents the logical "Key N" key on the keyboard.
keyN,
/// Represents the logical "Key O" key on the keyboard.
keyO,
/// Represents the logical "Key P" key on the keyboard.
keyP,
/// Represents the logical "Key Q" key on the keyboard.
keyQ,
/// Represents the logical "Key R" key on the keyboard.
keyR,
/// Represents the logical "Key S" key on the keyboard.
keyS,
/// Represents the logical "Key T" key on the keyboard.
keyT,
/// Represents the logical "Key U" key on the keyboard.
keyU,
/// Represents the logical "Key V" key on the keyboard.
keyV,
/// Represents the logical "Key W" key on the keyboard.
keyW,
/// Represents the logical "Key X" key on the keyboard.
keyX,
/// Represents the logical "Key Y" key on the keyboard.
keyY,
/// Represents the logical "Key Z" key on the keyboard.
keyZ,
/// Represents the logical "Digit 1" key on the keyboard.
digit1,
/// Represents the logical "Digit 2" key on the keyboard.
digit2,
/// Represents the logical "Digit 3" key on the keyboard.
digit3,
/// Represents the logical "Digit 4" key on the keyboard.
digit4,
/// Represents the logical "Digit 5" key on the keyboard.
digit5,
/// Represents the logical "Digit 6" key on the keyboard.
digit6,
/// Represents the logical "Digit 7" key on the keyboard.
digit7,
/// Represents the logical "Digit 8" key on the keyboard.
digit8,
/// Represents the logical "Digit 9" key on the keyboard.
digit9,
/// Represents the logical "Digit 0" key on the keyboard.
digit0,
/// Represents the logical "Enter" key on the keyboard.
enter,
/// Represents the logical "Escape" key on the keyboard.
escape,
/// Represents the logical "Backspace" key on the keyboard.
backspace,
/// Represents the logical "Tab" key on the keyboard.
tab,
/// Represents the logical "Space" key on the keyboard.
space,
/// Represents the logical "Minus" key on the keyboard.
minus,
/// Represents the logical "Equal" key on the keyboard.
equal,
/// Represents the logical "Bracket Left" key on the keyboard.
bracketLeft,
/// Represents the logical "Bracket Right" key on the keyboard.
bracketRight,
/// Represents the logical "Backslash" key on the keyboard.
backslash,
/// Represents the logical "Semicolon" key on the keyboard.
semicolon,
/// Represents the logical "Quote" key on the keyboard.
quote,
/// Represents the logical "Backquote" key on the keyboard.
backquote,
/// Represents the logical "Comma" key on the keyboard.
comma,
/// Represents the logical "Period" key on the keyboard.
period,
/// Represents the logical "Slash" key on the keyboard.
slash,
/// Represents the logical "Caps Lock" key on the keyboard.
capsLock,
/// Represents the logical "F1" key on the keyboard.
f1,
/// Represents the logical "F2" key on the keyboard.
f2,
/// Represents the logical "F3" key on the keyboard.
f3,
/// Represents the logical "F4" key on the keyboard.
f4,
/// Represents the logical "F5" key on the keyboard.
f5,
/// Represents the logical "F6" key on the keyboard.
f6,
/// Represents the logical "F7" key on the keyboard.
f7,
/// Represents the logical "F8" key on the keyboard.
f8,
/// Represents the logical "F9" key on the keyboard.
f9,
/// Represents the logical "F10" key on the keyboard.
f10,
/// Represents the logical "F11" key on the keyboard.
f11,
/// Represents the logical "F12" key on the keyboard.
f12,
/// Represents the logical "Print Screen" key on the keyboard.
printScreen,
/// Represents the logical "Scroll Lock" key on the keyboard.
scrollLock,
/// Represents the logical "Pause" key on the keyboard.
pause,
/// Represents the logical "Insert" key on the keyboard.
insert,
/// Represents the logical "Home" key on the keyboard.
home,
/// Represents the logical "Page Up" key on the keyboard.
pageUp,
/// Represents the logical "Delete" key on the keyboard.
delete,
/// Represents the logical "End" key on the keyboard.
end,
/// Represents the logical "Page Down" key on the keyboard.
pageDown,
/// Represents the logical "Arrow Right" key on the keyboard.
arrowRight,
/// Represents the logical "Arrow Left" key on the keyboard.
arrowLeft,
/// Represents the logical "Arrow Down" key on the keyboard.
arrowDown,
/// Represents the logical "Arrow Up" key on the keyboard.
arrowUp,
/// Represents the logical "Num Lock" key on the keyboard.
numLock,
/// Represents the logical "Numpad Divide" key on the keyboard.
numpadDivide,
/// Represents the logical "Numpad Multiply" key on the keyboard.
numpadMultiply,
/// Represents the logical "Numpad Subtract" key on the keyboard.
numpadSubtract,
/// Represents the logical "Numpad Add" key on the keyboard.
numpadAdd,
/// Represents the logical "Numpad Enter" key on the keyboard.
numpadEnter,
/// Represents the logical "Numpad 1" key on the keyboard.
numpad1,
/// Represents the logical "Numpad 2" key on the keyboard.
numpad2,
/// Represents the logical "Numpad 3" key on the keyboard.
numpad3,
/// Represents the logical "Numpad 4" key on the keyboard.
numpad4,
/// Represents the logical "Numpad 5" key on the keyboard.
numpad5,
/// Represents the logical "Numpad 6" key on the keyboard.
numpad6,
/// Represents the logical "Numpad 7" key on the keyboard.
numpad7,
/// Represents the logical "Numpad 8" key on the keyboard.
numpad8,
/// Represents the logical "Numpad 9" key on the keyboard.
numpad9,
/// Represents the logical "Numpad 0" key on the keyboard.
numpad0,
/// Represents the logical "Numpad Decimal" key on the keyboard.
numpadDecimal,
/// Represents the logical "Intl Backslash" key on the keyboard.
intlBackslash,
/// Represents the logical "Context Menu" key on the keyboard.
contextMenu,
/// Represents the logical "Power" key on the keyboard.
power,
/// Represents the logical "Numpad Equal" key on the keyboard.
numpadEqual,
/// Represents the logical "F13" key on the keyboard.
f13,
/// Represents the logical "F14" key on the keyboard.
f14,
/// Represents the logical "F15" key on the keyboard.
f15,
/// Represents the logical "F16" key on the keyboard.
f16,
/// Represents the logical "F17" key on the keyboard.
f17,
/// Represents the logical "F18" key on the keyboard.
f18,
/// Represents the logical "F19" key on the keyboard.
f19,
/// Represents the logical "F20" key on the keyboard.
f20,
/// Represents the logical "F21" key on the keyboard.
f21,
/// Represents the logical "F22" key on the keyboard.
f22,
/// Represents the logical "F23" key on the keyboard.
f23,
/// Represents the logical "F24" key on the keyboard.
f24,
/// Represents the logical "Open" key on the keyboard.
open,
/// Represents the logical "Help" key on the keyboard.
help,
/// Represents the logical "Select" key on the keyboard.
select,
/// Represents the logical "Again" key on the keyboard.
again,
/// Represents the logical "Undo" key on the keyboard.
undo,
/// Represents the logical "Cut" key on the keyboard.
cut,
/// Represents the logical "Copy" key on the keyboard.
copy,
/// Represents the logical "Paste" key on the keyboard.
paste,
/// Represents the logical "Find" key on the keyboard.
find,
/// Represents the logical "Audio Volume Mute" key on the keyboard.
audioVolumeMute,
/// Represents the logical "Audio Volume Up" key on the keyboard.
audioVolumeUp,
/// Represents the logical "Audio Volume Down" key on the keyboard.
audioVolumeDown,
/// Represents the logical "Numpad Comma" key on the keyboard.
numpadComma,
/// Represents the logical "Intl Ro" key on the keyboard.
intlRo,
/// Represents the logical "Kana Mode" key on the keyboard.
kanaMode,
/// Represents the logical "Intl Yen" key on the keyboard.
intlYen,
/// Represents the logical "Convert" key on the keyboard.
convert,
/// Represents the logical "Non Convert" key on the keyboard.
nonConvert,
/// Represents the logical "Lang 1" key on the keyboard.
lang1,
/// Represents the logical "Lang 2" key on the keyboard.
lang2,
/// Represents the logical "Lang 3" key on the keyboard.
lang3,
/// Represents the logical "Lang 4" key on the keyboard.
lang4,
/// Represents the logical "Lang 5" key on the keyboard.
lang5,
/// Represents the logical "Abort" key on the keyboard.
abort,
/// Represents the logical "Props" key on the keyboard.
props,
/// Represents the logical "Numpad Paren Left" key on the keyboard.
numpadParenLeft,
/// Represents the logical "Numpad Paren Right" key on the keyboard.
numpadParenRight,
/// Represents the logical "Numpad Backspace" key on the keyboard.
numpadBackspace,
/// Represents the logical "Numpad Memory Store" key on the keyboard.
numpadMemoryStore,
/// Represents the logical "Numpad Memory Recall" key on the keyboard.
numpadMemoryRecall,
/// Represents the logical "Numpad Memory Clear" key on the keyboard.
numpadMemoryClear,
/// Represents the logical "Numpad Memory Add" key on the keyboard.
numpadMemoryAdd,
/// Represents the logical "Numpad Memory Subtract" key on the keyboard.
numpadMemorySubtract,
/// Represents the logical "Numpad Sign Change" key on the keyboard.
numpadSignChange,
/// Represents the logical "Numpad Clear" key on the keyboard.
numpadClear,
/// Represents the logical "Numpad Clear Entry" key on the keyboard.
numpadClearEntry,
/// Represents the logical "Control Left" key on the keyboard.
controlLeft,
/// Represents the logical "Shift Left" key on the keyboard.
shiftLeft,
/// Represents the logical "Alt Left" key on the keyboard.
altLeft,
/// Represents the logical "Meta Left" key on the keyboard.
metaLeft,
/// Represents the logical "Control Right" key on the keyboard.
controlRight,
/// Represents the logical "Shift Right" key on the keyboard.
shiftRight,
/// Represents the logical "Alt Right" key on the keyboard.
altRight,
/// Represents the logical "Meta Right" key on the keyboard.
metaRight,
/// Represents the logical "Info" key on the keyboard.
info,
/// Represents the logical "Closed Caption Toggle" key on the keyboard.
closedCaptionToggle,
/// Represents the logical "Brightness Up" key on the keyboard.
brightnessUp,
/// Represents the logical "Brightness Down" key on the keyboard.
brightnessDown,
/// Represents the logical "Brightness Toggle" key on the keyboard.
brightnessToggle,
/// Represents the logical "Brightness Minimum" key on the keyboard.
brightnessMinimum,
/// Represents the logical "Brightness Maximum" key on the keyboard.
brightnessMaximum,
/// Represents the logical "Brightness Auto" key on the keyboard.
brightnessAuto,
/// Represents the logical "Media Last" key on the keyboard.
mediaLast,
/// Represents the logical "Launch Phone" key on the keyboard.
launchPhone,
/// Represents the logical "Program Guide" key on the keyboard.
programGuide,
/// Represents the logical "Exit" key on the keyboard.
exit,
/// Represents the logical "Channel Up" key on the keyboard.
channelUp,
/// Represents the logical "Channel Down" key on the keyboard.
channelDown,
/// Represents the logical "Media Play" key on the keyboard.
mediaPlay,
/// Represents the logical "Media Pause" key on the keyboard.
mediaPause,
/// Represents the logical "Media Record" key on the keyboard.
mediaRecord,
/// Represents the logical "Media Fast Forward" key on the keyboard.
mediaFastForward,
/// Represents the logical "Media Rewind" key on the keyboard.
mediaRewind,
/// Represents the logical "Media Track Next" key on the keyboard.
mediaTrackNext,
/// Represents the logical "Media Track Previous" key on the keyboard.
mediaTrackPrevious,
/// Represents the logical "Media Stop" key on the keyboard.
mediaStop,
/// Represents the logical "Eject" key on the keyboard.
eject,
/// Represents the logical "Media Play Pause" key on the keyboard.
mediaPlayPause,
/// Represents the logical "Speech Input Toggle" key on the keyboard.
speechInputToggle,
/// Represents the logical "Bass Boost" key on the keyboard.
bassBoost,
/// Represents the logical "Media Select" key on the keyboard.
mediaSelect,
/// Represents the logical "Launch Word Processor" key on the keyboard.
launchWordProcessor,
/// Represents the logical "Launch Spreadsheet" key on the keyboard.
launchSpreadsheet,
/// Represents the logical "Launch Mail" key on the keyboard.
launchMail,
/// Represents the logical "Launch Contacts" key on the keyboard.
launchContacts,
/// Represents the logical "Launch Calendar" key on the keyboard.
launchCalendar,
/// Represents the logical "Launch App2" key on the keyboard.
launchApp2,
/// Represents the logical "Launch App1" key on the keyboard.
launchApp1,
/// Represents the logical "Launch Internet Browser" key on the keyboard.
launchInternetBrowser,
/// Represents the logical "Log Off" key on the keyboard.
logOff,
/// Represents the logical "Lock Screen" key on the keyboard.
lockScreen,
/// Represents the logical "Launch Control Panel" key on the keyboard.
launchControlPanel,
/// Represents the logical "Select Task" key on the keyboard.
selectTask,
/// Represents the logical "Launch Documents" key on the keyboard.
launchDocuments,
/// Represents the logical "Spell Check" key on the keyboard.
spellCheck,
/// Represents the logical "Launch Keyboard Layout" key on the keyboard.
launchKeyboardLayout,
/// Represents the logical "Launch Screen Saver" key on the keyboard.
launchScreenSaver,
/// Represents the logical "Launch Assistant" key on the keyboard.
launchAssistant,
/// Represents the logical "Launch Audio Browser" key on the keyboard.
launchAudioBrowser,
/// Represents the logical "New Key" key on the keyboard.
newKey,
/// Represents the logical "Close" key on the keyboard.
close,
/// Represents the logical "Save" key on the keyboard.
save,
/// Represents the logical "Print" key on the keyboard.
print,
/// Represents the logical "Browser Search" key on the keyboard.
browserSearch,
/// Represents the logical "Browser Home" key on the keyboard.
browserHome,
/// Represents the logical "Browser Back" key on the keyboard.
browserBack,
/// Represents the logical "Browser Forward" key on the keyboard.
browserForward,
/// Represents the logical "Browser Stop" key on the keyboard.
browserStop,
/// Represents the logical "Browser Refresh" key on the keyboard.
browserRefresh,
/// Represents the logical "Browser Favorites" key on the keyboard.
browserFavorites,
/// Represents the logical "Zoom In" key on the keyboard.
zoomIn,
/// Represents the logical "Zoom Out" key on the keyboard.
zoomOut,
/// Represents the logical "Zoom Toggle" key on the keyboard.
zoomToggle,
/// Represents the logical "Redo" key on the keyboard.
redo,
/// Represents the logical "Mail Reply" key on the keyboard.
mailReply,
/// Represents the logical "Mail Forward" key on the keyboard.
mailForward,
/// Represents the logical "Mail Send" key on the keyboard.
mailSend,
/// Represents the logical "Keyboard Layout Select" key on the keyboard.
keyboardLayoutSelect,
/// Represents the logical "Show All Windows" key on the keyboard.
showAllWindows,
/// Represents the logical "Game Button 1" key on the keyboard.
gameButton1,
/// Represents the logical "Game Button 2" key on the keyboard.
gameButton2,
/// Represents the logical "Game Button 3" key on the keyboard.
gameButton3,
/// Represents the logical "Game Button 4" key on the keyboard.
gameButton4,
/// Represents the logical "Game Button 5" key on the keyboard.
gameButton5,
/// Represents the logical "Game Button 6" key on the keyboard.
gameButton6,
/// Represents the logical "Game Button 7" key on the keyboard.
gameButton7,
/// Represents the logical "Game Button 8" key on the keyboard.
gameButton8,
/// Represents the logical "Game Button 9" key on the keyboard.
gameButton9,
/// Represents the logical "Game Button 10" key on the keyboard.
gameButton10,
/// Represents the logical "Game Button 11" key on the keyboard.
gameButton11,
/// Represents the logical "Game Button 12" key on the keyboard.
gameButton12,
/// Represents the logical "Game Button 13" key on the keyboard.
gameButton13,
/// Represents the logical "Game Button 14" key on the keyboard.
gameButton14,
/// Represents the logical "Game Button 15" key on the keyboard.
gameButton15,
/// Represents the logical "Game Button 16" key on the keyboard.
gameButton16,
/// Represents the logical "Game Button A" key on the keyboard.
gameButtonA,
/// Represents the logical "Game Button B" key on the keyboard.
gameButtonB,
/// Represents the logical "Game Button C" key on the keyboard.
gameButtonC,
/// Represents the logical "Game Button Left 1" key on the keyboard.
gameButtonLeft1,
/// Represents the logical "Game Button Left 2" key on the keyboard.
gameButtonLeft2,
/// Represents the logical "Game Button Mode" key on the keyboard.
gameButtonMode,
/// Represents the logical "Game Button Right 1" key on the keyboard.
gameButtonRight1,
/// Represents the logical "Game Button Right 2" key on the keyboard.
gameButtonRight2,
/// Represents the logical "Game Button Select" key on the keyboard.
gameButtonSelect,
/// Represents the logical "Game Button Start" key on the keyboard.
gameButtonStart,
/// Represents the logical "Game Button Thumb Left" key on the keyboard.
gameButtonThumbLeft,
/// Represents the logical "Game Button Thumb Right" key on the keyboard.
gameButtonThumbRight,
/// Represents the logical "Game Button X" key on the keyboard.
gameButtonX,
/// Represents the logical "Game Button Y" key on the keyboard.
gameButtonY,
/// Represents the logical "Game Button Z" key on the keyboard.
gameButtonZ,
/// Represents the logical "Fn" key on the keyboard.
fn,
/// Represents the logical "Shift" key on the keyboard.
///
/// This key represents the union of the keys {shiftLeft, shiftRight} when
/// comparing keys. This key will never be generated directly, its main use is
/// in defining key maps.
shift,
/// Represents the logical "Meta" key on the keyboard.
///
/// This key represents the union of the keys {metaLeft, metaRight} when
/// comparing keys. This key will never be generated directly, its main use is
/// in defining key maps.
meta,
/// Represents the logical "Alt" key on the keyboard.
///
/// This key represents the union of the keys {altLeft, altRight} when
/// comparing keys. This key will never be generated directly, its main use is
/// in defining key maps.
alt,
/// Represents the logical "Control" key on the keyboard.
///
/// This key represents the union of the keys {controlLeft, controlRight} when
/// comparing keys. This key will never be generated directly, its main use is
/// in defining key maps.
control,
// Missing flutter keys.
backtab,
returnKey,
}
@@ -0,0 +1,113 @@
import 'package:xterm/src/core/input/keys.dart';
import 'package:xterm/src/core/input/keytab/keytab_default.dart';
import 'package:xterm/src/core/input/keytab/keytab_parse.dart';
import 'package:xterm/src/core/input/keytab/keytab_record.dart';
import 'package:xterm/src/core/input/keytab/keytab_token.dart';
class Keytab {
Keytab({
required this.name,
required this.records,
});
factory Keytab.parse(String source) {
final tokens = tokenize(source).toList();
final parser = KeytabParser()..addTokens(tokens);
return parser.result;
}
static final defaultKeytab = Keytab.parse(kDefaultKeytab);
final String? name;
final List<KeytabRecord> records;
KeytabRecord? find(
TerminalKey key, {
bool ctrl = false,
bool alt = false,
bool shift = false,
bool newLineMode = false,
bool appCursorKeys = false,
bool appKeyPad = false,
bool keyPad = false,
bool appScreen = false,
bool macos = false,
// bool meta,
}) {
for (var record in records) {
if (record.key != key) {
continue;
}
if (record.anyModifier == true) {
if (ctrl == false && alt == false && shift == false) {
continue;
}
} else if (record.anyModifier == false) {
if (ctrl != false || alt != false || shift != false) {
continue;
}
} else {
if (record.ctrl != null && record.ctrl != ctrl) {
continue;
}
if (record.shift != null && record.shift != shift) {
continue;
}
if (record.alt != null && record.alt != alt) {
continue;
}
}
if (record.newLine != null && record.newLine != newLineMode) {
continue;
}
if (record.appCursorKeys != null &&
record.appCursorKeys != appCursorKeys) {
continue;
}
if (record.appKeyPad != null && record.appKeyPad != appKeyPad) {
continue;
}
if (record.keyPad != null && record.keyPad != keyPad) {
continue;
}
if (record.appScreen != null && record.appScreen != appScreen) {
continue;
}
if (record.macos != null && record.macos != macos) {
continue;
}
// TODO: support VT52
if (record.ansi == false) {
continue;
}
return record;
}
return null;
}
@override
String toString() {
final buffer = StringBuffer();
buffer.writeln('keyboard "$name"');
for (var record in records) {
buffer.writeln(record);
}
return buffer.toString();
}
}
@@ -0,0 +1,213 @@
import 'package:xterm/src/core/input/keytab/keytab_parse.dart';
import 'package:xterm/src/core/input/keytab/keytab_token.dart';
const kDefaultKeytab = r'''
# [README.default.Keytab] Default Keyboard Table
#
# To customize your keyboard, copy this file to something ending with
# .keytab and change it to meet you needs.
#
# Please read the README-KeyTab and the doc/user/README.keyboard files
# in this case.
#
# --------------------------------------------------------------
keyboard "Default (XFree 4)"
# --------------------------------------------------------------
#
# Note that this particular table is a "risc" version made to
# ease customization without bothering with obsolete details.
# See VT100.keytab for the more hairy stuff.
#
# --------------------------------------------------------------
# common keys
key Escape : "\E"
key Tab -Shift : "\t"
key Tab +Shift+Ansi : "\E[Z"
key Tab +Shift-Ansi : "\t"
key Backtab +Ansi : "\E[Z"
key Backtab -Ansi : "\t"
key Return-Shift-NewLine : "\r"
key Return-Shift+NewLine : "\r\n"
key Return+Shift : "\EOM"
key Backspace +Alt : "\x17"
# Backspace and Delete codes are preserving CTRL-H.
#
# Backspace without CTRL sends '^?'; this matches XTerm behaviour, so that
# pressing Alt+Backspace will send \E + Del, which is the expected behaviour
# in some apps (e.g. emacs), and it was the behaviour before the commit
# that add the Backspace +Control rule
key Backspace -Control : "\x7f"
# Match xterm behaviour: Backspace sends '^H' when Control is pressed
# BS, hex \x08, \b
key Backspace +Control : "\b"
# Arrow keys in VT52 mode
# shift up/down are reserved for scrolling.
# shift left/right are reserved for switching between tabs (this is hardcoded).
key Up -Shift-Ansi : "\EA"
key Down -Shift-Ansi : "\EB"
key Right-Shift-Ansi : "\EC"
key Left -Shift-Ansi : "\ED"
# Arrow keys in ANSI mode with Application - and Normal Cursor Mode)
key Up -Shift-AnyMod+Ansi+AppCuKeys : "\EOA"
key Down -Shift-AnyMod+Ansi+AppCuKeys : "\EOB"
key Right -Shift-AnyMod+Ansi+AppCuKeys : "\EOC"
key Left -Shift-AnyMod+Ansi+AppCuKeys : "\EOD"
key Up -Shift-AnyMod+Ansi-AppCuKeys : "\E[A"
key Down -Shift-AnyMod+Ansi-AppCuKeys : "\E[B"
key Right -Shift-AnyMod+Ansi-AppCuKeys : "\E[C"
key Left -Shift-AnyMod+Ansi-AppCuKeys : "\E[D"
key Up -Shift+AnyMod+Ansi : "\E[1;5A"
key Down -Shift+AnyMod+Ansi : "\E[1;5B"
# Right / Left with Control
key Right -Shift-Alt+Control+Ansi : "\E[1;5C"
key Left -Shift-Alt+Control+Ansi : "\E[1;5D"
# Right / Left with Alt not on a Mac
key Right -Shift+Alt-Control+Ansi-Mac : "\E[1;5C"
key Left -Shift+Alt-Control+Ansi-Mac : "\E[1;5D"
# Right / Left with Alt on a Mac
key Right -Shift+Alt-Control+Ansi+Mac : "\Ef"
key Left -Shift+Alt-Control+Ansi+Mac : "\Eb"
key Up +Shift+AppScreen : "\E[1;*A"
key Down +Shift+AppScreen : "\E[1;*B"
key Left +Shift+AppScreen : "\E[1;*D"
key Right +Shift+AppScreen : "\E[1;*C"
# Keypad keys with NumLock ON
# (see https://web.archive.org/web/20070807181942/http://www.nw.com/nw/WWW/products/wizcon/vt100.html
# https://vt100.net/docs/vt100-ug/chapter3.html)
#
# Not enabled for now because it breaks the keypad in Vim.
#
#key 0 +KeyPad+AppKeyPad : "\EOp"
#key 1 +KeyPad+AppKeyPad : "\EOq"
#key 2 +KeyPad+AppKeyPad : "\EOr"
#key 3 +KeyPad+AppKeyPad : "\EOs"
#key 4 +KeyPad+AppKeyPad : "\EOt"
#key 5 +KeyPad+AppKeyPad : "\EOu"
#key 6 +KeyPad+AppKeyPad : "\EOv"
#key 7 +KeyPad+AppKeyPad : "\EOw"
#key 8 +KeyPad+AppKeyPad : "\EOx"
#key 9 +KeyPad+AppKeyPad : "\EOy"
#key + +KeyPad+AppKeyPad : "\EOl"
#key - +KeyPad+AppKeyPad : "\EOm"
#key . +KeyPad+AppKeyPad : "\EOn"
#key * +KeyPad+AppKeyPad : "\EOM"
#key Enter +KeyPad+AppKeyPad : "\r"
# Keypad keys with NumLock Off
key Up -Shift+Ansi+AppCuKeys+KeyPad : "\EOA"
key Down -Shift+Ansi+AppCuKeys+KeyPad : "\EOB"
key Right -Shift+Ansi+AppCuKeys+KeyPad : "\EOC"
key Left -Shift+Ansi+AppCuKeys+KeyPad : "\EOD"
key Up -Shift+Ansi-AppCuKeys+KeyPad : "\E[A"
key Down -Shift+Ansi-AppCuKeys+KeyPad : "\E[B"
key Right -Shift+Ansi-AppCuKeys+KeyPad : "\E[C"
key Left -Shift+Ansi-AppCuKeys+KeyPad : "\E[D"
key Home +AppCuKeys+KeyPad : "\EOH"
key End +AppCuKeys+KeyPad : "\EOF"
key Home -AppCuKeys+KeyPad : "\E[H"
key End -AppCuKeys+KeyPad : "\E[F"
key Insert +KeyPad : "\E[2~"
key Delete +KeyPad : "\E[3~"
key PgUp -Shift+KeyPad : "\E[5~"
key PgDown -Shift+KeyPad : "\E[6~"
# the key labelled 5 on the Keypad, is Qt::Key_Clear (a very intuitive
# and discoverable name...)
key Clear +KeyPad : "\E[E"
# other grey PC keys
key Enter+NewLine : "\r\n"
key Enter-NewLine : "\r"
key NumEnter+NewLine : "\r\n"
key NumEnter-NewLine : "\r"
key Home -AnyMod-AppCuKeys : "\E[H"
key End -AnyMod-AppCuKeys : "\E[F"
key Home -AnyMod+AppCuKeys : "\EOH"
key End -AnyMod+AppCuKeys : "\EOF"
key Home +AnyMod : "\E[1;*H"
key End +AnyMod : "\E[1;*F"
key Insert -AnyMod : "\E[2~"
key Delete -AnyMod : "\E[3~"
key Insert +AnyMod : "\E[2;*~"
key Delete +AnyMod : "\E[3;*~"
key PgUp -Shift-AnyMod : "\E[5~"
key PgDown -Shift-AnyMod : "\E[6~"
key PgUp -Shift+AnyMod : "\E[5;*~"
key PgDown -Shift+AnyMod : "\E[6;*~"
# Function keys
key F1 -AnyMod : "\EOP"
key F2 -AnyMod : "\EOQ"
key F3 -AnyMod : "\EOR"
key F4 -AnyMod : "\EOS"
key F5 -AnyMod : "\E[15~"
key F6 -AnyMod : "\E[17~"
key F7 -AnyMod : "\E[18~"
key F8 -AnyMod : "\E[19~"
key F9 -AnyMod : "\E[20~"
key F10 -AnyMod : "\E[21~"
key F11 -AnyMod : "\E[23~"
key F12 -AnyMod : "\E[24~"
key F1 +AnyMod : "\EO*P"
key F2 +AnyMod : "\EO*Q"
key F3 +AnyMod : "\EO*R"
key F4 +AnyMod : "\EO*S"
key F5 +AnyMod : "\E[15;*~"
key F6 +AnyMod : "\E[17;*~"
key F7 +AnyMod : "\E[18;*~"
key F8 +AnyMod : "\E[19;*~"
key F9 +AnyMod : "\E[20;*~"
key F10 +AnyMod : "\E[21;*~"
key F11 +AnyMod : "\E[23;*~"
key F12 +AnyMod : "\E[24;*~"
# Work around dead keys
key Space +Control : "\x00"
# Some keys are used by konsole to cause operations.
# The scroll* operations refer to the history buffer.
key Up +Shift-AppScreen : scrollLineUp
key PgUp +Shift-AppScreen : scrollPageUp
key Home +Shift-AppScreen : scrollUpToTop
key Down +Shift-AppScreen : scrollLineDown
key PgDown +Shift-AppScreen : scrollPageDown
key End +Shift-AppScreen : scrollDownToBottom
''';
void main() {
final tokens = tokenize(kDefaultKeytab).toList();
final parser = KeytabParser()..addTokens(tokens);
print(parser.result);
}
@@ -0,0 +1,21 @@
final _esc = String.fromCharCode(0x1b);
String keytabUnescape(String str) {
str = str
.replaceAll(r'\E', _esc)
.replaceAll(r'\\', '\\')
.replaceAll(r'\"', '"')
.replaceAll(r'\t', '\t')
.replaceAll(r'\r', '\r')
.replaceAll(r'\n', '\n')
.replaceAll(r'\b', '\b');
final hexPattern = RegExp(r'\\x([0-9a-fA-F][0-9a-fA-F])');
str = str.replaceAllMapped(hexPattern, (match) {
final hexString = match.group(1)!;
final hexValue = int.parse(hexString, radix: 16);
return String.fromCharCode(hexValue);
});
return str;
}
@@ -0,0 +1,186 @@
import 'package:xterm/src/core/input/keytab/keytab.dart';
import 'package:xterm/src/core/input/keytab/keytab_record.dart';
import 'package:xterm/src/core/input/keytab/keytab_token.dart';
import 'package:xterm/src/core/input/keytab/qt_keyname.dart';
class ParseError {}
class TokensReader {
TokensReader(this.tokens);
final List<KeytabToken> tokens;
var _pos = 0;
bool get done => _pos > tokens.length - 1;
KeytabToken? take() {
final result = peek();
_pos += 1;
return result;
}
KeytabToken? peek() {
if (done) return null;
return tokens[_pos];
}
}
class KeytabParser {
String? _name;
final _records = <KeytabRecord>[];
void addTokens(List<KeytabToken> tokens) {
final reader = TokensReader(tokens);
while (!reader.done) {
if (reader.peek()!.type == KeytabTokenType.keyboard) {
_parseName(reader);
continue;
}
if (reader.peek()!.type == KeytabTokenType.keyDefine) {
_parseKeyDefine(reader);
continue;
}
throw ParseError();
}
}
Keytab get result {
return Keytab(name: _name, records: _records);
}
void _parseName(TokensReader reader) {
if (reader.take()!.type != KeytabTokenType.keyboard) {
throw ParseError();
}
final name = reader.take()!;
if (name.type != KeytabTokenType.input) {
throw ParseError();
}
_name = name.value;
}
void _parseKeyDefine(TokensReader reader) {
if (reader.take()!.type != KeytabTokenType.keyDefine) {
throw ParseError();
}
final keyName = reader.take()!;
if (keyName.type != KeytabTokenType.keyName) {
throw ParseError();
}
final key = qtKeynameMap[keyName.value];
if (key == null) {
throw ParseError();
}
bool? alt;
bool? ctrl;
bool? shift;
bool? anyModifier;
bool? ansi;
bool? appScreen;
bool? keyPad;
bool? appCursorKeys;
bool? appKeyPad;
bool? newLine;
bool? mac;
while (reader.peek()!.type == KeytabTokenType.modeStatus) {
bool modeStatus;
switch (reader.take()!.value) {
case '+':
modeStatus = true;
break;
case '-':
modeStatus = false;
break;
default:
throw ParseError();
}
final mode = reader.take();
if (mode!.type != KeytabTokenType.mode) {
throw ParseError();
}
switch (mode.value) {
case 'Alt':
alt = modeStatus;
break;
case 'Control':
ctrl = modeStatus;
break;
case 'Shift':
shift = modeStatus;
break;
case 'AnyMod':
anyModifier = modeStatus;
break;
case 'Ansi':
ansi = modeStatus;
break;
case 'AppScreen':
appScreen = modeStatus;
break;
case 'KeyPad':
keyPad = modeStatus;
break;
case 'AppCuKeys':
appCursorKeys = modeStatus;
break;
case 'AppKeyPad':
appKeyPad = modeStatus;
break;
case 'NewLine':
newLine = modeStatus;
break;
case 'Mac':
mac = modeStatus;
break;
default:
throw ParseError();
}
}
if (reader.take()!.type != KeytabTokenType.colon) {
throw ParseError();
}
final actionToken = reader.take()!;
KeytabAction action;
if (actionToken.type == KeytabTokenType.input) {
action = KeytabAction(KeytabActionType.input, actionToken.value);
} else if (actionToken.type == KeytabTokenType.shortcut) {
action = KeytabAction(KeytabActionType.shortcut, actionToken.value);
} else {
throw ParseError();
}
final record = KeytabRecord(
qtKeyName: keyName.value,
key: key,
action: action,
alt: alt,
ctrl: ctrl,
shift: shift,
anyModifier: anyModifier,
ansi: ansi,
appScreen: appScreen,
keyPad: keyPad,
appCursorKeys: appCursorKeys,
appKeyPad: appKeyPad,
newLine: newLine,
macos: mac,
);
_records.add(record);
}
}
@@ -0,0 +1,134 @@
import 'package:xterm/src/core/input/keys.dart';
import 'package:xterm/src/core/input/keytab/keytab_escape.dart';
enum KeytabActionType {
input,
shortcut,
}
class KeytabAction {
KeytabAction(this.type, this.value);
final KeytabActionType type;
final String value;
String unescapedValue() {
if (type == KeytabActionType.input) {
return keytabUnescape(value);
} else {
return value;
}
}
@override
String toString() {
switch (type) {
case KeytabActionType.input:
return '"$value"';
case KeytabActionType.shortcut:
return value;
}
}
}
class KeytabRecord {
KeytabRecord({
required this.qtKeyName,
required this.key,
required this.action,
required this.alt,
required this.ctrl,
required this.shift,
required this.anyModifier,
required this.ansi,
required this.appScreen,
required this.keyPad,
required this.appCursorKeys,
required this.appKeyPad,
required this.newLine,
required this.macos,
});
String qtKeyName;
TerminalKey key;
KeytabAction action;
bool? alt;
bool? ctrl;
bool? shift;
bool? anyModifier;
bool? ansi;
bool? appScreen;
bool? keyPad;
bool? appCursorKeys;
bool? appKeyPad;
bool? newLine;
bool? macos;
@override
String toString() {
final buffer = StringBuffer();
buffer.write('$qtKeyName ');
if (alt != null) {
buffer.write(_toMode(alt!, 'Alt'));
}
if (ctrl != null) {
buffer.write(_toMode(ctrl!, 'Control'));
}
if (shift != null) {
buffer.write(_toMode(shift!, 'Shift'));
}
if (anyModifier != null) {
buffer.write(_toMode(anyModifier!, 'AnyMod'));
}
if (ansi != null) {
buffer.write(_toMode(ansi!, 'Ansi'));
}
if (appScreen != null) {
buffer.write(_toMode(appScreen!, 'AppScreen'));
}
if (keyPad != null) {
buffer.write(_toMode(keyPad!, 'KeyPad'));
}
if (appCursorKeys != null) {
buffer.write(_toMode(appCursorKeys!, 'AppCuKeys'));
}
if (appKeyPad != null) {
buffer.write(_toMode(appKeyPad!, 'AppKeyPad'));
}
if (newLine != null) {
buffer.write(_toMode(newLine!, 'NewLine'));
}
if (macos != null) {
buffer.write(_toMode(macos!, 'Mac'));
}
buffer.write(' : $action');
return buffer.toString();
}
static String _toMode(bool status, String mode) {
if (status == true) {
return '+$mode';
}
if (status == false) {
return '-$mode';
}
return '';
}
}
@@ -0,0 +1,179 @@
import 'dart:math' show min;
enum KeytabTokenType {
keyDefine,
keyboard,
keyName,
mode,
modeStatus,
colon,
input,
shortcut,
}
class KeytabToken {
KeytabToken(this.type, this.value);
final KeytabTokenType type;
final String value;
@override
String toString() {
return '$type<$value>';
}
}
class LineReader {
LineReader(this.line);
final String line;
var _pos = 0;
bool get done => _pos > line.length - 1;
String? take([int count = 1]) {
final result = peek(count);
_pos += count;
return result;
}
String? peek([int count = 1]) {
if (done) return null;
final end = min(_pos + count, line.length);
final result = line.substring(_pos, end);
return result;
}
void skipWhitespace() {
while (peek() == ' ' || peek() == '\t') {
_pos += 1;
}
}
String readString() {
final buffer = StringBuffer();
final pattern = RegExp(r'\w|_');
while (!done && line[_pos].contains(pattern)) {
buffer.write(line[_pos]);
_pos++;
}
return buffer.toString();
}
String readUntil(Pattern pattern, {bool inclusive = false}) {
final buffer = StringBuffer();
while (!done && !line[_pos].contains(pattern)) {
buffer.write(line[_pos]);
_pos++;
}
if (!done && inclusive) {
buffer.write(line[_pos]);
_pos++;
}
return buffer.toString();
}
}
class TokenizeError {}
Iterable<KeytabToken> tokenize(String source) sync* {
final lines = source.split('\n');
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
line = line.replaceFirst(RegExp('#.*'), '');
if (line == '') {
continue;
}
if (_isKeyboardNameDefine(line)) {
yield* _parseKeyboardNameDefine(line);
}
if (_isKeyDefine(line)) {
yield* _parseKeyDefine(line);
}
}
}
bool _isKeyboardNameDefine(String line) {
return line.startsWith('keyboard ');
}
bool _isKeyDefine(String line) {
return line.startsWith('key ');
}
Iterable<KeytabToken> _parseKeyboardNameDefine(String line) sync* {
final reader = LineReader(line.trim());
if (reader.readString() == 'keyboard') {
yield KeytabToken(KeytabTokenType.keyboard, 'keyboard');
} else {
throw TokenizeError();
}
reader.skipWhitespace();
yield _readInput(reader);
}
Iterable<KeytabToken> _parseKeyDefine(String line) sync* {
final reader = LineReader(line.trim());
if (reader.readString() == 'key') {
yield KeytabToken(KeytabTokenType.keyDefine, 'key');
} else {
throw TokenizeError();
}
reader.skipWhitespace();
final keyName = reader.readString();
yield KeytabToken(KeytabTokenType.keyName, keyName);
reader.skipWhitespace();
while (reader.peek() == '+' || reader.peek() == '-') {
final modeStatus = reader.take()!;
yield KeytabToken(KeytabTokenType.modeStatus, modeStatus);
final mode = reader.readString();
yield KeytabToken(KeytabTokenType.mode, mode);
reader.skipWhitespace();
}
if (reader.take() == ':') {
yield KeytabToken(KeytabTokenType.colon, ':');
} else {
throw TokenizeError();
}
reader.skipWhitespace();
if (reader.peek() == '"') {
yield _readInput(reader);
} else {
final action = reader.readString();
yield KeytabToken(KeytabTokenType.shortcut, action);
}
}
KeytabToken _readInput(LineReader reader) {
reader.skipWhitespace();
if (reader.take() != '"') {
throw TokenizeError();
}
final value = reader.readUntil('"');
reader.take();
return KeytabToken(KeytabTokenType.input, value);
}
@@ -0,0 +1,477 @@
import 'package:xterm/src/core/input/keys.dart';
/// See: https://doc.qt.io/qt-5/qt.html#Key-enum
const qtKeynameMap = <String, TerminalKey>{
'Escape': TerminalKey.escape,
'Tab': TerminalKey.tab,
'Backtab': TerminalKey.backtab,
'Backspace': TerminalKey.backspace,
'Return': TerminalKey.returnKey,
'Enter': TerminalKey.enter,
'NumEnter': TerminalKey.numpadEnter,
'Insert': TerminalKey.insert,
'Delete': TerminalKey.delete,
'Pause': TerminalKey.pause,
'Print': TerminalKey.print,
// 'SysReq': TerminalKey.sysReq,
'Clear': TerminalKey.numpadClear,
'Home': TerminalKey.home,
'End': TerminalKey.end,
'Left': TerminalKey.arrowLeft,
'Up': TerminalKey.arrowUp,
'Right': TerminalKey.arrowRight,
'Down': TerminalKey.arrowDown,
'PageUp': TerminalKey.pageUp,
'PageDown': TerminalKey.pageDown,
'PgUp': TerminalKey.pageUp,
'PgDown': TerminalKey.pageDown,
'Shift': TerminalKey.shift,
'Control': TerminalKey.control,
'Meta': TerminalKey.meta,
'Alt': TerminalKey.alt,
// 'AltGr': TerminalKey.altGr,
'CapsLock': TerminalKey.capsLock,
'NumLock': TerminalKey.numLock,
'ScrollLock': TerminalKey.scrollLock,
'F1': TerminalKey.f1,
'F2': TerminalKey.f2,
'F3': TerminalKey.f3,
'F4': TerminalKey.f4,
'F5': TerminalKey.f5,
'F6': TerminalKey.f6,
'F7': TerminalKey.f7,
'F8': TerminalKey.f8,
'F9': TerminalKey.f9,
'F10': TerminalKey.f10,
'F11': TerminalKey.f11,
'F12': TerminalKey.f12,
'F13': TerminalKey.f13,
'F14': TerminalKey.f14,
'F15': TerminalKey.f15,
'F16': TerminalKey.f16,
'F17': TerminalKey.f17,
'F18': TerminalKey.f18,
'F19': TerminalKey.f19,
'F20': TerminalKey.f20,
'F21': TerminalKey.f21,
'F22': TerminalKey.f22,
'F23': TerminalKey.f23,
'F24': TerminalKey.f24,
// 'F25': TerminalKey.f25,
// 'F26': TerminalKey.f26,
// 'F27': TerminalKey.f27,
// 'F28': TerminalKey.f28,
// 'F29': TerminalKey.f29,
// 'F30': TerminalKey.f30,
// 'F31': TerminalKey.f31,
// 'F32': TerminalKey.f32,
// 'F33': TerminalKey.f33,
// 'F34': TerminalKey.f34,
// 'F35': TerminalKey.f35,
// 'Super_L': TerminalKey.super_L,
// 'Super_R': TerminalKey.super_R,
// 'Menu': TerminalKey.menu,
// 'Hyper_L': TerminalKey.hyper_L,
// 'Hyper_R': TerminalKey.hyper_R,
'Help': TerminalKey.help,
// 'Direction_L': TerminalKey.direction_L,
// 'Direction_R': TerminalKey.direction_R,
'Space': TerminalKey.space,
// 'Any': TerminalKey.any,
// 'Exclam': TerminalKey.exclam,
// 'QuoteDbl': TerminalKey.quoteDbl,
// 'NumberSign': TerminalKey.numberSign,
// 'Dollar': TerminalKey.dollar,
// 'Percent': TerminalKey.percent,
// 'Ampersand': TerminalKey.ampersand,
// 'Apostrophe': TerminalKey.apostrophe,
'ParenLeft': TerminalKey.numpadParenLeft,
'ParenRight': TerminalKey.numpadParenRight,
// 'Asterisk': TerminalKey.asterisk,
// 'Plus': TerminalKey.plus,
'Comma': TerminalKey.comma,
'Minus': TerminalKey.minus,
'Period': TerminalKey.period,
'Slash': TerminalKey.slash,
'0': TerminalKey.digit0,
'1': TerminalKey.digit1,
'2': TerminalKey.digit2,
'3': TerminalKey.digit3,
'4': TerminalKey.digit4,
'5': TerminalKey.digit5,
'6': TerminalKey.digit6,
'7': TerminalKey.digit7,
'8': TerminalKey.digit8,
'9': TerminalKey.digit9,
// 'Colon': TerminalKey.colon,
'Semicolon': TerminalKey.semicolon,
// 'Less': TerminalKey.less,
// 'Equal': TerminalKey.equal,
// 'Greater': TerminalKey.greater,
// 'Question': TerminalKey.question,
// 'At': TerminalKey.at,
'A': TerminalKey.keyA,
'B': TerminalKey.keyB,
'C': TerminalKey.keyC,
'D': TerminalKey.keyD,
'E': TerminalKey.keyE,
'F': TerminalKey.keyF,
'G': TerminalKey.keyG,
'H': TerminalKey.keyH,
'I': TerminalKey.keyI,
'J': TerminalKey.keyJ,
'K': TerminalKey.keyK,
'L': TerminalKey.keyL,
'M': TerminalKey.keyM,
'N': TerminalKey.keyN,
'O': TerminalKey.keyO,
'P': TerminalKey.keyP,
'Q': TerminalKey.keyQ,
'R': TerminalKey.keyR,
'S': TerminalKey.keyS,
'T': TerminalKey.keyT,
'U': TerminalKey.keyU,
'V': TerminalKey.keyV,
'W': TerminalKey.keyW,
'X': TerminalKey.keyX,
'Y': TerminalKey.keyY,
'Z': TerminalKey.keyZ,
'BracketLeft': TerminalKey.bracketLeft,
'Backslash': TerminalKey.backslash,
'BracketRight': TerminalKey.bracketRight,
// 'AsciiCircum': TerminalKey.asciiCircum,
// 'Underscore': TerminalKey.underscore,
// 'QuoteLeft': TerminalKey.quoteLeft,
// 'BraceLeft': TerminalKey.braceLeft,
// 'Bar': TerminalKey.bar,
// 'BraceRight': TerminalKey.braceRight,
// 'AsciiTilde': TerminalKey.asciiTilde,
// 'nobreakspace': TerminalKey.nobreakspace,
// 'exclamdown': TerminalKey.exclamdown,
// 'cent': TerminalKey.cent,
// 'sterling': TerminalKey.sterling,
// 'currency': TerminalKey.currency,
// 'yen': TerminalKey.yen,
// 'brokenbar': TerminalKey.brokenbar,
// 'section': TerminalKey.section,
// 'diaeresis': TerminalKey.diaeresis,
// 'copyright': TerminalKey.copyright,
// 'ordfeminine': TerminalKey.ordfeminine,
// 'guillemotleft': TerminalKey.guillemotleft,
// 'notsign': TerminalKey.notsign,
// 'hyphen': TerminalKey.hyphen,
// 'registered': TerminalKey.registered,
// 'macron': TerminalKey.macron,
// 'degree': TerminalKey.degree,
// 'plusminus': TerminalKey.plusminus,
// 'twosuperior': TerminalKey.twosuperior,
// 'threesuperior': TerminalKey.threesuperior,
// 'acute': TerminalKey.acute,
// // 'mu': TerminalKey.mu,
// 'paragraph': TerminalKey.paragraph,
// 'periodcentered': TerminalKey.periodcentered,
// 'cedilla': TerminalKey.cedilla,
// 'onesuperior': TerminalKey.onesuperior,
// 'masculine': TerminalKey.masculine,
// 'guillemotright': TerminalKey.guillemotright,
// 'onequarter': TerminalKey.onequarter,
// 'onehalf': TerminalKey.onehalf,
// 'threequarters': TerminalKey.threequarters,
// 'questiondown': TerminalKey.questiondown,
// 'Agrave': TerminalKey.agrave,
// 'Aacute': TerminalKey.aacute,
// 'Acircumflex': TerminalKey.acircumflex,
// 'Atilde': TerminalKey.atilde,
// 'Adiaeresis': TerminalKey.adiaeresis,
// 'Aring': TerminalKey.aring,
// 'AE': TerminalKey.aE,
// 'Ccedilla': TerminalKey.ccedilla,
// 'Egrave': TerminalKey.egrave,
// 'Eacute': TerminalKey.eacute,
// 'Ecircumflex': TerminalKey.ecircumflex,
// 'Ediaeresis': TerminalKey.ediaeresis,
// 'Igrave': TerminalKey.igrave,
// 'Iacute': TerminalKey.iacute,
// 'Icircumflex': TerminalKey.icircumflex,
// 'Idiaeresis': TerminalKey.idiaeresis,
// 'ETH': TerminalKey.eTH,
// 'Ntilde': TerminalKey.ntilde,
// 'Ograve': TerminalKey.ograve,
// 'Oacute': TerminalKey.oacute,
// 'Ocircumflex': TerminalKey.ocircumflex,
// 'Otilde': TerminalKey.otilde,
// 'Odiaeresis': TerminalKey.odiaeresis,
// 'multiply': TerminalKey.multiply,
// 'Ooblique': TerminalKey.ooblique,
// 'Ugrave': TerminalKey.ugrave,
// 'Uacute': TerminalKey.uacute,
// 'Ucircumflex': TerminalKey.ucircumflex,
// 'Udiaeresis': TerminalKey.udiaeresis,
// 'Yacute': TerminalKey.yacute,
// 'THORN': TerminalKey.tHORN,
// 'ssharp': TerminalKey.ssharp,
// 'division': TerminalKey.division,
// 'ydiaeresis': TerminalKey.ydiaeresis,
// 'Multi_key': TerminalKey.multi_key,
// 'Codeinput': TerminalKey.codeinput,
// 'SingleCandidate': TerminalKey.singleCandidate,
// 'MultipleCandidate': TerminalKey.multipleCandidate,
// 'PreviousCandidate': TerminalKey.previousCandidate,
// 'Mode_switch': TerminalKey.mode_switch,
// 'Kanji': TerminalKey.kanji,
// 'Muhenkan': TerminalKey.muhenkan,
// 'Henkan': TerminalKey.henkan,
// 'Romaji': TerminalKey.romaji,
// 'Hiragana': TerminalKey.hiragana,
// 'Katakana': TerminalKey.katakana,
// 'Hiragana_Katakana': TerminalKey.hiragana_Katakana,
// 'Zenkaku': TerminalKey.zenkaku,
// 'Hankaku': TerminalKey.hankaku,
// 'Zenkaku_Hankaku': TerminalKey.zenkaku_Hankaku,
// 'Touroku': TerminalKey.touroku,
// 'Massyo': TerminalKey.massyo,
// 'Kana_Lock': TerminalKey.kana_Lock,
// 'Kana_Shift': TerminalKey.kana_Shift,
// 'Eisu_Shift': TerminalKey.eisu_Shift,
// 'Eisu_toggle': TerminalKey.eisu_toggle,
// 'Hangul': TerminalKey.hangul,
// 'Hangul_Start': TerminalKey.hangul_Start,
// 'Hangul_End': TerminalKey.hangul_End,
// 'Hangul_Hanja': TerminalKey.hangul_Hanja,
// 'Hangul_Jamo': TerminalKey.hangul_Jamo,
// 'Hangul_Romaja': TerminalKey.hangul_Romaja,
// 'Hangul_Jeonja': TerminalKey.hangul_Jeonja,
// 'Hangul_Banja': TerminalKey.hangul_Banja,
// 'Hangul_PreHanja': TerminalKey.hangul_PreHanja,
// 'Hangul_PostHanja': TerminalKey.hangul_PostHanja,
// 'Hangul_Special': TerminalKey.hangul_Special,
// 'Dead_Grave': TerminalKey.dead_Grave,
// 'Dead_Acute': TerminalKey.dead_Acute,
// 'Dead_Circumflex': TerminalKey.dead_Circumflex,
// 'Dead_Tilde': TerminalKey.dead_Tilde,
// 'Dead_Macron': TerminalKey.dead_Macron,
// 'Dead_Breve': TerminalKey.dead_Breve,
// 'Dead_Abovedot': TerminalKey.dead_Abovedot,
// 'Dead_Diaeresis': TerminalKey.dead_Diaeresis,
// 'Dead_Abovering': TerminalKey.dead_Abovering,
// 'Dead_Doubleacute': TerminalKey.dead_Doubleacute,
// 'Dead_Caron': TerminalKey.dead_Caron,
// 'Dead_Cedilla': TerminalKey.dead_Cedilla,
// 'Dead_Ogonek': TerminalKey.dead_Ogonek,
// 'Dead_Iota': TerminalKey.dead_Iota,
// 'Dead_Voiced_Sound': TerminalKey.dead_Voiced_Sound,
// 'Dead_Semivoiced_Sound': TerminalKey.dead_Semivoiced_Sound,
// 'Dead_Belowdot': TerminalKey.dead_Belowdot,
// 'Dead_Hook': TerminalKey.dead_Hook,
// 'Dead_Horn': TerminalKey.dead_Horn,
// 'Dead_Stroke': TerminalKey.dead_Stroke,
// 'Dead_Abovecomma': TerminalKey.dead_Abovecomma,
// 'Dead_Abovereversedcomma': TerminalKey.dead_Abovereversedcomma,
// 'Dead_Doublegrave': TerminalKey.dead_Doublegrave,
// 'Dead_Belowring': TerminalKey.dead_Belowring,
// 'Dead_Belowmacron': TerminalKey.dead_Belowmacron,
// 'Dead_Belowcircumflex': TerminalKey.dead_Belowcircumflex,
// 'Dead_Belowtilde': TerminalKey.dead_Belowtilde,
// 'Dead_Belowbreve': TerminalKey.dead_Belowbreve,
// 'Dead_Belowdiaeresis': TerminalKey.dead_Belowdiaeresis,
// 'Dead_Invertedbreve': TerminalKey.dead_Invertedbreve,
// 'Dead_Belowcomma': TerminalKey.dead_Belowcomma,
// 'Dead_Currency': TerminalKey.dead_Currency,
// 'Dead_a': TerminalKey.dead_a,
// 'Dead_A': TerminalKey.dead_A,
// 'Dead_e': TerminalKey.dead_e,
// 'Dead_E': TerminalKey.dead_E,
// 'Dead_i': TerminalKey.dead_i,
// 'Dead_I': TerminalKey.dead_I,
// 'Dead_o': TerminalKey.dead_o,
// 'Dead_O': TerminalKey.dead_O,
// 'Dead_u': TerminalKey.dead_u,
// 'Dead_U': TerminalKey.dead_U,
// 'Dead_Small_Schwa': TerminalKey.dead_Small_Schwa,
// 'Dead_Capital_Schwa': TerminalKey.dead_Capital_Schwa,
// 'Dead_Greek': TerminalKey.dead_Greek,
// 'Dead_Lowline': TerminalKey.dead_Lowline,
// 'Dead_Aboveverticalline': TerminalKey.dead_Aboveverticalline,
// 'Dead_Belowverticalline': TerminalKey.dead_Belowverticalline,
// 'Dead_Longsolidusoverlay': TerminalKey.dead_Longsolidusoverlay,
// 'Back': TerminalKey.back,
// 'Forward': TerminalKey.forward,
// 'Stop': TerminalKey.stop,
// 'Refresh': TerminalKey.refresh,
'VolumeDown': TerminalKey.audioVolumeDown,
'VolumeMute': TerminalKey.audioVolumeMute,
'VolumeUp': TerminalKey.audioVolumeUp,
'BassBoost': TerminalKey.bassBoost,
// 'BassUp': TerminalKey.bassUp,
// 'BassDown': TerminalKey.bassDown,
// 'TrebleUp': TerminalKey.trebleUp,
// 'TrebleDown': TerminalKey.trebleDown,
'MediaPlay': TerminalKey.mediaPlay,
'MediaStop': TerminalKey.mediaStop,
// 'MediaPrevious': TerminalKey.mediaPrevious,
// 'MediaNext': TerminalKey.mediaNext,
'MediaRecord': TerminalKey.mediaRecord,
'MediaPause': TerminalKey.mediaPause,
'MediaTogglePlayPause': TerminalKey.mediaPlayPause,
'HomePage': TerminalKey.browserHome,
// 'Favorites': TerminalKey.favorites,
// 'Search': TerminalKey.search,
// 'Standby': TerminalKey.standby,
// 'OpenUrl': TerminalKey.openUrl,
// 'LaunchMail': TerminalKey.launchMail,
// 'LaunchMedia': TerminalKey.launchMedia,
// 'Launch0': TerminalKey.launch0,
// 'Launch1': TerminalKey.launch1,
// 'Launch2': TerminalKey.launch2,
// 'Launch3': TerminalKey.launch3,
// 'Launch4': TerminalKey.launch4,
// 'Launch5': TerminalKey.launch5,
// 'Launch6': TerminalKey.launch6,
// 'Launch7': TerminalKey.launch7,
// 'Launch8': TerminalKey.launch8,
// 'Launch9': TerminalKey.launch9,
// 'LaunchA': TerminalKey.launchA,
// 'LaunchB': TerminalKey.launchB,
// 'LaunchC': TerminalKey.launchC,
// 'LaunchD': TerminalKey.launchD,
// 'LaunchE': TerminalKey.launchE,
// 'LaunchF': TerminalKey.launchF,
// 'LaunchG': TerminalKey.launchG,
// 'LaunchH': TerminalKey.launchH,
'MonBrightnessUp': TerminalKey.brightnessUp,
'MonBrightnessDown': TerminalKey.brightnessDown,
// 'KeyboardLightOnOff': TerminalKey.keyboardLightOnOff,
// 'KeyboardBrightnessUp': TerminalKey.keyboardBrightnessUp,
// 'KeyboardBrightnessDown': TerminalKey.keyboardBrightnessDown,
'PowerOff': TerminalKey.power,
'WakeUp': TerminalKey.wakeUp,
'Eject': TerminalKey.eject,
// 'ScreenSaver': TerminalKey.screenSaver,
// 'WWW': TerminalKey.wWW,
// 'Memo': TerminalKey.memo,
// 'LightBulb': TerminalKey.lightBulb,
// 'Shop': TerminalKey.shop,
// 'History': TerminalKey.history,
// 'AddFavorite': TerminalKey.addFavorite,
// 'HotLinks': TerminalKey.hotLinks,
// 'BrightnessAdjust': TerminalKey.brightnessAdjust,
// 'Finance': TerminalKey.finance,
// 'Community': TerminalKey.community,
// 'AudioRewind': TerminalKey.audioRewind,
// 'BackForward': TerminalKey.backForward,
// 'ApplicationLeft': TerminalKey.applicationLeft,
// 'ApplicationRight': TerminalKey.applicationRight,
// 'Book': TerminalKey.book,
// 'CD': TerminalKey.cD,
// 'Calculator': TerminalKey.calculator,
// 'ToDoList': TerminalKey.toDoList,
// 'ClearGrab': TerminalKey.clearGrab,
'Close': TerminalKey.close,
'Copy': TerminalKey.copy,
'Cut': TerminalKey.cut,
// 'Display': TerminalKey.display,
// 'DOS': TerminalKey.dOS,
// 'Documents': TerminalKey.documents,
// 'Excel': TerminalKey.excel,
// 'Explorer': TerminalKey.explorer,
// 'Game': TerminalKey.game,
// 'Go': TerminalKey.go,
// 'iTouch': TerminalKey.iTouch,
// 'LogOff': TerminalKey.logOff,
// 'Market': TerminalKey.market,
// 'Meeting': TerminalKey.meeting,
// 'MenuKB': TerminalKey.menuKB,
// 'MenuPB': TerminalKey.menuPB,
// 'MySites': TerminalKey.mySites,
// 'News': TerminalKey.news,
// 'OfficeHome': TerminalKey.officeHome,
// 'Option': TerminalKey.option,
// 'Paste': TerminalKey.paste,
// 'Phone': TerminalKey.phone,
// 'Calendar': TerminalKey.calendar,
// 'Reply': TerminalKey.reply,
// 'Reload': TerminalKey.reload,
// 'RotateWindows': TerminalKey.rotateWindows,
// 'RotationPB': TerminalKey.rotationPB,
// 'RotationKB': TerminalKey.rotationKB,
'Save': TerminalKey.save,
// 'Send': TerminalKey.send,
// 'Spell': TerminalKey.spell,
// 'SplitScreen': TerminalKey.splitScreen,
// 'Support': TerminalKey.support,
// 'TaskPane': TerminalKey.taskPane,
// 'Terminal': TerminalKey.terminal,
// 'Tools': TerminalKey.tools,
// 'Travel': TerminalKey.travel,
// 'Video': TerminalKey.video,
// 'Word': TerminalKey.word,
// 'Xfer': TerminalKey.xfer,
'ZoomIn': TerminalKey.zoomIn,
'ZoomOut': TerminalKey.zoomOut,
// 'Away': TerminalKey.away,
// 'Messenger': TerminalKey.messenger,
// 'WebCam': TerminalKey.webCam,
// 'MailForward': TerminalKey.mailForward,
// 'Pictures': TerminalKey.pictures,
// 'Music': TerminalKey.music,
// 'Battery': TerminalKey.battery,
// 'Bluetooth': TerminalKey.bluetooth,
// 'WLAN': TerminalKey.wLAN,
// 'UWB': TerminalKey.uWB,
// 'AudioForward': TerminalKey.audioForward,
// 'AudioRepeat': TerminalKey.audioRepeat,
// 'AudioRandomPlay': TerminalKey.audioRandomPlay,
// 'Subtitle': TerminalKey.subtitle,
// 'AudioCycleTrack': TerminalKey.audioCycleTrack,
// 'Time': TerminalKey.time,
// 'Hibernate': TerminalKey.hibernate,
// 'View': TerminalKey.view,
// 'TopMenu': TerminalKey.topMenu,
// 'PowerDown': TerminalKey.powerDown,
// 'Suspend': TerminalKey.suspend,
// 'ContrastAdjust': TerminalKey.contrastAdjust,
// 'TouchpadToggle': TerminalKey.touchpadToggle,
// 'TouchpadOn': TerminalKey.touchpadOn,
// 'TouchpadOff': TerminalKey.touchpadOff,
// 'MicMute': TerminalKey.micMute,
// 'Red': TerminalKey.red,
// 'Green': TerminalKey.green,
// 'Yellow': TerminalKey.yellow,
// 'Blue': TerminalKey.blue,
'ChannelUp': TerminalKey.channelUp,
'ChannelDown': TerminalKey.channelDown,
// 'Guide': TerminalKey.guide,
'Info': TerminalKey.info,
// 'Settings': TerminalKey.settings,
// 'MicVolumeUp': TerminalKey.micVolumeUp,
// 'MicVolumeDown': TerminalKey.micVolumeDown,
// 'New': TerminalKey.new,
'Open': TerminalKey.open,
'Find': TerminalKey.find,
'Undo': TerminalKey.undo,
'Redo': TerminalKey.redo,
'MediaLast': TerminalKey.mediaLast,
// 'unknown': TerminalKey.unknown,
// 'Call': TerminalKey.call,
// 'Camera': TerminalKey.camera,
// 'CameraFocus': TerminalKey.cameraFocus,
// 'Context1': TerminalKey.context1,
// 'Context2': TerminalKey.context2,
// 'Context3': TerminalKey.context3,
// 'Context4': TerminalKey.context4,
// 'Flip': TerminalKey.flip,
// 'Hangup': TerminalKey.hangup,
// 'No': TerminalKey.no,
'Select': TerminalKey.select,
// 'Yes': TerminalKey.yes,
// 'ToggleCallHangup': TerminalKey.toggleCallHangup,
// 'VoiceDial': TerminalKey.voiceDial,
// 'LastNumberRedial': TerminalKey.lastNumberRedial,
// 'Execute': TerminalKey.execute,
// 'Printer': TerminalKey.printer,
// 'Play': TerminalKey.play,
'Sleep': TerminalKey.sleep,
// 'Zoom': TerminalKey.zoom,
'Exit': TerminalKey.exit,
// 'Cancel': TerminalKey.cancel,
};
+31
View File
@@ -0,0 +1,31 @@
enum TerminalMouseButton {
left(id: 0),
middle(id: 1),
right(id: 2),
/// No button: the pointer moved with no button held (mode 1003 motion).
none(id: 3),
wheelUp(id: 64 + 0, isWheel: true),
wheelDown(id: 64 + 1, isWheel: true),
wheelLeft(id: 64 + 2, isWheel: true),
wheelRight(id: 64 + 3, isWheel: true),
;
/// The button code reported to the program, before modifiers and the
/// motion flag are added.
///
/// The wheel is reported as buttons 4-7, which the protocol encodes by
/// setting bit 6 (64) on codes 0-3: wheel up is 64, wheel down 65.
final int id;
/// Whether this button is a mouse wheel button.
final bool isWheel;
const TerminalMouseButton({required this.id, this.isWheel = false});
}
@@ -0,0 +1,5 @@
enum TerminalMouseButtonState {
up,
down,
}
+150
View File
@@ -0,0 +1,150 @@
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/mouse/button_state.dart';
import 'package:xterm/src/core/mouse/mode.dart';
import 'package:xterm/src/core/mouse/button.dart';
import 'package:xterm/src/core/mouse/reporter.dart';
import 'package:xterm/src/core/platform.dart';
import 'package:xterm/src/core/state.dart';
class TerminalMouseEvent {
/// The button that is pressed or released.
final TerminalMouseButton button;
/// The current state of the button.
final TerminalMouseButtonState buttonState;
/// The zero-based screen cell of the event.
final CellOffset position;
/// The state of the terminal.
final TerminalState state;
/// The platform of the terminal.
final TerminalTargetPlatform platform;
/// Whether the pointer moved (with [button] held, or [TerminalMouseButton.none])
/// rather than a button changing state.
final bool motion;
final bool shift;
final bool alt;
final bool ctrl;
TerminalMouseEvent({
required this.button,
required this.buttonState,
required this.position,
required this.state,
required this.platform,
this.motion = false,
this.shift = false,
this.alt = false,
this.ctrl = false,
});
/// The modifier bits of the report.
int get modifiers =>
(shift ? MouseReporter.shiftBit : 0) |
(alt ? MouseReporter.altBit : 0) |
(ctrl ? MouseReporter.ctrlBit : 0);
}
const defaultMouseHandler = CascadeMouseHandler([
ClickMouseHandler(),
UpDownMouseHandler(),
]);
abstract class TerminalMouseHandler {
const TerminalMouseHandler();
String? call(TerminalMouseEvent event);
}
class CascadeMouseHandler implements TerminalMouseHandler {
final List<TerminalMouseHandler> _handlers;
const CascadeMouseHandler(this._handlers);
@override
String? call(TerminalMouseEvent event) {
for (var handler in _handlers) {
final result = handler(event);
if (result != null) {
return result;
}
}
return null;
}
}
/// X10 compatibility mode (`CSI ? 9 h`): button presses only, no
/// modifiers, no wheel.
class ClickMouseHandler implements TerminalMouseHandler {
const ClickMouseHandler();
@override
String? call(TerminalMouseEvent event) {
switch (event.state.mouseMode) {
case MouseMode.clickOnly:
if (event.buttonState == TerminalMouseButtonState.down &&
!event.motion &&
event.button.id < 3) {
return MouseReporter.report(
event.button,
event.buttonState,
event.position,
event.state.mouseReportMode,
);
}
return null;
case MouseMode.none:
case MouseMode.upDownScroll:
case MouseMode.upDownScrollDrag:
case MouseMode.upDownScrollMove:
return null;
}
}
}
/// Normal (1000), button-event (1002) and any-event (1003) tracking:
/// presses, releases and the wheel; 1002 adds motion with a button held,
/// 1003 all motion.
class UpDownMouseHandler implements TerminalMouseHandler {
const UpDownMouseHandler();
@override
String? call(TerminalMouseEvent event) {
final mode = event.state.mouseMode;
switch (mode) {
case MouseMode.none:
case MouseMode.clickOnly:
return null;
case MouseMode.upDownScroll:
case MouseMode.upDownScrollDrag:
case MouseMode.upDownScrollMove:
if (event.motion) {
final reported = mode == MouseMode.upDownScrollMove ||
mode == MouseMode.upDownScrollDrag &&
event.button != TerminalMouseButton.none;
if (!reported) return null;
} else if (event.button == TerminalMouseButton.none) {
return null;
}
// Up events are never reported for mouse wheel buttons.
if (event.button.isWheel &&
event.buttonState == TerminalMouseButtonState.up) {
return null;
}
return MouseReporter.report(
event.button,
event.buttonState,
event.position,
event.state.mouseReportMode,
motion: event.motion,
modifiers: event.modifiers,
);
}
}
}
+36
View File
@@ -0,0 +1,36 @@
/// https://terminalguide.namepad.de/mouse/
enum MouseMode {
none,
clickOnly,
upDownScroll(reportScroll: true),
upDownScrollDrag(reportScroll: true),
upDownScrollMove(reportScroll: true),
;
const MouseMode({this.reportScroll = false});
final bool reportScroll;
}
/// https://terminalguide.namepad.de/mouse/
enum MouseReportMode {
/// The default mouse reporting mode where digits are encoded as bytes with
/// `32 + code`. This mode has a range from 1 to 223.
normal,
/// When code < 96 this is the same as [normal], otherwise the `code + 32` is
/// encoded as 2 bytes in UTF-8. This mode has a range from 1 to 2015.
utf,
/// In this mode the code are encoded as 10-based numbers. Tha range is
/// unlimited.
sgr,
/// Similar to [sgr], the difference is that the button id is encoded as
/// `32 + code`.
urxvt,
}
+59
View File
@@ -0,0 +1,59 @@
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/mouse/mode.dart';
import 'package:xterm/src/core/mouse/button.dart';
import 'package:xterm/src/core/mouse/button_state.dart';
abstract class MouseReporter {
/// Modifier bits added to the button code.
static const shiftBit = 4;
static const altBit = 8;
static const ctrlBit = 16;
/// Added to the button code for a motion event (modes 1002 and 1003).
static const motionBit = 32;
/// Encodes a mouse event at the zero-based screen cell [position].
///
/// [modifiers] is a combination of [shiftBit], [altBit] and [ctrlBit];
/// [motion] marks a move rather than a press or release.
static String report(
TerminalMouseButton button,
TerminalMouseButtonState state,
CellOffset position,
MouseReportMode reportMode, {
bool motion = false,
int modifiers = 0,
}) {
// x and y offsets have to be incremented by 1 as the offset if 0-based,
// The position has to be reported using 1-based coordinates.
final x = position.x + 1;
final y = position.y + 1;
final extra = modifiers | (motion ? motionBit : 0);
switch (reportMode) {
case MouseReportMode.normal:
case MouseReportMode.utf:
// Button code 3 signals a release; these encodings cannot say which
// button was released.
final code =
(state == TerminalMouseButtonState.up && !motion ? 3 : button.id) |
extra;
// The code and coordinates are sent as 32 + value. Normal mode only
// reaches 223, utf mode 2015; beyond that a null byte is sent.
final limit = reportMode == MouseReportMode.normal ? 223 : 2015;
String encode(int value) =>
value > limit ? '\x00' : String.fromCharCode(32 + value);
return '\x1b[M${String.fromCharCode(32 + code)}${encode(x)}${encode(y)}';
case MouseReportMode.sgr:
// SGR reports the released button and marks a release with `m`.
final code = button.id | extra;
final upDown =
state == TerminalMouseButtonState.up && !motion ? 'm' : 'M';
return '\x1b[<$code;$x;$y$upDown';
case MouseReportMode.urxvt:
final code =
(state == TerminalMouseButtonState.up && !motion ? 3 : button.id) |
extra;
return '\x1b[${32 + code};$x;${y}M';
}
}
}
+17
View File
@@ -0,0 +1,17 @@
enum TerminalTargetPlatform {
unknown,
android,
ios,
fuchsia,
linux,
macos,
windows,
web,
}
+197
View File
@@ -0,0 +1,197 @@
import 'package:xterm/src/core/buffer/line.dart';
import 'package:xterm/src/utils/circular_buffer.dart';
class _LineBuilder {
_LineBuilder([this._capacity = 80]) {
_result = BufferLine(_capacity);
}
final int _capacity;
late BufferLine _result;
int _length = 0;
int get length => _length;
bool get isEmpty => _length == 0;
bool get isNotEmpty => _length != 0;
/// Adds a range of cells from [src] to the builder. Anchors within the range
/// will be reparented to the new line returned by [take].
void add(BufferLine src, int start, int length) {
_result.copyFrom(src, start, _length, length);
_length += length;
}
/// Reuses the given [line] as the initial buffer for this builder.
void setBuffer(BufferLine line, int length) {
_result = line;
_length = length;
}
void addAnchor(CellAnchor anchor, int offset) {
anchor.reparent(_result, _length + offset);
}
BufferLine take({required bool wrapped}) {
final result = _result;
result.isWrapped = wrapped;
// result.resize(_length);
_result = BufferLine(_capacity);
_length = 0;
return result;
}
}
/// Holds a the state of reflow operation of a single logical line.
class _LineReflow {
final int oldWidth;
final int newWidth;
_LineReflow(this.oldWidth, this.newWidth);
final _lines = <BufferLine>[];
late final _builder = _LineBuilder(newWidth);
/// Adds a line to the reflow operation. This method will try to reuse the
/// given line if possible.
void add(BufferLine line) {
final trimmedLength = line.getTrimmedLength(oldWidth);
// A fast path for empty lines
if (trimmedLength == 0) {
_lines.add(line);
return;
}
// We already have some content in the buffer, so we copy the content into
// the builder instead of reusing the line.
if (_lines.isNotEmpty || _builder.isNotEmpty) {
_addPart(line, from: 0, to: trimmedLength);
return;
}
if (newWidth >= oldWidth) {
// Reuse the line to avoid copying the content and object allocation.
_builder.setBuffer(line, trimmedLength);
} else {
_lines.add(line);
if (trimmedLength > newWidth) {
if (line.getWidth(newWidth - 1) == 2) {
_addPart(line, from: newWidth - 1, to: trimmedLength);
} else {
_addPart(line, from: newWidth, to: trimmedLength);
}
}
}
line.resize(newWidth);
if (line.getWidth(newWidth - 1) == 2) {
line.resetCell(newWidth - 1);
}
}
/// Adds part of [line] from [from] to [to] to the reflow operation.
/// Anchors within the range will be removed from [line] and reparented to
/// the new line(s) returned by [finish].
void _addPart(BufferLine line, {required int from, required int to}) {
var cellsLeft = to - from;
while (cellsLeft > 0) {
final bufferRemainingCells = newWidth - _builder.length;
// How many cells we should copy in this iteration.
var cellsToCopy = cellsLeft;
// Whether the buffer is filled up in this iteration.
var lineFilled = false;
if (cellsToCopy >= bufferRemainingCells) {
cellsToCopy = bufferRemainingCells;
lineFilled = true;
}
// Leave the last cell to the next iteration if it's a wide char.
if (lineFilled && line.getWidth(from + cellsToCopy - 1) == 2) {
cellsToCopy--;
}
for (var anchor in line.anchors.toList()) {
if (anchor.x >= from && anchor.x <= from + cellsToCopy) {
_builder.addAnchor(anchor, anchor.x - from);
}
}
_builder.add(line, from, cellsToCopy);
from += cellsToCopy;
cellsLeft -= cellsToCopy;
// Create a new line if the buffer is filled up.
if (lineFilled) {
_lines.add(_builder.take(wrapped: _lines.isNotEmpty));
}
}
if (line.anchors.isNotEmpty) {
for (var anchor in line.anchors.toList()) {
if (anchor.x >= to) {
_builder.addAnchor(anchor, anchor.x - to);
}
}
}
}
/// Finalizes the reflow operation and returns the result.
List<BufferLine> finish() {
if (_builder.isNotEmpty) {
_lines.add(_builder.take(wrapped: _lines.isNotEmpty));
}
return _lines;
}
}
List<BufferLine> reflow(
IndexAwareCircularBuffer<BufferLine> lines,
int oldWidth,
int newWidth,
) {
final result = <BufferLine>[];
for (var i = 0; i < lines.length; i++) {
final line = lines[i];
final reflow = _LineReflow(oldWidth, newWidth);
reflow.add(line);
for (var offset = i + 1; offset < lines.length; offset++) {
final nextLine = lines[offset];
if (!nextLine.isWrapped) {
break;
}
i++;
reflow.add(nextLine);
}
result.addAll(reflow.finish());
}
for (var line in result) {
line.resize(newWidth);
}
return result;
}
+3
View File
@@ -0,0 +1,3 @@
abstract class TerminalSnapshot {
void trimScrollback();
}
+44
View File
@@ -0,0 +1,44 @@
import 'package:xterm/src/core/cursor.dart';
import 'package:xterm/src/core/mouse/mode.dart';
abstract class TerminalState {
int get viewWidth;
int get viewHeight;
CursorStyle get cursor;
bool get reflowEnabled;
/* Modes */
bool get insertMode;
bool get lineFeedMode;
/* DEC Private modes */
bool get cursorKeysMode;
bool get reverseDisplayMode;
bool get originMode;
bool get autoWrapMode;
MouseMode get mouseMode;
MouseReportMode get mouseReportMode;
bool get cursorBlinkMode;
bool get cursorVisibleMode;
bool get appKeypadMode;
bool get reportFocusMode;
bool get altBufferMouseScrollMode;
bool get bracketedPasteMode;
}
+78
View File
@@ -0,0 +1,78 @@
import 'dart:math' show min;
const _kMaxColumns = 1024;
/// Manages the tab stop state for a terminal.
class TabStops {
final _stops = List<bool>.filled(_kMaxColumns, false);
TabStops() {
_initialize();
}
/// Initializes the tab stops to the default 8 column intervals.
void _initialize() {
const interval = 8;
for (var i = 0; i < _kMaxColumns; i += interval) {
_stops[i] = true;
}
}
/// Finds the next tab stop index, which satisfies [start] <= index < [end].
int? find(int start, int end) {
if (start >= end) {
return null;
}
end = min(end, _stops.length);
for (var i = start; i < end; i++) {
if (_stops[i]) {
return i;
}
}
return null;
}
/// Finds the closest tab stop index below [start], or null without one.
int? findPrevious(int start) {
for (var i = min(start, _stops.length) - 1; i >= 0; i--) {
if (_stops[i]) {
return i;
}
}
return null;
}
/// Sets the tab stop at [index]. If there is already a tab stop at [index],
/// this method does nothing.
///
/// See also:
/// * [clearAt] which does the opposite.
void setAt(int index) {
assert(index >= 0 && index < _kMaxColumns);
_stops[index] = true;
}
/// Clears the tab stop at [index]. If there is no tab stop at [index], this
/// method does nothing.
void clearAt(int index) {
assert(index >= 0 && index < _kMaxColumns);
_stops[index] = false;
}
/// Clears all tab stops without resetting them to the default 8 column
/// intervals.
void clearAll() {
_stops.fillRange(0, _kMaxColumns, false);
}
/// Returns true if there is a tab stop at [index].
bool isSetAt(int index) {
return _stops[index];
}
/// Resets the tab stops to the default 8 column intervals.
void reset() {
clearAll();
_initialize();
}
}
File diff suppressed because it is too large Load Diff
+565
View File
@@ -0,0 +1,565 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/input/keys.dart';
import 'package:xterm/src/terminal.dart';
import 'package:xterm/src/ui/controller.dart';
import 'package:xterm/src/ui/cursor_type.dart';
import 'package:xterm/src/ui/custom_text_edit.dart';
import 'package:xterm/src/ui/gesture/gesture_handler.dart';
import 'package:xterm/src/ui/input_map.dart';
import 'package:xterm/src/ui/keyboard_listener.dart';
import 'package:xterm/src/ui/keyboard_visibility.dart';
import 'package:xterm/src/ui/mouse_listener.dart';
import 'package:xterm/src/ui/render.dart';
import 'package:xterm/src/ui/scroll_handler.dart';
import 'package:xterm/src/ui/shortcut/actions.dart';
import 'package:xterm/src/ui/shortcut/shortcuts.dart';
import 'package:xterm/src/ui/terminal_text_style.dart';
import 'package:xterm/src/ui/terminal_theme.dart';
import 'package:xterm/src/ui/themes.dart';
class TerminalView extends StatefulWidget {
const TerminalView(
this.terminal, {
super.key,
this.controller,
this.theme = TerminalThemes.defaultTheme,
this.textStyle = const TerminalStyle(),
this.textScaler,
this.padding,
this.scrollController,
this.autoResize = true,
this.backgroundOpacity = 1,
this.focusNode,
this.autofocus = false,
this.onTapUp,
this.onSecondaryTapDown,
this.onSecondaryTapUp,
this.mouseCursor = SystemMouseCursors.text,
this.keyboardType = TextInputType.emailAddress,
this.keyboardAppearance = Brightness.dark,
this.cursorType = TerminalCursorType.block,
this.alwaysShowCursor = false,
this.deleteDetection = false,
this.shortcuts,
this.onKeyEvent,
this.readOnly = false,
this.hardwareKeyboardOnly = false,
this.simulateScroll = true,
});
/// The underlying terminal that this widget renders.
final Terminal terminal;
final TerminalController? controller;
/// The theme to use for this terminal.
final TerminalTheme theme;
/// The style to use for painting characters.
final TerminalStyle textStyle;
final TextScaler? textScaler;
/// Padding around the inner [Scrollable] widget.
final EdgeInsets? padding;
/// Scroll controller for the inner [Scrollable] widget.
final ScrollController? scrollController;
/// Should this widget automatically notify the underlying terminal when its
/// size changes. [true] by default.
final bool autoResize;
/// Opacity of the terminal background. Set to 0 to make the terminal
/// background transparent.
final double backgroundOpacity;
/// An optional focus node to use as the focus node for this widget.
final FocusNode? focusNode;
/// True if this widget will be selected as the initial focus when no other
/// node in its scope is currently focused.
final bool autofocus;
/// Callback for when the user taps on the terminal.
final void Function(TapUpDetails, CellOffset)? onTapUp;
/// Function called when the user taps on the terminal with a secondary
/// button.
final void Function(TapDownDetails, CellOffset)? onSecondaryTapDown;
/// Function called when the user stops holding down a secondary button.
final void Function(TapUpDetails, CellOffset)? onSecondaryTapUp;
/// The mouse cursor for mouse pointers that are hovering over the terminal.
/// [SystemMouseCursors.text] by default.
final MouseCursor mouseCursor;
/// The type of information for which to optimize the text input control.
/// [TextInputType.emailAddress] by default.
final TextInputType keyboardType;
/// The appearance of the keyboard. [Brightness.dark] by default.
///
/// This setting is only honored on iOS devices.
final Brightness keyboardAppearance;
/// The type of cursor to use. [TerminalCursorType.block] by default.
final TerminalCursorType cursorType;
/// Whether to always show the cursor. This is useful for debugging.
/// [false] by default.
final bool alwaysShowCursor;
/// Workaround to detect delete key for platforms and IMEs that does not
/// emit hardware delete event. Prefered on mobile platforms. [false] by
/// default.
final bool deleteDetection;
/// Shortcuts for this terminal. This has higher priority than input handler
/// of the terminal If not provided, [defaultTerminalShortcuts] will be used.
final Map<ShortcutActivator, Intent>? shortcuts;
/// Keyboard event handler of the terminal. This has higher priority than
/// [shortcuts] and input handler of the terminal.
final FocusOnKeyEventCallback? onKeyEvent;
/// True if no input should send to the terminal.
final bool readOnly;
/// True if only hardware keyboard events should be used as input. This will
/// also prevent any on-screen keyboard to be shown.
final bool hardwareKeyboardOnly;
/// 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
/// keys to the application. This is standard behavior for most terminal
/// emulators. True by default.
final bool simulateScroll;
@override
State<TerminalView> createState() => TerminalViewState();
}
class TerminalViewState extends State<TerminalView> {
late FocusNode _focusNode;
late final ShortcutManager _shortcutManager;
final _customTextEditKey = GlobalKey<CustomTextEditState>();
final _scrollableKey = GlobalKey<ScrollableState>();
final _viewportKey = GlobalKey();
String? _composingText;
late TerminalController _controller;
late ScrollController _scrollController;
RenderTerminal get renderTerminal =>
_viewportKey.currentContext!.findRenderObject() as RenderTerminal;
/// Whether the latest mouse press was reported to the program (mouse
/// tracking on, Shift not held), so the gestures it starts do not select.
bool mousePressReported = false;
@override
void initState() {
_focusNode = widget.focusNode ?? FocusNode();
_focusNode.addListener(_onFocusChange);
_hadFocus = _focusNode.hasFocus;
_controller = widget.controller ?? TerminalController();
_scrollController = widget.scrollController ?? ScrollController();
_shortcutManager = ShortcutManager(
shortcuts: widget.shortcuts ?? defaultTerminalShortcuts,
);
super.initState();
}
bool _hadFocus = false;
/// Reports focus changes to a program that asked for them (`CSI ? 1004 h`).
void _onFocusChange() {
final hasFocus = _focusNode.hasFocus;
if (hasFocus == _hadFocus) return;
_hadFocus = hasFocus;
if (!widget.readOnly) widget.terminal.focusInput(hasFocus);
}
@override
void didUpdateWidget(TerminalView oldWidget) {
if (oldWidget.focusNode != widget.focusNode) {
_focusNode.removeListener(_onFocusChange);
if (oldWidget.focusNode == null) {
_focusNode.dispose();
}
_focusNode = widget.focusNode ?? FocusNode();
_focusNode.addListener(_onFocusChange);
_hadFocus = _focusNode.hasFocus;
}
if (oldWidget.controller != widget.controller) {
if (oldWidget.controller == null) {
_controller.dispose();
}
_controller = widget.controller ?? TerminalController();
}
if (oldWidget.scrollController != widget.scrollController) {
if (oldWidget.scrollController == null) {
_scrollController.dispose();
}
_scrollController = widget.scrollController ?? ScrollController();
}
_shortcutManager.shortcuts = widget.shortcuts ?? defaultTerminalShortcuts;
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
_focusNode.removeListener(_onFocusChange);
if (widget.focusNode == null) {
_focusNode.dispose();
}
if (widget.controller == null) {
_controller.dispose();
}
if (widget.scrollController == null) {
_scrollController.dispose();
}
_shortcutManager.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
Widget child = Scrollable(
key: _scrollableKey,
controller: _scrollController,
viewportBuilder: (context, offset) {
return _TerminalView(
key: _viewportKey,
terminal: widget.terminal,
controller: _controller,
offset: offset,
padding: MediaQuery.of(context).padding,
autoResize: widget.autoResize,
textStyle: widget.textStyle,
textScaler: widget.textScaler ?? MediaQuery.textScalerOf(context),
theme: widget.theme,
focusNode: _focusNode,
cursorType: widget.cursorType,
alwaysShowCursor: widget.alwaysShowCursor,
onEditableRect: _onEditableRect,
composingText: _composingText,
);
},
);
child = TerminalScrollGestureHandler(
terminal: widget.terminal,
simulateScroll: widget.simulateScroll,
getCellOffset: (globalPosition) => renderTerminal.getScreenCellOffset(
renderTerminal.globalToLocal(globalPosition),
),
getLineHeight: () => renderTerminal.lineHeight,
child: child,
);
if (!widget.hardwareKeyboardOnly) {
child = CustomTextEdit(
key: _customTextEditKey,
focusNode: _focusNode,
autofocus: widget.autofocus,
inputType: widget.keyboardType,
keyboardAppearance: widget.keyboardAppearance,
deleteDetection: widget.deleteDetection,
onInsert: _onInsert,
onDelete: () {
_scrollToBottom();
widget.terminal.keyInput(TerminalKey.backspace);
},
onComposing: _onComposing,
onAction: (action) {
_scrollToBottom();
if (action == TextInputAction.done) {
widget.terminal.keyInput(TerminalKey.enter);
}
},
onKeyEvent: _handleKeyEvent,
readOnly: widget.readOnly,
child: child,
);
} else if (!widget.readOnly) {
// Only listen for key input from a hardware keyboard.
child = CustomKeyboardListener(
child: child,
focusNode: _focusNode,
autofocus: widget.autofocus,
onInsert: _onInsert,
onComposing: _onComposing,
onKeyEvent: _handleKeyEvent,
);
}
child = TerminalActions(
terminal: widget.terminal,
controller: _controller,
child: child,
);
child = KeyboardVisibilty(
onKeyboardShow: _onKeyboardShow,
child: child,
);
child = TerminalMouseListener(
terminal: widget.terminal,
controller: _controller,
renderTerminal: () => renderTerminal,
readOnly: widget.readOnly,
onPressReported: (reported) => mousePressReported = reported,
child: child,
);
child = TerminalGestureHandler(
terminalView: this,
terminalController: _controller,
onTapUp: _onTapUp,
onTapDown: _onTapDown,
onSecondaryTapDown:
widget.onSecondaryTapDown != null ? _onSecondaryTapDown : null,
onSecondaryTapUp:
widget.onSecondaryTapUp != null ? _onSecondaryTapUp : null,
readOnly: widget.readOnly,
child: child,
);
child = MouseRegion(
cursor: widget.mouseCursor,
child: child,
);
child = Container(
color: widget.theme.background.withOpacity(widget.backgroundOpacity),
padding: widget.padding,
child: child,
);
return child;
}
void requestKeyboard() {
_customTextEditKey.currentState?.requestKeyboard();
}
void closeKeyboard() {
_customTextEditKey.currentState?.closeKeyboard();
}
Rect get cursorRect {
return renderTerminal.cursorOffset & renderTerminal.cellSize;
}
Rect get globalCursorRect {
return renderTerminal.localToGlobal(renderTerminal.cursorOffset) &
renderTerminal.cellSize;
}
void _onTapUp(TapUpDetails details) {
final offset = renderTerminal.getCellOffset(details.localPosition);
widget.onTapUp?.call(details, offset);
}
void _onTapDown(_) {
if (_controller.selection != null) {
_controller.clearSelection();
} else {
if (!widget.hardwareKeyboardOnly) {
_customTextEditKey.currentState?.requestKeyboard();
} else {
_focusNode.requestFocus();
}
}
}
void _onSecondaryTapDown(TapDownDetails details) {
final offset = renderTerminal.getCellOffset(details.localPosition);
widget.onSecondaryTapDown?.call(details, offset);
}
void _onSecondaryTapUp(TapUpDetails details) {
final offset = renderTerminal.getCellOffset(details.localPosition);
widget.onSecondaryTapUp?.call(details, offset);
}
bool get hasInputConnection {
return _customTextEditKey.currentState?.hasInputConnection == true;
}
void _onInsert(String text) {
final key = charToTerminalKey(text.trim());
// On mobile platforms there is no guarantee that virtual keyboard will
// generate hardware key events. So we need first try to send the key
// as a hardware key event. If it fails, then we send it as a text input.
final consumed = key == null ? false : widget.terminal.keyInput(key);
if (!consumed) {
widget.terminal.textInput(text);
}
_scrollToBottom();
}
void _onComposing(String? text) {
setState(() => _composingText = text);
}
KeyEventResult _handleKeyEvent(FocusNode focusNode, KeyEvent event) {
final resultOverride = widget.onKeyEvent?.call(focusNode, event);
if (resultOverride != null && resultOverride != KeyEventResult.ignored) {
return resultOverride;
}
// ignore: invalid_use_of_protected_member
final shortcutResult = _shortcutManager.handleKeypress(
focusNode.context!,
event,
);
if (shortcutResult != KeyEventResult.ignored) {
return shortcutResult;
}
if (event is KeyUpEvent) {
return KeyEventResult.ignored;
}
final key = keyToTerminalKey(event.logicalKey);
if (key == null) {
return KeyEventResult.ignored;
}
final handled = widget.terminal.keyInput(
key,
ctrl: HardwareKeyboard.instance.isControlPressed,
alt: HardwareKeyboard.instance.isAltPressed,
shift: HardwareKeyboard.instance.isShiftPressed,
);
if (handled) {
_scrollToBottom();
}
return handled ? KeyEventResult.handled : KeyEventResult.ignored;
}
void _onKeyboardShow() {
if (_focusNode.hasFocus) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollToBottom();
});
}
}
void _onEditableRect(Rect rect, Rect caretRect) {
_customTextEditKey.currentState?.setEditableRect(rect, caretRect);
}
void _scrollToBottom() {
final position = _scrollableKey.currentState?.position;
if (position != null) {
position.jumpTo(position.maxScrollExtent);
}
}
}
class _TerminalView extends LeafRenderObjectWidget {
const _TerminalView({
super.key,
required this.terminal,
required this.controller,
required this.offset,
required this.padding,
required this.autoResize,
required this.textStyle,
required this.textScaler,
required this.theme,
required this.focusNode,
required this.cursorType,
required this.alwaysShowCursor,
this.onEditableRect,
this.composingText,
});
final Terminal terminal;
final TerminalController controller;
final ViewportOffset offset;
final EdgeInsets padding;
final bool autoResize;
final TerminalStyle textStyle;
final TextScaler textScaler;
final TerminalTheme theme;
final FocusNode focusNode;
final TerminalCursorType cursorType;
final bool alwaysShowCursor;
final EditableRectCallback? onEditableRect;
final String? composingText;
@override
RenderTerminal createRenderObject(BuildContext context) {
return RenderTerminal(
terminal: terminal,
controller: controller,
offset: offset,
padding: padding,
autoResize: autoResize,
textStyle: textStyle,
textScaler: textScaler,
theme: theme,
focusNode: focusNode,
cursorType: cursorType,
alwaysShowCursor: alwaysShowCursor,
onEditableRect: onEditableRect,
composingText: composingText,
);
}
@override
void updateRenderObject(BuildContext context, RenderTerminal renderObject) {
renderObject
..terminal = terminal
..controller = controller
..offset = offset
..padding = padding
..autoResize = autoResize
..textStyle = textStyle
..textScaler = textScaler
..theme = theme
..focusNode = focusNode
..cursorType = cursorType
..alwaysShowCursor = alwaysShowCursor
..onEditableRect = onEditableRect
..composingText = composingText;
}
}
+21
View File
@@ -0,0 +1,21 @@
import 'dart:ui';
import 'package:flutter/painting.dart';
import 'package:xterm/src/ui/terminal_text_style.dart';
Size calcCharSize(TerminalStyle style, TextScaler textScaler) {
const test = 'mmmmmmmmmm';
final textStyle = style.toTextStyle();
final builder = ParagraphBuilder(textStyle.getParagraphStyle());
builder.pushStyle(textStyle.getTextStyle(textScaler: textScaler));
builder.addText(test);
final paragraph = builder.build();
paragraph.layout(ParagraphConstraints(width: double.infinity));
return Size(
paragraph.maxIntrinsicWidth / test.length,
paragraph.height,
);
}
+176
View File
@@ -0,0 +1,176 @@
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import 'package:xterm/src/base/disposable.dart';
import 'package:xterm/src/core/buffer/cell_offset.dart';
import 'package:xterm/src/core/buffer/line.dart';
import 'package:xterm/src/core/buffer/range.dart';
import 'package:xterm/src/core/buffer/range_block.dart';
import 'package:xterm/src/core/buffer/range_line.dart';
import 'package:xterm/src/ui/pointer_input.dart';
import 'package:xterm/src/ui/selection_mode.dart';
class TerminalController with ChangeNotifier {
TerminalController({
SelectionMode selectionMode = SelectionMode.line,
// Every kind by default: the program opts into each with its mouse
// mode, so drags (1002) and motion (1003) are reported when asked for.
PointerInputs pointerInputs = const PointerInputs.all(),
bool suspendPointerInput = false,
}) : _selectionMode = selectionMode,
_pointerInputs = pointerInputs,
_suspendPointerInputs = suspendPointerInput;
CellAnchor? _selectionBase;
CellAnchor? _selectionExtent;
SelectionMode get selectionMode => _selectionMode;
SelectionMode _selectionMode;
/// The set of pointer events which will be used as mouse input for the terminal.
PointerInputs get pointerInput => _pointerInputs;
PointerInputs _pointerInputs;
/// True if sending pointer events to the terminal is suspended.
bool get suspendedPointerInputs => _suspendPointerInputs;
bool _suspendPointerInputs;
List<TerminalHighlight> get highlights => _highlights;
final _highlights = <TerminalHighlight>[];
BufferRange? get selection {
final base = _selectionBase;
final extent = _selectionExtent;
if (base == null || extent == null) {
return null;
}
if (!base.attached || !extent.attached) {
return null;
}
return _createRange(base.offset, extent.offset);
}
/// Set selection on the terminal from [base] to [extent]. This method takes
/// the ownership of [base] and [extent] and will dispose them when the
/// selection is cleared or changed.
void setSelection(CellAnchor base, CellAnchor extent, {SelectionMode? mode}) {
_selectionBase?.dispose();
_selectionBase = base;
_selectionExtent?.dispose();
_selectionExtent = extent;
if (mode != null) {
_selectionMode = mode;
}
notifyListeners();
}
BufferRange _createRange(CellOffset begin, CellOffset end) {
switch (selectionMode) {
case SelectionMode.line:
return BufferRangeLine(begin, end);
case SelectionMode.block:
return BufferRangeBlock(begin, end);
}
}
/// Controls how the terminal behaves when the user selects a range of text.
/// The default is [SelectionMode.line]. Setting this to [SelectionMode.block]
/// enables block selection mode.
void setSelectionMode(SelectionMode newSelectionMode) {
// If the new mode is the same as the old mode,
// nothing has to be changed.
if (_selectionMode == newSelectionMode) {
return;
}
// Set the new mode.
_selectionMode = newSelectionMode;
notifyListeners();
}
/// Clears the current selection.
void clearSelection() {
_selectionBase?.dispose();
_selectionBase = null;
_selectionExtent?.dispose();
_selectionExtent = null;
notifyListeners();
}
// Select which type of pointer events are send to the terminal.
void setPointerInputs(PointerInputs pointerInput) {
_pointerInputs = pointerInput;
notifyListeners();
}
// Toggle sending pointer events to the terminal.
void setSuspendPointerInput(bool suspend) {
_suspendPointerInputs = suspend;
notifyListeners();
}
// Returns true if this type of PointerInput should be send to the Terminal.
@internal
bool shouldSendPointerInput(PointerInput pointerInput) {
// Always return false if pointer input is suspended.
return _suspendPointerInputs
? false
: _pointerInputs.inputs.contains(pointerInput);
}
/// Creates a new highlight on the terminal from [p1] to [p2] with the given
/// [color]. The highlight will be removed when the returned object is
/// disposed.
TerminalHighlight highlight({
required CellAnchor p1,
required CellAnchor p2,
required Color color,
}) {
final highlight = TerminalHighlight(
this,
p1: p1,
p2: p2,
color: color,
);
_highlights.add(highlight);
notifyListeners();
highlight.registerCallback(() {
_highlights.remove(highlight);
notifyListeners();
});
return highlight;
}
}
class TerminalHighlight with Disposable {
final TerminalController owner;
final CellAnchor p1;
final CellAnchor p2;
final Color color;
TerminalHighlight(
this.owner, {
required this.p1,
required this.p2,
required this.color,
});
/// Returns the range of the highlight. May be null if the anchors that
/// define the highlight are not attached to the terminal.
BufferRange? get range {
if (!p1.attached || !p2.attached) {
return null;
}
return BufferRangeLine(p1.offset, p2.offset);
}
}
+7
View File
@@ -0,0 +1,7 @@
enum TerminalCursorType {
block,
underline,
verticalBar,
}
+281
View File
@@ -0,0 +1,281 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class CustomTextEdit extends StatefulWidget {
CustomTextEdit({
super.key,
required this.child,
required this.onInsert,
required this.onDelete,
required this.onComposing,
required this.onAction,
required this.onKeyEvent,
required this.focusNode,
this.autofocus = false,
this.readOnly = false,
// this.initEditingState = TextEditingValue.empty,
this.inputType = TextInputType.text,
this.inputAction = TextInputAction.newline,
this.keyboardAppearance = Brightness.light,
this.deleteDetection = false,
});
final Widget child;
final void Function(String) onInsert;
final void Function() onDelete;
final void Function(String?) onComposing;
final void Function(TextInputAction) onAction;
final KeyEventResult Function(FocusNode, KeyEvent) onKeyEvent;
final FocusNode focusNode;
final bool autofocus;
final bool readOnly;
final TextInputType inputType;
final TextInputAction inputAction;
final Brightness keyboardAppearance;
final bool deleteDetection;
@override
CustomTextEditState createState() => CustomTextEditState();
}
class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
TextInputConnection? _connection;
@override
void initState() {
widget.focusNode.addListener(_onFocusChange);
super.initState();
}
@override
void didUpdateWidget(CustomTextEdit oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.focusNode != oldWidget.focusNode) {
oldWidget.focusNode.removeListener(_onFocusChange);
widget.focusNode.addListener(_onFocusChange);
}
if (!_shouldCreateInputConnection) {
_closeInputConnectionIfNeeded();
} else {
if (oldWidget.readOnly && widget.focusNode.hasFocus) {
_openInputConnection();
}
}
}
@override
void dispose() {
widget.focusNode.removeListener(_onFocusChange);
_closeInputConnectionIfNeeded();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Focus(
focusNode: widget.focusNode,
autofocus: widget.autofocus,
onKeyEvent: _onKeyEvent,
child: widget.child,
);
}
bool get hasInputConnection => _connection != null && _connection!.attached;
void requestKeyboard() {
if (widget.focusNode.hasFocus) {
_openInputConnection();
} else {
widget.focusNode.requestFocus();
}
}
void closeKeyboard() {
if (hasInputConnection) {
_connection?.close();
}
}
void setEditingState(TextEditingValue value) {
_currentEditingState = value;
_connection?.setEditingState(value);
}
void setEditableRect(Rect rect, Rect caretRect) {
if (!hasInputConnection) {
return;
}
_connection?.setEditableSizeAndTransform(
rect.size,
Matrix4.translationValues(0, 0, 0),
);
_connection?.setCaretRect(caretRect);
}
void _onFocusChange() {
_openOrCloseInputConnectionIfNeeded();
}
KeyEventResult _onKeyEvent(FocusNode focusNode, KeyEvent event) {
if (_currentEditingState.composing.isCollapsed) {
return widget.onKeyEvent(focusNode, event);
}
return KeyEventResult.skipRemainingHandlers;
}
void _openOrCloseInputConnectionIfNeeded() {
if (widget.focusNode.hasFocus && widget.focusNode.consumeKeyboardToken()) {
_openInputConnection();
} else if (!widget.focusNode.hasFocus) {
_closeInputConnectionIfNeeded();
}
}
bool get _shouldCreateInputConnection => kIsWeb || !widget.readOnly;
void _openInputConnection() {
if (!_shouldCreateInputConnection) {
return;
}
if (hasInputConnection) {
_connection!.show();
} else {
final config = TextInputConfiguration(
inputType: widget.inputType,
inputAction: widget.inputAction,
keyboardAppearance: widget.keyboardAppearance,
autocorrect: false,
enableSuggestions: false,
enableIMEPersonalizedLearning: false,
);
_connection = TextInput.attach(this, config);
_connection!.show();
// setEditableRect(Rect.zero, Rect.zero);
_connection!.setEditingState(_initEditingState);
}
}
void _closeInputConnectionIfNeeded() {
if (_connection != null && _connection!.attached) {
_connection!.close();
_connection = null;
}
}
TextEditingValue get _initEditingState => widget.deleteDetection
? const TextEditingValue(
text: ' ',
selection: TextSelection.collapsed(offset: 2),
)
: const TextEditingValue(
text: '',
selection: TextSelection.collapsed(offset: 0),
);
late var _currentEditingState = _initEditingState.copyWith();
@override
TextEditingValue? get currentTextEditingValue {
return _currentEditingState;
}
@override
AutofillScope? get currentAutofillScope {
return null;
}
@override
void updateEditingValue(TextEditingValue value) {
_currentEditingState = value;
// Get input after composing is done
if (!_currentEditingState.composing.isCollapsed) {
final text = _currentEditingState.text;
final composingText = _currentEditingState.composing.textInside(text);
widget.onComposing(composingText);
return;
}
widget.onComposing(null);
if (_currentEditingState.text.length < _initEditingState.text.length) {
widget.onDelete();
} else {
final textDelta = _currentEditingState.text.substring(
_initEditingState.text.length,
);
widget.onInsert(textDelta);
}
// Reset editing state if composing is done
if (_currentEditingState.composing.isCollapsed &&
_currentEditingState.text != _initEditingState.text) {
_connection!.setEditingState(_initEditingState);
}
}
@override
void performAction(TextInputAction action) {
// print('performAction $action');
widget.onAction(action);
}
@override
void updateFloatingCursor(RawFloatingCursorPoint point) {
// print('updateFloatingCursor $point');
}
@override
void showAutocorrectionPromptRect(int start, int end) {
// print('showAutocorrectionPromptRect');
}
@override
void connectionClosed() {
// print('connectionClosed');
}
@override
void performPrivateCommand(String action, Map<String, dynamic> data) {
// print('performPrivateCommand $action');
}
@override
void insertTextPlaceholder(Size size) {
// print('insertTextPlaceholder');
}
@override
void removeTextPlaceholder() {
// print('removeTextPlaceholder');
}
@override
void showToolbar() {
// print('showToolbar');
}
}
@@ -0,0 +1,162 @@
import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
class TerminalGestureDetector extends StatefulWidget {
const TerminalGestureDetector({
super.key,
this.child,
this.onSingleTapUp,
this.onTapUp,
this.onTapDown,
this.onSecondaryTapDown,
this.onSecondaryTapUp,
this.onTertiaryTapDown,
this.onTertiaryTapUp,
this.onLongPressStart,
this.onLongPressMoveUpdate,
this.onLongPressUp,
this.onDragStart,
this.onDragUpdate,
this.onDoubleTapDown,
});
final Widget? child;
final GestureTapUpCallback? onTapUp;
final GestureTapUpCallback? onSingleTapUp;
final GestureTapDownCallback? onTapDown;
final GestureTapDownCallback? onSecondaryTapDown;
final GestureTapUpCallback? onSecondaryTapUp;
final GestureTapDownCallback? onDoubleTapDown;
final GestureTapDownCallback? onTertiaryTapDown;
final GestureTapUpCallback? onTertiaryTapUp;
final GestureLongPressStartCallback? onLongPressStart;
final GestureLongPressMoveUpdateCallback? onLongPressMoveUpdate;
final GestureLongPressUpCallback? onLongPressUp;
final GestureDragStartCallback? onDragStart;
final GestureDragUpdateCallback? onDragUpdate;
@override
State<TerminalGestureDetector> createState() =>
_TerminalGestureDetectorState();
}
class _TerminalGestureDetectorState extends State<TerminalGestureDetector> {
Timer? _doubleTapTimer;
Offset? _lastTapOffset;
// True if a second tap down of a double tap is detected. Used to discard
// subsequent tap up / tap hold of the same tap.
bool _isDoubleTap = false;
// The down handler is force-run on success of a single tap and optimistically
// run before a long press success.
void _handleTapDown(TapDownDetails details) {
widget.onTapDown?.call(details);
if (_doubleTapTimer != null &&
_isWithinDoubleTapTolerance(details.globalPosition)) {
// If there was already a previous tap, the second down hold/tap is a
// double tap down.
widget.onDoubleTapDown?.call(details);
_doubleTapTimer!.cancel();
_doubleTapTimeout();
_isDoubleTap = true;
}
}
void _handleTapUp(TapUpDetails details) {
if (!_isDoubleTap) {
widget.onSingleTapUp?.call(details);
_lastTapOffset = details.globalPosition;
_doubleTapTimer = Timer(kDoubleTapTimeout, _doubleTapTimeout);
}
_isDoubleTap = false;
}
void _doubleTapTimeout() {
_doubleTapTimer = null;
_lastTapOffset = null;
}
bool _isWithinDoubleTapTolerance(Offset secondTapOffset) {
if (_lastTapOffset == null) {
return false;
}
final Offset difference = secondTapOffset - _lastTapOffset!;
return difference.distance <= kDoubleTapSlop;
}
@override
Widget build(BuildContext context) {
final gestures = <Type, GestureRecognizerFactory>{};
gestures[TapGestureRecognizer] =
GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
() => TapGestureRecognizer(debugOwner: this),
(TapGestureRecognizer instance) {
instance
..onTapDown = _handleTapDown
..onTapUp = _handleTapUp
..onSecondaryTapDown = widget.onSecondaryTapDown
..onSecondaryTapUp = widget.onSecondaryTapUp
..onTertiaryTapDown = widget.onTertiaryTapDown
..onTertiaryTapUp = widget.onTertiaryTapUp;
},
);
gestures[LongPressGestureRecognizer] =
GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
() => LongPressGestureRecognizer(
debugOwner: this,
supportedDevices: {
PointerDeviceKind.touch,
// PointerDeviceKind.mouse, // for debugging purposes only
},
),
(LongPressGestureRecognizer instance) {
instance
..onLongPressStart = widget.onLongPressStart
..onLongPressMoveUpdate = widget.onLongPressMoveUpdate
..onLongPressUp = widget.onLongPressUp;
},
);
gestures[PanGestureRecognizer] =
GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
() => PanGestureRecognizer(
debugOwner: this,
supportedDevices: <PointerDeviceKind>{PointerDeviceKind.mouse},
),
(PanGestureRecognizer instance) {
instance
..dragStartBehavior = DragStartBehavior.down
..onStart = widget.onDragStart
..onUpdate = widget.onDragUpdate;
},
);
return RawGestureDetector(
gestures: gestures,
excludeFromSemantics: true,
child: widget.child,
);
}
}
@@ -0,0 +1,210 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import 'package:xterm/src/core/mouse/button.dart';
import 'package:xterm/src/core/mouse/button_state.dart';
import 'package:xterm/src/terminal_view.dart';
import 'package:xterm/src/ui/controller.dart';
import 'package:xterm/src/ui/gesture/gesture_detector.dart';
import 'package:xterm/src/ui/pointer_input.dart';
import 'package:xterm/src/ui/render.dart';
class TerminalGestureHandler extends StatefulWidget {
const TerminalGestureHandler({
super.key,
required this.terminalView,
required this.terminalController,
this.child,
this.onTapUp,
this.onSingleTapUp,
this.onTapDown,
this.onSecondaryTapDown,
this.onSecondaryTapUp,
this.onTertiaryTapDown,
this.onTertiaryTapUp,
this.readOnly = false,
});
final TerminalViewState terminalView;
final TerminalController terminalController;
final Widget? child;
final GestureTapUpCallback? onTapUp;
final GestureTapUpCallback? onSingleTapUp;
final GestureTapDownCallback? onTapDown;
final GestureTapDownCallback? onSecondaryTapDown;
final GestureTapUpCallback? onSecondaryTapUp;
final GestureTapDownCallback? onTertiaryTapDown;
final GestureTapUpCallback? onTertiaryTapUp;
final bool readOnly;
@override
State<TerminalGestureHandler> createState() => _TerminalGestureHandlerState();
}
class _TerminalGestureHandlerState extends State<TerminalGestureHandler> {
TerminalViewState get terminalView => widget.terminalView;
RenderTerminal get renderTerminal => terminalView.renderTerminal;
DragStartDetails? _lastDragStartDetails;
LongPressStartDetails? _lastLongPressStartDetails;
@override
Widget build(BuildContext context) {
return TerminalGestureDetector(
child: widget.child,
onTapUp: widget.onTapUp,
onSingleTapUp: onSingleTapUp,
onTapDown: onTapDown,
onSecondaryTapDown: onSecondaryTapDown,
onSecondaryTapUp: onSecondaryTapUp,
onTertiaryTapDown: onTertiaryTapDown,
onTertiaryTapUp: onTertiaryTapUp,
onLongPressStart: onLongPressStart,
onLongPressMoveUpdate: onLongPressMoveUpdate,
// onLongPressUp: onLongPressUp,
onDragStart: onDragStart,
onDragUpdate: onDragUpdate,
onDoubleTapDown: onDoubleTapDown,
);
}
bool get _shouldSendTapEvent =>
!widget.readOnly &&
widget.terminalController.shouldSendPointerInput(PointerInput.tap);
void _tapDown(
GestureTapDownCallback? callback,
TapDownDetails details,
TerminalMouseButton button, {
bool forceCallback = false,
}) {
// Check if the terminal should and can handle the tap down event. A
// mouse press was already reported by the TerminalMouseListener.
var handled = _isReportedMouse(details.kind);
if (!_isMouse(details.kind) && _shouldSendTapEvent) {
handled = renderTerminal.mouseEvent(
button,
TerminalMouseButtonState.down,
details.localPosition,
);
}
// If the event was not handled by the terminal, use the supplied callback.
if (!handled || forceCallback) {
callback?.call(details);
}
}
void _tapUp(
GestureTapUpCallback? callback,
TapUpDetails details,
TerminalMouseButton button, {
bool forceCallback = false,
}) {
// Check if the terminal should and can handle the tap up event.
var handled = _isReportedMouse(details.kind);
if (!_isMouse(details.kind) && _shouldSendTapEvent) {
handled = renderTerminal.mouseEvent(
button,
TerminalMouseButtonState.up,
details.localPosition,
);
}
// If the event was not handled by the terminal, use the supplied callback.
if (!handled || forceCallback) {
callback?.call(details);
}
}
void onTapDown(TapDownDetails details) {
// onTapDown is special, as it will always call the supplied callback.
// The TerminalView depends on it to bring the terminal into focus.
_tapDown(
widget.onTapDown,
details,
TerminalMouseButton.left,
forceCallback: true,
);
}
void onSingleTapUp(TapUpDetails details) {
_tapUp(widget.onSingleTapUp, details, TerminalMouseButton.left);
}
void onSecondaryTapDown(TapDownDetails details) {
_tapDown(widget.onSecondaryTapDown, details, TerminalMouseButton.right);
}
void onSecondaryTapUp(TapUpDetails details) {
_tapUp(widget.onSecondaryTapUp, details, TerminalMouseButton.right);
}
void onTertiaryTapDown(TapDownDetails details) {
_tapDown(widget.onTertiaryTapDown, details, TerminalMouseButton.middle);
}
void onTertiaryTapUp(TapUpDetails details) {
_tapUp(widget.onTertiaryTapUp, details, TerminalMouseButton.middle);
}
/// Whether [kind] is a mouse, whose presses the TerminalMouseListener
/// reports instead of this handler.
static bool _isMouse(PointerDeviceKind? kind) =>
kind == PointerDeviceKind.mouse;
/// Whether the current press is a mouse press reported to the program,
/// which therefore must not select text.
bool _isReportedMouse(PointerDeviceKind? kind) =>
_isMouse(kind) && terminalView.mousePressReported;
void onDoubleTapDown(TapDownDetails details) {
if (_isReportedMouse(details.kind)) return;
renderTerminal.selectWord(details.localPosition);
}
void onLongPressStart(LongPressStartDetails details) {
_lastLongPressStartDetails = details;
renderTerminal.selectWord(details.localPosition);
}
void onLongPressMoveUpdate(LongPressMoveUpdateDetails details) {
renderTerminal.selectWord(
_lastLongPressStartDetails!.localPosition,
details.localPosition,
);
}
// void onLongPressUp() {}
void onDragStart(DragStartDetails details) {
if (_isReportedMouse(details.kind)) {
// The program follows the drag (mode 1002/1003), not the selection.
_lastDragStartDetails = null;
return;
}
_lastDragStartDetails = details;
details.kind == PointerDeviceKind.mouse
? renderTerminal.selectCharacters(details.localPosition)
: renderTerminal.selectWord(details.localPosition);
}
void onDragUpdate(DragUpdateDetails details) {
final start = _lastDragStartDetails;
if (start == null) return;
renderTerminal.selectCharacters(
start.localPosition,
details.localPosition,
);
}
}
@@ -0,0 +1,115 @@
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
/// The function called when the user scrolls the [InfiniteScrollView]. [offset]
/// is the current offset of the scroll view, ranging from [double.negativeInfinity]
/// to [double.infinity].
typedef ScrollCallback = void Function(double offset);
/// A [Scrollable] that can be scrolled infinitely in both directions. When
/// scroll happens, the [onScroll] callback is called with the new offset.
class InfiniteScrollView extends StatelessWidget {
const InfiniteScrollView({
super.key,
required this.onScroll,
required this.child,
});
final ScrollCallback onScroll;
final Widget child;
@override
Widget build(BuildContext context) {
return Scrollable(
viewportBuilder: (context, position) {
return _InfiniteScrollView(
position: position,
onScroll: onScroll,
child: child,
);
},
);
}
}
class _InfiniteScrollView extends SingleChildRenderObjectWidget {
const _InfiniteScrollView({
// super.key,
super.child,
required this.position,
required this.onScroll,
});
final ViewportOffset position;
final ScrollCallback onScroll;
@override
RenderObject createRenderObject(BuildContext context) {
return _RenderInfiniteScrollView(
position: position,
onScroll: onScroll,
);
}
@override
void updateRenderObject(
BuildContext context,
_RenderInfiniteScrollView renderObject,
) {
renderObject
..position = position
..onScroll = onScroll;
}
}
class _RenderInfiniteScrollView extends RenderShiftedBox {
_RenderInfiniteScrollView({
RenderBox? child,
required ViewportOffset position,
required ScrollCallback onScroll,
}) : _position = position,
_scrollCallback = onScroll,
super(child);
ViewportOffset _position;
set position(ViewportOffset value) {
if (_position == value) return;
if (attached) _position.removeListener(markNeedsLayout);
_position = value;
if (attached) _position.addListener(markNeedsLayout);
markNeedsLayout();
}
ScrollCallback _scrollCallback;
set onScroll(ScrollCallback value) {
if (_scrollCallback == value) return;
_scrollCallback = value;
markNeedsLayout();
}
void _onScroll() {
_scrollCallback(_position.pixels);
}
@override
void attach(covariant PipelineOwner owner) {
super.attach(owner);
_position.addListener(_onScroll);
}
@override
void detach() {
super.detach();
_position.removeListener(_onScroll);
}
@override
void performLayout() {
child?.layout(constraints, parentUsesSize: true);
size = child?.size ?? Size.zero;
_position.applyViewportDimension(size.height);
_position.applyContentDimensions(double.negativeInfinity, double.infinity);
}
}
+288
View File
@@ -0,0 +1,288 @@
import 'package:flutter/services.dart';
import 'package:xterm/src/core/input/keys.dart';
final _keyToTerminalKey = {
LogicalKeyboardKey.hyper: TerminalKey.hyper,
LogicalKeyboardKey.superKey: TerminalKey.superKey,
LogicalKeyboardKey.fnLock: TerminalKey.fnLock,
LogicalKeyboardKey.suspend: TerminalKey.suspend,
LogicalKeyboardKey.resume: TerminalKey.resume,
LogicalKeyboardKey.sleep: TerminalKey.sleep,
LogicalKeyboardKey.wakeUp: TerminalKey.wakeUp,
LogicalKeyboardKey.keyA: TerminalKey.keyA,
LogicalKeyboardKey.keyB: TerminalKey.keyB,
LogicalKeyboardKey.keyC: TerminalKey.keyC,
LogicalKeyboardKey.keyD: TerminalKey.keyD,
LogicalKeyboardKey.keyE: TerminalKey.keyE,
LogicalKeyboardKey.keyF: TerminalKey.keyF,
LogicalKeyboardKey.keyG: TerminalKey.keyG,
LogicalKeyboardKey.keyH: TerminalKey.keyH,
LogicalKeyboardKey.keyI: TerminalKey.keyI,
LogicalKeyboardKey.keyJ: TerminalKey.keyJ,
LogicalKeyboardKey.keyK: TerminalKey.keyK,
LogicalKeyboardKey.keyL: TerminalKey.keyL,
LogicalKeyboardKey.keyM: TerminalKey.keyM,
LogicalKeyboardKey.keyN: TerminalKey.keyN,
LogicalKeyboardKey.keyO: TerminalKey.keyO,
LogicalKeyboardKey.keyP: TerminalKey.keyP,
LogicalKeyboardKey.keyQ: TerminalKey.keyQ,
LogicalKeyboardKey.keyR: TerminalKey.keyR,
LogicalKeyboardKey.keyS: TerminalKey.keyS,
LogicalKeyboardKey.keyT: TerminalKey.keyT,
LogicalKeyboardKey.keyU: TerminalKey.keyU,
LogicalKeyboardKey.keyV: TerminalKey.keyV,
LogicalKeyboardKey.keyW: TerminalKey.keyW,
LogicalKeyboardKey.keyX: TerminalKey.keyX,
LogicalKeyboardKey.keyY: TerminalKey.keyY,
LogicalKeyboardKey.keyZ: TerminalKey.keyZ,
LogicalKeyboardKey.digit1: TerminalKey.digit1,
LogicalKeyboardKey.digit2: TerminalKey.digit2,
LogicalKeyboardKey.digit3: TerminalKey.digit3,
LogicalKeyboardKey.digit4: TerminalKey.digit4,
LogicalKeyboardKey.digit5: TerminalKey.digit5,
LogicalKeyboardKey.digit6: TerminalKey.digit6,
LogicalKeyboardKey.digit7: TerminalKey.digit7,
LogicalKeyboardKey.digit8: TerminalKey.digit8,
LogicalKeyboardKey.digit9: TerminalKey.digit9,
LogicalKeyboardKey.digit0: TerminalKey.digit0,
LogicalKeyboardKey.enter: TerminalKey.enter,
LogicalKeyboardKey.escape: TerminalKey.escape,
LogicalKeyboardKey.backspace: TerminalKey.backspace,
LogicalKeyboardKey.tab: TerminalKey.tab,
LogicalKeyboardKey.space: TerminalKey.space,
LogicalKeyboardKey.minus: TerminalKey.minus,
LogicalKeyboardKey.equal: TerminalKey.equal,
LogicalKeyboardKey.bracketLeft: TerminalKey.bracketLeft,
LogicalKeyboardKey.bracketRight: TerminalKey.bracketRight,
LogicalKeyboardKey.backslash: TerminalKey.backslash,
LogicalKeyboardKey.semicolon: TerminalKey.semicolon,
LogicalKeyboardKey.quote: TerminalKey.quote,
LogicalKeyboardKey.backquote: TerminalKey.backquote,
LogicalKeyboardKey.comma: TerminalKey.comma,
LogicalKeyboardKey.period: TerminalKey.period,
LogicalKeyboardKey.slash: TerminalKey.slash,
LogicalKeyboardKey.capsLock: TerminalKey.capsLock,
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.printScreen: TerminalKey.printScreen,
LogicalKeyboardKey.scrollLock: TerminalKey.scrollLock,
LogicalKeyboardKey.pause: TerminalKey.pause,
LogicalKeyboardKey.insert: TerminalKey.insert,
LogicalKeyboardKey.home: TerminalKey.home,
LogicalKeyboardKey.pageUp: TerminalKey.pageUp,
LogicalKeyboardKey.delete: TerminalKey.delete,
LogicalKeyboardKey.end: TerminalKey.end,
LogicalKeyboardKey.pageDown: TerminalKey.pageDown,
LogicalKeyboardKey.arrowRight: TerminalKey.arrowRight,
LogicalKeyboardKey.arrowLeft: TerminalKey.arrowLeft,
LogicalKeyboardKey.arrowDown: TerminalKey.arrowDown,
LogicalKeyboardKey.arrowUp: TerminalKey.arrowUp,
LogicalKeyboardKey.numLock: TerminalKey.numLock,
LogicalKeyboardKey.numpadDivide: TerminalKey.numpadDivide,
LogicalKeyboardKey.numpadMultiply: TerminalKey.numpadMultiply,
LogicalKeyboardKey.numpadSubtract: TerminalKey.numpadSubtract,
LogicalKeyboardKey.numpadAdd: TerminalKey.numpadAdd,
LogicalKeyboardKey.numpadEnter: TerminalKey.numpadEnter,
LogicalKeyboardKey.numpad1: TerminalKey.numpad1,
LogicalKeyboardKey.numpad2: TerminalKey.numpad2,
LogicalKeyboardKey.numpad3: TerminalKey.numpad3,
LogicalKeyboardKey.numpad4: TerminalKey.numpad4,
LogicalKeyboardKey.numpad5: TerminalKey.numpad5,
LogicalKeyboardKey.numpad6: TerminalKey.numpad6,
LogicalKeyboardKey.numpad7: TerminalKey.numpad7,
LogicalKeyboardKey.numpad8: TerminalKey.numpad8,
LogicalKeyboardKey.numpad9: TerminalKey.numpad9,
LogicalKeyboardKey.numpad0: TerminalKey.numpad0,
LogicalKeyboardKey.numpadDecimal: TerminalKey.numpadDecimal,
LogicalKeyboardKey.intlBackslash: TerminalKey.intlBackslash,
LogicalKeyboardKey.contextMenu: TerminalKey.contextMenu,
LogicalKeyboardKey.power: TerminalKey.power,
LogicalKeyboardKey.numpadEqual: TerminalKey.numpadEqual,
LogicalKeyboardKey.f13: TerminalKey.f13,
LogicalKeyboardKey.f14: TerminalKey.f14,
LogicalKeyboardKey.f15: TerminalKey.f15,
LogicalKeyboardKey.f16: TerminalKey.f16,
LogicalKeyboardKey.f17: TerminalKey.f17,
LogicalKeyboardKey.f18: TerminalKey.f18,
LogicalKeyboardKey.f19: TerminalKey.f19,
LogicalKeyboardKey.f20: TerminalKey.f20,
LogicalKeyboardKey.f21: TerminalKey.f21,
LogicalKeyboardKey.f22: TerminalKey.f22,
LogicalKeyboardKey.f23: TerminalKey.f23,
LogicalKeyboardKey.f24: TerminalKey.f24,
LogicalKeyboardKey.open: TerminalKey.open,
LogicalKeyboardKey.help: TerminalKey.help,
LogicalKeyboardKey.select: TerminalKey.select,
LogicalKeyboardKey.again: TerminalKey.again,
LogicalKeyboardKey.undo: TerminalKey.undo,
LogicalKeyboardKey.cut: TerminalKey.cut,
LogicalKeyboardKey.copy: TerminalKey.copy,
LogicalKeyboardKey.paste: TerminalKey.paste,
LogicalKeyboardKey.find: TerminalKey.find,
LogicalKeyboardKey.audioVolumeMute: TerminalKey.audioVolumeMute,
LogicalKeyboardKey.audioVolumeUp: TerminalKey.audioVolumeUp,
LogicalKeyboardKey.audioVolumeDown: TerminalKey.audioVolumeDown,
LogicalKeyboardKey.numpadComma: TerminalKey.numpadComma,
LogicalKeyboardKey.intlRo: TerminalKey.intlRo,
LogicalKeyboardKey.kanaMode: TerminalKey.kanaMode,
LogicalKeyboardKey.intlYen: TerminalKey.intlYen,
LogicalKeyboardKey.convert: TerminalKey.convert,
LogicalKeyboardKey.nonConvert: TerminalKey.nonConvert,
LogicalKeyboardKey.lang1: TerminalKey.lang1,
LogicalKeyboardKey.lang2: TerminalKey.lang2,
LogicalKeyboardKey.lang3: TerminalKey.lang3,
LogicalKeyboardKey.lang4: TerminalKey.lang4,
LogicalKeyboardKey.lang5: TerminalKey.lang5,
LogicalKeyboardKey.abort: TerminalKey.abort,
LogicalKeyboardKey.props: TerminalKey.props,
LogicalKeyboardKey.numpadParenLeft: TerminalKey.numpadParenLeft,
LogicalKeyboardKey.numpadParenRight: TerminalKey.numpadParenRight,
LogicalKeyboardKey.controlLeft: TerminalKey.controlLeft,
LogicalKeyboardKey.shiftLeft: TerminalKey.shiftLeft,
LogicalKeyboardKey.altLeft: TerminalKey.altLeft,
LogicalKeyboardKey.metaLeft: TerminalKey.metaLeft,
LogicalKeyboardKey.controlRight: TerminalKey.controlRight,
LogicalKeyboardKey.shiftRight: TerminalKey.shiftRight,
LogicalKeyboardKey.altRight: TerminalKey.altRight,
LogicalKeyboardKey.metaRight: TerminalKey.metaRight,
LogicalKeyboardKey.info: TerminalKey.info,
LogicalKeyboardKey.closedCaptionToggle: TerminalKey.closedCaptionToggle,
LogicalKeyboardKey.brightnessUp: TerminalKey.brightnessUp,
LogicalKeyboardKey.brightnessDown: TerminalKey.brightnessDown,
LogicalKeyboardKey.mediaLast: TerminalKey.mediaLast,
LogicalKeyboardKey.launchPhone: TerminalKey.launchPhone,
LogicalKeyboardKey.exit: TerminalKey.exit,
LogicalKeyboardKey.channelUp: TerminalKey.channelUp,
LogicalKeyboardKey.channelDown: TerminalKey.channelDown,
LogicalKeyboardKey.mediaPlay: TerminalKey.mediaPlay,
LogicalKeyboardKey.mediaPause: TerminalKey.mediaPause,
LogicalKeyboardKey.mediaRecord: TerminalKey.mediaRecord,
LogicalKeyboardKey.mediaFastForward: TerminalKey.mediaFastForward,
LogicalKeyboardKey.mediaRewind: TerminalKey.mediaRewind,
LogicalKeyboardKey.mediaTrackNext: TerminalKey.mediaTrackNext,
LogicalKeyboardKey.mediaTrackPrevious: TerminalKey.mediaTrackPrevious,
LogicalKeyboardKey.mediaStop: TerminalKey.mediaStop,
LogicalKeyboardKey.eject: TerminalKey.eject,
LogicalKeyboardKey.mediaPlayPause: TerminalKey.mediaPlayPause,
LogicalKeyboardKey.speechInputToggle: TerminalKey.speechInputToggle,
LogicalKeyboardKey.launchWordProcessor: TerminalKey.launchWordProcessor,
LogicalKeyboardKey.launchSpreadsheet: TerminalKey.launchSpreadsheet,
LogicalKeyboardKey.launchMail: TerminalKey.launchMail,
LogicalKeyboardKey.launchContacts: TerminalKey.launchContacts,
LogicalKeyboardKey.launchCalendar: TerminalKey.launchCalendar,
LogicalKeyboardKey.logOff: TerminalKey.logOff,
LogicalKeyboardKey.launchControlPanel: TerminalKey.launchControlPanel,
LogicalKeyboardKey.spellCheck: TerminalKey.spellCheck,
LogicalKeyboardKey.launchScreenSaver: TerminalKey.launchScreenSaver,
LogicalKeyboardKey.launchAssistant: TerminalKey.launchAssistant,
LogicalKeyboardKey.newKey: TerminalKey.newKey,
LogicalKeyboardKey.close: TerminalKey.close,
LogicalKeyboardKey.save: TerminalKey.save,
LogicalKeyboardKey.print: TerminalKey.print,
LogicalKeyboardKey.browserSearch: TerminalKey.browserSearch,
LogicalKeyboardKey.browserHome: TerminalKey.browserHome,
LogicalKeyboardKey.browserBack: TerminalKey.browserBack,
LogicalKeyboardKey.browserForward: TerminalKey.browserForward,
LogicalKeyboardKey.browserStop: TerminalKey.browserStop,
LogicalKeyboardKey.browserRefresh: TerminalKey.browserRefresh,
LogicalKeyboardKey.browserFavorites: TerminalKey.browserFavorites,
LogicalKeyboardKey.zoomIn: TerminalKey.zoomIn,
LogicalKeyboardKey.zoomOut: TerminalKey.zoomOut,
LogicalKeyboardKey.zoomToggle: TerminalKey.zoomToggle,
LogicalKeyboardKey.redo: TerminalKey.redo,
LogicalKeyboardKey.mailReply: TerminalKey.mailReply,
LogicalKeyboardKey.mailForward: TerminalKey.mailForward,
LogicalKeyboardKey.mailSend: TerminalKey.mailSend,
LogicalKeyboardKey.gameButton1: TerminalKey.gameButton1,
LogicalKeyboardKey.gameButton2: TerminalKey.gameButton2,
LogicalKeyboardKey.gameButton3: TerminalKey.gameButton3,
LogicalKeyboardKey.gameButton4: TerminalKey.gameButton4,
LogicalKeyboardKey.gameButton5: TerminalKey.gameButton5,
LogicalKeyboardKey.gameButton6: TerminalKey.gameButton6,
LogicalKeyboardKey.gameButton7: TerminalKey.gameButton7,
LogicalKeyboardKey.gameButton8: TerminalKey.gameButton8,
LogicalKeyboardKey.gameButton9: TerminalKey.gameButton9,
LogicalKeyboardKey.gameButton10: TerminalKey.gameButton10,
LogicalKeyboardKey.gameButton11: TerminalKey.gameButton11,
LogicalKeyboardKey.gameButton12: TerminalKey.gameButton12,
LogicalKeyboardKey.gameButton13: TerminalKey.gameButton13,
LogicalKeyboardKey.gameButton14: TerminalKey.gameButton14,
LogicalKeyboardKey.gameButton15: TerminalKey.gameButton15,
LogicalKeyboardKey.gameButton16: TerminalKey.gameButton16,
LogicalKeyboardKey.gameButtonA: TerminalKey.gameButtonA,
LogicalKeyboardKey.gameButtonB: TerminalKey.gameButtonB,
LogicalKeyboardKey.gameButtonC: TerminalKey.gameButtonC,
LogicalKeyboardKey.gameButtonLeft1: TerminalKey.gameButtonLeft1,
LogicalKeyboardKey.gameButtonLeft2: TerminalKey.gameButtonLeft2,
LogicalKeyboardKey.gameButtonMode: TerminalKey.gameButtonMode,
LogicalKeyboardKey.gameButtonRight1: TerminalKey.gameButtonRight1,
LogicalKeyboardKey.gameButtonRight2: TerminalKey.gameButtonRight2,
LogicalKeyboardKey.gameButtonSelect: TerminalKey.gameButtonSelect,
LogicalKeyboardKey.gameButtonStart: TerminalKey.gameButtonStart,
LogicalKeyboardKey.gameButtonThumbLeft: TerminalKey.gameButtonThumbLeft,
LogicalKeyboardKey.gameButtonThumbRight: TerminalKey.gameButtonThumbRight,
LogicalKeyboardKey.gameButtonX: TerminalKey.gameButtonX,
LogicalKeyboardKey.gameButtonY: TerminalKey.gameButtonY,
LogicalKeyboardKey.gameButtonZ: TerminalKey.gameButtonZ,
LogicalKeyboardKey.fn: TerminalKey.fn,
LogicalKeyboardKey.shift: TerminalKey.shift,
LogicalKeyboardKey.meta: TerminalKey.meta,
LogicalKeyboardKey.alt: TerminalKey.alt,
LogicalKeyboardKey.control: TerminalKey.control,
};
final _keyById = () {
final map = <int, TerminalKey>{};
for (final entry in _keyToTerminalKey.entries) {
map[entry.key.keyId] = entry.value;
}
return map;
}();
final _keyByChar = () {
final map = <String, TerminalKey>{};
for (final entry in _keyToTerminalKey.entries) {
final label = entry.key.keyLabel;
if (label.isEmpty || label.length > 1) {
continue;
}
map[label] = entry.value;
map[label.toUpperCase()] = entry.value;
map[label.toLowerCase()] = entry.value;
}
return map;
}();
/// Converts a [LogicalKeyboardKey] to a [TerminalKey]. Returns `null` if the
/// key does not have a corresponding [TerminalKey].
///
/// For example, `LogicalKeyboardKey.keyA` will be converted to
/// `TerminalKey.keyA`.
TerminalKey? keyToTerminalKey(LogicalKeyboardKey key) {
return _keyById[key.keyId];
}
/// Converts a character to a [TerminalKey]. Returns `null` if the character
/// does not have a corresponding [TerminalKey].
///
/// For example, `charToTerminalKey('a')` or `charToTerminalKey('A')` will both
/// return [TerminalKey.a].
TerminalKey? charToTerminalKey(String char) {
if (char.length != 1) {
return null;
}
return _keyByChar[char];
}
+49
View File
@@ -0,0 +1,49 @@
import 'package:flutter/widgets.dart';
class CustomKeyboardListener extends StatelessWidget {
final Widget child;
final FocusNode focusNode;
final bool autofocus;
final void Function(String) onInsert;
final void Function(String?) onComposing;
final KeyEventResult Function(FocusNode, KeyEvent) onKeyEvent;
const CustomKeyboardListener({
super.key,
required this.child,
required this.focusNode,
this.autofocus = false,
required this.onInsert,
required this.onComposing,
required this.onKeyEvent,
});
KeyEventResult _onKeyEvent(FocusNode focusNode, KeyEvent keyEvent) {
// First try to handle the key event directly.
final handled = onKeyEvent(focusNode, keyEvent);
if (handled == KeyEventResult.ignored) {
// If it was not handled, but the key corresponds to a character,
// insert the character.
if (keyEvent.character != null && keyEvent.character != "") {
onInsert(keyEvent.character!);
return KeyEventResult.handled;
}
}
return handled;
}
@override
Widget build(BuildContext context) {
return Focus(
focusNode: focusNode,
autofocus: autofocus,
onKeyEvent: _onKeyEvent,
child: child,
);
}
}

Some files were not shown because too many files have changed in this diff Show More