1091 lines
36 KiB
Dart
1091 lines
36 KiB
Dart
import 'dart:async';
|
||
import 'dart:convert';
|
||
import 'dart:io';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:meshport_flutter/meshport_flutter.dart';
|
||
import 'config_import_dialog.dart';
|
||
import 'network_telemetry.dart';
|
||
|
||
class LabScreen extends StatefulWidget {
|
||
const LabScreen({super.key, this.initializeNative = true});
|
||
final bool initializeNative;
|
||
@override
|
||
State<LabScreen> createState() => _LabScreenState();
|
||
}
|
||
|
||
class _LabScreenState extends State<LabScreen> {
|
||
MeshPortClient? client, applicationClient, systemClient;
|
||
String runtimeMode = 'application';
|
||
bool rememberConfig = false;
|
||
String? savedConfig;
|
||
String? loadedConfig, loadedForm;
|
||
static const vpnChannel = MethodChannel('meshport/system_vpn');
|
||
Timer? timer;
|
||
int page = 0, configTab = 0, completed = 0, failed = 0;
|
||
bool busy = false,
|
||
udp = false,
|
||
echo = false,
|
||
stability = false,
|
||
cancel = false;
|
||
bool refreshing = false;
|
||
String eventInstance = '';
|
||
int eventSequence = 0, traceSequence = 0;
|
||
bool autoIp = false, latencyFirst = true, ipv6 = true;
|
||
String routeMode = 'adaptive';
|
||
bool preferUdp = true;
|
||
final relayIds = TextEditingController();
|
||
final qualitySamples = <Map<String, dynamic>>[];
|
||
bool qualityRunning = false;
|
||
Map<String, dynamic> status = {'state': 'Stopped', 'peer_count': 0};
|
||
Map<String, dynamic>? result;
|
||
final logs = <String>[];
|
||
final latencies = <double>[];
|
||
final name = TextEditingController(text: 'game-net');
|
||
final secret = TextEditingController();
|
||
final hostname = TextEditingController(text: 'MeshPort');
|
||
final ip = TextEditingController(text: '10.77.0.11');
|
||
final peers = TextEditingController();
|
||
final target = TextEditingController(text: '10.77.0.2:7007');
|
||
final count = TextEditingController(text: '100');
|
||
String error = '';
|
||
bool get running => status['state'] == 'Running';
|
||
bool get profileSupported => Platform.isMacOS || Platform.isAndroid;
|
||
String get profileStorage =>
|
||
Platform.isAndroid ? 'Android 安全存储' : 'macOS 钥匙串';
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
if (widget.initializeNative) {
|
||
unawaited(initialize());
|
||
}
|
||
}
|
||
|
||
Future<void> initialize() async {
|
||
try {
|
||
const path = String.fromEnvironment('MESHPORT_LIBRARY');
|
||
final opened = await MeshPortClient.open(
|
||
libraryPath: path.isEmpty ? null : path,
|
||
);
|
||
if (!mounted) {
|
||
await opened.close();
|
||
return;
|
||
}
|
||
client = applicationClient = opened;
|
||
log('原生库已加载 · ABI v1');
|
||
if (profileSupported) {
|
||
try {
|
||
final stored = (await vpnChannel.invokeMethod<String>(
|
||
'load_profile',
|
||
))?.replaceAll(RegExp(r'^subnet_routes\s*=.*$', multiLine: true), '');
|
||
if (stored != null) {
|
||
await loadForm(stored);
|
||
if (mounted) {
|
||
setState(() {
|
||
savedConfig = stored;
|
||
rememberConfig = true;
|
||
});
|
||
}
|
||
log('已自动载入保存的网络配置,点击连接即可组网');
|
||
}
|
||
} catch (_) {
|
||
log('读取已保存配置失败,请在设置中重试');
|
||
}
|
||
}
|
||
final diagnostics = await opened.enableDiagnostics();
|
||
log(diagnostics['enabled'] == true ? '穿透详细日志采集已开启' : '穿透日志未接管:宿主已有日志订阅器');
|
||
if (Platform.isAndroid) {
|
||
final snapshot = await androidVpnRequest({'op': 'status'});
|
||
final data = snapshot['data'] as Map?;
|
||
if (data?['state'] == 'Running') {
|
||
systemClient = client = MeshPortClient.fromTransport(
|
||
request: androidVpnRequest,
|
||
close: () async {
|
||
await androidVpnRequest({'op': 'stop'});
|
||
},
|
||
);
|
||
runtimeMode = 'system_vpn';
|
||
log('已恢复正在运行的 Android VPN 会话');
|
||
await refresh();
|
||
}
|
||
}
|
||
timer = Timer.periodic(const Duration(seconds: 2), (_) {
|
||
if (!busy) {
|
||
unawaited(refresh());
|
||
}
|
||
});
|
||
} catch (e) {
|
||
if (mounted) {
|
||
setState(() => error = '原生库未加载,请先构建并指定 MESHPORT_LIBRARY。$e');
|
||
}
|
||
}
|
||
}
|
||
|
||
Future<Map<String, dynamic>> androidVpnRequest(
|
||
Map<String, dynamic> request,
|
||
) async {
|
||
final response = await vpnChannel.invokeMethod<String>(
|
||
'android_vpn_request',
|
||
jsonEncode(request),
|
||
);
|
||
return jsonDecode(response!) as Map<String, dynamic>;
|
||
}
|
||
|
||
void log(String text) {
|
||
if (!mounted) {
|
||
return;
|
||
}
|
||
setState(() {
|
||
logs.insert(
|
||
0,
|
||
'${DateTime.now().toIso8601String().substring(11, 19)} $text',
|
||
);
|
||
if (logs.length > 300) {
|
||
logs.removeLast();
|
||
}
|
||
});
|
||
}
|
||
|
||
Future<void> refresh() async {
|
||
if (refreshing) return;
|
||
refreshing = true;
|
||
try {
|
||
final next = await client?.status();
|
||
if (mounted && next != null) {
|
||
final instance = next['instance_id'] as String? ?? '';
|
||
if (eventInstance != instance) {
|
||
eventInstance = instance;
|
||
eventSequence = 0;
|
||
}
|
||
for (final event in next['native_events'] as List? ?? []) {
|
||
final sequence = (event['sequence'] as num).toInt();
|
||
if (sequence > eventSequence) {
|
||
log('原生 · ${event['message']}');
|
||
eventSequence = sequence;
|
||
}
|
||
}
|
||
for (final trace in next['diagnostic_traces'] as List? ?? []) {
|
||
final sequence = (trace['sequence'] as num).toInt();
|
||
if (sequence > traceSequence) {
|
||
log('穿透 · ${trace['message']}');
|
||
traceSequence = sequence;
|
||
}
|
||
}
|
||
setState(() => status = next);
|
||
}
|
||
} catch (e) {
|
||
if (mounted && systemClient != null && status['state'] != 'Failed') {
|
||
setState(() {
|
||
status = {
|
||
'state': 'Failed',
|
||
'runtime_mode': 'system_vpn',
|
||
'peer_count': 0,
|
||
};
|
||
error = 'VPN 辅助进程已断开,请重新连接。';
|
||
});
|
||
}
|
||
} finally {
|
||
refreshing = false;
|
||
}
|
||
}
|
||
|
||
Future<void> perform(Future<void> Function(MeshPortClient) action) async {
|
||
if (busy || client == null) {
|
||
return;
|
||
}
|
||
setState(() {
|
||
busy = true;
|
||
error = '';
|
||
});
|
||
try {
|
||
await action(client!);
|
||
await refresh();
|
||
} catch (e) {
|
||
log('操作失败:$e');
|
||
if (mounted) {
|
||
setState(() => error = '$e');
|
||
}
|
||
} finally {
|
||
if (mounted) {
|
||
setState(() => busy = false);
|
||
}
|
||
}
|
||
}
|
||
|
||
String buildConfig() {
|
||
final form = buildFormConfig();
|
||
return loadedForm == form && loadedConfig != null ? loadedConfig! : form;
|
||
}
|
||
|
||
Future<void> loadForm(String config) async {
|
||
final validated = await applicationClient!.request({
|
||
'op': 'validate',
|
||
'toml': config,
|
||
'include_profile': true,
|
||
});
|
||
if (!mounted) return;
|
||
final profile = validated['profile'] as Map;
|
||
final optimization = profile['optimization'] as Map;
|
||
setState(() {
|
||
name.text = profile['network_name'] as String;
|
||
secret.text = profile['network_secret'] as String;
|
||
hostname.text = profile['hostname'] as String;
|
||
ip.text = profile['ipv4'] as String;
|
||
autoIp = profile['dhcp'] == true;
|
||
peers.text = (profile['peers'] as List).join('\n');
|
||
ipv6 = profile['enable_ipv6'] == true;
|
||
latencyFirst = profile['latency_first'] == true;
|
||
runtimeMode = validated['runtime_mode'] as String;
|
||
routeMode = optimization['mode'] as String;
|
||
preferUdp = optimization['prefer_udp'] == true;
|
||
relayIds.text = (optimization['relay_peer_ids'] as List).join(',');
|
||
loadedConfig = config;
|
||
loadedForm = buildFormConfig();
|
||
});
|
||
}
|
||
|
||
String buildFormConfig() {
|
||
final addresses = peers.text
|
||
.split('\n')
|
||
.map((v) => v.trim())
|
||
.where((v) => v.isNotEmpty);
|
||
return 'hostname = ${jsonEncode(hostname.text)}\n${autoIp ? 'dhcp = true' : 'ipv4 = ${jsonEncode(ip.text)}'}\nlisteners = []\n'
|
||
'${addresses.map((v) => '[[peer]]\nuri = ${jsonEncode(v)}\n').join()}'
|
||
'[network_identity]\nnetwork_name = ${jsonEncode(name.text)}\nnetwork_secret = ${jsonEncode(secret.text)}\n'
|
||
'[flags]\nno_tun = ${runtimeMode == 'application'}\nuse_smoltcp = ${runtimeMode == 'application'}\nenable_encryption = true\ndefault_protocol = "udp"\nlatency_first = $latencyFirst\nenable_ipv6 = $ipv6\n'
|
||
'[runtime]\nmode = ${jsonEncode(runtimeMode)}\n'
|
||
'[optimization]\nmode = ${jsonEncode(routeMode)}\nprefer_udp = $preferUdp\nrelay_peer_ids = [${relayIds.text.split(RegExp(r"[,\s]+")).where((v) => v.isNotEmpty).join(',')}]\n';
|
||
}
|
||
|
||
Future<void> connect(MeshPortClient c) async {
|
||
final config = buildConfig();
|
||
await startConfig(config);
|
||
log('组网引擎已启动,等待节点连接');
|
||
}
|
||
|
||
Future<void> startConfig(String config) async {
|
||
// Validation selects mode from effective flags, avoiding ad-hoc TOML parsing.
|
||
final validated = await applicationClient!.request({
|
||
'op': 'validate',
|
||
'toml': config,
|
||
});
|
||
final system = validated['runtime_mode'] == 'system_vpn';
|
||
if (systemClient != null) {
|
||
try {
|
||
await systemClient!.close();
|
||
} catch (_) {}
|
||
systemClient = null;
|
||
client = applicationClient;
|
||
}
|
||
if (!system) {
|
||
await applicationClient!.start(config);
|
||
await saveProfile(config);
|
||
return;
|
||
}
|
||
final opened = Platform.isAndroid
|
||
? await openAndroidSystemVpn(
|
||
prepare: () async {
|
||
log('等待 Android VPN 授权');
|
||
await vpnChannel.invokeMethod<void>('prepare_android_vpn');
|
||
},
|
||
request: androidVpnRequest,
|
||
)
|
||
: await openMacSystemVpn(
|
||
launch: (path, uid) async {
|
||
log('等待管理员授权以创建虚拟网卡');
|
||
await vpnChannel.invokeMethod<void>('launch', {
|
||
'socket': path,
|
||
'uid': uid,
|
||
});
|
||
},
|
||
);
|
||
try {
|
||
await opened.enableDiagnostics();
|
||
await opened.start(config);
|
||
systemClient = client = opened;
|
||
log('系统 VPN 已启动,接入虚拟网段与远端子网');
|
||
await saveProfile(config);
|
||
} catch (_) {
|
||
await opened.close();
|
||
rethrow;
|
||
}
|
||
}
|
||
|
||
Future<void> saveProfile(String config, {bool explicit = false}) async {
|
||
if ((!rememberConfig && !explicit) || !profileSupported) return;
|
||
try {
|
||
await applicationClient!.request({'op': 'validate', 'toml': config});
|
||
await vpnChannel.invokeMethod<void>('save_profile', config);
|
||
if (mounted) {
|
||
setState(() {
|
||
savedConfig = config;
|
||
rememberConfig = true;
|
||
});
|
||
}
|
||
log('网络配置已保存到 $profileStorage');
|
||
} catch (_) {
|
||
if (explicit) throw StateError('配置保存失败,请检查配置和安全存储访问权限');
|
||
log('连接成功,但配置未能保存到 $profileStorage');
|
||
}
|
||
}
|
||
|
||
Future<void> stopActive(MeshPortClient c) async {
|
||
try {
|
||
await c.stop();
|
||
} finally {
|
||
if (systemClient != null) {
|
||
try {
|
||
await systemClient!.close();
|
||
} finally {
|
||
systemClient = null;
|
||
client = applicationClient;
|
||
}
|
||
}
|
||
}
|
||
log('已停止并释放网络资源');
|
||
}
|
||
|
||
Future<void> probe(MeshPortClient c) async {
|
||
final next = await c.probe(target.text.trim(), udp: udp, echo: echo || udp);
|
||
if (mounted) {
|
||
setState(() {
|
||
result = next;
|
||
latencies.add((next['elapsed_ms'] as num).toDouble());
|
||
if (latencies.length > 60) {
|
||
latencies.removeAt(0);
|
||
}
|
||
});
|
||
}
|
||
log(
|
||
'${next['protocol']} ${next['kind']} 成功 · ${(next['elapsed_ms'] as num).toStringAsFixed(1)} ms',
|
||
);
|
||
}
|
||
|
||
Future<void> repeat(MeshPortClient c) async {
|
||
final rounds = int.tryParse(count.text);
|
||
if (rounds == null || rounds < 1 || rounds > 10000) {
|
||
throw ArgumentError('测试次数应为 1–10000');
|
||
}
|
||
cancel = false;
|
||
setState(() {
|
||
completed = 0;
|
||
failed = 0;
|
||
});
|
||
for (var i = 0; i < rounds && !cancel && mounted; i++) {
|
||
try {
|
||
await probe(c);
|
||
} catch (e) {
|
||
if (mounted) {
|
||
setState(() => failed++);
|
||
}
|
||
log('第 ${i + 1} 次失败:$e');
|
||
}
|
||
if (mounted) {
|
||
setState(() => completed++);
|
||
}
|
||
if (!cancel) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||
}
|
||
}
|
||
log('重复探测结束:$completed 次,失败 $failed 次');
|
||
}
|
||
|
||
Future<void> measureQuality(MeshPortClient c) async {
|
||
cancel = false;
|
||
setState(() {
|
||
qualitySamples.clear();
|
||
qualityRunning = true;
|
||
});
|
||
int? socket;
|
||
final nonce = DateTime.now().microsecondsSinceEpoch;
|
||
final address = target.text.trim();
|
||
try {
|
||
socket = await c.bindUdp();
|
||
await c.sampleUdpQuality(
|
||
socket,
|
||
address,
|
||
nonce,
|
||
); // Warm up before measured samples.
|
||
for (var i = 0; i < 60 && !cancel && mounted; i++) {
|
||
final sample = await c.sampleUdpQuality(socket, address, nonce + i + 1);
|
||
if (mounted) setState(() => qualitySamples.add(sample));
|
||
if (!cancel) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||
}
|
||
}
|
||
log('线路质量测量完成 · ${qualitySamples.length} 次 UDP 回显');
|
||
} finally {
|
||
if (socket != null) await c.closeResource(socket);
|
||
if (mounted) setState(() => qualityRunning = false);
|
||
}
|
||
}
|
||
|
||
Widget qualityPanel() {
|
||
final groups = <String, List<Map<String, dynamic>>>{};
|
||
for (final sample in qualitySamples) {
|
||
final path = sample['route_changed'] == true
|
||
? '路径切换期间'
|
||
: sample['next_hop_peer_id']?.toString() ?? '未知';
|
||
groups.putIfAbsent(path, () => []).add(sample);
|
||
}
|
||
String ms(double? value) =>
|
||
value == null ? '—' : '${value.toStringAsFixed(1)} ms';
|
||
return panel('线路质量 · 端到端 UDP 回显', [
|
||
Text(
|
||
status['runtime_mode'] == 'system_vpn'
|
||
? '系统 VPN 首版可使用上方系统 socket 建连/回显测试;批量质量测量暂限应用内模式。'
|
||
: '使用上方目标地址。需要回显服务;测量当前实际路径,不强制切换候选线路。',
|
||
),
|
||
const SizedBox(height: 10),
|
||
FilledButton.icon(
|
||
onPressed: busy || !running || status['runtime_mode'] == 'system_vpn'
|
||
? null
|
||
: () => perform(measureQuality),
|
||
icon: const Icon(Icons.analytics_outlined),
|
||
label: const Text('测量线路质量(60 次)'),
|
||
),
|
||
if (qualityRunning)
|
||
TextButton(
|
||
onPressed: () => setState(() => cancel = true),
|
||
child: const Text('停止测量'),
|
||
),
|
||
for (final entry in groups.entries) ...[
|
||
const SizedBox(height: 12),
|
||
Text('下一跳 ${entry.key} · ${entry.value.length} 次'),
|
||
Builder(
|
||
builder: (_) {
|
||
final summary = QualitySummary(entry.value);
|
||
return Text(
|
||
'中位 RTT ${ms(summary.medianMs)} · P95 ${ms(summary.p95Ms)}\n抖动 ${ms(summary.jitterMs)} · 未响应 ${summary.lossPercent?.toStringAsFixed(1) ?? '—'}%',
|
||
);
|
||
},
|
||
),
|
||
],
|
||
const Text('抖动为相邻成功样本 RTT 差的平均值。超时可能来自丢包或服务未响应。'),
|
||
]);
|
||
}
|
||
|
||
@override
|
||
void dispose() {
|
||
cancel = true;
|
||
timer?.cancel();
|
||
if (client != null) {
|
||
unawaited(client!.close());
|
||
if (applicationClient != client) unawaited(applicationClient!.close());
|
||
}
|
||
for (final c in [
|
||
name,
|
||
secret,
|
||
hostname,
|
||
ip,
|
||
peers,
|
||
target,
|
||
count,
|
||
relayIds,
|
||
]) {
|
||
c.dispose();
|
||
}
|
||
super.dispose();
|
||
}
|
||
|
||
Widget panel(String title, List<Widget> children) => Card(
|
||
child: Padding(
|
||
padding: const EdgeInsets.all(18),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Text(
|
||
title,
|
||
style: const TextStyle(fontSize: 17, fontWeight: FontWeight.w600),
|
||
),
|
||
const SizedBox(height: 14),
|
||
...children,
|
||
],
|
||
),
|
||
),
|
||
);
|
||
Widget field(
|
||
String label,
|
||
TextEditingController c, {
|
||
bool obscure = false,
|
||
int lines = 1,
|
||
}) => Padding(
|
||
padding: const EdgeInsets.only(bottom: 12),
|
||
child: TextField(
|
||
controller: c,
|
||
obscureText: obscure,
|
||
maxLines: lines,
|
||
decoration: InputDecoration(labelText: label),
|
||
enabled: !busy && !running,
|
||
),
|
||
);
|
||
Widget metric(String title, String value) => Expanded(
|
||
child: panel(title, [
|
||
Text(
|
||
value,
|
||
style: const TextStyle(
|
||
fontSize: 30,
|
||
fontWeight: FontWeight.w600,
|
||
color: Color(0xff8a611c),
|
||
),
|
||
),
|
||
]),
|
||
);
|
||
Widget overview() => Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Card(
|
||
color: const Color(0xffe4f3f5),
|
||
child: ListTile(
|
||
leading: Icon(
|
||
running ? Icons.circle : Icons.circle_outlined,
|
||
color: const Color(0xff087d8e),
|
||
),
|
||
title: Text(running ? '引擎运行中 · ${status['peer_count']} 个节点' : '尚未连接'),
|
||
subtitle: Text(
|
||
'虚拟 IP:${status['ipv4'] ?? '—'} · ${status['runtime_mode'] == 'system_vpn' ? '系统 VPN · ${status['platform_network']?['ready'] == true ? '虚拟网卡就绪' : '虚拟网卡未就绪'}' : '应用内网络'}',
|
||
),
|
||
trailing: TextButton(
|
||
onPressed: busy || client == null
|
||
? null
|
||
: () => perform(
|
||
running
|
||
? (c) async {
|
||
await stopActive(c);
|
||
}
|
||
: connect,
|
||
),
|
||
child: Text(running ? '断开连接' : '连接网络'),
|
||
),
|
||
),
|
||
),
|
||
Row(
|
||
children: [
|
||
metric(
|
||
'最近测试耗时',
|
||
result == null
|
||
? '—'
|
||
: '${(result!['elapsed_ms'] as num).toStringAsFixed(1)} ms',
|
||
),
|
||
metric('远端节点', '${status['peer_count'] ?? 0}'),
|
||
],
|
||
),
|
||
panel('网络流量', [
|
||
Row(
|
||
children: [
|
||
metric(
|
||
'↓ 下载速率',
|
||
formatBytes(
|
||
status['traffic']?['rx_bytes_per_second'] as num?,
|
||
rate: true,
|
||
),
|
||
),
|
||
metric(
|
||
'↑ 上传速率',
|
||
formatBytes(
|
||
status['traffic']?['tx_bytes_per_second'] as num?,
|
||
rate: true,
|
||
),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 8),
|
||
Text(
|
||
'本次引擎运行累计 ↓ ${formatBytes(status['traffic']?['rx_bytes'] as num?)} ↑ ${formatBytes(status['traffic']?['tx_bytes'] as num?)}',
|
||
),
|
||
const Text('隧道流量,包含心跳与组网控制报文;每 2 秒刷新'),
|
||
]),
|
||
panel('远端子网', [
|
||
Text(
|
||
'自动接入:${(status['platform_network']?['subnet_routes'] as List? ?? []).isEmpty ? '无' : (status['platform_network']['subnet_routes'] as List).join(', ')}',
|
||
),
|
||
const Text('自动学习节点发布的子网;列表显示允许接入的路由。系统模式可在路由表确认接口。'),
|
||
]),
|
||
panel('节点链路', [NodeTelemetry(status: status)]),
|
||
panel('NAT 与穿透诊断', [
|
||
Text(
|
||
'UDP NAT:${status['connectivity']?['udp_nat_type'] ?? '等待检测'} · TCP NAT:${status['connectivity']?['tcp_nat_type'] ?? '等待检测'}',
|
||
),
|
||
Text(
|
||
'实际监听:${(status['connectivity']?['listeners'] as List? ?? []).join(', ').isEmpty ? '无普通监听端口' : (status['connectivity']['listeners'] as List).join(', ')}',
|
||
),
|
||
const Text('本库未启用 UPnP;无普通监听端口不等于关闭打洞。'),
|
||
TextButton.icon(
|
||
onPressed: () async {
|
||
await Clipboard.setData(
|
||
ClipboardData(
|
||
text: const JsonEncoder.withIndent(' ').convert(status),
|
||
),
|
||
);
|
||
log('网络诊断已复制(不含网络密钥,含节点名称和地址)');
|
||
},
|
||
icon: const Icon(Icons.copy),
|
||
label: const Text('复制网络诊断'),
|
||
),
|
||
]),
|
||
panel('最近测试趋势', [
|
||
const Text('显示连接或回显耗时,并非持续服务器 RTT'),
|
||
const SizedBox(height: 12),
|
||
SizedBox(height: 140, child: CustomPaint(painter: _Trend(latencies))),
|
||
]),
|
||
panel('快速测试', [
|
||
Text('目标 ${target.text}'),
|
||
const SizedBox(height: 12),
|
||
FilledButton.icon(
|
||
onPressed: () => setState(() => page = 2),
|
||
icon: const Icon(Icons.play_arrow),
|
||
label: const Text('打开连接测试'),
|
||
),
|
||
]),
|
||
panel(
|
||
'最近事件',
|
||
logs
|
||
.take(4)
|
||
.map(
|
||
(v) => Padding(
|
||
padding: const EdgeInsets.only(bottom: 8),
|
||
child: Text(v),
|
||
),
|
||
)
|
||
.toList(),
|
||
),
|
||
],
|
||
);
|
||
Widget nodes() => panel('节点与链路', [NodeTelemetry(status: status)]);
|
||
|
||
Widget tests() => Column(
|
||
children: [
|
||
SegmentedButton<bool>(
|
||
segments: const [
|
||
ButtonSegment(value: false, label: Text('连接测试')),
|
||
ButtonSegment(value: true, label: Text('稳定性')),
|
||
],
|
||
selected: {stability},
|
||
onSelectionChanged: busy
|
||
? null
|
||
: (s) => setState(() => stability = s.first),
|
||
),
|
||
const SizedBox(height: 12),
|
||
panel(stability ? '重复探测' : 'TCP / UDP 连接测试', [
|
||
TextField(
|
||
controller: target,
|
||
enabled: !busy,
|
||
decoration: const InputDecoration(labelText: '目标虚拟 IP:端口'),
|
||
),
|
||
const SizedBox(height: 12),
|
||
SegmentedButton<bool>(
|
||
segments: const [
|
||
ButtonSegment(value: false, label: Text('TCP')),
|
||
ButtonSegment(value: true, label: Text('UDP')),
|
||
],
|
||
selected: {udp},
|
||
onSelectionChanged: busy
|
||
? null
|
||
: (s) => setState(() => udp = s.first),
|
||
),
|
||
SwitchListTile(
|
||
contentPadding: EdgeInsets.zero,
|
||
title: const Text('回显与数据校验'),
|
||
subtitle: Text(udp ? 'UDP 必须有回显服务端响应' : '关闭时只验证 TCP 建连;开启需回显服务端'),
|
||
value: echo || udp,
|
||
onChanged: busy || udp ? null : (v) => setState(() => echo = v),
|
||
),
|
||
if (stability) ...[
|
||
TextField(
|
||
controller: count,
|
||
enabled: !busy,
|
||
keyboardType: TextInputType.number,
|
||
decoration: const InputDecoration(labelText: '次数(1–10000)'),
|
||
),
|
||
const SizedBox(height: 12),
|
||
Text('完成 $completed · 失败 $failed'),
|
||
const SizedBox(height: 10),
|
||
const Text('此模式反复创建连接/套接字,不重启组网引擎。'),
|
||
],
|
||
const SizedBox(height: 12),
|
||
FilledButton(
|
||
onPressed: busy || !running
|
||
? null
|
||
: () => perform(stability ? repeat : probe),
|
||
child: Text(busy ? '测试进行中…' : '开始测试'),
|
||
),
|
||
if (busy && stability)
|
||
OutlinedButton(
|
||
onPressed: () => setState(() => cancel = true),
|
||
child: const Text('停止(当前探测结束后)'),
|
||
),
|
||
]),
|
||
qualityPanel(),
|
||
if (result != null)
|
||
panel('最近成功结果', [
|
||
Text(
|
||
const JsonEncoder.withIndent(' ').convert(result),
|
||
style: const TextStyle(fontFamily: 'monospace'),
|
||
),
|
||
]),
|
||
],
|
||
);
|
||
Widget profilePanel() => panel('配置保存', [
|
||
Text(
|
||
savedConfig == null
|
||
? '保存后,下次启动自动填写网络配置。网络密钥保存在 $profileStorage 中。'
|
||
: '已保存网络配置 · 启动时自动载入,手动点击连接。',
|
||
),
|
||
const SizedBox(height: 12),
|
||
Wrap(
|
||
spacing: 12,
|
||
runSpacing: 8,
|
||
children: [
|
||
FilledButton.icon(
|
||
onPressed: busy || client == null
|
||
? null
|
||
: () =>
|
||
perform((_) => saveProfile(buildConfig(), explicit: true)),
|
||
icon: const Icon(Icons.save_outlined),
|
||
label: const Text('保存配置'),
|
||
),
|
||
if (savedConfig != null) ...[
|
||
OutlinedButton(
|
||
onPressed: busy || running
|
||
? null
|
||
: () => perform((_) => loadForm(savedConfig!)),
|
||
child: const Text('重新载入配置'),
|
||
),
|
||
TextButton(
|
||
onPressed: busy || running
|
||
? null
|
||
: () async {
|
||
try {
|
||
await vpnChannel.invokeMethod<void>('delete_profile');
|
||
if (mounted) {
|
||
setState(() {
|
||
savedConfig = null;
|
||
rememberConfig = false;
|
||
});
|
||
}
|
||
log('已删除保存的配置');
|
||
} catch (_) {
|
||
log('删除已保存配置失败');
|
||
}
|
||
},
|
||
child: const Text('删除已保存配置'),
|
||
),
|
||
],
|
||
],
|
||
),
|
||
SwitchListTile(
|
||
contentPadding: EdgeInsets.zero,
|
||
title: const Text('连接成功后自动保存配置'),
|
||
subtitle: const Text('包含网络密钥;不会在启动时自动连接'),
|
||
value: rememberConfig,
|
||
onChanged: busy
|
||
? null
|
||
: (value) => setState(() => rememberConfig = value),
|
||
),
|
||
if (loadedConfig != null)
|
||
const Text('载入的完整 TOML 会原样保留;修改表单后,连接和保存将使用表单生成的配置。'),
|
||
]);
|
||
|
||
Widget settings() => Column(
|
||
children: [
|
||
if (profileSupported) profilePanel(),
|
||
panel('网络配置', [
|
||
if (running)
|
||
const Padding(
|
||
padding: EdgeInsets.only(bottom: 12),
|
||
child: Text('编辑配置前请先断开连接。'),
|
||
),
|
||
SegmentedButton<int>(
|
||
segments: const [
|
||
ButtonSegment(value: 0, label: Text('基础')),
|
||
ButtonSegment(value: 1, label: Text('连接')),
|
||
ButtonSegment(value: 2, label: Text('导入')),
|
||
],
|
||
selected: {configTab},
|
||
onSelectionChanged: (s) => setState(() => configTab = s.first),
|
||
),
|
||
const SizedBox(height: 16),
|
||
if (configTab == 0) ...[
|
||
DropdownButtonFormField<String>(
|
||
key: ValueKey(runtimeMode),
|
||
initialValue: runtimeMode,
|
||
decoration: const InputDecoration(labelText: '运行模式'),
|
||
items: [
|
||
const DropdownMenuItem(
|
||
value: 'application',
|
||
child: Text('应用内 · 仅 SDK 通信'),
|
||
),
|
||
DropdownMenuItem(
|
||
value: 'system_vpn',
|
||
enabled: Platform.isMacOS || Platform.isAndroid,
|
||
child: Text(
|
||
'系统 VPN · 供其他应用使用(${Platform.isAndroid ? 'Android' : 'macOS'})',
|
||
),
|
||
),
|
||
],
|
||
onChanged: busy || running
|
||
? null
|
||
: (v) => setState(() {
|
||
runtimeMode = v!;
|
||
if (v == 'system_vpn') autoIp = false;
|
||
}),
|
||
),
|
||
if (runtimeMode == 'system_vpn')
|
||
Text(
|
||
'${Platform.isAndroid ? '连接时需要 Android VPN 授权。' : '连接时需要管理员授权。'}使用静态私有 IPv4,仅路由虚拟网段和允许接入的私有子网,不修改默认网关或 DNS。',
|
||
),
|
||
...[
|
||
const Text('自动模式过滤默认路由、公网网段、过宽网段及与本机接口重叠的子网。最多接入 32 个 /16~/32 子网。'),
|
||
],
|
||
field('网络名称', name),
|
||
field('网络密钥', secret, obscure: true),
|
||
field('节点名称', hostname),
|
||
SwitchListTile(
|
||
contentPadding: EdgeInsets.zero,
|
||
title: const Text('自动分配虚拟 IP'),
|
||
value: autoIp,
|
||
onChanged: busy || running || runtimeMode == 'system_vpn'
|
||
? null
|
||
: (v) => setState(() => autoIp = v),
|
||
),
|
||
if (!autoIp) field('虚拟 IPv4', ip),
|
||
field('初始节点(每行一个 tcp:// 或 udp:// 地址)', peers, lines: 3),
|
||
],
|
||
if (configTab == 1) ...[
|
||
DropdownButtonFormField<String>(
|
||
key: ValueKey(routeMode),
|
||
initialValue: routeMode,
|
||
decoration: const InputDecoration(labelText: '线路策略'),
|
||
items: const [
|
||
DropdownMenuItem(
|
||
value: 'adaptive',
|
||
child: Text('自适应 · 质量接近优先直连'),
|
||
),
|
||
DropdownMenuItem(value: 'direct', child: Text('优先直连')),
|
||
DropdownMenuItem(value: 'latency', child: Text('延迟估算优先')),
|
||
DropdownMenuItem(value: 'hop', child: Text('最少跳数')),
|
||
],
|
||
onChanged: busy || running
|
||
? null
|
||
: (v) => setState(() {
|
||
routeMode = v!;
|
||
latencyFirst = v == 'adaptive' || v == 'latency';
|
||
}),
|
||
),
|
||
const Text('自适应:估算改善至少 15 ms 且 15%,持续 10 秒;切换冷却 30 秒。'),
|
||
SwitchListTile(
|
||
title: const Text('优先使用已确认的 UDP 连接'),
|
||
value: preferUdp,
|
||
onChanged: busy || running
|
||
? null
|
||
: (v) => setState(() => preferUdp = v),
|
||
),
|
||
field('中继下一跳节点 ID(逗号分隔,留空不限制)', relayIds),
|
||
SwitchListTile(
|
||
title: const Text('底层 IPv6'),
|
||
value: ipv6,
|
||
onChanged: busy || running ? null : (v) => setState(() => ipv6 = v),
|
||
),
|
||
const Text('当前支持 UDP/TCP 传输和 IPv4 数据面。高级配置可通过 TOML 导入;不支持的选项会明确拒绝。'),
|
||
],
|
||
if (configTab == 2) ...[
|
||
OutlinedButton(
|
||
onPressed: busy || running ? null : importConfig,
|
||
child: const Text('粘贴 TOML 并连接'),
|
||
),
|
||
OutlinedButton(
|
||
onPressed: () async {
|
||
final text = buildFormConfig().replaceFirst(
|
||
RegExp(r'network_secret = .*'),
|
||
'network_secret = ""',
|
||
);
|
||
await Clipboard.setData(ClipboardData(text: text));
|
||
log('已复制配置(不含密钥)');
|
||
},
|
||
child: const Text('复制配置(不含密钥)'),
|
||
),
|
||
],
|
||
const SizedBox(height: 12),
|
||
FilledButton(
|
||
onPressed: busy || running || client == null
|
||
? null
|
||
: () => perform(connect),
|
||
child: const Text('校验并连接'),
|
||
),
|
||
]),
|
||
panel('日志', [
|
||
Row(
|
||
children: [
|
||
Expanded(child: Text('${logs.length} 条事件')),
|
||
TextButton(
|
||
onPressed: () async {
|
||
await Clipboard.setData(ClipboardData(text: logs.join('\n')));
|
||
log('日志已复制');
|
||
},
|
||
child: const Text('复制日志'),
|
||
),
|
||
],
|
||
),
|
||
...logs
|
||
.take(30)
|
||
.map(
|
||
(v) => Padding(
|
||
padding: const EdgeInsets.only(bottom: 8),
|
||
child: Text(
|
||
v,
|
||
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
|
||
),
|
||
),
|
||
),
|
||
]),
|
||
panel('关于', [
|
||
const Text(
|
||
'MeshPort 0.1.0 · 预览版\n应用内模式:仅 SDK 连接进入虚拟网络。\n系统 VPN:创建虚拟网卡,自动接入虚拟网段与节点公告子网。\n不修改默认网关和系统 DNS。\nAndroid 已接入应用内与系统 VPN;iOS 尚待验证。',
|
||
),
|
||
]),
|
||
],
|
||
);
|
||
Future<void> importConfig() async {
|
||
final text = await showDialog<String>(
|
||
context: context,
|
||
builder: (_) => const ConfigImportDialog(),
|
||
);
|
||
if (text != null && mounted) {
|
||
await perform((c) async {
|
||
await loadForm(text);
|
||
await startConfig(text);
|
||
log('导入配置并启动引擎');
|
||
});
|
||
}
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final pages = [overview, nodes, tests, settings];
|
||
const labels = ['概览', '节点', '测试', '设置'];
|
||
final wide = MediaQuery.sizeOf(context).width >= 850;
|
||
final body = Column(
|
||
children: [
|
||
if (error.isNotEmpty)
|
||
MaterialBanner(
|
||
content: Text(error),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () => setState(() => error = ''),
|
||
child: const Text('关闭'),
|
||
),
|
||
],
|
||
),
|
||
Expanded(
|
||
child: SingleChildScrollView(
|
||
padding: const EdgeInsets.all(16),
|
||
child: Center(
|
||
child: ConstrainedBox(
|
||
constraints: const BoxConstraints(maxWidth: 1000),
|
||
child: pages[page](),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
],
|
||
);
|
||
const destinations = [
|
||
NavigationDestination(icon: Icon(Icons.dashboard_outlined), label: '概览'),
|
||
NavigationDestination(icon: Icon(Icons.hub_outlined), label: '节点'),
|
||
NavigationDestination(icon: Icon(Icons.science_outlined), label: '测试'),
|
||
NavigationDestination(icon: Icon(Icons.settings_outlined), label: '设置'),
|
||
];
|
||
return Scaffold(
|
||
appBar: AppBar(
|
||
title: Row(
|
||
children: [
|
||
Image.asset(
|
||
'assets/branding/meshport.png',
|
||
width: 32,
|
||
height: 32,
|
||
semanticLabel: 'MeshPort',
|
||
),
|
||
const SizedBox(width: 10),
|
||
Text('MeshPort / ${labels[page]}'),
|
||
],
|
||
),
|
||
actions: [
|
||
Padding(
|
||
padding: const EdgeInsets.only(right: 20),
|
||
child: Center(child: Text(name.text)),
|
||
),
|
||
],
|
||
),
|
||
body: wide
|
||
? Row(
|
||
children: [
|
||
NavigationRail(
|
||
selectedIndex: page,
|
||
onDestinationSelected: (v) => setState(() => page = v),
|
||
labelType: NavigationRailLabelType.all,
|
||
destinations: destinations
|
||
.map(
|
||
(d) => NavigationRailDestination(
|
||
icon: d.icon,
|
||
label: Text(d.label),
|
||
),
|
||
)
|
||
.toList(),
|
||
),
|
||
const VerticalDivider(width: 1),
|
||
Expanded(child: body),
|
||
],
|
||
)
|
||
: body,
|
||
bottomNavigationBar: wide
|
||
? null
|
||
: NavigationBar(
|
||
selectedIndex: page,
|
||
onDestinationSelected: (v) => setState(() => page = v),
|
||
destinations: destinations,
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
class _Trend extends CustomPainter {
|
||
final List<double> samples;
|
||
_Trend(this.samples);
|
||
@override
|
||
void paint(Canvas canvas, Size size) {
|
||
final grid = Paint()
|
||
..color = const Color(0xffe9e6e0)
|
||
..strokeWidth = 1;
|
||
for (var i = 0; i < 5; i++) {
|
||
final y = size.height * i / 4;
|
||
canvas.drawLine(Offset(0, y), Offset(size.width, y), grid);
|
||
}
|
||
if (samples.length < 2) {
|
||
return;
|
||
}
|
||
final max = samples.reduce((a, b) => a > b ? a : b) * 1.2 + 1;
|
||
final path = Path();
|
||
for (var i = 0; i < samples.length; i++) {
|
||
final p = Offset(
|
||
size.width * i / (samples.length - 1),
|
||
size.height * (1 - samples[i] / max),
|
||
);
|
||
if (i == 0) {
|
||
path.moveTo(p.dx, p.dy);
|
||
} else {
|
||
path.lineTo(p.dx, p.dy);
|
||
}
|
||
}
|
||
canvas.drawPath(
|
||
path,
|
||
Paint()
|
||
..color = const Color(0xff087d8e)
|
||
..style = PaintingStyle.stroke
|
||
..strokeWidth = 2,
|
||
);
|
||
}
|
||
|
||
@override
|
||
bool shouldRepaint(_Trend oldDelegate) => true;
|
||
}
|