Files
pipelines/app/lib/features/chat/shell/chat_shell_terminal_actions.dart
T

98 lines
3.0 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
/// What one terminal view does locally, for its keys and its context menu:
/// copy, paste, select, clear the scrollback and scroll it.
class ChatShellTerminalActions {
ChatShellTerminalActions({
required this.terminal,
required this.controller,
required this.scroll,
required this.view,
});
final Terminal terminal;
final TerminalController controller;
final ScrollController scroll;
final GlobalKey<TerminalViewState> view;
/// Copies the selected text and clears the selection; false with none.
bool copySelection() {
final selection = controller.selection;
if (selection == null) return false;
final text = terminal.buffer.getText(selection);
if (text.isEmpty) return false;
Clipboard.setData(ClipboardData(text: text));
controller.clearSelection();
return true;
}
/// Pastes the clipboard into the process (bracketed when it asked).
Future<void> paste() async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text;
if (text == null || text.isEmpty) return;
terminal.paste(text);
controller.clearSelection();
scrollToBottom();
}
/// Selects everything the buffer holds, scrollback included.
void selectAll() {
final buffer = terminal.buffer;
controller.setSelection(
buffer.createAnchor(0, 0),
buffer.createAnchor(terminal.viewWidth, buffer.height - 1),
mode: SelectionMode.line,
);
}
/// Drops the scrollback above the screen (this view's copy only: the
/// server keeps the output, and a reload draws it again).
void clearScrollback() {
controller.clearSelection();
terminal.mainBuffer.clearScrollback();
terminal.notifyListeners();
}
double get _lineHeight => view.currentState?.renderTerminal.lineHeight ?? 0;
/// Scrolls the scrollback one screen up ([pages] < 0) or down, keeping a
/// line of context.
void scrollPages(int pages) {
if (!scroll.hasClients) return;
final position = scroll.position;
final step = position.viewportDimension - _lineHeight;
_jump(position.pixels + pages * (step > 0 ? step : _lineHeight));
}
void scrollToTop() {
if (scroll.hasClients) _jump(0);
}
void scrollToBottom() {
if (scroll.hasClients) _jump(scroll.position.maxScrollExtent);
}
/// Scrolls buffer row [y] into view, centred, unless it already shows.
void reveal(int y) {
final line = _lineHeight;
if (!scroll.hasClients || line <= 0) return;
final position = scroll.position;
final top = y * line;
final shown =
top >= position.pixels &&
top + line <= position.pixels + position.viewportDimension;
if (shown) return;
_jump(top - (position.viewportDimension - line) / 2);
}
void _jump(double pixels) {
final position = scroll.position;
position.jumpTo(
pixels.clamp(position.minScrollExtent, position.maxScrollExtent),
);
}
}