import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../state.dart'; import '../storage.dart'; import 'scan_qr_screen.dart'; import '../l10n.dart'; /// The first screen: the saved servers, or the connect form. class ServersScreen extends StatefulWidget { final AppState app; /// Open the "add server" form straight away (pushed from the server sheet /// while a connection is live). final bool startEditing; const ServersScreen({super.key, required this.app, this.startEditing = false}); @override State createState() => _ServersScreenState(); } class _ServersScreenState extends State { bool _editing = false; bool _editNew = true; Connection? _edit; String _label = ''; String _url = ''; String _proxy = ''; bool _insecure = false; String _fingerprint = ''; String _password = ''; bool _connecting = false; String? _formError; // A server may ask for a password only after the first attempt; the field // is always there, but this one takes the focus when it is what is missing. final FocusNode _passwordFocus = FocusNode(); @override void initState() { super.initState(); if (widget.startEditing) _editing = true; } @override void dispose() { _passwordFocus.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return ListenableBuilder( listenable: widget.app, builder: (context, _) { if (_editing) return _form(); return _list(); }, ); } Widget _list() { final theme = Theme.of(context); final conns = widget.app.connections; return Scaffold( body: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.fromLTRB(20, 20, 20, 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ AppText('OpenChamber', style: theme.textTheme.headlineMedium ?.copyWith(fontWeight: FontWeight.bold)), const SizedBox(height: 4), AppText('Connect to your OpenChamber server', style: theme.textTheme.bodyMedium ?.copyWith(color: theme.hintColor)), ], ), ), if (widget.app.error != null) Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), child: Text(widget.app.error!, style: TextStyle(color: theme.colorScheme.error, fontSize: 13)), ), Expanded( child: ListView( padding: const EdgeInsets.all(16), children: [ for (final c in conns) _serverCard(c), const SizedBox(height: 12), Row( children: [ Expanded( child: OutlinedButton.icon( onPressed: () => _startEdit(null), icon: const Icon(Icons.add), label: const AppText('Add server'), ), ), const SizedBox(width: 8), Expanded( child: FilledButton.tonalIcon( onPressed: _pair, icon: const Icon(Icons.qr_code_2, size: 18), label: const AppText('Pairing link'), ), ), ], ), ], ), ), ], ), ), ); } Widget _serverCard(Connection c) { final theme = Theme.of(context); final connected = widget.app.conn?.id == c.id; return Card( margin: const EdgeInsets.only(bottom: 10), child: ListTile( title: Text(c.label, style: const TextStyle(fontWeight: FontWeight.w600)), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(c.isRelay ? trArgs('Via Relay · {0}', [c.serverId]) : c.url, maxLines: 1, overflow: TextOverflow.ellipsis), if (!c.isRelay && c.proxy.isNotEmpty) AppText(trArgs('Via {0}', [c.proxy]), maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: theme.hintColor)), ], ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ if (connected) AppText('Connected', style: TextStyle(color: theme.colorScheme.primary)) else TextButton(onPressed: () => _connect(c), child: const AppText('Connect')), PopupMenuButton( onSelected: (v) { if (v == 'edit') { _startEdit(c); } else if (v == 'delete') { _confirmDelete(c); } }, itemBuilder: (_) => const [ PopupMenuItem(value: 'edit', child: AppText('Edit')), PopupMenuItem(value: 'delete', child: AppText('Delete')), ], ), ], ), ), ); } void _connect(Connection c) async { setState(() { _connecting = true; _editNew = false; _edit = c; }); await widget.app.connect(c); if (mounted && widget.app.client == null && widget.app.lastError != null) { setState(() { _connecting = false; _editing = true; _edit = c; _label = c.label; _url = c.url; _proxy = c.proxy; _insecure = c.insecure; _fingerprint = c.fingerprint; _password = ''; _formError = widget.app.lastError; }); _focusPasswordIfNeeded(_formError); widget.app.clearLastError(); } else if (mounted) { setState(() => _connecting = false); } } void _startEdit(Connection? c) { widget.app.error = null; widget.app.clearLastError(); setState(() { _editing = true; _editNew = c == null; _edit = c; _label = c?.label ?? ''; _url = c?.url ?? ''; _proxy = c?.proxy ?? ''; _insecure = c?.insecure ?? false; _fingerprint = c?.fingerprint ?? ''; _password = ''; _formError = null; }); } Widget _form() { final theme = Theme.of(context); return Scaffold( appBar: AppBar( leading: IconButton( icon: const Icon(Icons.arrow_back), onPressed: () { widget.app.error = null; widget.app.clearLastError(); setState(() => _editing = false); }, ), title: AppText(_editNew ? 'Add server' : trArgs('Connect to {0}', [_edit!.label])), ), body: ListView( padding: const EdgeInsets.all(16), children: [ _labelText('Name'), TextField( controller: TextEditingController(text: _label), onChanged: (v) => _label = v, decoration: InputDecoration( hintText: tr('e.g. My computer'), border: const OutlineInputBorder()), ), const SizedBox(height: 12), if (_edit?.isRelay == true) ...[ const ListTile( contentPadding: EdgeInsets.zero, leading: Icon(Icons.lock_outline, size: 20), title: AppText('Connect through Relay'), subtitle: AppText('End-to-end encrypted; the server and device token stay the same'), ), ] else ...[ _labelText('Server address'), TextField( controller: TextEditingController(text: _url), onChanged: (v) => _url = v, keyboardType: TextInputType.url, decoration: const InputDecoration( hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()), ), const SizedBox(height: 12), _labelText('Proxy (optional)'), TextField( controller: TextEditingController(text: _proxy), onChanged: (v) => _proxy = v, keyboardType: TextInputType.url, decoration: InputDecoration( hintText: tr('http://… or socks5://…'), border: const OutlineInputBorder()), ), const SizedBox(height: 12), _labelText('Self-signed certificate fingerprint (optional)'), TextField( controller: TextEditingController(text: _fingerprint), onChanged: (v) => _fingerprint = v, decoration: InputDecoration( hintText: tr('SHA-256 hex'), border: const OutlineInputBorder()), ), SwitchListTile( contentPadding: EdgeInsets.zero, title: const AppText('Trust self-signed certificates'), value: _insecure, onChanged: (v) => setState(() => _insecure = v), ), // Shown for new servers too: a password-protected instance rejects // the first attempt, and this is where the password goes. _labelText('Password (if required)'), TextField( controller: TextEditingController(text: _password), focusNode: _passwordFocus, onChanged: (v) => _password = v, obscureText: true, decoration: InputDecoration( hintText: tr('Server password; leave empty if the server has none'), border: const OutlineInputBorder()), ), ], if (_formError != null) Padding( padding: const EdgeInsets.only(top: 8), child: Text(_formError!, style: TextStyle(color: theme.colorScheme.error)), ), const SizedBox(height: 16), FilledButton( onPressed: _connecting ? null : _submit, child: _connecting ? const SizedBox( height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2)) : const AppText('Connect'), ), ], ), ); } Widget _labelText(String s) => Padding( padding: const EdgeInsets.only(bottom: 4), child: AppText(s, style: Theme.of(context).textTheme.bodySmall), ); Future _submit() async { setState(() { _connecting = true; _formError = null; }); final relay = _edit?.isRelay == true ? _edit : null; final c = relay != null ? relay.copyWith( label: _label.isEmpty ? relay.label : _label, lastUsedAt: DateTime.now().millisecondsSinceEpoch, ) : Connection( id: _edit?.id ?? Storage.newId(), label: _label.isEmpty ? _hostOf(_url) : _label, url: _url, proxy: _proxy, insecure: _insecure, fingerprint: _fingerprint, ); // Only a connection that works is saved (AppState saves it on success), // so failed attempts do not pile up in the server list. await widget.app.connect(c, password: _password); if (mounted) { if (widget.app.client != null) { setState(() => _editing = false); // Pushed on top of a live session list: return there. if (Navigator.of(context).canPop()) Navigator.of(context).pop(); } else { setState(() { _connecting = false; _formError = widget.app.lastError; }); _focusPasswordIfNeeded(_formError); widget.app.clearLastError(); } } } /// The server asked for a password: put the caret where it is typed. void _focusPasswordIfNeeded(String? message) { // The message is already in the UI's language; look for the same word. if (message == null || !message.contains(tr('Password'))) return; WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) _passwordFocus.requestFocus(); }); } void _pair() { widget.app.error = null; widget.app.clearLastError(); showPairingDialog(context, widget.app); } void _confirmDelete(Connection c) { showDialog( context: context, builder: (context) => AlertDialog( title: const AppText('Delete server?'), content: AppText(trArgs('“{0}” will be removed from the list, and its device token will be deleted.', [c.label])), actions: [ TextButton(onPressed: () => Navigator.pop(context), child: const AppText('Cancel')), FilledButton( onPressed: () { Navigator.pop(context); widget.app.removeConnection(c); }, child: const AppText('Delete'), ), ], ), ); } static String _hostOf(String raw) { try { return Uri.parse(raw).host; } catch (_) { return raw; } } } /// Opens the paste-a-pairing-link dialog (also reachable from the connected /// sidebar's server sheet). Future showPairingDialog(BuildContext context, AppState app) { app.error = null; app.clearLastError(); return showDialog( context: context, builder: (_) => _PairingDialog(app: app), ); } /// Paste an `openchamber://connect` link and pair. The relay candidate in the /// link is used when no direct address answers. class _PairingDialog extends StatefulWidget { final AppState app; const _PairingDialog({required this.app}); @override State<_PairingDialog> createState() => _PairingDialogState(); } class _PairingDialogState extends State<_PairingDialog> { final TextEditingController _text = TextEditingController(); bool _busy = false; String? _error; @override void dispose() { _text.dispose(); super.dispose(); } Future _scan() async { final text = await scanPairingQr(context); if (!mounted || text == null) return; setState(() => _text.text = text); // A scan is an explicit "connect these": do not make the person press // another button after pointing the camera at the code. await _connect(); } Future _paste() async { final data = await Clipboard.getData(Clipboard.kTextPlain); final text = data?.text?.trim() ?? ''; if (text.isEmpty || !mounted) return; setState(() => _text.text = text); } Future _connect() async { final link = _text.text.trim(); if (link.isEmpty || _busy) return; setState(() { _busy = true; _error = null; }); final paired = await widget.app.connectWithPairing(link); if (!mounted) return; if (paired && widget.app.client != null) { Navigator.of(context).pop(); return; } setState(() { _busy = false; _error = widget.app.lastError ?? tr('Pairing failed'); }); widget.app.clearLastError(); } @override Widget build(BuildContext context) { final theme = Theme.of(context); return AlertDialog( title: const AppText('Pairing link'), content: SizedBox( width: 420, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ AppText( 'In the OpenChamber web app, open “Connect a device”, then paste the link or scan the QR code. The link carries a one-time key and either a direct address or a private Relay.', style: TextStyle(fontSize: 12.5, color: theme.hintColor), ), const SizedBox(height: 12), TextField( controller: _text, autofocus: true, minLines: 2, maxLines: 4, keyboardType: TextInputType.multiline, style: const TextStyle(fontFamily: 'monospace', fontSize: 12), decoration: const InputDecoration( hintText: 'openchamber://connect?v=2&p=…', border: OutlineInputBorder(), ), ), if (_error != null) Padding( padding: const EdgeInsets.only(top: 8), child: Text(_error!, style: TextStyle(color: theme.colorScheme.error, fontSize: 12.5)), ), Row( children: [ TextButton.icon( onPressed: _busy ? null : _scan, icon: const Icon(Icons.qr_code_scanner, size: 18), label: const AppText('Scan QR code'), ), const SizedBox(width: 4), TextButton.icon( onPressed: _busy ? null : _paste, icon: const Icon(Icons.content_paste, size: 18), label: const AppText('Paste'), ), ], ), ], ), ), actions: [ TextButton( onPressed: _busy ? null : () => Navigator.of(context).pop(), child: const AppText('Cancel'), ), FilledButton( onPressed: _busy ? null : _connect, child: _busy ? const SizedBox( width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2)) : const AppText('Pair and connect'), ), ], ); } }