import 'package:xterm/core.dart'; import '../../terminal/terminal_layout.dart'; import 'chat_shell_run.dart'; import 'chat_shell_terminal_emulator.dart'; import 'chat_shell_terminal_events.dart'; import 'chat_shell_terminal_feed.dart'; import 'chat_shell_terminal_key_input.dart'; import 'chat_shell_terminal_sticky.dart'; /// Lines a terminal keeps unless the setting says otherwise. const int chatShellTerminalScrollback = terminalScrollbackDefault; /// The terminal emulator state of one run: the xterm [terminal] fed with the /// run's output in order, and the bridge from what the operator types (or /// the emulator answers) to the running process. /// /// It keeps no copy of typed input: [Terminal.onOutput] hands each key or /// paste straight to [onInput], which sends it. /// /// Several clients may draw one terminal. The emulator's automatic answers /// to queries in the output (cursor position, device attributes) go to /// [onReply] instead, so the server can let only the active client's /// answers through; a view gaining focus calls [activate], which makes this /// client the active one at its size ([onActivate]). class ChatShellTerminalSession { ChatShellTerminalSession( ChatShellRun run, { required this.onInput, required this.onResize, this.onReply, this.onActivate, bool Function()? optionAsMeta, TerminalLayout? layout, }) : layout = layout ?? TerminalLayout.instance, optionAsMeta = optionAsMeta ?? (() => (layout ?? TerminalLayout.instance).optionAsMeta), terminal = ChatShellTerminal( maxLines: (layout ?? TerminalLayout.instance).scrollback, ) { events = ChatShellTerminalEvents( terminal, quiet: () => _replaying || !_live, ); this.layout.addListener(_layoutChanged); terminal.inputHandler = CascadeInputHandler([ ChatShellInputHandler(optionAsMeta: this.optionAsMeta), defaultInputHandler, ]); _feed = ChatShellTerminalFeed(_write); // Drawn at the process's own size until a view lays it out at its own. if (run.cols > 0 && run.rows > 0) terminal.resize(run.cols, run.rows); terminal.onOutput = _output; terminal.onResize = (cols, rows, _, _) { _viewSize = (cols, rows); onResize(cols, rows); }; replay(run); } final Terminal terminal; /// The terminal preferences (text size, scrollback, bell) views follow. final TerminalLayout layout; /// The bell, clipboard and folder the program reports. late final ChatShellTerminalEvents events; /// Whether a Mac's Option key is Meta (Settings → Appearance → Terminal). final bool Function() optionAsMeta; /// The touch key row's held Ctrl and Alt, shared by every view of this /// terminal so a soft keyboard's next character takes them. It holds /// no resources, so it outlives the session's views undisposed. final ChatShellStickyModifiers modifiers = ChatShellStickyModifiers(); /// Receives what the operator types for the process; only called while /// the run is live. final void Function(String data) onInput; /// Receives the size the view laid the terminal out at. final void Function(int cols, int rows) onResize; /// Receives the emulator's automatic answers to queries in the live /// output; [onInput] receives them when this is null. final void Function(String data)? onReply; /// Receives this client's size when a view of it gains focus. final void Function(int cols, int rows)? onActivate; late final ChatShellTerminalFeed _feed; bool _live = false; bool _replaying = false; bool _drawing = false; (int, int)? _viewSize; /// The absolute output byte this terminal has drawn up to, or will once /// the output waiting in its feed is written. int get end => _feed.end; /// The absolute output byte actually drawn so far. int get drawn => _feed.drawn; /// Called with the new [drawn] end each time a chunk is drawn whole. set onDrawn(void Function(int end)? callback) => _feed.onDrawn = callback; /// Whether typing reaches a running process. bool get live => _live; /// The size a view last laid the terminal out at; null before any did. (int, int)? get viewSize => _viewSize; /// A view of this terminal gained focus: this client becomes the one the /// process is sized for and whose answers it receives. void activate() { final size = _viewSize; if (_live && size != null) onActivate?.call(size.$1, size.$2); } /// Draws [run]'s held output from scratch: on open, after a gap and after /// a readback replaced the card's copy. A machine terminal's read from /// before the server's tail is the server's snapshot /// ([ChatShellRun.snapshot]), which resets the emulator and restores the /// screens, scrollback, cursor and modes; it is drawn the same way. /// Answers the emulator gives to old queries in that output are not sent: /// the process asked them long ago. /// A large output is drawn in slices across turns of the event loop /// (ChatShellTerminalFeed), so it never stalls the UI. void replay(ChatShellRun run) { _live = run.running && run.terminal; terminal.reflowEnabled = !_live; _feed.restart(run.outputStart); _replaying = true; try { terminal.useMainBuffer(); terminal.buffer.clear(); terminal.buffer.setCursor(0, 0); // A full reset (RIS): modes a program set in the output drawn before // (mouse reporting, bracketed paste, the alternate screen) end too. terminal.write('\x1bc'); terminal.setCursorVisibleMode(true); terminal.write('\x1b[0m'); if (run.truncated) { terminal.write('\x1b[2m[earlier output was dropped]\x1b[0m\r\n'); } } finally { _replaying = false; } var output = _drawable(run, run.output); // A finished run's final newline would leave an empty line below it. if (!run.running && output.endsWith('\r\n')) { output = output.substring(0, output.length - 2); } _feed.add(output, run.outputEnd, replay: true); if (!run.running) _feed.then(() => terminal.setCursorVisibleMode(false)); } /// Draws one live chunk covering bytes [offset, end) of [run], which /// already holds it. A chunk after a hole redraws the whole held copy. void append(ChatShellRun run, String text, int offset, int end) { if (end <= _feed.end) return; if (offset != _feed.end) { replay(run); return; } _feed.add(_drawable(run, text), end); } /// The run ended: nothing typed reaches it any more. void finish(ChatShellRun run) { if (!_live) return; _live = false; terminal.reflowEnabled = true; _feed.then(() => terminal.setCursorVisibleMode(false)); } /// Stops drawing what still waits (the emulator is going away). void dispose() { layout.removeListener(_layoutChanged); events.dispose(); _feed.dispose(); } /// A changed scrollback length applies to this running terminal too. void _layoutChanged() => terminal.maxLines = layout.scrollback; /// Writes one slice. What the emulator sends while drawing live output /// answers that output (onReply); during a replay it is not sent at all. void _write(String text, bool replay) { _replaying = replay; _drawing = !replay; try { terminal.write(text); } finally { _replaying = false; _drawing = false; } } /// The rows the drawn output takes, through the cursor's line, when the /// terminal is [cols] wide: a finished run's box is sized by it before the /// view lays the terminal out, so a card never changes height after it. int rowsAt(int cols) { final buffer = terminal.buffer; final last = buffer.absoluteCursorY.clamp(0, buffer.height - 1); var rows = 0; var length = 0; void close() => rows += length <= 0 ? 1 : (length + cols - 1) ~/ cols; for (var y = 0; y <= last; y++) { final line = buffer.lines[y]; if (y > 0 && !line.isWrapped) { close(); length = 0; } // A row the next one continues is full to the terminal's width. final continued = y + 1 < buffer.height && buffer.lines[y + 1].isWrapped; length += continued ? line.length : line.getTrimmedLength(); } close(); return rows; } void _output(String data) { if (!_live || _replaying) return; final reply = onReply; if (_drawing && reply != null) { reply(data); } else { onInput(data); } } /// Plain-pipe output has bare newlines, which a terminal draws as a line /// feed without a carriage return. static String _drawable(ChatShellRun run, String text) => run.terminal ? text : text.replaceAll('\n', '\r\n'); }