import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../core/transport/pipelines_client.dart' as transport; import '../../core/transport/server_url.dart'; import 'settings_copy.dart'; import 'settings_store.dart'; /// The ping request the status card makes once per connection. The default is /// the shared client's own `ping` request; tests inject a recorded callback. typedef PingCallback = Future> Function(); /// The integer wire protocol this app speaks. Mirrors `PROTOCOL_VERSION` in /// `web/src/protocol.js` and `ProtocolVersion` in `internal/protocol/identity.go`. const int clientProtocolVersion = 1; /// The warning naming both values when the last `pong` reported a different /// protocol. A server that omits the field (an older build) is never flagged, /// and the values are compared as numbers, never as strings — the web's /// `protocolMismatch` rule. String? protocolMismatchWarning(num? serverProtocol) { if (serverProtocol == null) return null; if (serverProtocol == clientProtocolVersion) return null; return 'Protocol mismatch: this page speaks protocol ' '$clientProtocolVersion, the server reports $serverProtocol.'; } /// Owns the Settings screen's draft text, validation and the actions that drive /// the shared [transport.PipelinesClient]. /// /// The feature never owns the client: it subscribes to the client's state and /// calls connect/disconnect, but never calls `dispose()` on it, and it never /// opens a connection by itself. One controller is created per screen, not per /// rebuild, so rebuilding Settings cannot start a second connection. class SettingsController extends ChangeNotifier { SettingsController({ required this.client, required this.store, this.initialEndpoint, String defaultEndpoint = '', PingCallback? ping, }) : _defaultServerUrl = defaultEndpoint, _ping = ping ?? (() => client.call('ping')), _connection = client.state { _lastKind = _connection.kind; _subscription = client.states.listen(_onConnectionState); // Details belong to the current socket, not to the preferences read. // Mark them pending before the first frame when opening Settings live. if (_connection.kind == transport.ConnectionKind.connected) _requestPing(); } final transport.PipelinesClient client; final SettingsStore store; final Uri? initialEndpoint; final String _defaultServerUrl; final PingCallback _ping; late final StreamSubscription _subscription; transport.ConnectionState _connection; transport.ConnectionKind _lastKind = transport.ConnectionKind.idle; String _serverUrl = ''; String _urlError = ''; String _workspaceDraft = ''; String _savedWorkspace = ''; String _workspaceSaveError = ''; String _endpointSaveError = ''; String _actionError = ''; String _buildVersion = ''; String _buildCommit = ''; String _serverTime = ''; num? _serverProtocol; String _pingError = ''; bool _pingInFlight = false; bool _pingRequestedForConnected = false; int _pingToken = 0; bool _initialized = false; bool _serverUrlEdited = false; bool _workspaceEdited = false; bool _disposed = false; transport.ConnectionState get connection => _connection; String get serverUrl => _serverUrl; String get urlError => _urlError; String get workspaceDraft => _workspaceDraft; String get savedWorkspace => _savedWorkspace; String get workspaceError => validateWorkspacePath(_workspaceDraft) ?? ''; String get workspaceSaveError => _workspaceSaveError; String get endpointSaveError => _endpointSaveError; String get actionError => _actionError; String get buildVersion => _buildVersion; String get buildCommit => _buildCommit; String get serverTime => _serverTime; /// The warning for a last `pong` whose protocol differs from this app's. /// The last reported value is kept across a drop (as the web Settings page /// keeps `serverProtocol`), so a foreground reconnect cannot hide a known /// mismatch while the new socket is still connecting. String? get protocolWarning => protocolMismatchWarning(_serverProtocol); String get pingError => _pingError; bool get pingInFlight => _pingInFlight; bool get connectionActive => _connection.kind == transport.ConnectionKind.connected || _connection.kind == transport.ConnectionKind.connecting; String get primaryActionLabel => connectionActive ? 'Disconnect' : 'Connect'; /// Connecting again to the URL in the field; while connected that is a /// reconnect, so it never reads `Connect` beside `Disconnect`. String get secondaryActionLabel => 'Reconnect'; List get connectionLines => connectionCardLines( _connection, buildVersion: _buildVersion, buildCommit: _buildCommit, serverTime: _serverTime, pingError: _pingError, pingInFlight: _pingInFlight, ); /// Reads the feature's own persisted values once. A draft the operator has /// already typed into is never overwritten by the asynchronous read. Future initialize() async { if (_initialized) return; _initialized = true; final values = await store.load(); if (_disposed) return; if (!_serverUrlEdited) { final saved = values.serverUrl.trim(); _serverUrl = initialEndpoint?.toString() ?? (saved.isNotEmpty ? saved : _defaultServerUrl); } if (!_workspaceEdited) { _workspaceDraft = values.workspace; _savedWorkspace = values.workspace.trim(); } // The screen may be opened while the shared client is already connected; // find out what that server is. This never opens a connection. if (_connection.kind == transport.ConnectionKind.connected) _requestPing(); _notify(); } void updateServerUrl(String value) { _serverUrlEdited = true; _serverUrl = value; _urlError = ''; _actionError = ''; _notify(); } void updateWorkspace(String value) { _workspaceEdited = true; _workspaceDraft = value; _workspaceSaveError = ''; _notify(); } /// Validates the draft, persists the endpoint and connects the shared client. /// An invalid draft names the problem on the field and touches no socket. Future connect() async { final raw = _serverUrl; String wsUrl; try { wsUrl = ServerUrl.validate(raw).wsUrl; } on FormatException catch (error) { _urlError = error.message.toString(); _notify(); return; } _urlError = ''; _actionError = ''; if (_serverUrl != wsUrl) _serverUrl = wsUrl; final stored = await store.saveServerUrl(wsUrl); if (_disposed) return; _endpointSaveError = stored ? '' : 'The server URL could not be saved; it applies to this session only.'; _notify(); try { await client.connect(Uri.parse(wsUrl)); } catch (error) { if (_disposed) return; _actionError = 'Could not connect: ${_describe(error)}'; _notify(); } } /// Re-opening the validated endpoint is the same client operation as /// connecting; only the label differs, matching the web/Android settings. Future reconnect() => connect(); /// Closes this screen's connection through the shared client. It never /// disposes the client: other features keep using the same instance. Future disconnect() async { _actionError = ''; try { await client.disconnect(); } catch (error) { if (_disposed) return; _actionError = 'Could not disconnect: ${_describe(error)}'; } if (!_disposed) _notify(); } /// Persists the trimmed absolute workspace. Only a stored value updates the /// `Saved workspace:` line; a failed write says so instead of claiming one. Future saveWorkspace() async { if (!canSaveWorkspace(_workspaceDraft)) { _notify(); return; } final value = _workspaceDraft.trim(); final stored = await store.saveWorkspace(value); if (_disposed) return; _workspaceDraft = value; if (stored) { _savedWorkspace = value; _workspaceSaveError = ''; } else { _workspaceSaveError = 'The workspace could not be saved; it is not stored on this device.'; } _notify(); } void _onConnectionState(transport.ConnectionState state) { if (_disposed) return; final previous = _lastKind; _connection = state; _lastKind = state.kind; if (state.kind == transport.ConnectionKind.connected) { _requestPing(); } else { // Never keep one server's build/time while another connection, or no // connection, is being shown. _clearPingDetails(); if (previous == transport.ConnectionKind.connected) _pingToken++; } _notify(); } void _requestPing() { if (_disposed || _pingRequestedForConnected) return; _pingRequestedForConnected = true; _pingError = ''; _pingInFlight = true; final token = ++_pingToken; unawaited(_runPing(token)); } Future _runPing(int token) async { try { final reply = await _ping(); if (!_isCurrentPing(token)) return; final build = reply['build']; _buildVersion = build is Map ? '${build['version'] ?? ''}'.trim() : '${build ?? ''}'.trim(); _buildCommit = build is Map ? '${build['commit'] ?? ''}'.trim() : ''; _serverTime = '${reply['time'] ?? ''}'.trim(); _serverProtocol = _reportedProtocol(reply['protocol']); _pingError = ''; } catch (error) { if (!_isCurrentPing(token)) return; _pingError = 'Server details unavailable: ${_describe(error)}'; } finally { if (_isCurrentPing(token)) { _pingInFlight = false; _notify(); } } } bool _isCurrentPing(int token) => !_disposed && token == _pingToken && _pingRequestedForConnected; /// The `pong.protocol` value as the number the comparison needs. A missing, /// blank or non-numeric value is absent — never coerced to zero, which would /// invent a mismatch. num? _reportedProtocol(Object? value) { if (value is num) return value; final text = '${value ?? ''}'.trim(); if (text.isEmpty) return null; return num.tryParse(text); } void _clearPingDetails() { _pingRequestedForConnected = false; _pingInFlight = false; _pingError = ''; _buildVersion = ''; _buildCommit = ''; _serverTime = ''; // _serverProtocol is deliberately retained: it belongs to the server the // last pong described, and its warning must stay visible through the // reconnect the app performs when it returns to the foreground. } String _describe(Object error) { final text = error.toString().trim(); return text.isEmpty ? 'unknown error' : text; } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { if (_disposed) return; _disposed = true; _pingToken++; _subscription.cancel(); // The shared client outlives this screen; it is deliberately not disposed. super.dispose(); } }