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_links.dart'; import 'chat_shell_terminal_session.dart'; import 'chat_shell_terminal_theme.dart'; import '../../../ui/input/keyboard_owner.dart'; /// 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; /// The terminal's own key shortcuts. Cmd-C, Cmd-V and Cmd-A on Apple /// platforms; elsewhere Ctrl-V (and the terminal convention Ctrl-Shift-V) /// paste and Ctrl-Shift-C or Ctrl-Insert copies, so every other Ctrl key, /// Ctrl-A included, reaches the process. Ctrl-C copies too while text is /// selected (see [chatShellCopyKey]); a browser keeps Ctrl-Shift-C for its /// developer tools, so there it is the key that works. Map chatShellTerminalShortcuts() { const paste = PasteTextIntent(SelectionChangedCause.keyboard); final apple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS; if (apple) { return const { SingleActivator(LogicalKeyboardKey.keyC, meta: true): CopySelectionTextIntent.copy, SingleActivator(LogicalKeyboardKey.keyV, meta: true): paste, SingleActivator(LogicalKeyboardKey.keyA, meta: true): SelectAllTextIntent( SelectionChangedCause.keyboard, ), }; } return const { SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true): CopySelectionTextIntent.copy, SingleActivator(LogicalKeyboardKey.insert, control: true): CopySelectionTextIntent.copy, SingleActivator(LogicalKeyboardKey.keyV, control: true): paste, SingleActivator(LogicalKeyboardKey.keyV, control: true, shift: true): paste, }; } /// Whether [event] is Ctrl-C outside Apple platforms: with text selected in /// the terminal it copies the selection instead of interrupting the process, /// as terminals in browsers and on Windows do. Without a selection Ctrl-C /// stays the process's. bool chatShellCopyKey(KeyEvent event, HardwareKeyboard keyboard) { final apple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS; return !apple && event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.keyC && keyboard.isControlPressed && !keyboard.isShiftPressed && !keyboard.isAltPressed && !keyboard.isMetaPressed; } /// 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. 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 createState() => _ChatShellTerminalViewState(); } class _ChatShellTerminalViewState extends State { final TerminalController _controller = TerminalController(); final FocusNode _focus = FocusNode(debugLabel: 'chat-shell-terminal'); final FocusNode _outputFocus = FocusNode(debugLabel: 'chat-shell-output'); @override void initState() { super.initState(); // A paste while the terminal has focus goes to the process, not to the // chat composer. ChatComposerPasteFocus.registerInput(_focus); } @override void dispose() { ChatComposerPasteFocus.unregisterInput(_focus); _controller.dispose(); _focus.dispose(); _outputFocus.dispose(); super.dispose(); } /// Copies the selected text and clears the selection; false with none. bool _copySelection() { final selection = _controller.selection; if (selection == null) return false; final text = widget.session.terminal.buffer.getText(selection); if (text.isEmpty) return false; Clipboard.setData(ClipboardData(text: text)); _controller.clearSelection(); 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; /// A finished run's output takes no keys of its own, so the copy keys are /// answered here while it has the keyboard. KeyEventResult _readOnlyKey(FocusNode node, KeyEvent event) { if (event is! KeyDownEvent || event.logicalKey != LogicalKeyboardKey.keyC && event.logicalKey != LogicalKeyboardKey.insert) { return KeyEventResult.ignored; } final keyboard = HardwareKeyboard.instance; if (!keyboard.isControlPressed && !keyboard.isMetaPressed) { return KeyEventResult.ignored; } return _copySelection() ? KeyEventResult.handled : KeyEventResult.ignored; } void _tapped(TapUpDetails details, CellOffset offset) { final uri = chatShellLinkAt(widget.session.terminal.buffer, offset); if (uri != null) openChatLink(context, uri); } @override Widget build(BuildContext context) { final session = widget.session; final live = session.live; final style = chatShellTerminalStyle(context); const padding = EdgeInsets.all(8); Widget 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: TerminalView( session.terminal, controller: _controller, 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: chatShellTerminalShortcuts(), cursorType: TerminalCursorType.block, onTapUp: _tapped, onKeyEvent: _key, ), ), ); 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); 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, ); }, ); } }