Files
TTSTDConnect/flutter_sender/lib/features/settings/settings_page.dart
T
tongtong a1c3f79cd8 feat: 控制通道权限分级(仅查看 / 查看+控制 / 全权限)
- 协议新增 msgType=10 access 应答,sessionConfig 增加 access 请求字段,三端同步
- rust_core:解码/编码 Access 事件,收到后入队给界面;send_control 支持 msgType=10
- android_receiver:新增 AccessLevel,被控端按本机上限裁剪请求并回送有效等级
- android_receiver:越权帧真正丢弃——输入/剪贴板需 control,文件子协议需 full 且回错误响应
- android_receiver:主界面增加权限单选(持久化),调整后当前连接立即生效并通知主控端
- flutter_sender:AppSettings 增加请求等级并在设置页可选,连接后自动下发
- flutter_sender:接收 msgType=10 更新有效等级,越权操作在界面禁用并提示
- docs:README/AGENTS 补充权限协议与各操作的最低等级
2026-11-27 20:55:54 +08:00

504 lines
19 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'package:flutter/material.dart';
import '../../core/bridge.dart';
import '../../core/models.dart';
import '../../core/service_check.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({
super.key,
required this.settings,
required this.bridge,
});
final AppSettings settings;
final SenderBridge bridge;
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
late final TextEditingController _signalingUrl;
late final TextEditingController _localPort;
late final TextEditingController _filePort;
late final TextEditingController _fileToken;
late bool _useLocalSignaling;
late bool _localSignalingEnabled;
late bool _localRunning;
late bool _preferH265;
late bool _audioEnabled;
late bool _clipboardSync;
late bool _fileTransfer;
late bool _relayEnabled;
late AccessLevel _access;
late int _bitrateMbps;
DeviceInfo? _localListener;
ServiceCheckResult? _serviceResult;
bool _checkingServices = false;
bool _listenerRunning = false;
@override
void initState() {
super.initState();
_signalingUrl = TextEditingController(text: widget.settings.signalingUrl);
_localPort = TextEditingController(text: '${widget.settings.localSignalingPort}');
_filePort = TextEditingController(text: '${widget.settings.filePort}');
_fileToken = TextEditingController(text: widget.settings.fileToken);
_useLocalSignaling = widget.settings.useLocalSignaling;
_localSignalingEnabled = widget.settings.localSignalingEnabled;
_localRunning = widget.bridge.isLocalSignalingRunning;
_preferH265 = widget.settings.preferH265;
_audioEnabled = widget.settings.audioEnabled;
_clipboardSync = widget.settings.clipboardSync;
_fileTransfer = widget.settings.fileTransfer;
_relayEnabled = widget.settings.relayEnabled;
_access = widget.settings.access;
_bitrateMbps = widget.settings.bitrateMbps;
_loadLocalListener();
_refreshListenerState();
}
@override
void dispose() {
_signalingUrl.dispose();
_localPort.dispose();
_filePort.dispose();
_fileToken.dispose();
super.dispose();
}
int get _port {
final parsed = int.tryParse(_localPort.text.trim());
return parsed != null && parsed >= 1 && parsed <= 65535 ? parsed : 8080;
}
void _snack(String message) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
}
}
Future<void> _loadLocalListener() async {
final listener = await widget.bridge.localListener();
if (!mounted) return;
setState(() => _localListener = listener);
}
void _refreshListenerState() {
try {
final status = widget.bridge.demoStatus();
_listenerRunning = status['running'] == true;
} on Object catch (_) {
_listenerRunning = false;
}
}
Future<void> _runServiceCheck() async {
setState(() => _checkingServices = true);
final url = _useLocalSignaling
? widget.bridge.localSignalingUrl(_port)
: _signalingUrl.text.trim();
final listener = _localListener ?? await widget.bridge.localListener();
final host = listener?.ip ?? '127.0.0.1';
final results = await Future.wait<bool>([
ServiceChecker.checkSignaling(url),
ServiceChecker.checkTcp(host, 41001),
]);
Map<String, dynamic> status = const <String, dynamic>{'running': false};
try {
status = widget.bridge.demoStatus();
} on Object catch (_) {}
if (!mounted) return;
setState(() {
_localListener = listener;
_listenerRunning = status['running'] == true;
_serviceResult = ServiceCheckResult(
nativeCoreLoaded: widget.bridge.nativeCore != null,
localSignalingRunning: widget.bridge.isLocalSignalingRunning,
signalingReachable: results[0],
listenerRunning: _listenerRunning,
listenerReachable: results[1],
signalingUrl: url,
listenerHost: host,
listenerPort: 41001,
);
_checkingServices = false;
});
}
Future<void> _toggleListener() async {
if (_listenerRunning) {
widget.bridge.stopDemoServer();
if (!mounted) return;
setState(() => _listenerRunning = false);
} else {
final started = widget.bridge.startDemoServer();
var running = started;
if (!running) {
try {
running = widget.bridge.demoStatus()['running'] == true;
} on Object catch (_) {}
}
if (!mounted) return;
setState(() => _listenerRunning = running);
if (!running) _snack('本机监听启动失败');
}
await _runServiceCheck();
}
Widget _serviceRow(String label, bool? ok) {
final theme = Theme.of(context);
final icon = ok == null
? Icons.help_outline
: ok
? Icons.check_circle
: Icons.cancel;
final color = ok == null
? theme.colorScheme.outline
: ok
? theme.colorScheme.primary
: theme.colorScheme.error;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Row(
children: [
Icon(icon, size: 18, color: color),
const SizedBox(width: 8),
Expanded(child: Text(label, style: theme.textTheme.bodySmall)),
Text(
ok == null ? '未检测' : ok ? '正常' : '异常',
style: theme.textTheme.bodySmall?.copyWith(color: color),
),
],
),
);
}
void _setLocalServer(bool enabled) {
setState(() => _localSignalingEnabled = enabled);
}
Future<void> _save() async {
if (!_useLocalSignaling && _signalingUrl.text.trim().isEmpty) {
_snack('请填写外部信令服务器地址');
return;
}
if (_relayEnabled && _useLocalSignaling) {
_snack('中继需要被控端也能访问的信令地址,请改用外部信令');
return;
}
if (int.tryParse(_localPort.text.trim()) == null) {
_snack('本机端口必须是数字');
return;
}
if (_localSignalingEnabled) {
if (!_localRunning || _port != widget.settings.localSignalingPort) {
await widget.bridge.stopLocalSignaling();
final started = await widget.bridge.startLocalSignaling(_port);
if (!mounted) return;
setState(() => _localRunning = started);
if (!started) _snack('本机信令服务启动失败');
}
} else if (_localRunning) {
await widget.bridge.stopLocalSignaling();
if (!mounted) return;
setState(() => _localRunning = false);
}
if (!mounted) return;
Navigator.of(context).pop(AppSettings(
signalingUrl: _signalingUrl.text.trim(),
useLocalSignaling: _useLocalSignaling,
localSignalingEnabled: _localSignalingEnabled,
localSignalingPort: _port,
preferH265: _preferH265,
audioEnabled: _audioEnabled,
clipboardSync: _clipboardSync,
fileTransfer: _fileTransfer,
relayEnabled: _relayEnabled,
access: _access,
bitrateMbps: _bitrateMbps,
filePort: int.tryParse(_filePort.text.trim()) ?? widget.settings.filePort,
fileToken: _fileToken.text.trim(),
));
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: const Text('设置')),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.dns, color: theme.colorScheme.primary),
const SizedBox(width: 8),
Text('信令服务器', style: theme.textTheme.titleMedium),
],
),
const SizedBox(height: 8),
SwitchListTile(
title: const Text('使用本机信令服务器'),
subtitle: const Text('默认开启;安装包内置独立 Go 信令服务'),
value: _useLocalSignaling,
onChanged: (value) => setState(() => _useLocalSignaling = value),
),
if (_useLocalSignaling) ...[
SwitchListTile(
title: const Text('开启本机信令服务'),
subtitle: Text(
!_localSignalingEnabled
? '已关闭'
: (_localRunning ? '服务运行中' : '保存设置后启动'),
style: TextStyle(
color: _localSignalingEnabled && _localRunning
? theme.colorScheme.primary
: theme.colorScheme.error,
),
),
value: _localSignalingEnabled,
onChanged: _setLocalServer,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: TextField(
controller: _localPort,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: '本机监听端口',
hintText: '8080',
prefixIcon: Icon(Icons.numbers),
border: OutlineInputBorder(),
),
),
),
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
'本机地址:${widget.bridge.localSignalingUrl(_port)}\n手机端扫码或手动填写该地址即可注册。',
style: theme.textTheme.bodySmall,
),
),
if (!_localSignalingEnabled)
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: Text(
'本机服务已关闭,但当前仍选择“使用本机信令服务器”,设备列表将不可用。',
style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.error),
),
),
] else ...[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: TextField(
controller: _signalingUrl,
decoration: const InputDecoration(
labelText: '外部信令服务器',
hintText: 'http://<信令服务器IP>:8080',
prefixIcon: Icon(Icons.cloud),
border: OutlineInputBorder(),
),
),
),
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
'跨网段时通过自部署信令服务器交换地址。',
style: theme.textTheme.bodySmall,
),
),
],
],
),
),
),
const SizedBox(height: 12),
Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.health_and_safety, color: theme.colorScheme.primary),
const SizedBox(width: 8),
Text('服务检测', style: theme.textTheme.titleMedium),
const Spacer(),
TextButton.icon(
onPressed: _checkingServices ? null : _runServiceCheck,
icon: _checkingServices
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.refresh),
label: Text(_checkingServices ? '检测中' : '检测'),
),
],
),
const SizedBox(height: 8),
_serviceRow('Rust Core 动态库', _serviceResult?.nativeCoreLoaded),
_serviceRow('本机信令进程', _serviceResult?.localSignalingRunning),
_serviceRow('信令 /healthz', _serviceResult?.signalingReachable),
_serviceRow('本机监听服务', _serviceResult?.listenerRunning),
_serviceRow('主控监听端口 41001', _serviceResult?.listenerReachable),
const Divider(height: 24),
Row(
children: [
Expanded(
child: Text('本机监听端点', style: theme.textTheme.titleSmall),
),
TextButton.icon(
onPressed: _toggleListener,
icon: Icon(
_listenerRunning ? Icons.stop : Icons.play_arrow,
size: 18,
),
label: Text(_listenerRunning ? '停止' : '启动'),
),
],
),
Text(
_localListener == null
? '未获取到本机 IPv4 地址'
: '${_localListener!.ip}:${_localListener!.controlPort} · 媒体 ${_localListener!.mediaPort}',
style: theme.textTheme.bodySmall,
),
const SizedBox(height: 4),
Text(
'该端点仅用于被控端接入,不再显示在主页设备列表。',
style: theme.textTheme.bodySmall,
),
if (_serviceResult != null && _serviceResult!.signalingUrl.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
'检测地址:${_serviceResult!.signalingUrl}',
style: theme.textTheme.labelSmall,
),
),
],
),
),
),
const Divider(height: 32),
SwitchListTile(
title: const Text('优先使用 H.265'),
subtitle: const Text('带宽更省,要求被控端支持'),
value: _preferH265,
onChanged: (value) => setState(() => _preferH265 = value),
),
SwitchListTile(
title: const Text('启用音频'),
subtitle: const Text('AudioPlaybackCapture / OPUS'),
value: _audioEnabled,
onChanged: (value) => setState(() => _audioEnabled = value),
),
SwitchListTile(
title: const Text('剪贴板同步'),
subtitle: const Text('通过控制通道双向同步文本'),
value: _clipboardSync,
onChanged: (value) => setState(() => _clipboardSync = value),
),
SwitchListTile(
title: const Text('允许文件传输'),
subtitle: const Text('浏览/下载/上传被控端文件(LocalSend 风格 HTTP)'),
value: _fileTransfer,
onChanged: (value) => setState(() => _fileTransfer = value),
),
ListTile(
title: const Text('请求权限等级'),
subtitle: Text(
'当前:${_access.label}。被控端有自己的上限,'
'实际等级取两者更严格的一方,超出部分的操作会被禁用。',
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: SegmentedButton<AccessLevel>(
segments: AccessLevel.values
.map(
(level) => ButtonSegment<AccessLevel>(
value: level,
label: Text(level.label),
),
)
.toList(growable: false),
selected: <AccessLevel>{_access},
onSelectionChanged: (selection) =>
setState(() => _access = selection.first),
),
),
SwitchListTile(
title: const Text('连接走信令中继'),
subtitle: const Text('跨网段时使用;中继只承载控制通道,不能投屏/传音频'),
value: _relayEnabled,
onChanged: (value) => setState(() => _relayEnabled = value),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
child: Row(
children: [
Expanded(
child: TextField(
controller: _filePort,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: '文件服务端口',
isDense: true,
),
),
),
const SizedBox(width: 12),
Expanded(
flex: 2,
child: TextField(
controller: _fileToken,
decoration: const InputDecoration(
labelText: '文件服务令牌(被控端主界面显示)',
isDense: true,
),
),
),
],
),
),
const Divider(height: 32),
ListTile(
title: const Text('投屏码率'),
subtitle: Text('$_bitrateMbps Mbps · 1080p 建议 6–10 Mbps'),
),
Slider(
min: 2,
max: 20,
divisions: 18,
value: _bitrateMbps.toDouble(),
label: '$_bitrateMbps Mbps',
onChanged: (value) => setState(() => _bitrateMbps = value.round()),
),
const SizedBox(height: 24),
FilledButton.icon(
onPressed: _save,
icon: const Icon(Icons.save),
label: const Text('保存设置'),
),
],
),
);
}
}