import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../core/api_gateway.dart'; import 'terminal_info.dart'; import 'terminal_listing.dart'; import 'terminal_machines.dart'; import 'terminal_tab.dart'; /// Every machine terminal the app shows, across the connected machines: /// the tabs, the selected one, and their link to each machine's socket. /// /// The hub belongs to the app, not to a view: terminals keep running and /// keep their output while the panel is hidden or the window is minimised. /// When a machine connects (first, or again after a drop or a server /// restart) its terminals are listed, new ones get a tab, and every tab /// resumes its output from the last byte it holds. class TerminalHub extends ChangeNotifier { TerminalHub(this.machines); final TerminalMachines machines; final Map _links = {}; bool _active = false; final List _tabs = []; String? _selected; bool _disposed = false; /// The last refusal of an open or close, in the server's words. String? error; /// Whether this app run has had its first terminal: the first time the /// terminal is shown it starts one (`openTerminalIfNone`), later shows /// only show it. Opening one by hand counts. bool firstOpenDone = false; /// The first show's start, while it runs. Future? firstOpening; List get tabs => List.unmodifiable(_tabs); List get connected => machines.value; TerminalTab? get selected => _tabs.where((tab) => tab.key == _selected).firstOrNull ?? _tabs.firstOrNull; /// Whether the tabs come from more than one machine (or more than one /// is connected), so each names its machine. bool get multiMachine => connected.length > 1 || _tabs.map((tab) => tab.machineId).toSet().length > 1; /// Starts following the machines: their terminals are listed now and on /// every reconnect. The surface calls it the first time the terminal is /// shown, so an app that never shows it sends no terminal requests (each /// connection sends one request at a time; the first screen's read goes /// first). void activate() { if (_active || _disposed) return; _active = true; machines.addListener(_machinesChanged); _machinesChanged(); } bool get active => _active; void select(TerminalTab tab) { if (_selected == tab.key) return; _selected = tab.key; _notify(); } /// Selects the tab [step] places after the selected one, wrapping round. void step(int step) { final current = selected; if (current == null) return; final index = _tabs.indexOf(current); select(_tabs[(index + step) % _tabs.length]); } final TerminalListing _listing = TerminalListing(); /// Completes once no machine's terminal list is still being read. Future listed() => _listing.idle(); /// The machine [gateway] belongs to, if it is connected. TerminalMachine? machineFor(String? id) => connected.where((machine) => machine.id == id).firstOrNull; /// Opens a terminal on [machineId] (the first connected machine when /// null) and selects its tab: it shows that machine's login prompt, and /// after the password the shell starts in [cwd] (home when empty). /// Returns the refusal. Future open({String? machineId, String cwd = ''}) async { activate(); final machine = machineId == null ? connected.firstOrNull : machineFor(machineId); if (machine == null) { return error = 'No machine is connected to open a terminal on.'; } try { final reply = await machine.gateway.call('terminal_open', { 'terminal_request': {'cwd': ?(cwd.isEmpty ? null : cwd)}, }); final record = reply['terminal']; if (record is! Map) throw StateError('The server sent no terminal.'); final tab = _adopt(machine, TerminalInfo.fromJson(record)); firstOpenDone = true; _selected = tab.key; error = null; _notify(); return null; } catch (failure) { error = '$failure'; _notify(); return error; } } /// Ends [tab]'s login or shell and removes the tab. A tab /// whose machine is not connected cannot be closed yet. Future close(TerminalTab tab) async { if (!tab.connected) { return error = '${tab.machineName} is not connected.'; } try { await tab.gateway.call('terminal_close', { 'terminal_request': {'terminal_id': tab.info.id}, }); _remove(tab.key); error = null; return null; } catch (failure) { error = '$failure'; _notify(); return error; } } TerminalTab _adopt(TerminalMachine machine, TerminalInfo info) { final key = terminalKey(machine.id, info.id); final existing = _tabs.where((tab) => tab.key == key).firstOrNull; if (existing != null) { existing.machineName = machine.name; existing.attach(machine.gateway, info); return existing; } final tab = TerminalTab( machineId: machine.id, machineName: machine.name, gateway: machine.gateway, info: info, )..addListener(_notify); _tabs.add(tab); unawaited(tab.resume()); return tab; } void _remove(String key) { final index = _tabs.indexWhere((tab) => tab.key == key); if (index < 0) return; final tab = _tabs.removeAt(index); if (_selected == key) { _selected = _tabs.isEmpty ? null : _tabs[index.clamp(0, _tabs.length - 1)].key; } tab ..removeListener(_notify) ..dispose(); _notify(); } void _machinesChanged() { if (_disposed) return; final ids = {for (final machine in connected) machine.id}; for (final id in _links.keys.where((id) => !ids.contains(id)).toList()) { _links.remove(id)!.cancel(); for (final tab in _tabs.where((tab) => tab.machineId == id)) { tab.disconnected(); } } for (final machine in connected) { final link = _links[machine.id]; if (link != null && identical(link.gateway, machine.gateway)) continue; link?.cancel(); _links[machine.id] = _Link( machine.gateway, machine.gateway.frames.listen((frame) => _frame(machine, frame)), ); unawaited(_sync(machine)); } _notify(); } /// Lists [machine]'s terminals: each gets (or keeps) a tab, which then /// resumes its output; tabs of terminals the machine no longer has go. Future _sync(TerminalMachine machine) => _listing.track(() => _list(machine)); Future _list(TerminalMachine machine) async { final List infos; try { infos = terminalInfos(await machine.gateway.call('terminal_list')); } catch (failure) { // A server without terminals answers with an error; its tabs stay. error = '$failure'; _notify(); return; } if (_disposed || !identical(_links[machine.id]?.gateway, machine.gateway)) { return; } final listed = {}; for (final info in infos.where((info) => !info.closed)) { listed.add(_adopt(machine, info).key); } for (final tab in _tabs.toList()) { if (tab.machineId == machine.id && !listed.contains(tab.key)) { _remove(tab.key); } } _notify(); } void _frame(TerminalMachine machine, JsonMap frame) { if (frame['type'] != 'terminal_event') return; final event = frame['terminal_event']; if (event is! Map) return; final key = terminalKey(machine.id, '${event['terminal_id'] ?? ''}'); final record = event['terminal']; if (record is Map) { final info = TerminalInfo.fromJson(record); if (info.closed) return _remove(key); // A terminal another client opened appears here too. if (!_tabs.any((tab) => tab.key == key)) { _adopt(machine, info); _notify(); return; } } _tabs.where((tab) => tab.key == key).firstOrNull?.frame(event); } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; if (_active) machines.removeListener(_machinesChanged); for (final link in _links.values) { link.cancel(); } for (final tab in _tabs) { tab.dispose(); } super.dispose(); } } class _Link { _Link(this.gateway, this.frames); final ApiGateway gateway; final StreamSubscription frames; void cancel() => unawaited(frames.cancel()); }