Files
shenleiandClaude Opus 5.5 dc1bfc99d2 Move mesh networking logic into the SDK and fix lifecycle bugs
SDK:
- Add build_config/migrate_config, mesh_cidrs, route_generation, health
  and start_bridged; expose abi_info (capability revision 2).
- Add wait_routes long-poll; stop wakes waiters, and context_free now
  stops the network immediately instead of waiting for waiters to time out.

Hosts:
- Dart: waitRoutes(), MeshProxySession route watcher, ABI capability check.
- Android: fix a deadlock where every VPN request waited on its own
  single-thread worker; requests are now async, status is served from a
  snapshot, and combined mode reports Partial when the mesh stops.
- macOS helper: mesh-only unified mode stops when the mesh is lost;
  installed_subnet_routes excludes the overlay.
- Lab: restore Partial sessions, write migrated profiles back, remove the
  unreachable TOML import dialog; native test now connects via the form.

Docs updated accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:17:42 +09:00

1780 lines
60 KiB
Dart
Raw Permalink 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 '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 'package:meshport_client_core/meshport_client_core.dart';
import 'package:singbox_flutter/singbox_flutter.dart';
import 'network_telemetry.dart';
import 'proxy_panel.dart';
import 'configuration_pages.dart';
import 'detail_pages.dart';
import 'runtime_diagnostics.dart';
import 'proxy_speed_test.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;
MacSystemVpnSession? macVpnSession;
bool legacyMigrationPending = false;
String localProfilePath = Platform.isAndroid
? 'APP 私有目录/MeshPort/'
: '~/Library/Application Support/MeshPort/';
String runtimeMode = Platform.isMacOS || Platform.isAndroid
? 'unified_vpn'
: 'application';
bool singBoxEnabled = false;
MeshProxySession? proxySession;
ProxyProfile proxyProfile = ProxyProfile()
..feature = 'proxy'
..mode = 'global'
..entry = (Platform.isMacOS || Platform.isAndroid
? 'unified_vpn'
: 'application');
String runningProxyLabel = '', runningProxyMode = '';
bool proxyDraftChanged = false;
int proxySavesPending = 0;
bool proxySaveFailed = false;
Future<void> proxySaveTail = Future.value();
bool rememberConfig = false;
String? savedConfig;
String? loadedConfig, loadedForm;
static const vpnChannel = MethodChannel('meshport/system_vpn');
Timer? timer, subscriptionTimer;
bool subscriptionUpdating = false;
String? savedProxyJson;
final subscriptionRetry = <String, DateTime>{};
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;
Map<String, dynamic> networkExtra = {};
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 proxySpeedTest = ProxySpeedTest();
bool speedTesting = false;
ProxySpeedResult? speedResult;
String speedError = '';
double speedProgressMbps = 0;
int speedBytes = 0;
final diagnosticRedactor = DiagnosticRedactor();
String lastProxyState = '';
int proxyEventSequence = 0;
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' ||
status['state'] == 'Partial' ||
proxySession?.state == 'Running' ||
proxySession?.state == 'Partial';
bool get profileSupported => Platform.isMacOS || Platform.isAndroid;
String get profileStorage => '本地配置目录 $localProfilePath';
@override
void initState() {
super.initState();
if (widget.initializeNative) {
unawaited(initialize());
}
}
Future<void> initialize() async {
try {
log('客户端启动 · ${Platform.operatingSystem} · 代理诊断日志已开启');
// A --dart-define wins; the process environment serves `flutter test`
// and development runs. Release builds use the bundled library.
const defined = String.fromEnvironment('MESHPORT_LIBRARY');
final path = defined.isNotEmpty
? defined
: Platform.environment['MESHPORT_LIBRARY'];
final opened = await diagnosticStage(
'加载 MeshPort 动态库',
() => MeshPortClient.open(libraryPath: path),
);
if (!mounted) {
await opened.close();
return;
}
client = applicationClient = opened;
log('原生库已加载 · ABI v1');
if (profileSupported) {
try {
final stored = await vpnChannel.invokeMethod<String>(
'load_proxy_profile',
);
if (stored != null) {
proxyProfile = ProxyProfile.fromJson(
jsonDecode(stored) as Map<String, dynamic>,
);
if (proxyProfile.entry == 'system_vpn') {
proxyProfile.feature = 'mesh';
}
savedProxyJson = jsonEncode(proxyProfile.toJson());
}
} catch (_) {
log('代理配置载入失败,已保留组网配置');
}
}
bool restored = false;
if (profileSupported) {
try {
final stored = await loadMigratedProfile();
if (stored != null) {
await loadForm(stored);
restored = true;
if (mounted) {
setState(() {
savedConfig = stored;
rememberConfig = true;
});
}
log('已自动载入保存的网络配置,点击连接即可组网');
}
} catch (_) {
log('读取已保存配置失败,请在设置中重试');
}
}
if (!restored) {
try {
String defaults;
try {
defaults = await rootBundle.loadString(
'assets/config/default.toml',
);
} on FlutterError {
defaults = await rootBundle.loadString(
'assets/config/default.example.toml',
);
}
await loadForm(defaults);
if (mounted) setState(() => rememberConfig = profileSupported);
log(
proxyProfile.feature == 'proxy'
? (proxyProfile.nodes.isEmpty
? '默认代理设置已就绪,导入节点后即可连接'
: '已载入代理设置,点击连接即可使用')
: secret.text.isEmpty
? '已载入默认配置,首次填写网络密钥后保存即可'
: '已载入默认网络配置,点击连接即可组网',
);
} catch (_) {
log('默认配置加载失败,请在设置中导入配置');
}
}
if (savedProxyJson != null || !restored) {
runtimeMode = proxyProfile.entry;
} else {
proxyProfile.feature = 'mesh';
proxyProfile.entry = runtimeMode;
}
singBoxEnabled = proxyProfile.proxyEnabled;
final diagnostics = await opened.enableDiagnostics();
log(diagnostics['enabled'] == true ? '穿透详细日志采集已开启' : '穿透日志未接管:宿主已有日志订阅器');
if (profileSupported) await checkLocalProfileMigration();
if (Platform.isAndroid) {
final snapshot = await androidVpnRequest({'op': 'status'});
final data = snapshot['data'] as Map?;
// Partial: a combined VPN whose mesh stopped still carries the proxy.
if (data?['state'] == 'Running' || data?['state'] == 'Partial') {
systemClient = client = MeshPortClient.fromTransport(
request: androidVpnRequest,
close: () async {
await androidVpnRequest({'op': 'stop'});
},
);
runtimeMode = data?['runtime_mode'] == 'unified_vpn'
? 'unified_vpn'
: 'system_vpn';
log('已恢复正在运行的 Android VPN 会话');
await refresh();
}
}
subscriptionTimer = Timer.periodic(
const Duration(minutes: 1),
(_) => unawaited(updateDueSubscriptions()),
);
if (Platform.isMacOS || Platform.isAndroid) {
try {
final preferences = await vpnChannel.invokeMapMethod<String, dynamic>(
'startup_status',
);
if (preferences?['auto_connect'] == true &&
!legacyMigrationPending &&
!running &&
(restored ||
(singBoxEnabled && proxyProfile.feature == 'proxy'))) {
log('按已保存配置自动连接');
await perform((_) async {
await startConfig(await startableFormConfig());
runningProxyMode = proxyProfile.modeLabel;
runningProxyLabel =
proxyProfile.nodes
.where((n) => n.id == proxyProfile.selectedId)
.firstOrNull
?.name ??
'无代理节点';
});
}
} catch (_) {
log('自动连接未完成,请手动连接并检查授权');
}
}
unawaited(updateDueSubscriptions());
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;
}
diagnosticRedactor.remember({'network_secret': secret.text});
diagnosticRedactor.remember(proxyProfile.toJson());
text = diagnosticRedactor.sanitize(text);
if ((Platform.isMacOS || Platform.isAndroid) && widget.initializeNative) {
unawaited(
vpnChannel
.invokeMethod<void>('runtime_log', text)
.catchError((Object _) {}),
);
}
setState(() {
logs.insert(
0,
'${DateTime.now().toIso8601String().substring(11, 19)} $text',
);
if (logs.length > 300) {
logs.removeLast();
}
});
}
Future<T> diagnosticStage<T>(
String stage,
Future<T> Function() action,
) async {
final elapsed = Stopwatch()..start();
log('[$stage] 开始');
try {
final result = await action();
log('[$stage] 成功 · ${elapsed.elapsedMilliseconds} ms');
return result;
} catch (e) {
log('[$stage] 失败 · ${elapsed.elapsedMilliseconds} ms · $e');
rethrow;
}
}
Future<void> refresh() async {
if (refreshing) return;
refreshing = true;
try {
final next = client == applicationClient && proxySession != null
? await proxySession!.refresh()
: await client?.status();
if (mounted && next != null) {
for (final event
in (next['proxy'] as Map?)?['runtime_events'] as List? ?? []) {
final sequence = (event['sequence'] as num).toInt();
if (sequence > proxyEventSequence) {
log('代理 · ${event['message']}');
proxyEventSequence = sequence;
}
}
final proxyState = proxySession?.state ?? '';
if (proxyState != lastProxyState) {
lastProxyState = proxyState;
if (proxyState.isNotEmpty) log('代理会话状态 → $proxyState');
}
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) {
log('状态刷新失败 · $e');
if (mounted && proxySession?.state == 'Failed') {
setState(() {
status = {'state': 'Failed', 'peer_count': 0};
error = '代理组网会话已停止:$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);
}
}
}
Future<String> buildConfig() async {
final form = await 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;
networkExtra = Map<String, dynamic>.from(profile);
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(',');
});
// Rendered from the fields just loaded, so an untouched form maps back
// to the original text (and keeps options the form cannot show).
final form = await buildFormConfig();
if (!mounted) return;
loadedConfig = config;
loadedForm = form;
}
Map<String, dynamic> networkValues() => {
...networkExtra,
'runtime_mode': runtimeMode,
'network_name': name.text,
'network_secret': secret.text,
'hostname': hostname.text,
'ipv4': ip.text,
'dhcp': autoIp,
'enable_ipv6': ipv6,
'peers': peers.text
.split('\n')
.map((v) => v.trim())
.where((v) => v.isNotEmpty)
.toList(),
'optimization': {
'min_improvement_ms': 15,
'min_improvement_ratio': 0.15,
'hold_seconds': 10,
'cooldown_seconds': 30,
...?networkExtra['optimization'] as Map<String, dynamic>?,
'mode': routeMode,
'prefer_udp': preferUdp,
'relay_peer_ids': relayIds.text
.split(RegExp(r'[,\s]+'))
.where((v) => v.isNotEmpty)
.map(int.parse)
.toList(),
},
};
Future<String> buildFormConfig() =>
NetworkProfile(networkValues()).toToml(applicationClient!);
/// Application-mode internet-only proxying never starts the mesh, so an
/// incomplete network form must not block it.
Future<String> startableFormConfig() async =>
runtimeMode == 'application' &&
singBoxEnabled &&
proxyProfile.feature == 'proxy'
? ''
: await buildFormConfig();
/// Drops options earlier releases saved; the SDK owns the migration rules.
Future<String?> migratedProfile(String? stored) async =>
stored == null ? null : await applicationClient!.migrateConfig(stored);
/// Loads the saved network profile and, when the SDK migrates it, writes
/// the migrated text back so the legacy form is not reloaded next launch.
Future<String?> loadMigratedProfile() async {
final stored = await vpnChannel.invokeMethod<String>('load_profile');
final migrated = await migratedProfile(stored);
if (migrated != null && migrated != stored) {
try {
await applicationClient!.validate(migrated);
await vpnChannel.invokeMethod<void>('save_profile', migrated);
log('已移除旧版配置项并保存迁移后的网络配置');
} catch (_) {
log('旧版配置已在内存中迁移,但未能写回 $profileStorage');
}
}
return migrated;
}
Future<void> saveNetworkValues(Map<String, dynamic> values) async {
final incoming = NetworkProfile(values).values;
final policy = incoming['optimization'] as Map;
policy['relay_peer_ids'] = (policy['relay_peer_ids'] as List? ?? [])
.map((v) => v is int ? v : int.parse('$v'))
.toList();
if (incoming['runtime_mode'] != 'application') incoming['dhcp'] = false;
final toml = await NetworkProfile(incoming).toToml(applicationClient!);
await applicationClient!.request({'op': 'validate', 'toml': toml});
await saveProfile(toml, explicit: true);
await loadForm(toml);
proxyProfile.entry = incoming['runtime_mode'];
await saveProxyProfile();
setState(() {
networkExtra = incoming;
runtimeMode = incoming['runtime_mode'];
singBoxEnabled = runtimeMode == 'unified_vpn' || singBoxEnabled;
});
}
Future<void> openDetail(String title, Widget Function() builder) =>
Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => LiveDetailPage(title: title, builder: builder),
),
);
Future<void> openNetworkConfig(String section) async {
await Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => NetworkConfigPage(
section: section,
initial: networkValues(),
save: saveNetworkValues,
),
),
);
}
Future<void> connect(MeshPortClient c) async {
final config = await buildConfig();
await startConfig(config);
proxyProfile.entry = runtimeMode;
proxyProfile.proxyEnabled = singBoxEnabled;
if (profileSupported) await saveProxyProfile();
log(
singBoxEnabled && proxyProfile.feature == 'proxy'
? '代理引擎已启动'
: '组网引擎已启动,等待节点连接',
);
}
Future<void> startConfig(String config) async {
proxySpeedTest.cancel();
speedResult = null;
speedError = '';
proxyEventSequence = 0;
if (singBoxEnabled) proxyProfile.validateConnection();
// Validation selects mode from effective flags, avoiding ad-hoc TOML parsing.
final validated = singBoxEnabled && proxyProfile.feature == 'proxy'
? <String, dynamic>{'runtime_mode': 'application'}
: await diagnosticStage(
'校验组网配置',
() =>
applicationClient!.request({'op': 'validate', 'toml': config}),
);
final unified = runtimeMode == 'unified_vpn';
final system = validated['runtime_mode'] == 'system_vpn' || unified;
if (proxySession != null) {
await proxySession!.close();
proxySession = null;
}
if (systemClient != null) {
try {
if (Platform.isMacOS && macVpnSession != null) {
await macVpnSession!.release(systemClient!);
} else {
await systemClient!.close();
}
} catch (_) {}
systemClient = null;
client = applicationClient;
}
if (!system) {
if (singBoxEnabled) {
proxySession = MeshProxySession(
mesh: applicationClient!,
proxy: await diagnosticStage(
'加载 sing-box 动态库',
NativeProxyEngine.open,
),
profile:
jsonDecode(jsonEncode(proxyProfile.runtime()))
as Map<String, dynamic>,
);
await diagnosticStage('启动应用内代理会话', () => proxySession!.start(config));
log('sing-box 组网入口:${proxySession!.endpoint ?? '等待虚拟地址'}');
} else {
await diagnosticStage('启动组网引擎', () => applicationClient!.start(config));
}
if (!singBoxEnabled || proxyProfile.feature != 'proxy') {
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 (macVpnSession ??= MacSystemVpnSession(
open: () => openMacSystemVpn(
launch: (path, uid) async {
log('等待管理员授权以创建虚拟网卡');
await diagnosticStage(
'授权并启动 macOS VPN 辅助进程',
() => vpnChannel.invokeMethod<void>('launch', {
'socket': path,
'uid': uid,
}),
);
},
),
)).acquire();
try {
await opened.enableDiagnostics();
if (unified) {
await diagnosticStage(
'启动统一 VPN 代理',
() => opened.request({
'op': 'start',
'toml': config,
'unified_profile': proxyProfile.runtime(),
}),
);
} else {
await opened.start(config);
}
systemClient = client = opened;
log(
unified && proxyProfile.feature == 'proxy'
? '统一 VPN 已启动,互联网流量已接入'
: '系统 VPN 已启动,接入虚拟网段与远端子网',
);
await saveProfile(config);
} catch (_) {
await opened.close();
rethrow;
}
}
Future<void> checkLocalProfileMigration() async {
try {
final info = await vpnChannel.invokeMapMethod<String, dynamic>(
'profile_storage_status',
);
if (mounted) {
setState(() {
legacyMigrationPending = info?['migration_pending'] == true;
if (info?['path'] is String) {
localProfilePath = info!['path'] as String;
}
});
}
if (legacyMigrationPending) log('旧配置需要迁移,请在设置中点击“迁移旧配置”');
} catch (_) {
log('无法检查本地配置目录,请在设置中重试');
}
}
Future<void> migrateLegacyProfiles() async {
await vpnChannel.invokeMethod<void>('migrate_profiles');
final proxy = await vpnChannel.invokeMethod<String>('load_proxy_profile');
final network = await loadMigratedProfile();
if (network != null) await loadForm(network);
if (proxy != null) {
final imported = ProxyProfile.fromJson(
jsonDecode(proxy) as Map<String, dynamic>,
);
if (imported.entry == 'system_vpn') imported.feature = 'mesh';
proxyProfile = imported;
savedProxyJson = jsonEncode(imported.toJson());
runtimeMode = imported.entry;
singBoxEnabled = imported.proxyEnabled;
}
if (network != null) {
savedConfig = network;
rememberConfig = true;
}
await checkLocalProfileMigration();
if (mounted) setState(() {});
log('旧配置已迁移,后续读取和保存使用本地文件');
}
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 {
proxySpeedTest.cancel();
try {
if (c == applicationClient && proxySession != null) {
await proxySession!.stop();
}
if (Platform.isMacOS && c == systemClient && macVpnSession != null) {
await macVpnSession!.release(c);
} else {
await c.stop();
}
} finally {
if (systemClient != null) {
try {
if (!Platform.isMacOS || macVpnSession == null) {
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;
proxySpeedTest.cancel();
timer?.cancel();
subscriptionTimer?.cancel();
unawaited(
macVpnSession?.close().catchError((Object _) {}) ?? Future<void>.value(),
);
if (client != null) {
final active = client!,
application = applicationClient,
session = proxySession;
unawaited(
() async {
try {
await session?.close();
} finally {
await active.close();
if (application != null && application != active) {
await application.close();
}
}
}().catchError((Object _) {}),
);
}
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),
for (final child in children) ...[child, const SizedBox(height: 12)],
],
),
),
);
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) => panel(title, [
Text(
value,
style: const TextStyle(
fontSize: 30,
fontWeight: FontWeight.w600,
color: Color(0xff8a611c),
),
),
]);
Widget metricGroup(List<Widget> children) => LayoutBuilder(
builder: (context, constraints) {
final narrow =
constraints.maxWidth < 520 ||
MediaQuery.textScalerOf(context).scale(1) > 1.3;
return narrow
? Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
)
: Row(
children: [for (final child in children) Expanded(child: child)],
);
},
);
Future<void> measureProxySpeed() async {
if (speedTesting || busy || !running) return;
setState(() {
speedTesting = true;
speedResult = null;
speedError = '';
speedBytes = 0;
speedProgressMbps = 0;
});
log('代理测速 · 开始 · $runningProxyMode · $runningProxyLabel');
var lastUpdate = Duration.zero;
try {
final measured = await proxySpeedTest.run(
port: proxySession?.port ?? 10818,
onProgress: (bytes, elapsed) {
if (!mounted ||
elapsed - lastUpdate < const Duration(milliseconds: 250)) {
return;
}
lastUpdate = elapsed;
setState(() {
speedBytes = bytes;
speedProgressMbps =
bytes * 8 / elapsed.inMicroseconds.clamp(1, 1 << 62);
});
},
);
if (!mounted) return;
setState(() {
speedResult = measured;
speedBytes = measured.bytes;
});
log(
'代理测速 · ${measured.mbps.toStringAsFixed(1)} Mbps · '
'${formatBytes(measured.bytes)} · 首字节 ${measured.firstByte.inMilliseconds} ms',
);
} catch (e) {
if (mounted) {
setState(() => speedError = diagnosticRedactor.sanitize('$e'));
log('代理测速 · $e');
}
} finally {
if (mounted) setState(() => speedTesting = false);
}
}
Widget speedPanel() => panel('代理测速', [
Text(
speedTesting
? '${speedProgressMbps.toStringAsFixed(1)} Mbps · 已下载 ${formatBytes(speedBytes)}'
: speedResult == null
? '尚未测速'
: '${speedResult!.mbps.toStringAsFixed(1)} Mbps · '
'${(speedResult!.mbps / 8).toStringAsFixed(2)} MB/s',
),
if (speedResult != null)
Text(
'首字节 ${speedResult!.firstByte.inMilliseconds} ms · '
'下载 ${formatBytes(speedResult!.bytes)}',
),
if (speedTesting) const LinearProgressIndicator(),
if (speedError.isNotEmpty) Text(speedError),
const Text(
'通过当前代理入口下载 Cloudflare 测试资源,遵循当前分流规则。最多 32 MB / 15 秒,会占用带宽;结果不代表视频站点速度。',
),
if (!running) const Text('连接代理后可测速'),
Wrap(
spacing: 12,
children: [
FilledButton.tonalIcon(
onPressed: !running || busy || speedTesting
? null
: measureProxySpeed,
icon: const Icon(Icons.speed),
label: const Text('开始测速'),
),
if (speedTesting)
TextButton(
onPressed: proxySpeedTest.cancel,
child: const Text('取消测速'),
),
],
),
]);
Widget overview() {
if (proxyProfile.feature != 'proxy') return networkOverview();
final selected = proxyProfile.nodes
.where((node) => node.id == proxyProfile.selectedId)
.firstOrNull;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
panel('连接', [
ListTile(
leading: Icon(
running ? Icons.check_circle_outline : Icons.power_settings_new,
),
title: Text(running ? '代理已连接' : '尚未连接'),
subtitle: Text(
running && runningProxyLabel.isNotEmpty
? '$runningProxyMode · $runningProxyLabel'
: selected == null
? '导入一个节点即可开始'
: '${proxyProfile.modeLabel} · ${selected.name}',
),
trailing: TextButton(
onPressed: busy || client == null ? null : primaryConnection,
child: Text(
running ? (proxyDraftChanged ? '重连应用修改' : '断开连接') : '连接',
),
),
),
if (proxyDraftChanged) const Text('配置已修改,重连后生效。'),
Wrap(
spacing: 12,
runSpacing: 12,
children: [
FilledButton.tonal(
onPressed: () => setState(() => page = 1),
child: const Text('管理代理节点'),
),
OutlinedButton(
onPressed: () => openDetail(
'运行日志',
() => LogsPageBody(
logs: logs,
onClear: () => setState(() => logs.clear()),
),
),
child: const Text('诊断与日志'),
),
],
),
]),
speedPanel(),
if (logs.isNotEmpty)
panel('最近事件', [
...logs.take(3).map((line) => Text(line)),
TextButton.icon(
onPressed: () async {
await Clipboard.setData(ClipboardData(text: logs.join('\n')));
log('已复制全部运行日志(${logs.length} 条)');
},
icon: const Icon(Icons.copy),
label: Text('复制全部日志(${logs.length} 条)'),
),
]),
],
);
}
Widget networkOverview() => 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(
proxySession?.state == 'Partial'
? '代理运行中 · 组网暂不可用'
: running
? '引擎运行中 · ${status['peer_count'] ?? 0} 个节点'
: '尚未连接',
),
subtitle: Text(
'虚拟 IP:${status['ipv4'] ?? '—'} · ${status['runtime_mode'] == 'unified_vpn'
? '统一 VPN · sing-box TUN'
: status['runtime_mode'] == 'system_vpn'
? '系统 VPN · ${status['platform_network']?['ready'] == true ? '虚拟网卡就绪' : '虚拟网卡未就绪'}'
: '应用内网络'}',
),
trailing: TextButton(
onPressed: busy || client == null ? null : primaryConnection,
child: Text(
running ? (proxyDraftChanged ? '重连应用修改' : '断开连接') : '连接',
),
),
),
),
if (singBoxEnabled && runtimeMode == 'application')
panel('sing-box 组网入口', [
Text(
'状态:${proxySession?.state ?? 'Stopped'} · 运行模式:$runningProxyMode',
),
Text(
'运行出口:$runningProxyLabel${proxyDraftChanged ? ' · 草稿尚未生效' : ''}',
),
SelectableText('SOCKS5:${proxySession?.endpoint ?? '—'}'),
const Text('TCP / UDP · 自动公告分流。子网变化时重建引擎,已有代理连接需重连。'),
]),
if (proxyProfile.feature == 'combined') speedPanel(),
panel('网络流量', [
metricGroup([
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('最近事件', [
...logs
.take(4)
.map(
(v) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(v),
),
),
TextButton.icon(
onPressed: () async {
await Clipboard.setData(ClipboardData(text: logs.join('\n')));
log('已复制全部运行日志(${logs.length} 条)');
},
icon: const Icon(Icons.copy),
label: Text('复制全部日志(${logs.length} 条)'),
),
]),
],
);
Widget nodes() => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
panel('组网配置', [
ListTile(
title: const Text('基础配置'),
trailing: const Icon(Icons.chevron_right),
onTap: () => openNetworkConfig('基础配置'),
),
ExpansionTile(
title: const Text('高级组网设置'),
children: [
for (final title in ['连接与打洞', '高级配置', '线路策略'])
ListTile(
title: Text(title),
trailing: const Icon(Icons.chevron_right),
onTap: () => openNetworkConfig(title),
),
],
),
ListTile(
title: const Text('自动接入子网'),
trailing: const Icon(Icons.chevron_right),
onTap: () => openDetail(
'自动接入子网',
() => SubnetListPageBody(
status: status,
statusProvider: () => status,
),
),
),
ListTile(
title: const Text('网络诊断'),
trailing: const Icon(Icons.chevron_right),
onTap: () => openDetail('网络诊断', tests),
),
]),
panel('节点与链路', [
NodeTelemetry(
status: status,
onNode: (node, peer) => openDetail('节点详情', () {
return NodeDetailBody(node: node, peer: peer, 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 Text('优先级:已保存配置 → 安装包默认 → 空配置。自用安装包内的默认密钥可以被提取。'),
OutlinedButton(
onPressed: busy
? null
: () async {
if (!await confirmDiscard(context)) return;
String defaults;
try {
defaults = await rootBundle.loadString(
'assets/config/default.toml',
);
} catch (_) {
defaults = await rootBundle.loadString(
'assets/config/default.example.toml',
);
}
await loadForm(defaults);
log('已恢复安装包默认到草稿,尚未保存或连接');
},
child: const Text('恢复安装包默认(草稿)'),
),
const SizedBox(height: 12),
Wrap(
spacing: 12,
runSpacing: 8,
children: [
FilledButton.icon(
onPressed: busy || client == null
? null
: () => perform(
(_) async => saveProfile(await 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: [
panel('应用设置', [
if (profileSupported) ...[
ListTile(
title: const Text('配置保存位置'),
subtitle: Text(localProfilePath),
),
if (legacyMigrationPending)
ListTile(
title: const Text('迁移旧配置'),
subtitle: Text(
Platform.isMacOS
? '点击后可能需要钥匙串授权;迁移后使用本地文件。'
: '读取旧版保存的配置并迁移到本地文件。',
),
trailing: const Icon(Icons.chevron_right),
onTap: busy || running
? null
: () => perform((_) => migrateLegacyProfiles()),
),
],
ListTile(
title: const Text('DNS 设置'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) =>
DnsPage(profile: proxyProfile, changed: proxyChanged),
),
),
),
ListTile(
title: const Text('默认配置'),
trailing: const Icon(Icons.chevron_right),
onTap: () => openDetail('默认配置', profilePanel),
),
ListTile(
title: const Text('启动与后台'),
trailing: const Icon(Icons.chevron_right),
onTap: () =>
openDetail('启动与后台', () => StartupPageBody(channel: vpnChannel)),
),
ListTile(
title: const Text('运行日志'),
trailing: const Icon(Icons.chevron_right),
onTap: () => openDetail(
'运行日志',
() => LogsPageBody(
logs: logs,
onClear: () => setState(() => logs.clear()),
),
),
),
ListTile(
title: const Text('首次使用说明'),
trailing: const Icon(Icons.chevron_right),
onTap: () => openDetail('首次使用', () => const OnboardingBody()),
),
]),
panel('关于', [
const Text(
'MeshPort 0.1.0 · 开发版\n应用内:SDK 组网及可选本机 SOCKS5 代理入口。\n独立系统组网:仅接管虚拟网段与公告子网。\nAndroid 统一 VPN:单一 TUN 分流原型,待真机验证。\nmacOS 统一 TUN 已接入 helper,实际运行验证以文档记录为准;iOS 尚未接入。',
),
]),
],
);
Future<void> updateDueSubscriptions() async {
if (!mounted ||
busy ||
subscriptionUpdating ||
proxySavesPending > 0 ||
savedProxyJson != jsonEncode(proxyProfile.toJson()) ||
!profileSupported) {
return;
}
subscriptionUpdating = true;
try {
for (final sub in List<Map<String, dynamic>>.from(
proxyProfile.subscriptions,
)) {
final now = DateTime.now(), id = sub['id'] as String;
if (!subscriptionDue(sub, now) ||
(subscriptionRetry[id]?.isAfter(now) ?? false)) {
continue;
}
final before = jsonEncode(proxyProfile.toJson());
try {
final preview = await fetchSubscription(
sub['url'] as String,
source: id,
);
if (!mounted || busy || jsonEncode(proxyProfile.toJson()) != before) {
continue;
}
final next = ProxyProfile.fromJson(
jsonDecode(before) as Map<String, dynamic>,
);
replaceSubscription(next, id, preview, DateTime.now());
final encoded = jsonEncode(next.toJson());
if (utf8.encode(encoded).length > 65536) {
throw const FormatException('订阅更新后配置超过 64 KiB');
}
await vpnChannel.invokeMethod<void>('save_proxy_profile', encoded);
if (!mounted) return;
// Native persistence is asynchronous. Never replace edits made meanwhile.
if (jsonEncode(proxyProfile.toJson()) != before) {
await saveProxyProfile();
continue;
}
setState(() {
// Merge in place so open editors keep their profile/source references.
replaceSubscription(
proxyProfile,
id,
preview,
DateTime.parse(
next.subscriptions.firstWhere((s) => s['id'] == id)['updated']
as String,
),
);
savedProxyJson = encoded;
proxyDraftChanged = running;
});
subscriptionRetry.remove(id);
log('订阅自动更新完成;运行中的出口保持到重连');
} catch (_) {
subscriptionRetry[id] = DateTime.now().add(
const Duration(minutes: 15),
);
log('订阅自动更新失败,保留旧配置,15 分钟后重试');
}
}
} finally {
subscriptionUpdating = false;
}
}
Future<void> saveProxyProfile() async {
if (const bool.fromEnvironment('MESHPORT_UI_PREVIEW')) return;
final text = jsonEncode(proxyProfile.toJson());
if (utf8.encode(text).length > 65536) {
if (mounted) setState(() => proxySaveFailed = true);
throw const FormatException('保存配置超过 64 KiB,请减少节点数量');
}
if (!profileSupported) return;
if (mounted) setState(() => proxySavesPending++);
final job = proxySaveTail.then((_) async {
try {
await vpnChannel.invokeMethod<void>('save_proxy_profile', text);
savedProxyJson = text;
if (mounted) setState(() => proxySaveFailed = false);
} catch (_) {
if (mounted) setState(() => proxySaveFailed = true);
rethrow;
} finally {
if (mounted) setState(() => proxySavesPending--);
}
});
proxySaveTail = job.then<void>(
(_) {},
onError: (Object error, StackTrace trace) {},
);
await job;
}
void proxyChanged() {
if (!mounted) return;
setState(() => proxyDraftChanged = running);
unawaited(
saveProxyProfile().catchError((Object _) {
log('自动保存失败,请在代理页重试保存');
}),
);
}
Future<void> primaryConnection() async {
if (running && !proxyDraftChanged) {
await perform(stopActive);
} else {
await connectProxy();
}
}
Future<void> connectProxy() async {
log(
'请求代理连接 · 入口=$runtimeMode · 功能=${proxyProfile.feature} · '
'模式=${proxyProfile.mode} · 节点数=${proxyProfile.nodes.length} · '
'已选择出口=${proxyProfile.nodes.any((n) => n.id == proxyProfile.selectedId)} · '
'代理 DNS=已配置',
);
await diagnosticStage('校验代理配置', () async {
if (runtimeMode != 'system_vpn') proxyProfile.validateConnection();
});
if (!mounted) return;
await perform((c) async {
if (runtimeMode == 'system_vpn' && proxyProfile.feature != 'mesh') {
throw StateError('互联网代理需要选择统一 VPN 或应用内入口');
}
await proxySaveTail;
proxyProfile.entry = runtimeMode;
if (profileSupported) await saveProxyProfile();
// build_config validates, so a bad form fails before stopping anything.
if (proxyProfile.feature != 'proxy') await buildFormConfig();
if (running) await stopActive(c);
singBoxEnabled =
runtimeMode == 'unified_vpn' ||
(runtimeMode == 'application' && proxyProfile.feature != 'mesh');
await startConfig(await startableFormConfig());
runningProxyLabel =
proxyProfile.nodes
.where((n) => n.id == proxyProfile.selectedId)
.firstOrNull
?.name ??
'无代理节点';
runningProxyMode = proxyProfile.modeLabel;
proxyProfile.proxyEnabled = singBoxEnabled;
await saveProxyProfile();
if (mounted) setState(() => proxyDraftChanged = false);
});
}
Widget proxyPage() => ProxyPanel(
entry: runtimeMode,
entryChanged: (v) {
setState(() {
runtimeMode = v;
proxyProfile.entry = v;
});
proxyChanged();
},
profile: proxyProfile,
busy: busy,
running: running,
save: saveProxyProfile,
connect: primaryConnection,
changed: proxyChanged,
draftChanged: proxyDraftChanged,
saving: proxySavesPending > 0,
saveFailed: proxySaveFailed,
showLogs: () => openDetail(
'运行日志',
() =>
LogsPageBody(logs: logs, onClear: () => setState(() => logs.clear())),
),
);
@override
Widget build(BuildContext context) {
final pages = [overview, proxyPage, nodes, 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.language_outlined), label: '代理'),
NavigationDestination(icon: Icon(Icons.hub_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),
Expanded(
child: Text(
'MeshPort / ${labels[page]}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
actions: [
if (wide && proxyProfile.feature != 'proxy')
Padding(
padding: const EdgeInsets.only(right: 20),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 200),
child: Center(
child: Text(
name.text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
],
),
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,
),
);
}
}