import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:xterm/core.dart'; /// What a terminal's program asks of the app beyond drawing: the bell /// (BEL), setting the clipboard (OSC 52) and reporting its working folder /// (OSC 7). Old output drawn again (a replay) asks for nothing: [quiet] is /// true then, so a reload neither rings nor overwrites the clipboard. class ChatShellTerminalEvents { ChatShellTerminalEvents(this.terminal, {required this.quiet}) { terminal ..onBell = _bell ..onClipboardSet = _clipboard ..onWorkingDirectoryChange = _directory; } final Terminal terminal; final bool Function() quiet; /// Counts the bells rung by live output. final ValueNotifier bells = ValueNotifier(0); /// The folder the program last reported (OSC 7), as a path; null before. final ValueNotifier workingDirectory = ValueNotifier(null); /// How many views draw this terminal now: a bell while none does dots the /// terminal's tab. final ValueNotifier viewers = ValueNotifier(0); final List _toasts = []; bool _disposed = false; /// A view shows "Copied from terminal" with [toast] while it is the most /// recently attached one; [detach] undoes both. void attach(void Function(String text) toast) { _toasts.add(toast); viewers.value++; } /// A view may outlive the session by a frame (the tab closed first). void detach(void Function(String text) toast) { _toasts.remove(toast); if (!_disposed) viewers.value--; } void _bell() { if (!quiet()) bells.value++; } /// Only setting is supported (the emulator never reads the clipboard for /// the program). An empty text clears nothing. void _clipboard(String text, String selection) { if (quiet() || text.isEmpty) return; Clipboard.setData(ClipboardData(text: text)); if (_toasts.isNotEmpty) _toasts.last(text); } void _directory(String uri) { final path = chatShellWorkingDirectoryPath(uri); if (path != null) workingDirectory.value = path; } void dispose() { _disposed = true; terminal ..onBell = null ..onClipboardSet = null ..onWorkingDirectoryChange = null; bells.dispose(); workingDirectory.dispose(); viewers.dispose(); } } /// The path of an OSC 7 `file://host/path` report (percent-decoded), or /// null when it is not a file URI with a path. String? chatShellWorkingDirectoryPath(String uri) { final parsed = Uri.tryParse(uri.trim()); if (parsed == null || parsed.scheme != 'file') return null; final String path; try { path = Uri.decodeComponent(parsed.path); } on ArgumentError { return null; } return path.isEmpty ? null : path; }