2026-11-18 19:08:06 +08:00
import 'package:flutter/material.dart' ;
2026-11-22 16:51:44 +08:00
import 'package:flutter/services.dart' ;
2026-11-18 19:08:06 +08:00
import '../state.dart' ;
import '../storage.dart' ;
2026-11-22 17:52:47 +08:00
import 'scan_qr_screen.dart' ;
2026-11-26 09:04:25 +08:00
import '../l10n.dart' ;
2026-11-18 19:08:06 +08:00
/// The first screen: the saved servers, or the connect form.
class ServersScreen extends StatefulWidget {
final AppState app ;
2026-11-19 12:34:25 +08:00
/// 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 });
2026-11-18 19:08:06 +08:00
@ override
State < ServersScreen > createState () => _ServersScreenState ();
}
class _ServersScreenState extends State < ServersScreen > {
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 ;
2026-11-22 11:38:24 +08:00
// 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 ();
2026-11-18 19:08:06 +08:00
2026-11-19 12:34:25 +08:00
@ override
void initState () {
super . initState ();
if ( widget . startEditing ) _editing = true ;
}
2026-11-22 11:38:24 +08:00
@ override
void dispose () {
_passwordFocus . dispose ();
super . dispose ();
}
2026-11-18 19:08:06 +08:00
@ 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: [
2026-11-26 09:04:25 +08:00
AppText ( 'OpenChamber' ,
2026-11-18 19:08:06 +08:00
style: theme . textTheme . headlineMedium
? . copyWith ( fontWeight: FontWeight . bold )),
const SizedBox ( height: 4 ),
2026-11-26 11:48:16 +08:00
AppText ( 'Connect to your OpenChamber server' ,
2026-11-18 19:08:06 +08:00
style: theme . textTheme . bodyMedium
? . copyWith ( color: theme . hintColor )),
],
),
),
if ( widget . app . error != null )
Padding (
padding: const EdgeInsets . symmetric ( horizontal: 16 , vertical: 4 ),
2026-11-26 11:48:16 +08:00
child: Text ( widget . app . error ! ,
2026-11-18 19:08:06 +08:00
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 ),
2026-11-22 16:51:44 +08:00
Row (
children: [
Expanded (
child: OutlinedButton . icon (
onPressed: () => _startEdit ( null ),
icon: const Icon ( Icons . add ),
2026-11-26 11:48:16 +08:00
label: const AppText ( 'Add server' ),
2026-11-22 16:51:44 +08:00
),
),
const SizedBox ( width: 8 ),
Expanded (
child: FilledButton . tonalIcon (
onPressed: _pair ,
icon: const Icon ( Icons . qr_code_2 , size: 18 ),
2026-11-26 11:48:16 +08:00
label: const AppText ( 'Pairing link' ),
2026-11-22 16:51:44 +08:00
),
),
],
2026-11-18 19:08:06 +08:00
),
],
),
),
],
),
),
);
}
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 (
2026-11-26 11:48:16 +08:00
title: Text ( c . label , style: const TextStyle ( fontWeight: FontWeight . w600 )),
2026-11-18 22:18:45 +08:00
subtitle: Column (
crossAxisAlignment: CrossAxisAlignment . start ,
children: [
2026-11-26 11:48:16 +08:00
Text ( c . isRelay ? trArgs ( 'Via Relay · {0}' , [ c . serverId ]) : c . url ,
2026-11-22 16:51:44 +08:00
maxLines: 1 , overflow: TextOverflow . ellipsis ),
if ( ! c . isRelay && c . proxy . isNotEmpty )
2026-11-26 11:48:16 +08:00
AppText ( trArgs ( 'Via {0}' , [ c . proxy ]),
2026-11-18 22:18:45 +08:00
maxLines: 1 ,
overflow: TextOverflow . ellipsis ,
style: TextStyle ( fontSize: 12 , color: theme . hintColor )),
],
),
2026-11-18 19:08:06 +08:00
trailing: Row (
mainAxisSize: MainAxisSize . min ,
children: [
if ( connected )
2026-11-26 11:48:16 +08:00
AppText ( 'Connected' , style: TextStyle ( color: theme . colorScheme . primary ))
2026-11-18 19:08:06 +08:00
else
2026-11-26 11:48:16 +08:00
TextButton ( onPressed: () => _connect ( c ), child: const AppText ( 'Connect' )),
2026-11-18 19:08:06 +08:00
PopupMenuButton < String > (
onSelected: ( v ) {
if ( v == 'edit' ) {
_startEdit ( c );
} else if ( v == 'delete' ) {
_confirmDelete ( c );
}
},
itemBuilder: ( _ ) => const [
2026-11-26 11:48:16 +08:00
PopupMenuItem ( value: 'edit' , child: AppText ( 'Edit' )),
PopupMenuItem ( value: 'delete' , child: AppText ( 'Delete' )),
2026-11-18 19:08:06 +08:00
],
),
],
),
),
);
}
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 ;
});
2026-11-22 11:38:24 +08:00
_focusPasswordIfNeeded ( _formError );
2026-11-18 19:08:06 +08:00
widget . app . clearLastError ();
} else if ( mounted ) {
setState (() => _connecting = false );
}
}
void _startEdit ( Connection ? c ) {
2026-11-18 22:18:45 +08:00
widget . app . error = null ;
widget . app . clearLastError ();
2026-11-18 19:08:06 +08:00
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 ),
2026-11-18 22:18:45 +08:00
onPressed: () {
widget . app . error = null ;
widget . app . clearLastError ();
setState (() => _editing = false );
},
2026-11-18 19:08:06 +08:00
),
2026-11-26 11:48:16 +08:00
title: AppText ( _editNew ? 'Add server' : trArgs ( 'Connect to {0}' , [ _edit ! . label ])),
2026-11-18 19:08:06 +08:00
),
body: ListView (
padding: const EdgeInsets . all ( 16 ),
children: [
2026-11-26 11:48:16 +08:00
_labelText ( 'Name' ),
2026-11-18 19:08:06 +08:00
TextField (
controller: TextEditingController ( text: _label ),
onChanged: ( v ) => _label = v ,
2026-11-26 09:04:25 +08:00
decoration: InputDecoration (
2026-11-26 11:48:16 +08:00
hintText: tr ( 'e.g. My computer' ), border: const OutlineInputBorder ()),
2026-11-18 19:08:06 +08:00
),
const SizedBox ( height: 12 ),
2026-11-22 16:51:44 +08:00
if ( _edit ? . isRelay == true ) ...[
const ListTile (
contentPadding: EdgeInsets . zero ,
leading: Icon ( Icons . lock_outline , size: 20 ),
2026-11-26 11:48:16 +08:00
title: AppText ( 'Connect through Relay' ),
subtitle: AppText ( 'End-to-end encrypted; the server and device token stay the same' ),
2026-11-22 16:51:44 +08:00
),
] else ...[
2026-11-26 11:48:16 +08:00
_labelText ( 'Server address' ),
2026-11-22 16:51:44 +08:00
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 ),
2026-11-26 11:48:16 +08:00
_labelText ( 'Proxy (optional)' ),
2026-11-22 16:51:44 +08:00
TextField (
controller: TextEditingController ( text: _proxy ),
onChanged: ( v ) => _proxy = v ,
keyboardType: TextInputType . url ,
2026-11-26 09:04:25 +08:00
decoration: InputDecoration (
2026-11-26 11:48:16 +08:00
hintText: tr ( 'http://… or socks5://…' ),
2026-11-26 09:04:25 +08:00
border: const OutlineInputBorder ()),
2026-11-22 16:51:44 +08:00
),
const SizedBox ( height: 12 ),
2026-11-26 11:48:16 +08:00
_labelText ( 'Self-signed certificate fingerprint (optional)' ),
2026-11-22 16:51:44 +08:00
TextField (
controller: TextEditingController ( text: _fingerprint ),
onChanged: ( v ) => _fingerprint = v ,
2026-11-26 09:04:25 +08:00
decoration: InputDecoration (
2026-11-26 11:48:16 +08:00
hintText: tr ( 'SHA-256 hex' ),
2026-11-26 09:04:25 +08:00
border: const OutlineInputBorder ()),
2026-11-22 16:51:44 +08:00
),
SwitchListTile (
contentPadding: EdgeInsets . zero ,
2026-11-26 11:48:16 +08:00
title: const AppText ( 'Trust self-signed certificates' ),
2026-11-22 16:51:44 +08:00
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.
2026-11-26 11:48:16 +08:00
_labelText ( 'Password (if required)' ),
2026-11-22 16:51:44 +08:00
TextField (
controller: TextEditingController ( text: _password ),
focusNode: _passwordFocus ,
onChanged: ( v ) => _password = v ,
obscureText: true ,
2026-11-26 09:04:25 +08:00
decoration: InputDecoration (
2026-11-26 11:48:16 +08:00
hintText: tr ( 'Server password; leave empty if the server has none' ),
2026-11-26 09:04:25 +08:00
border: const OutlineInputBorder ()),
2026-11-22 16:51:44 +08:00
),
],
2026-11-18 19:08:06 +08:00
if ( _formError != null )
Padding (
padding: const EdgeInsets . only ( top: 8 ),
2026-11-26 11:48:16 +08:00
child: Text ( _formError ! ,
2026-11-18 19:08:06 +08:00
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 ))
2026-11-26 11:48:16 +08:00
: const AppText ( 'Connect' ),
2026-11-18 19:08:06 +08:00
),
],
),
);
}
Widget _labelText ( String s ) => Padding (
padding: const EdgeInsets . only ( bottom: 4 ),
2026-11-26 09:04:25 +08:00
child: AppText ( s , style: Theme . of ( context ). textTheme . bodySmall ),
2026-11-18 19:08:06 +08:00
);
Future < void > _submit () async {
setState (() {
_connecting = true ;
_formError = null ;
});
2026-11-22 16:51:44 +08:00
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 ,
);
2026-11-18 22:18:45 +08:00
// Only a connection that works is saved (AppState saves it on success),
// so failed attempts do not pile up in the server list.
2026-11-18 19:08:06 +08:00
await widget . app . connect ( c , password: _password );
if ( mounted ) {
if ( widget . app . client != null ) {
setState (() => _editing = false );
2026-11-19 12:34:25 +08:00
// Pushed on top of a live session list: return there.
if ( Navigator . of ( context ). canPop ()) Navigator . of ( context ). pop ();
2026-11-18 19:08:06 +08:00
} else {
setState (() {
_connecting = false ;
_formError = widget . app . lastError ;
});
2026-11-22 11:38:24 +08:00
_focusPasswordIfNeeded ( _formError );
2026-11-18 19:08:06 +08:00
widget . app . clearLastError ();
}
}
}
2026-11-22 11:38:24 +08:00
/// The server asked for a password: put the caret where it is typed.
void _focusPasswordIfNeeded ( String ? message ) {
2026-11-26 09:04:25 +08:00
// The message is already in the UI's language; look for the same word.
2026-11-26 11:48:16 +08:00
if ( message == null || ! message . contains ( tr ( 'Password' ))) return ;
2026-11-22 11:38:24 +08:00
WidgetsBinding . instance . addPostFrameCallback (( _ ) {
if ( mounted ) _passwordFocus . requestFocus ();
});
}
2026-11-22 16:51:44 +08:00
void _pair () {
widget . app . error = null ;
widget . app . clearLastError ();
showPairingDialog ( context , widget . app );
}
2026-11-18 19:08:06 +08:00
void _confirmDelete ( Connection c ) {
showDialog (
context: context ,
builder: ( context ) => AlertDialog (
2026-11-26 11:48:16 +08:00
title: const AppText ( 'Delete server?' ),
content: AppText ( trArgs ( '“{0}” will be removed from the list, and its device token will be deleted.' , [ c . label ])),
2026-11-18 19:08:06 +08:00
actions: [
2026-11-26 11:48:16 +08:00
TextButton ( onPressed: () => Navigator . pop ( context ), child: const AppText ( 'Cancel' )),
2026-11-18 19:08:06 +08:00
FilledButton (
onPressed: () {
Navigator . pop ( context );
widget . app . removeConnection ( c );
},
2026-11-26 11:48:16 +08:00
child: const AppText ( 'Delete' ),
2026-11-18 19:08:06 +08:00
),
],
),
);
}
static String _hostOf ( String raw ) {
try {
return Uri . parse ( raw ). host ;
} catch ( _ ) {
return raw ;
}
}
}
2026-11-22 16:51:44 +08:00
/// Opens the paste-a-pairing-link dialog (also reachable from the connected
/// sidebar's server sheet).
Future < void > showPairingDialog ( BuildContext context , AppState app ) {
app . error = null ;
app . clearLastError ();
return showDialog < void > (
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 ();
}
2026-11-22 17:52:47 +08:00
Future < void > _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 ();
}
2026-11-22 16:51:44 +08:00
Future < void > _paste () async {
final data = await Clipboard . getData ( Clipboard . kTextPlain );
final text = data ? . text ? . trim () ?? '' ;
if ( text . isEmpty || ! mounted ) return ;
setState (() => _text . text = text );
}
Future < void > _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 ;
2026-11-26 11:48:16 +08:00
_error = widget . app . lastError ?? tr ( 'Pairing failed' );
2026-11-22 16:51:44 +08:00
});
widget . app . clearLastError ();
}
@ override
Widget build ( BuildContext context ) {
final theme = Theme . of ( context );
return AlertDialog (
2026-11-26 11:48:16 +08:00
title: const AppText ( 'Pairing link' ),
2026-11-22 16:51:44 +08:00
content: SizedBox (
width: 420 ,
child: Column (
mainAxisSize: MainAxisSize . min ,
crossAxisAlignment: CrossAxisAlignment . stretch ,
children: [
2026-11-26 09:04:25 +08:00
AppText (
2026-11-26 11:48:16 +08:00
'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.' ,
2026-11-22 16:51:44 +08:00
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 ),
2026-11-26 11:48:16 +08:00
child: Text ( _error ! ,
2026-11-22 16:51:44 +08:00
style: TextStyle ( color: theme . colorScheme . error , fontSize: 12.5 )),
),
2026-11-22 17:52:47 +08:00
Row (
children: [
TextButton . icon (
onPressed: _busy ? null : _scan ,
icon: const Icon ( Icons . qr_code_scanner , size: 18 ),
2026-11-26 11:48:16 +08:00
label: const AppText ( 'Scan QR code' ),
2026-11-22 17:52:47 +08:00
),
const SizedBox ( width: 4 ),
TextButton . icon (
onPressed: _busy ? null : _paste ,
icon: const Icon ( Icons . content_paste , size: 18 ),
2026-11-26 11:48:16 +08:00
label: const AppText ( 'Paste' ),
2026-11-22 17:52:47 +08:00
),
],
2026-11-22 16:51:44 +08:00
),
],
),
),
actions: [
TextButton (
onPressed: _busy ? null : () => Navigator . of ( context ). pop (),
2026-11-26 11:48:16 +08:00
child: const AppText ( 'Cancel' ),
2026-11-22 16:51:44 +08:00
),
FilledButton (
onPressed: _busy ? null : _connect ,
child: _busy
? const SizedBox (
width: 18 , height: 18 , child: CircularProgressIndicator ( strokeWidth: 2 ))
2026-11-26 11:48:16 +08:00
: const AppText ( 'Pair and connect' ),
2026-11-22 16:51:44 +08:00
),
],
);
}
}