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

244 lines
8.6 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
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_bell.dart';
import 'chat_shell_terminal_key_input.dart';
import 'chat_shell_terminal_links.dart';
import 'chat_shell_terminal_session.dart';
import 'chat_shell_terminal_shortcuts.dart';
import 'chat_shell_terminal_theme.dart';
import 'chat_shell_terminal_find_host.dart';
import 'chat_shell_terminal_view_features.dart';
import '../../../ui/input/keyboard_owner.dart';
export 'chat_shell_terminal_shortcuts.dart'
show chatShellTerminalShortcuts, chatShellCopyKey;
/// Whether the soft keyboard is the main way to type here, so the key
/// toolbar offers a text field: the terminal itself takes hardware keys only.
bool chatShellTouchFirst() =>
defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS;
/// One run's terminal emulator view. In a card it is bounded to
/// [kChatShellOutputCollapsedLines] rows (a finished run shrinks to its
/// output); with [fill] it takes the space its parent gives (full screen).
/// It sizes the terminal to its own layout; a running process is resized to
/// match. Tapping a printed web link opens it in the browser.
///
/// Besides the process's keys it answers its own (see [chatShellLocalKey]):
/// find in the scrollback, text size, and Shift+PgUp/PgDn/Home/End
/// scrolling. A right-click opens its menu (unless the program reports the
/// mouse), a bell flashes its border, and an OSC 52 copy says so.
class ChatShellTerminalView extends StatefulWidget {
const ChatShellTerminalView({
super.key,
required this.session,
this.fill = false,
this.autofocus = false,
this.autoResize = true,
});
final ChatShellTerminalSession session;
final bool fill;
final bool autofocus;
/// False while another view of the same terminal (full screen) sizes it.
final bool autoResize;
@override
State<ChatShellTerminalView> createState() => _ChatShellTerminalViewState();
}
class _ChatShellTerminalViewState extends State<ChatShellTerminalView>
with
SingleTickerProviderStateMixin,
ChatShellTerminalFindHost<ChatShellTerminalView>,
ChatShellTerminalFeatures<ChatShellTerminalView> {
@override
final TerminalController controller = TerminalController();
@override
final FocusNode focus = FocusNode(debugLabel: 'chat-shell-terminal');
final FocusNode _outputFocus = FocusNode(debugLabel: 'chat-shell-output');
@override
final ScrollController scroll = ScrollController();
@override
final GlobalKey<TerminalViewState> viewKey = GlobalKey();
final Map<ShortcutActivator, Intent> _shortcuts =
chatShellTerminalShortcuts();
bool _focused = false;
@override
ChatShellTerminalSession get session => widget.session;
@override
void initState() {
super.initState();
// A paste while the terminal has focus goes to the process, not to the
// chat composer.
ChatComposerPasteFocus.registerInput(focus);
focus.addListener(_focusChanged);
initFeatures();
}
/// 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;
updateBlink();
}
@override
void dispose() {
focus.removeListener(_focusChanged);
disposeFeatures();
ChatComposerPasteFocus.unregisterInput(focus);
controller.dispose();
focus.dispose();
_outputFocus.dispose();
scroll.dispose();
super.dispose();
}
/// Ctrl-C with a selection copies; the view's own keys (find, zoom,
/// scrolling) are answered; 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) && actions.copySelection()) {
return KeyEventResult.handled;
}
if (localKey(event)) 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;
}
void _tapped(TapUpDetails details, CellOffset offset) {
final link = chatShellTerminalLinkAt(widget.session.terminal, offset);
if (link != null) openChatLink(context, link.uri);
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.session.layout,
builder: (context, _) => _build(context),
);
Widget _build(BuildContext context) {
final session = widget.session;
final live = session.live;
final style = chatShellTerminalStyle(
context,
fontSize: session.layout.fontSize,
);
currentFontSize = style.fontSize;
const padding = EdgeInsets.all(8);
Widget view = ListenableBuilder(
listenable: hover,
builder: (context, _) => TerminalView(
session.terminal,
key: viewKey,
controller: controller,
scrollController: scroll,
focusNode: focus,
autofocus: widget.autofocus && live,
autoResize: widget.autoResize,
theme: chatShellTerminalTheme(context),
textStyle: style,
padding: padding,
readOnly: !live,
// Desktop keys go straight to the process as key events (a focused
// text input stays closed in desktop browsers). On phones and
// tablets a tap opens the on-screen keyboard and typing goes to the
// terminal; the key toolbar's field stays as an alternative.
hardwareKeyboardOnly: !chatShellTouchFirst(),
// No autocorrect or suggestions rewriting what is sent to a shell.
keyboardType: TextInputType.visiblePassword,
shortcuts: _shortcuts,
cursorType: TerminalCursorType.block,
cursorBlinkVisible: blink.visible,
mouseCursor: hover.link == null
? SystemMouseCursors.text
: SystemMouseCursors.click,
onTapUp: _tapped,
onSecondaryTapUp: (details, _) => openMenu(details.globalPosition),
onKeyEvent: _key,
),
);
view = Semantics(
identifier: 'chat-shell-terminal',
label: live ? 'Terminal, type to send input' : 'Terminal output',
// App-wide shortcuts leave typing in the terminal alone.
child: TypingSurface(child: decorate(view)),
);
if (!live) {
// The read-only emulator attaches no keyboard: a press selects text
// and gives this node the keyboard, so the copy keys work.
view = Listener(
onPointerDown: (_) => _outputFocus.requestFocus(),
child: Focus(
focusNode: _outputFocus,
onKeyEvent: readOnlyKey,
child: view,
),
);
}
// The emulator would otherwise inset itself by the window's safe area.
view = MediaQuery.removePadding(
context: context,
removeTop: true,
removeBottom: true,
removeLeft: true,
removeRight: true,
child: view,
);
view = ClipRRect(borderRadius: BorderRadius.circular(8), child: view);
view = overlayFindBar(
ChatShellBellFlash(
bells: session.events.bells,
enabled: session.layout.bell,
child: view,
),
);
if (widget.fill) return view;
final cell = chatShellTerminalCellSize(context, style);
return LayoutBuilder(
builder: (context, constraints) {
// A finished run's box fits the rows its output takes at this width.
final cols = ((constraints.maxWidth - padding.horizontal) / cell.width)
.floor()
.clamp(1, 1000);
final rows = live
? kChatShellOutputCollapsedLines
: session.rowsAt(cols).clamp(1, kChatShellOutputCollapsedLines);
// A pixel of slack keeps rounding from losing the last row.
return SizedBox(
height: rows * cell.height + padding.vertical + 1,
child: view,
);
},
);
}
}