Vendor pristine xterm.dart 4.0.0 under app/third_party/xterm

Unmodified copy of lib/, LICENSE (MIT), pubspec.yaml and CHANGELOG.md from
pub.dev xterm 4.0.0; the upstream README is kept as UPSTREAM_README.md.
Committed on its own so later patches are reviewable as diffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 23:17:41 +00:00
parent 5ab1ec9e00
commit a6e04895ba
81 changed files with 13689 additions and 0 deletions
+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,
);
}
+174
View File
@@ -0,0 +1,174 @@
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,
PointerInputs pointerInputs = const PointerInputs({PointerInput.tap}),
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,191 @@
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: onSecondaryTapDown,
onTertiaryTapUp: onSecondaryTapUp,
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.
var handled = false;
if (_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 = false;
if (_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.right);
}
void onDoubleTapDown(TapDownDetails details) {
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) {
_lastDragStartDetails = details;
details.kind == PointerDeviceKind.mouse
? renderTerminal.selectCharacters(details.localPosition)
: renderTerminal.selectWord(details.localPosition);
}
void onDragUpdate(DragUpdateDetails details) {
renderTerminal.selectCharacters(
_lastDragStartDetails!.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,
);
}
}
@@ -0,0 +1,58 @@
import 'package:flutter/widgets.dart';
class KeyboardVisibilty extends StatefulWidget {
const KeyboardVisibilty({
super.key,
required this.child,
this.onKeyboardShow,
this.onKeyboardHide,
});
final Widget child;
final VoidCallback? onKeyboardShow;
final VoidCallback? onKeyboardHide;
@override
KeyboardVisibiltyState createState() => KeyboardVisibiltyState();
}
class KeyboardVisibiltyState extends State<KeyboardVisibilty>
with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeMetrics() {
final bottomInset = View.of(context).viewInsets.bottom;
if (bottomInset != _lastBottomInset) {
if (bottomInset > 0) {
widget.onKeyboardShow?.call();
} else {
widget.onKeyboardHide?.call();
}
}
_lastBottomInset = bottomInset;
super.didChangeMetrics();
}
var _lastBottomInset = 0.0;
@override
Widget build(BuildContext context) {
return widget.child;
}
}
+279
View File
@@ -0,0 +1,279 @@
import 'dart:ui';
import 'package:flutter/painting.dart';
import 'package:xterm/src/ui/palette_builder.dart';
import 'package:xterm/src/ui/paragraph_cache.dart';
import 'package:xterm/xterm.dart';
/// Encapsulates the logic for painting various terminal elements.
class TerminalPainter {
TerminalPainter({
required TerminalTheme theme,
required TerminalStyle textStyle,
required TextScaler textScaler,
}) : _textStyle = textStyle,
_theme = theme,
_textScaler = textScaler;
/// A lookup table from terminal colors to Flutter colors.
late var _colorPalette = PaletteBuilder(_theme).build();
/// Size of each character in the terminal.
late var _cellSize = _measureCharSize();
/// The cached for cells in the terminal. Should be cleared when the same
/// cell no longer produces the same visual output. For example, when
/// [_textStyle] is changed, or when the system font changes.
final _paragraphCache = ParagraphCache(10240);
TerminalStyle get textStyle => _textStyle;
TerminalStyle _textStyle;
set textStyle(TerminalStyle value) {
if (value == _textStyle) return;
_textStyle = value;
_cellSize = _measureCharSize();
_paragraphCache.clear();
}
TextScaler get textScaler => _textScaler;
TextScaler _textScaler = TextScaler.linear(1.0);
set textScaler(TextScaler value) {
if (value == _textScaler) return;
_textScaler = value;
_cellSize = _measureCharSize();
_paragraphCache.clear();
}
TerminalTheme get theme => _theme;
TerminalTheme _theme;
set theme(TerminalTheme value) {
if (value == _theme) return;
_theme = value;
_colorPalette = PaletteBuilder(value).build();
_paragraphCache.clear();
}
Size _measureCharSize() {
const test = 'mmmmmmmmmm';
final textStyle = _textStyle.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));
final result = Size(
paragraph.maxIntrinsicWidth / test.length,
paragraph.height,
);
paragraph.dispose();
return result;
}
/// The size of each character in the terminal.
Size get cellSize => _cellSize;
/// When the set of font available to the system changes, call this method to
/// clear cached state related to font rendering.
void clearFontCache() {
_cellSize = _measureCharSize();
_paragraphCache.clear();
}
/// Paints the cursor based on the current cursor type.
void paintCursor(
Canvas canvas,
Offset offset, {
required TerminalCursorType cursorType,
bool hasFocus = true,
}) {
final paint = Paint()
..color = _theme.cursor
..strokeWidth = 1;
if (!hasFocus) {
paint.style = PaintingStyle.stroke;
canvas.drawRect(offset & _cellSize, paint);
return;
}
switch (cursorType) {
case TerminalCursorType.block:
paint.style = PaintingStyle.fill;
canvas.drawRect(offset & _cellSize, paint);
return;
case TerminalCursorType.underline:
return canvas.drawLine(
Offset(offset.dx, _cellSize.height - 1),
Offset(offset.dx + _cellSize.width, _cellSize.height - 1),
paint,
);
case TerminalCursorType.verticalBar:
return canvas.drawLine(
Offset(offset.dx, 0),
Offset(offset.dx, _cellSize.height),
paint,
);
}
}
@pragma('vm:prefer-inline')
void paintHighlight(Canvas canvas, Offset offset, int length, Color color) {
final endOffset =
offset.translate(length * _cellSize.width, _cellSize.height);
final paint = Paint()
..color = color
..strokeWidth = 1;
canvas.drawRect(
Rect.fromPoints(offset, endOffset),
paint,
);
}
/// Paints [line] to [canvas] at [offset]. The x offset of [offset] is usually
/// 0, and the y offset is the top of the line.
void paintLine(
Canvas canvas,
Offset offset,
BufferLine line,
) {
final cellData = CellData.empty();
final cellWidth = _cellSize.width;
for (var i = 0; i < line.length; i++) {
line.getCellData(i, cellData);
final charWidth = cellData.content >> CellContent.widthShift;
final cellOffset = offset.translate(i * cellWidth, 0);
paintCell(canvas, cellOffset, cellData);
if (charWidth == 2) {
i++;
}
}
}
@pragma('vm:prefer-inline')
void paintCell(Canvas canvas, Offset offset, CellData cellData) {
paintCellBackground(canvas, offset, cellData);
paintCellForeground(canvas, offset, cellData);
}
/// Paints the character in the cell represented by [cellData] to [canvas] at
/// [offset].
@pragma('vm:prefer-inline')
void paintCellForeground(Canvas canvas, Offset offset, CellData cellData) {
final charCode = cellData.content & CellContent.codepointMask;
if (charCode == 0) return;
final cacheKey = cellData.getHash() ^ _textScaler.hashCode;
var paragraph = _paragraphCache.getLayoutFromCache(cacheKey);
if (paragraph == null) {
final cellFlags = cellData.flags;
var color = cellFlags & CellFlags.inverse == 0
? resolveForegroundColor(cellData.foreground)
: resolveBackgroundColor(cellData.background);
if (cellData.flags & CellFlags.faint != 0) {
color = color.withOpacity(0.5);
}
final style = _textStyle.toTextStyle(
color: color,
bold: cellFlags & CellFlags.bold != 0,
italic: cellFlags & CellFlags.italic != 0,
underline: cellFlags & CellFlags.underline != 0,
);
// Flutter does not draw an underline below a space which is not between
// other regular characters. As only single characters are drawn, this
// will never produce an underline below a space in the terminal. As a
// workaround the regular space CodePoint 0x20 is replaced with
// the CodePoint 0xA0. This is a non breaking space and a underline can be
// drawn below it.
var char = String.fromCharCode(charCode);
if (cellFlags & CellFlags.underline != 0 && charCode == 0x20) {
char = String.fromCharCode(0xA0);
}
paragraph = _paragraphCache.performAndCacheLayout(
char,
style,
_textScaler,
cacheKey,
);
}
canvas.drawParagraph(paragraph, offset);
}
/// Paints the background of a cell represented by [cellData] to [canvas] at
/// [offset].
@pragma('vm:prefer-inline')
void paintCellBackground(Canvas canvas, Offset offset, CellData cellData) {
late Color color;
final colorType = cellData.background & CellColor.typeMask;
if (cellData.flags & CellFlags.inverse != 0) {
color = resolveForegroundColor(cellData.foreground);
} else if (colorType == CellColor.normal) {
return;
} else {
color = resolveBackgroundColor(cellData.background);
}
final paint = Paint()..color = color;
final doubleWidth = cellData.content >> CellContent.widthShift == 2;
final widthScale = doubleWidth ? 2 : 1;
final size = Size(_cellSize.width * widthScale + 1, _cellSize.height);
canvas.drawRect(offset & size, paint);
}
/// Get the effective foreground color for a cell from information encoded in
/// [cellColor].
@pragma('vm:prefer-inline')
Color resolveForegroundColor(int cellColor) {
final colorType = cellColor & CellColor.typeMask;
final colorValue = cellColor & CellColor.valueMask;
switch (colorType) {
case CellColor.normal:
return _theme.foreground;
case CellColor.named:
case CellColor.palette:
return _colorPalette[colorValue];
case CellColor.rgb:
default:
return Color(colorValue | 0xFF000000);
}
}
/// Get the effective background color for a cell from information encoded in
/// [cellColor].
@pragma('vm:prefer-inline')
Color resolveBackgroundColor(int cellColor) {
final colorType = cellColor & CellColor.typeMask;
final colorValue = cellColor & CellColor.valueMask;
switch (colorType) {
case CellColor.normal:
return _theme.background;
case CellColor.named:
case CellColor.palette:
return _colorPalette[colorValue];
case CellColor.rgb:
default:
return Color(colorValue | 0xFF000000);
}
}
}
+118
View File
@@ -0,0 +1,118 @@
import 'package:flutter/widgets.dart';
import 'package:xterm/src/ui/terminal_theme.dart';
import 'package:xterm/src/utils/lookup_table.dart';
class PaletteBuilder {
final TerminalTheme theme;
PaletteBuilder(this.theme);
List<Color> build() {
return List<Color>.generate(
256,
paletteColor,
growable: false,
);
}
/// https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit
Color paletteColor(int colNum) {
switch (colNum) {
case 0:
return theme.black;
case 1:
return theme.red;
case 2:
return theme.green;
case 3:
return theme.yellow;
case 4:
return theme.blue;
case 5:
return theme.magenta;
case 6:
return theme.cyan;
case 7:
return theme.white;
case 8:
return theme.brightBlack;
case 9:
return theme.brightRed;
case 10:
return theme.brightGreen;
case 11:
return theme.brightYellow;
case 12:
return theme.brightBlue;
case 13:
return theme.brightMagenta;
case 14:
return theme.brightCyan;
case 15:
return theme.white;
}
if (colNum < 232) {
var r = 0;
var g = 0;
var b = 0;
final index = colNum - 16;
for (var i = 0; i < index; i++) {
if (b == 0) {
b = 95;
} else if (b < 255) {
b += 40;
} else {
b = 0;
if (g == 0) {
g = 95;
} else if (g < 255) {
g += 40;
} else {
g = 0;
if (r == 0) {
r = 95;
} else if (r < 255) {
r += 40;
} else {
break;
}
}
}
}
return Color.fromARGB(0xFF, r, g, b);
}
return Color(_grayscaleColors[colNum.clamp(232, 255)]!);
}
}
final _grayscaleColors = FastLookupTable({
232: 0xff080808,
233: 0xff121212,
234: 0xff1c1c1c,
235: 0xff262626,
236: 0xff303030,
237: 0xff3a3a3a,
238: 0xff444444,
239: 0xff4e4e4e,
240: 0xff585858,
241: 0xff626262,
242: 0xff6c6c6c,
243: 0xff767676,
244: 0xff808080,
245: 0xff8a8a8a,
246: 0xff949494,
247: 0xff9e9e9e,
248: 0xffa8a8a8,
249: 0xffb2b2b2,
250: 0xffbcbcbc,
251: 0xffc6c6c6,
252: 0xffd0d0d0,
253: 0xffdadada,
254: 0xffe4e4e4,
255: 0xffeeeeee,
});
+51
View File
@@ -0,0 +1,51 @@
import 'dart:ui';
import 'package:flutter/widgets.dart';
import 'package:quiver/collection.dart';
/// A cache of laid out [Paragraph]s. This is used to avoid laying out the same
/// text multiple times, which is expensive.
class ParagraphCache {
ParagraphCache(int maximumSize)
: _cache = LruMap<int, Paragraph>(maximumSize: maximumSize);
final LruMap<int, Paragraph> _cache;
/// Returns a [Paragraph] for the given [key]. [key] is the same as the
/// key argument to [performAndCacheLayout].
Paragraph? getLayoutFromCache(int key) {
return _cache[key];
}
/// Applies [style] and [textScaler] to [text] and lays it out to create
/// a [Paragraph]. The [Paragraph] is cached and can be retrieved with the
/// same [key] by calling [getLayoutFromCache].
Paragraph performAndCacheLayout(
String text,
TextStyle style,
TextScaler textScaler,
int key,
) {
final builder = ParagraphBuilder(style.getParagraphStyle());
builder.pushStyle(style.getTextStyle(textScaler: textScaler));
builder.addText(text);
final paragraph = builder.build();
paragraph.layout(ParagraphConstraints(width: double.infinity));
_cache[key] = paragraph;
return paragraph;
}
/// Clears the cache. This should be called when the same text and style
/// pair no longer produces the same layout. For example, when a font is
/// loaded.
void clear() {
_cache.clear();
}
/// Returns the number of [Paragraph]s in the cache.
int get length {
return _cache.length;
}
}
+29
View File
@@ -0,0 +1,29 @@
enum PointerInput {
/// Taps / buttons presses & releases.
tap,
/// Scroll / mouse wheels events.
scroll,
/// Drag events, a pointer is in a down state and dragged across the terminal.
drag,
/// Move events, a pointer is in an up state and moved across the terminal.
move,
}
class PointerInputs {
final Set<PointerInput> inputs;
const PointerInputs(this.inputs);
const PointerInputs.none() : inputs = const <PointerInput>{};
const PointerInputs.all()
: inputs = const <PointerInput>{
PointerInput.tap,
PointerInput.scroll,
PointerInput.drag,
PointerInput.move,
};
}
+552
View File
@@ -0,0 +1,552 @@
import 'dart:math' show max;
import 'dart:ui';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
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';
import 'package:xterm/src/core/mouse/button.dart';
import 'package:xterm/src/core/mouse/button_state.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/painter.dart';
import 'package:xterm/src/ui/selection_mode.dart';
import 'package:xterm/src/ui/terminal_size.dart';
import 'package:xterm/src/ui/terminal_text_style.dart';
import 'package:xterm/src/ui/terminal_theme.dart';
typedef EditableRectCallback = void Function(Rect rect, Rect caretRect);
class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
RenderTerminal({
required Terminal terminal,
required TerminalController controller,
required ViewportOffset offset,
required EdgeInsets padding,
required bool autoResize,
required TerminalStyle textStyle,
required TextScaler textScaler,
required TerminalTheme theme,
required FocusNode focusNode,
required TerminalCursorType cursorType,
required bool alwaysShowCursor,
EditableRectCallback? onEditableRect,
String? composingText,
}) : _terminal = terminal,
_controller = controller,
_offset = offset,
_padding = padding,
_autoResize = autoResize,
_focusNode = focusNode,
_cursorType = cursorType,
_alwaysShowCursor = alwaysShowCursor,
_onEditableRect = onEditableRect,
_composingText = composingText,
_painter = TerminalPainter(
theme: theme,
textStyle: textStyle,
textScaler: textScaler,
);
Terminal _terminal;
set terminal(Terminal terminal) {
if (_terminal == terminal) return;
if (attached) _terminal.removeListener(_onTerminalChange);
_terminal = terminal;
if (attached) _terminal.addListener(_onTerminalChange);
_resizeTerminalIfNeeded();
markNeedsLayout();
}
TerminalController _controller;
set controller(TerminalController controller) {
if (_controller == controller) return;
if (attached) _controller.removeListener(_onControllerUpdate);
_controller = controller;
if (attached) _controller.addListener(_onControllerUpdate);
markNeedsLayout();
}
ViewportOffset _offset;
set offset(ViewportOffset value) {
if (value == _offset) return;
if (attached) _offset.removeListener(_onScroll);
_offset = value;
if (attached) _offset.addListener(_onScroll);
markNeedsLayout();
}
EdgeInsets _padding;
set padding(EdgeInsets value) {
if (value == _padding) return;
_padding = value;
markNeedsLayout();
}
bool _autoResize;
set autoResize(bool value) {
if (value == _autoResize) return;
_autoResize = value;
markNeedsLayout();
}
set textStyle(TerminalStyle value) {
if (value == _painter.textStyle) return;
_painter.textStyle = value;
markNeedsLayout();
}
set textScaler(TextScaler value) {
if (value == _painter.textScaler) return;
_painter.textScaler = value;
markNeedsLayout();
}
set theme(TerminalTheme value) {
if (value == _painter.theme) return;
_painter.theme = value;
markNeedsPaint();
}
FocusNode _focusNode;
set focusNode(FocusNode value) {
if (value == _focusNode) return;
if (attached) _focusNode.removeListener(_onFocusChange);
_focusNode = value;
if (attached) _focusNode.addListener(_onFocusChange);
markNeedsPaint();
}
TerminalCursorType _cursorType;
set cursorType(TerminalCursorType value) {
if (value == _cursorType) return;
_cursorType = value;
markNeedsPaint();
}
bool _alwaysShowCursor;
set alwaysShowCursor(bool value) {
if (value == _alwaysShowCursor) return;
_alwaysShowCursor = value;
markNeedsPaint();
}
EditableRectCallback? _onEditableRect;
set onEditableRect(EditableRectCallback? value) {
if (value == _onEditableRect) return;
_onEditableRect = value;
markNeedsLayout();
}
String? _composingText;
set composingText(String? value) {
if (value == _composingText) return;
_composingText = value;
markNeedsPaint();
}
TerminalSize? _viewportSize;
final TerminalPainter _painter;
var _stickToBottom = true;
void _onScroll() {
_stickToBottom = _scrollOffset >= _maxScrollExtent;
markNeedsLayout();
_notifyEditableRect();
}
void _onFocusChange() {
markNeedsPaint();
}
void _onTerminalChange() {
markNeedsLayout();
_notifyEditableRect();
}
void _onControllerUpdate() {
markNeedsLayout();
}
@override
final isRepaintBoundary = true;
@override
void attach(PipelineOwner owner) {
super.attach(owner);
_offset.addListener(_onScroll);
_terminal.addListener(_onTerminalChange);
_controller.addListener(_onControllerUpdate);
_focusNode.addListener(_onFocusChange);
}
@override
void detach() {
super.detach();
_offset.removeListener(_onScroll);
_terminal.removeListener(_onTerminalChange);
_controller.removeListener(_onControllerUpdate);
_focusNode.removeListener(_onFocusChange);
}
@override
bool hitTestSelf(Offset position) {
return true;
}
@override
void systemFontsDidChange() {
_painter.clearFontCache();
super.systemFontsDidChange();
}
@override
void performLayout() {
size = constraints.biggest;
_updateViewportSize();
_updateScrollOffset();
if (_stickToBottom) {
_offset.correctBy(_maxScrollExtent - _scrollOffset);
}
}
/// Total height of the terminal in pixels. Includes scrollback buffer.
double get _terminalHeight =>
_terminal.buffer.lines.length * _painter.cellSize.height;
/// The distance from the top of the terminal to the top of the viewport.
// double get _scrollOffset => _offset.pixels;
double get _scrollOffset {
// return _offset.pixels ~/ _painter.cellSize.height * _painter.cellSize.height;
return _offset.pixels;
}
/// The height of a terminal line in pixels. This includes the line spacing.
/// Height of the entire terminal is expected to be a multiple of this value.
double get lineHeight => _painter.cellSize.height;
/// Get the top-left corner of the cell at [cellOffset] in pixels.
Offset getOffset(CellOffset cellOffset) {
final row = cellOffset.y;
final col = cellOffset.x;
final x = col * _painter.cellSize.width;
final y = row * _painter.cellSize.height;
return Offset(x + _padding.left, y + _padding.top - _scrollOffset);
}
/// Get the [CellOffset] of the cell that [offset] is in.
CellOffset getCellOffset(Offset offset) {
final x = offset.dx - _padding.left;
final y = offset.dy - _padding.top + _scrollOffset;
final row = y ~/ _painter.cellSize.height;
final col = x ~/ _painter.cellSize.width;
return CellOffset(
col.clamp(0, _terminal.viewWidth - 1),
row.clamp(0, _terminal.buffer.lines.length - 1),
);
}
/// Selects entire words in the terminal that contains [from] and [to].
void selectWord(Offset from, [Offset? to]) {
final fromOffset = getCellOffset(from);
final fromBoundary = _terminal.buffer.getWordBoundary(fromOffset);
if (fromBoundary == null) return;
if (to == null) {
_controller.setSelection(
_terminal.buffer.createAnchorFromOffset(fromBoundary.begin),
_terminal.buffer.createAnchorFromOffset(fromBoundary.end),
mode: SelectionMode.line,
);
} else {
final toOffset = getCellOffset(to);
final toBoundary = _terminal.buffer.getWordBoundary(toOffset);
if (toBoundary == null) return;
final range = fromBoundary.merge(toBoundary);
_controller.setSelection(
_terminal.buffer.createAnchorFromOffset(range.begin),
_terminal.buffer.createAnchorFromOffset(range.end),
mode: SelectionMode.line,
);
}
}
/// Selects characters in the terminal that starts from [from] to [to]. At
/// least one cell is selected even if [from] and [to] are same.
void selectCharacters(Offset from, [Offset? to]) {
final fromPosition = getCellOffset(from);
if (to == null) {
_controller.setSelection(
_terminal.buffer.createAnchorFromOffset(fromPosition),
_terminal.buffer.createAnchorFromOffset(fromPosition),
);
} else {
var toPosition = getCellOffset(to);
if (toPosition.x >= fromPosition.x) {
toPosition = CellOffset(toPosition.x + 1, toPosition.y);
}
_controller.setSelection(
_terminal.buffer.createAnchorFromOffset(fromPosition),
_terminal.buffer.createAnchorFromOffset(toPosition),
);
}
}
/// Send a mouse event at [offset] with [button] being currently in [buttonState].
bool mouseEvent(
TerminalMouseButton button,
TerminalMouseButtonState buttonState,
Offset offset,
) {
final position = getCellOffset(offset);
return _terminal.mouseInput(button, buttonState, position);
}
void _notifyEditableRect() {
final cursor = localToGlobal(cursorOffset);
final rect = Rect.fromLTRB(
cursor.dx,
cursor.dy,
size.width,
cursor.dy + _painter.cellSize.height,
);
final caretRect = cursor & _painter.cellSize;
_onEditableRect?.call(rect, caretRect);
}
/// Update the viewport size in cells based on the current widget size in
/// pixels.
void _updateViewportSize() {
if (size <= _painter.cellSize) {
return;
}
final viewportSize = TerminalSize(
size.width ~/ _painter.cellSize.width,
_viewportHeight ~/ _painter.cellSize.height,
);
if (_viewportSize != viewportSize) {
_viewportSize = viewportSize;
_resizeTerminalIfNeeded();
}
}
/// Notify the underlying terminal that the viewport size has changed.
void _resizeTerminalIfNeeded() {
if (_autoResize && _viewportSize != null) {
_terminal.resize(
_viewportSize!.width,
_viewportSize!.height,
_painter.cellSize.width.round(),
_painter.cellSize.height.round(),
);
}
}
/// Update the scroll offset based on the current terminal state. This should
/// be called in [performLayout] after the viewport size has been updated.
void _updateScrollOffset() {
_offset.applyViewportDimension(_viewportHeight);
_offset.applyContentDimensions(0, _maxScrollExtent);
}
bool get _isComposingText {
return _composingText != null && _composingText!.isNotEmpty;
}
bool get _shouldShowCursor {
return _terminal.cursorVisibleMode || _alwaysShowCursor || _isComposingText;
}
double get _viewportHeight {
return size.height - _padding.vertical;
}
double get _maxScrollExtent {
return max(_terminalHeight - _viewportHeight, 0.0);
}
double get _lineOffset {
return -_scrollOffset + _padding.top;
}
/// The offset of the cursor from the top left corner of this render object.
Offset get cursorOffset {
return Offset(
_terminal.buffer.cursorX * _painter.cellSize.width,
_terminal.buffer.absoluteCursorY * _painter.cellSize.height + _lineOffset,
);
}
Size get cellSize {
return _painter.cellSize;
}
@override
void paint(PaintingContext context, Offset offset) {
_paint(context, offset);
context.setWillChangeHint();
}
void _paint(PaintingContext context, Offset offset) {
final canvas = context.canvas;
final lines = _terminal.buffer.lines;
final charHeight = _painter.cellSize.height;
final firstLineOffset = _scrollOffset - _padding.top;
final lastLineOffset = _scrollOffset + size.height + _padding.bottom;
final firstLine = firstLineOffset ~/ charHeight;
final lastLine = lastLineOffset ~/ charHeight;
final effectFirstLine = firstLine.clamp(0, lines.length - 1);
final effectLastLine = lastLine.clamp(0, lines.length - 1);
for (var i = effectFirstLine; i <= effectLastLine; i++) {
_painter.paintLine(
canvas,
offset.translate(0, (i * charHeight + _lineOffset).truncateToDouble()),
lines[i],
);
}
if (_terminal.buffer.absoluteCursorY >= effectFirstLine &&
_terminal.buffer.absoluteCursorY <= effectLastLine) {
if (_isComposingText) {
_paintComposingText(canvas, offset + cursorOffset);
}
if (_shouldShowCursor) {
_painter.paintCursor(
canvas,
offset + cursorOffset,
cursorType: _cursorType,
hasFocus: _focusNode.hasFocus,
);
}
}
_paintHighlights(
canvas,
_controller.highlights,
effectFirstLine,
effectLastLine,
);
if (_controller.selection != null) {
_paintSelection(
canvas,
_controller.selection!,
effectFirstLine,
effectLastLine,
);
}
}
/// Paints the text that is currently being composed in IME to [canvas] at
/// [offset]. [offset] is usually the cursor position.
void _paintComposingText(Canvas canvas, Offset offset) {
final composingText = _composingText;
if (composingText == null) {
return;
}
final style = _painter.textStyle.toTextStyle(
color: _painter.resolveForegroundColor(_terminal.cursor.foreground),
backgroundColor: _painter.theme.background,
underline: true,
);
final builder = ParagraphBuilder(style.getParagraphStyle());
builder.addPlaceholder(
offset.dx,
_painter.cellSize.height,
PlaceholderAlignment.middle,
);
builder.pushStyle(
style.getTextStyle(textScaler: _painter.textScaler),
);
builder.addText(composingText);
final paragraph = builder.build();
paragraph.layout(ParagraphConstraints(width: size.width));
canvas.drawParagraph(paragraph, Offset(0, offset.dy));
}
void _paintSelection(
Canvas canvas,
BufferRange selection,
int firstLine,
int lastLine,
) {
for (final segment in selection.toSegments()) {
if (segment.line >= _terminal.buffer.lines.length) {
break;
}
if (segment.line < firstLine) {
continue;
}
if (segment.line > lastLine) {
break;
}
_paintSegment(canvas, segment, _painter.theme.selection);
}
}
void _paintHighlights(
Canvas canvas,
List<TerminalHighlight> highlights,
int firstLine,
int lastLine,
) {
for (var highlight in _controller.highlights) {
final range = highlight.range?.normalized;
if (range == null ||
range.begin.y > lastLine ||
range.end.y < firstLine) {
continue;
}
for (var segment in range.toSegments()) {
if (segment.line < firstLine) {
continue;
}
if (segment.line > lastLine) {
break;
}
_paintSegment(canvas, segment, highlight.color);
}
}
}
@pragma('vm:prefer-inline')
void _paintSegment(Canvas canvas, BufferSegment segment, Color color) {
final start = segment.start ?? 0;
final end = segment.end ?? _terminal.viewWidth;
final startOffset = Offset(
start * _painter.cellSize.width,
segment.line * _painter.cellSize.height + _lineOffset,
);
_painter.paintHighlight(canvas, startOffset, end - start, color);
}
}
+133
View File
@@ -0,0 +1,133 @@
import 'package:flutter/widgets.dart';
import 'package:xterm/core.dart';
import 'package:xterm/src/ui/infinite_scroll_view.dart';
/// Handles scrolling gestures in the alternate screen buffer. In alternate
/// screen buffer, the terminal don't have a scrollback buffer, instead, the
/// scroll gestures are converted to escape sequences based on the current
/// report mode declared by the application.
class TerminalScrollGestureHandler extends StatefulWidget {
const TerminalScrollGestureHandler({
super.key,
required this.terminal,
required this.getCellOffset,
required this.getLineHeight,
this.simulateScroll = true,
required this.child,
});
final Terminal terminal;
/// Returns the cell offset for the pixel offset.
final CellOffset Function(Offset) getCellOffset;
/// Returns the pixel height of lines in the terminal.
final double Function() getLineHeight;
/// Whether to simulate scroll events in the terminal when the application
/// doesn't declare it supports mouse wheel events. true by default as it
/// is the default behavior of most terminals.
final bool simulateScroll;
final Widget child;
@override
State<TerminalScrollGestureHandler> createState() =>
_TerminalScrollGestureHandlerState();
}
class _TerminalScrollGestureHandlerState
extends State<TerminalScrollGestureHandler> {
/// Whether the application is in alternate screen buffer. If false, then this
/// widget does nothing.
var isAltBuffer = false;
/// The variable that tracks the line offset in last scroll event. Used to
/// determine how many the scroll events should be sent to the terminal.
var lastLineOffset = 0;
/// This variable tracks the last offset where the scroll gesture started.
/// Used to calculate the cell offset of the terminal mouse event.
var lastPointerPosition = Offset.zero;
@override
void initState() {
widget.terminal.addListener(_onTerminalUpdated);
isAltBuffer = widget.terminal.isUsingAltBuffer;
super.initState();
}
@override
void dispose() {
widget.terminal.removeListener(_onTerminalUpdated);
super.dispose();
}
@override
void didUpdateWidget(covariant TerminalScrollGestureHandler oldWidget) {
if (oldWidget.terminal != widget.terminal) {
oldWidget.terminal.removeListener(_onTerminalUpdated);
widget.terminal.addListener(_onTerminalUpdated);
isAltBuffer = widget.terminal.isUsingAltBuffer;
}
super.didUpdateWidget(oldWidget);
}
void _onTerminalUpdated() {
if (isAltBuffer != widget.terminal.isUsingAltBuffer) {
isAltBuffer = widget.terminal.isUsingAltBuffer;
setState(() {});
}
}
/// Send a single scroll event to the terminal. If [simulateScroll] is true,
/// then if the application doesn't recognize mouse wheel events, this method
/// will simulate scroll events by sending up/down arrow keys.
void _sendScrollEvent(bool up) {
final position = widget.getCellOffset(lastPointerPosition);
final handled = widget.terminal.mouseInput(
up ? TerminalMouseButton.wheelUp : TerminalMouseButton.wheelDown,
TerminalMouseButtonState.down,
position,
);
if (!handled && widget.simulateScroll) {
widget.terminal.keyInput(
up ? TerminalKey.arrowUp : TerminalKey.arrowDown,
);
}
}
void _onScroll(double offset) {
final currentLineOffset = offset ~/ widget.getLineHeight();
final delta = currentLineOffset - lastLineOffset;
for (var i = 0; i < delta.abs(); i++) {
_sendScrollEvent(delta < 0);
}
lastLineOffset = currentLineOffset;
}
@override
Widget build(BuildContext context) {
if (!isAltBuffer) {
return widget.child;
}
return Listener(
onPointerSignal: (event) {
lastPointerPosition = event.position;
},
onPointerDown: (event) {
lastPointerPosition = event.position;
},
child: InfiniteScrollView(
onScroll: _onScroll,
child: widget.child,
),
);
}
}
+5
View File
@@ -0,0 +1,5 @@
enum SelectionMode {
line,
block,
}
+71
View File
@@ -0,0 +1,71 @@
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:xterm/src/terminal.dart';
import 'package:xterm/src/ui/controller.dart';
import 'package:xterm/src/ui/selection_mode.dart';
class TerminalActions extends StatelessWidget {
const TerminalActions({
super.key,
required this.terminal,
required this.controller,
required this.child,
});
final Terminal terminal;
final TerminalController controller;
final Widget child;
@override
Widget build(BuildContext context) {
return Actions(
actions: {
PasteTextIntent: CallbackAction<PasteTextIntent>(
onInvoke: (intent) async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text;
if (text != null) {
terminal.paste(text);
controller.clearSelection();
}
return null;
},
),
CopySelectionTextIntent: CallbackAction<CopySelectionTextIntent>(
onInvoke: (intent) async {
final selection = controller.selection;
if (selection == null) {
return;
}
final text = terminal.buffer.getText(selection);
await Clipboard.setData(ClipboardData(text: text));
return null;
},
),
SelectAllTextIntent: CallbackAction<SelectAllTextIntent>(
onInvoke: (intent) {
controller.setSelection(
terminal.buffer.createAnchor(
0,
terminal.buffer.height - terminal.viewHeight,
),
terminal.buffer.createAnchor(
terminal.viewWidth,
terminal.buffer.height - 1,
),
mode: SelectionMode.line,
);
return null;
},
),
},
child: child,
);
}
}
@@ -0,0 +1,34 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
Map<ShortcutActivator, Intent> get defaultTerminalShortcuts {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return _defaultShortcuts;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return _defaultAppleShortcuts;
}
}
final _defaultShortcuts = {
SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.keyV, control: true):
const PasteTextIntent(SelectionChangedCause.keyboard),
SingleActivator(LogicalKeyboardKey.keyA, control: true):
const SelectAllTextIntent(SelectionChangedCause.keyboard),
};
final _defaultAppleShortcuts = {
SingleActivator(LogicalKeyboardKey.keyC, meta: true):
CopySelectionTextIntent.copy,
SingleActivator(LogicalKeyboardKey.keyV, meta: true):
const PasteTextIntent(SelectionChangedCause.keyboard),
SingleActivator(LogicalKeyboardKey.keyA, meta: true):
const SelectAllTextIntent(SelectionChangedCause.keyboard),
};
+24
View File
@@ -0,0 +1,24 @@
class TerminalSize {
final int width;
final int height;
const TerminalSize(this.width, this.height);
@override
String toString() => 'TerminalSize($width, $height)';
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! TerminalSize) {
return false;
}
return other.width == width && other.height == height;
}
@override
int get hashCode => width.hashCode ^ height.hashCode;
}
@@ -0,0 +1,87 @@
import 'package:flutter/widgets.dart';
const _kDefaultFontSize = 13.0;
const _kDefaultHeight = 1.2;
const _kDefaultFontFamily = 'monospace';
const _kDefaultFontFamilyFallback = [
'Menlo',
'Monaco',
'Consolas',
'Liberation Mono',
'Courier New',
'Noto Sans Mono CJK SC',
'Noto Sans Mono CJK TC',
'Noto Sans Mono CJK KR',
'Noto Sans Mono CJK JP',
'Noto Sans Mono CJK HK',
'Noto Color Emoji',
'Noto Sans Symbols',
'monospace',
'sans-serif',
];
class TerminalStyle {
const TerminalStyle({
this.fontSize = _kDefaultFontSize,
this.height = _kDefaultHeight,
this.fontFamily = _kDefaultFontFamily,
this.fontFamilyFallback = _kDefaultFontFamilyFallback,
});
factory TerminalStyle.fromTextStyle(TextStyle textStyle) {
return TerminalStyle(
fontSize: textStyle.fontSize ?? _kDefaultFontSize,
height: textStyle.height ?? _kDefaultHeight,
fontFamily: textStyle.fontFamily ??
textStyle.fontFamilyFallback?.first ??
_kDefaultFontFamily,
fontFamilyFallback:
textStyle.fontFamilyFallback ?? _kDefaultFontFamilyFallback,
);
}
final double fontSize;
final double height;
final String fontFamily;
final List<String> fontFamilyFallback;
TextStyle toTextStyle({
Color? color,
Color? backgroundColor,
bool bold = false,
bool italic = false,
bool underline = false,
}) {
return TextStyle(
fontSize: fontSize,
height: height,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
color: color,
backgroundColor: backgroundColor,
fontWeight: bold ? FontWeight.bold : FontWeight.normal,
fontStyle: italic ? FontStyle.italic : FontStyle.normal,
decoration: underline ? TextDecoration.underline : TextDecoration.none,
);
}
TerminalStyle copyWith({
double? fontSize,
double? height,
String? fontFamily,
List<String>? fontFamilyFallback,
}) {
return TerminalStyle(
fontSize: fontSize ?? this.fontSize,
height: height ?? this.height,
fontFamily: fontFamily ?? this.fontFamily,
fontFamilyFallback: fontFamilyFallback ?? this.fontFamilyFallback,
);
}
}
+57
View File
@@ -0,0 +1,57 @@
import 'package:flutter/widgets.dart';
class TerminalTheme {
const TerminalTheme({
required this.cursor,
required this.selection,
required this.foreground,
required this.background,
required this.black,
required this.white,
required this.red,
required this.green,
required this.yellow,
required this.blue,
required this.magenta,
required this.cyan,
required this.brightBlack,
required this.brightRed,
required this.brightGreen,
required this.brightYellow,
required this.brightBlue,
required this.brightMagenta,
required this.brightCyan,
required this.brightWhite,
required this.searchHitBackground,
required this.searchHitBackgroundCurrent,
required this.searchHitForeground,
});
final Color cursor;
final Color selection;
final Color foreground;
final Color background;
final Color black;
final Color red;
final Color green;
final Color yellow;
final Color blue;
final Color magenta;
final Color cyan;
final Color white;
final Color brightBlack;
final Color brightRed;
final Color brightGreen;
final Color brightYellow;
final Color brightBlue;
final Color brightMagenta;
final Color brightCyan;
final Color brightWhite;
final Color searchHitBackground;
final Color searchHitBackgroundCurrent;
final Color searchHitForeground;
}
+56
View File
@@ -0,0 +1,56 @@
import 'package:flutter/widgets.dart';
import 'package:xterm/src/ui/terminal_theme.dart';
class TerminalThemes {
static const defaultTheme = TerminalTheme(
cursor: Color(0XAAAEAFAD),
selection: Color(0XAAAEAFAD),
foreground: Color(0XFFCCCCCC),
background: Color(0XFF1E1E1E),
black: Color(0XFF000000),
red: Color(0XFFCD3131),
green: Color(0XFF0DBC79),
yellow: Color(0XFFE5E510),
blue: Color(0XFF2472C8),
magenta: Color(0XFFBC3FBC),
cyan: Color(0XFF11A8CD),
white: Color(0XFFE5E5E5),
brightBlack: Color(0XFF666666),
brightRed: Color(0XFFF14C4C),
brightGreen: Color(0XFF23D18B),
brightYellow: Color(0XFFF5F543),
brightBlue: Color(0XFF3B8EEA),
brightMagenta: Color(0XFFD670D6),
brightCyan: Color(0XFF29B8DB),
brightWhite: Color(0XFFFFFFFF),
searchHitBackground: Color(0XFFFFFF2B),
searchHitBackgroundCurrent: Color(0XFF31FF26),
searchHitForeground: Color(0XFF000000),
);
static const whiteOnBlack = TerminalTheme(
cursor: Color(0XFFAEAFAD),
selection: Color(0XFFAEAFAD),
foreground: Color(0XFFFFFFFF),
background: Color(0XFF000000),
black: Color(0XFF000000),
red: Color(0XFFCD3131),
green: Color(0XFF0DBC79),
yellow: Color(0XFFE5E510),
blue: Color(0XFF2472C8),
magenta: Color(0XFFBC3FBC),
cyan: Color(0XFF11A8CD),
white: Color(0XFFE5E5E5),
brightBlack: Color(0XFF666666),
brightRed: Color(0XFFF14C4C),
brightGreen: Color(0XFF23D18B),
brightYellow: Color(0XFFF5F543),
brightBlue: Color(0XFF3B8EEA),
brightMagenta: Color(0XFFD670D6),
brightCyan: Color(0XFF29B8DB),
brightWhite: Color(0XFFFFFFFF),
searchHitBackground: Color(0XFFFFFF2B),
searchHitBackgroundCurrent: Color(0XFF31FF26),
searchHitForeground: Color(0XFF000000),
);
}