// The live terminal: the xterm model the view renders, and the socket that // carries its bytes. A directory can hold several tabs; the workspace keeps // them and owns which one is attached, so closing the panel (or switching // tabs) does not end the shells — reattaching replays the server's snapshot. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:xterm/xterm.dart'; import 'api/terminal.dart'; import 'state.dart'; import 'storage.dart'; /// One terminal tab. [state] holds the model and the socket; the label is the /// local name ("终端 1") the dropdown shows. class TerminalTab { final TerminalSessionState state; String label; TerminalTab(this.state, this.label); } /// A tab before its state exists: [id] is the server session when the tab is /// restored, null when it is about to be created. class TerminalTabPlan { final String? id; final String label; const TerminalTabPlan({this.id, required this.label}); } /// Every terminal tab of one working directory, and which one is showing. class TerminalWorkspace extends ChangeNotifier { final AppState app; final String directory; final List tabs = []; int activeIndex = 0; bool _loaded = false; bool _disposed = false; TerminalWorkspace(this.app, this.directory); TerminalTab? get activeTab => tabs.isEmpty ? null : tabs[activeIndex.clamp(0, tabs.length - 1)]; String get _connectionId => app.conn?.id ?? ''; /// Opens the workspace on first use: the saved tabs and the server's sessions /// for this directory are reconciled, then the active tab attaches. Later /// calls just make sure its socket is alive. Future ensureOpen() async { if (_disposed) return; if (_loaded) { await activeTab?.state.ensureOpen(); return; } _loaded = true; await _load(); } Future _load() async { final saved = await _savedTabs(); final server = await _serverTabs(); final plans = planTabs(saved: saved?.tabs ?? const [], server: server); await _applyPlans(plans, activeId: saved?.activeId); await activeTab?.state.ensureOpen(); } /// Tabs to show, given what was saved locally and what the server holds for /// the directory. A saved tab whose session is gone is dropped; sessions /// from elsewhere (the web UI, another phone) become tabs of their own. static List planTabs({ required List saved, required List? server, }) { final plans = []; String label() => freeLabel(plans.map((p) => p.label)); if (server == null) { // The listing failed: trust what was saved, and let the attach path // report a dead id. for (final tab in saved) { plans.add(TerminalTabPlan(id: tab.id, label: tab.label)); } if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const []))); return plans; } // Project-action command runners are PTYs too, but they are not the // person's terminal tabs. final sessions = [ for (final s in server) if (s.interactive) s, ]; final byId = {for (final s in sessions) s.sessionId: s}; final seen = {}; for (final tab in saved) { if (!byId.containsKey(tab.id) || !seen.add(tab.id)) continue; plans.add(TerminalTabPlan(id: tab.id, label: tab.label)); } final rest = [ for (final s in sessions) if (s.sessionId.isNotEmpty && !seen.contains(s.sessionId)) s, ]..sort((a, b) => (a.createdAt ?? 0).compareTo(b.createdAt ?? 0)); for (final session in rest) { if (!seen.add(session.sessionId)) continue; plans.add(TerminalTabPlan(id: session.sessionId, label: label())); } if (plans.isEmpty) plans.add(TerminalTabPlan(label: freeLabel(const []))); return plans; } /// The first free "终端 N" among [labels], so closing a tab makes its number /// available again. static String freeLabel(Iterable labels) { final used = {}; for (final label in labels) { final match = RegExp(r'^终端 (\d+)$').firstMatch(label.trim()); if (match != null) used.add(int.parse(match.group(1)!)); } var n = 1; while (used.contains(n)) { n++; } return '终端 $n'; } Future _savedTabs() async { final connection = _connectionId; if (connection.isEmpty) return null; return app.storage.terminalTabs(connection, directory); } /// The interactive terminals the server holds for this directory, or null /// when the listing failed (then the saved tabs are kept as they are). Future?> _serverTabs() async { final client = app.client; if (client == null) return null; try { final all = await client.listTerminals(cwd: directory); return [ for (final session in all) if (session.interactive) session, ]; } catch (_) { return null; } } Future _applyPlans(List plans, {String? activeId}) async { final reuse = {}; for (final tab in tabs) { final id = tab.state.sessionId; if (id != null) reuse[id] = tab; } final next = []; for (final plan in plans) { final existing = plan.id == null ? null : reuse[plan.id]; final state = existing?.state ?? TerminalSessionState(app, directory, onSessionIdChanged: _persistLater); if (plan.id != null) state.sessionId = plan.id; next.add(TerminalTab(state, plan.label)); } for (final tab in tabs) { if (!next.any((entry) => entry.state == tab.state)) tab.state.dispose(); } tabs ..clear() ..addAll(next); final match = activeId == null ? -1 : tabs.indexWhere((tab) => tab.state.sessionId == activeId); activeIndex = match >= 0 ? match : tabs.length - 1; notifyListeners(); await _persist(); } void _persistLater() { unawaited(_persist()); } Future _persist() async { final connection = _connectionId; if (connection.isEmpty || _disposed) return; final saved = [ for (final tab in tabs) if (tab.state.sessionId case final id?) SavedTerminalTab(id, tab.label), ]; if (saved.isEmpty) { await app.storage.clearTerminalTabs(connection, directory); return; } await app.storage.saveTerminalTabs(connection, directory, SavedTerminalTabs(saved, activeTab?.state.sessionId)); } /// Switches tabs: the old one detaches (its shell stays on the server) and /// the new one attaches or is created. Future select(int index) async { if (_disposed || tabs.isEmpty) return; index = index.clamp(0, tabs.length - 1); if (index == activeIndex) return; final previous = activeTab; activeIndex = index; notifyListeners(); await previous?.state.detach(); await activeTab?.state.ensureOpen(); await _persist(); } /// Adds an empty tab and shows it; its shell is created on open. Future addTab() async { if (_disposed) return; final previous = activeTab; final state = TerminalSessionState(app, directory, onSessionIdChanged: _persistLater); tabs.add(TerminalTab(state, freeLabel(tabs.map((tab) => tab.label)))); activeIndex = tabs.length - 1; notifyListeners(); await previous?.state.detach(); await state.ensureOpen(); await _persist(); } /// Closes the active tab on the server and in the list; when it was the last /// one, a fresh tab takes its place so the panel stays usable. Future closeActive() async { if (_disposed || tabs.isEmpty) return; final closing = tabs.removeAt(activeIndex.clamp(0, tabs.length - 1)); if (tabs.isEmpty) { final state = TerminalSessionState(app, directory, onSessionIdChanged: _persistLater); tabs.add(TerminalTab(state, freeLabel(const []))); activeIndex = 0; } else { activeIndex = activeIndex.clamp(0, tabs.length - 1); } notifyListeners(); await closing.state.closeSession(); closing.state.dispose(); await activeTab?.state.ensureOpen(); await _persist(); } /// Ends every shell and forgets the directory's tabs (an explicit /// disconnect, not the panel closing). Future closeAll() async { final connection = _connectionId; for (final tab in List.of(tabs)) { await tab.state.closeSession(); tab.state.dispose(); } tabs.clear(); _loaded = false; if (connection.isNotEmpty) { await app.storage.clearTerminalTabs(connection, directory); } notifyListeners(); } /// After the app returns from the background: the socket may be dead /// without having reported it. Future reconnectIfNeeded() async { await activeTab?.state.reconnectIfNeeded(); } @override void dispose() { _disposed = true; for (final tab in tabs) { tab.state.dispose(); } super.dispose(); } } class TerminalSessionState extends ChangeNotifier { final AppState app; final String directory; /// Called when [sessionId] changes (created, replaced, cleared), so the /// workspace can save its tab list. final VoidCallback? onSessionIdChanged; final Terminal model = Terminal(maxLines: 5000); TerminalSocket? _socket; TerminalLinkState link = TerminalLinkState.idle; String? detail; String? sessionId; /// Key-bar modifiers. They apply to the next character, whichever keyboard /// produced it: the on-screen bar or the phone's IME (which never sends /// Ctrl itself). bool ctrl = false; bool alt = false; bool shift = false; int _cols = 80; int _rows = 24; Timer? _resizeTimer; bool _opened = false; bool _disposed = false; bool _recovering = false; TerminalSessionState(this.app, this.directory, {this.onSessionIdChanged}) { model.onOutput = _onOutput; model.onResize = (cols, rows, _, __) { _cols = cols; _rows = rows; _scheduleResize(); }; } bool get isOpen => link == TerminalLinkState.open; bool get isRunning => link == TerminalLinkState.open || link == TerminalLinkState.connecting; /// Attaches to the tab's session, or creates one when the tab has none yet. Future ensureOpen() async { if (_disposed) return; if (!_opened) { _opened = true; if (sessionId == null) { await _create(); } else { await _attach(); } return; } if (_socket == null && link != TerminalLinkState.exited) await _attach(); } /// Drops the socket without ending the shell; [ensureOpen] attaches again. Future detach() async { await _socket?.dispose(); _socket = null; } void toggleCtrl() { ctrl = !ctrl; notifyListeners(); } void toggleAlt() { alt = !alt; notifyListeners(); } void toggleShift() { shift = !shift; notifyListeners(); } /// Sends one typed character, with whatever modifiers are pending, then /// drops them. Escape sequences (arrows, Home, …) arrive already complete /// and pass through untouched. void _onOutput(String data) { var out = data; if (out.isNotEmpty) { final code = out.codeUnitAt(0); final printable = out.length == 1 && code >= 0x20 && code != 0x7f; if (printable && ctrl) { if (code >= 0x61 && code <= 0x7a) { out = String.fromCharCode(code - 0x60); } else if (code >= 0x41 && code <= 0x5a) { out = String.fromCharCode(code - 0x40); } else if (code >= 0x5b && code <= 0x5f) { out = String.fromCharCode(code - 0x40); } else if (code == 0x20) { out = '\x00'; } } // Alt is an ESC prefix on the character. if (printable && alt) out = '\x1b$out'; } _socket?.write(out); if ((ctrl || alt || shift) && out.isNotEmpty) { ctrl = false; alt = false; shift = false; notifyListeners(); } } Future _create() async { final client = app.client; if (client == null) return; _set(TerminalLinkState.creating); try { final info = await client.createTerminal( cwd: directory, cols: _cols, rows: _rows); if (_disposed) return; sessionId = info.sessionId; _cols = info.cols; _rows = info.rows; onSessionIdChanged?.call(); await _attach(); } catch (error) { _set(TerminalLinkState.error, detail: _message(error)); } } Future _attach() async { final client = app.client; final id = sessionId; if (client == null || id == null || _disposed) return; await _socket?.dispose(); final socket = TerminalSocket( transport: client.transport, headers: client.eventHeaders, sessionId: id, onEvent: _onEvent, onState: (state, {detail}) => _set(state, detail: detail), ); _socket = socket; await socket.connect(); } void _onEvent(TerminalEvent event) { if (_disposed) return; switch (event.type) { case 'snapshot': // Replay at the size the server drew the history for, then clear what // this view already had: a reattach must not duplicate the screen. if (event.cols != null && event.rows != null) { model.resize(event.cols!, event.rows!); } _clear(); if (event.data.isNotEmpty) model.write(event.data); if (event.status == 'exited') { _set(TerminalLinkState.exited, detail: event.exitCode == null ? '已退出' : '退出码 ${event.exitCode}'); } break; case 'restarted': _clear(); if (event.data.isNotEmpty) model.write(event.data); _set(TerminalLinkState.open); break; case 'output': model.write(event.data); break; case 'exit': _set(TerminalLinkState.exited, detail: event.exitCode == null ? '已退出' : '退出码 ${event.exitCode}'); break; case 'error': if (event.fatal) { if (event.code == 'SESSION_NOT_FOUND') { // The remembered id outlived the server's session (a server // restart, or the idle reaper won a race with the attach): open a // new shell instead of leaving a dead panel. _recoverMissing(); } else { _set(TerminalLinkState.error, detail: event.message ?? event.code ?? '终端连接失败'); } } break; } } /// Clears the screen and the scrollback, then homes the cursor. void _clear() => model.write('\x1b[2J\x1b[3J\x1b[H'); void _set(TerminalLinkState state, {String? detail}) { link = state; if (detail != null) this.detail = detail; if (state == TerminalLinkState.open) this.detail = null; notifyListeners(); } void _scheduleResize() { _resizeTimer?.cancel(); _resizeTimer = Timer(const Duration(milliseconds: 250), () { final client = app.client; final id = sessionId; if (client == null || id == null || _disposed) return; client .resizeTerminal(id, _cols, _rows, directory: directory) .catchError((_) {}); }); } /// Restarts the shell in place (the server keeps the session id). Future restart() async { final client = app.client; final id = sessionId; if (client == null || id == null) return; _set(TerminalLinkState.connecting); try { await client.restartTerminal(id, cwd: directory, cols: _cols, rows: _rows); if (_disposed) return; _clear(); _set(TerminalLinkState.open); } catch (error) { _set(TerminalLinkState.error, detail: _message(error)); } } /// After the app returns from the background: the socket may be dead /// without having reported it. Future reconnectIfNeeded() async { if (_disposed) return; if (link == TerminalLinkState.exited || link == TerminalLinkState.error) { return; } if (_socket == null) await _attach(); } /// Ends the shell on the server and drops the socket. Future closeSession() async { final client = app.client; final id = sessionId; sessionId = null; _opened = false; link = TerminalLinkState.idle; detail = null; onSessionIdChanged?.call(); await _socket?.dispose(); _socket = null; if (!_disposed) notifyListeners(); if (client != null && id != null) { try { await client.closeTerminal(id, directory: directory); } catch (_) {} } } /// Drops a session the server no longer has and opens another one in its /// place, so a stale id does not leave the tab unusable. Future _recoverMissing() async { if (_recovering || _disposed) return; _recovering = true; try { sessionId = null; onSessionIdChanged?.call(); await _socket?.dispose(); _socket = null; if (_disposed) return; _opened = true; await _create(); } finally { _recovering = false; } } @override void dispose() { _disposed = true; _resizeTimer?.cancel(); _socket?.dispose(); _socket = null; // The session is left for the server's idle reaper when the app goes // away; [closeSession] handles an explicit disconnect. super.dispose(); } String _message(Object error) { final text = '$error'; return text.startsWith('ApiError') ? text : text; } }