Files
MeshPort/apps/meshport_lab/lib/features/proxy_panel.dart
T
shenleiandClaude Haiku 5.5 2f185f914d Snapshot uncommitted work: proxy UI, sing-box integration, socks bridge
- Lab app: proxy panel, node editor, configuration and detail pages,
  responsive layout, and related tests
- Add meshport-socks crate and sing-box bridge scripts/docs
- Add singbox_flutter binding and meshport_client_core package
- FFI, VPN helper (unified mac path), and Android/macOS runner updates
- Docs for architecture, client runtime, UI design, and validation
- UI design output artifacts under outputs/ui

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-12 10:06:15 +09:00

535 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 'dart:convert';
import 'package:flutter/material.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'proxy_node_editor.dart';
import 'configuration_pages.dart';
import 'proxy_source_pages.dart';
import 'detail_pages.dart';
class ProxyPanel extends StatefulWidget {
final ProxyProfile profile;
final String entry;
final void Function(String) entryChanged;
final bool busy, running;
final Future<void> Function() save, connect;
final VoidCallback changed;
const ProxyPanel({
super.key,
required this.profile,
required this.entry,
required this.entryChanged,
required this.busy,
required this.running,
required this.save,
required this.connect,
required this.changed,
});
@override
State<ProxyPanel> createState() => _ProxyPanelState();
}
class _ProxyPanelState extends State<ProxyPanel> {
ProxyProfile get p => widget.profile;
bool working = false;
String error = '';
void change(VoidCallback work) {
setState(work);
widget.changed();
}
Future<void> act(Future<void> Function() work) async {
if (working || widget.busy) return;
setState(() => working = true);
try {
await work();
} catch (e) {
if (mounted) {
setState(
() => error = e is FormatException
? e.message
: '操作失败,请检查配置、网络及概览中的实际运行状态。',
);
}
} finally {
if (mounted) setState(() => working = false);
}
}
Future<bool> confirm(String title, String text) async =>
await showDialog<bool>(
context: context,
builder: (c) => AlertDialog(
title: Text(title),
content: Text(text),
actions: [
TextButton(
onPressed: () => Navigator.pop(c, false),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(c, true),
child: const Text('确认'),
),
],
),
) ??
false;
Future<String?> input(
String title, {
String initial = '',
String hint = '',
bool secret = false,
}) => showDialog<String>(
context: context,
builder: (_) => _TextEditorDialog(
title: title,
initial: initial,
hint: hint,
secret: secret,
),
);
Future<void> importNodes() async {
final preview = await Navigator.push<Object>(
context,
MaterialPageRoute(builder: (_) => const ProxyImportPage()),
);
if (preview == null || !mounted) return;
if (preview is ImportPreview) {
change(() => p.nodes.addAll(preview.nodes));
}
if (preview is Map<String, dynamic>) {
final sub = await Navigator.push<Map<String, dynamic>>(
context,
MaterialPageRoute(
builder: (_) => SubscriptionEditor(subscription: preview),
),
);
if (sub != null && mounted) {
final next = Map<String, dynamic>.from(sub)..remove('update');
change(() => p.subscriptions.add(next));
if (sub['update'] == true) await updateSubscription(next);
}
}
}
Future<void> editNode([ProxyNode? existing]) async {
final transport = existing?.options['transport']?['type'];
if (transport != null && !{'ws', 'grpc'}.contains(transport)) {
final value = await input(
'高级节点 JSON',
initial: const JsonEncoder.withIndent(
' ',
).convert({...existing!.options, 'tag': existing.name}),
);
if (value == null) return;
final preview = importProxyNodes(value);
if (preview.nodes.length != 1) throw const FormatException('只接受一个节点');
final node = preview.nodes.single;
change(() {
if (existing.source == 'manual') {
p.nodes[p.nodes.indexWhere((n) => n.id == existing.id)] = ProxyNode(
id: existing.id,
name: node.name,
options: node.options,
);
} else {
p.nodes.add(node);
}
});
return;
}
final node = await Navigator.push<ProxyNode>(
context,
MaterialPageRoute(builder: (_) => ProxyNodeEditor(node: existing)),
);
if (node == null || !mounted) return;
change(
() => existing == null || existing.source != 'manual'
? p.nodes.add(node)
: p.nodes[p.nodes.indexWhere((n) => n.id == existing.id)] = node,
);
}
Future<void> editSubscription([Map<String, dynamic>? existing]) async {
final result = await Navigator.push<Map<String, dynamic>>(
context,
MaterialPageRoute(
builder: (_) => SubscriptionEditor(subscription: existing),
),
);
if (result == null || !mounted) return;
final next = Map<String, dynamic>.from(result)..remove('update');
change(
() => existing == null
? p.subscriptions.add(next)
: p.subscriptions[p.subscriptions.indexOf(existing)] = next,
);
if (result['update'] == true) await updateSubscription(next);
}
Future<void> updateSubscription(Map<String, dynamic> sub) async {
final source = sub['id'] as String;
final preview = await fetchSubscription(
sub['url'] as String,
source: source,
);
if (preview.nodes.isEmpty) throw const FormatException('订阅没有可用节点,保留原配置');
final old = p.nodes.where((n) => n.source == source).toList();
final replacement = preview.nodes.map((n) {
final retained = old
.where((o) => jsonEncode(o.options) == jsonEncode(n.options))
.firstOrNull;
return ProxyNode(
id: retained?.id ?? n.id,
name: n.name,
source: source,
options: n.options,
);
}).toList();
final removed =
p.selectedId != null &&
old.any((n) => n.id == p.selectedId) &&
!replacement.any((n) => n.id == p.selectedId);
if (!mounted ||
!await confirm(
'订阅更新预览',
'${replacement.length} 个支持节点,忽略 ${preview.unsupported} 个项目。${removed ? '当前选中节点将被删除,需重新选择;正在运行的出口保持到显式重连。' : '相同节点保留选择。'}',
)) {
return;
}
change(() {
p.nodes.removeWhere((n) => n.source == source);
p.nodes.addAll(replacement);
if (removed) p.selectedId = null;
sub['updated'] = DateTime.now().toIso8601String();
});
}
Widget subscriptionsBody() {
final disabled = working || widget.busy;
return section('订阅', [
OutlinedButton(
onPressed: disabled ? null : () => act(() => editSubscription()),
child: const Text('添加订阅'),
),
for (final sub in p.subscriptions)
ListTile(
title: Text(sub['name'] as String),
subtitle: Text(
'${sub['updated'] == null ? '尚未更新' : '更新于 ${sub['updated']}'} · ${sub['auto_update'] == true ? '自动更新 ${sub['interval_minutes'] ?? 360} 分钟' : '手动更新'}',
),
trailing: Wrap(
children: [
IconButton(
tooltip: '编辑',
onPressed: disabled
? null
: () => act(() => editSubscription(sub)),
icon: const Icon(Icons.edit_outlined),
),
IconButton(
tooltip: '更新并预览',
onPressed: disabled
? null
: () => act(() => updateSubscription(sub)),
icon: const Icon(Icons.sync),
),
IconButton(
tooltip: '删除订阅及所属节点',
onPressed: disabled
? null
: () => act(() async {
if (await confirm(
'删除订阅',
'删除该来源的节点,手动节点保留;正在运行的出口保持到重连。',
)) {
change(() {
p.nodes.removeWhere((n) => n.source == sub['id']);
p.subscriptions.remove(sub);
if (!p.nodes.any((n) => n.id == p.selectedId)) {
p.selectedId = null;
}
});
}
}),
icon: const Icon(Icons.delete_outline),
),
],
),
),
]);
}
Widget section(String title, List<Widget> children) => Card(
child: Padding(
padding: const EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(title, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 20),
for (final child in children) ...[child, const SizedBox(height: 18)],
],
),
),
);
@override
Widget build(BuildContext context) {
final disabled = widget.busy || working;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (error.isNotEmpty)
Text(
error,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
section('代理与组网', [
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: widget.entry,
decoration: const InputDecoration(labelText: '网络入口'),
items: const [
DropdownMenuItem(value: 'application', child: Text('应用内 SOCKS5')),
DropdownMenuItem(value: 'system_vpn', child: Text('独立系统组网')),
DropdownMenuItem(
value: 'unified_vpn',
child: Text('统一 VPN · 单一 TUN'),
),
],
onChanged: disabled ? null : (v) => widget.entryChanged(v!),
),
const Text(
'修改的是草稿。保存不会更改运行出口;连接或重连后生效。应用内模式通过 SOCKS5 127.0.0.1:10818 接入。',
),
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: p.feature,
decoration: const InputDecoration(labelText: '启用功能'),
items: const [
DropdownMenuItem(value: 'mesh', child: Text('仅组网')),
DropdownMenuItem(value: 'proxy', child: Text('仅代理')),
DropdownMenuItem(value: 'combined', child: Text('代理 + 组网')),
],
onChanged: disabled ? null : (v) => change(() => p.feature = v!),
),
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: p.mode,
decoration: const InputDecoration(labelText: '普通互联网流量模式'),
items: const [
DropdownMenuItem(value: 'bypass_cn', child: Text('绕过中国大陆')),
DropdownMenuItem(value: 'rule', child: Text('自定义规则')),
DropdownMenuItem(value: 'global', child: Text('全局代理')),
DropdownMenuItem(value: 'direct', child: Text('直连')),
],
onChanged: disabled || p.feature == 'mesh'
? null
: (v) => change(() => p.mode = v!),
),
if (widget.entry == 'system_vpn' && p.feature != 'mesh')
const Text('独立系统组网只支持仅组网;代理功能请选择统一 VPN 或应用内入口。'),
Text(
p.mode == 'bypass_cn' && p.feature != 'mesh'
? '中国大陆 IP 和普通私网直连,其余走所选代理;组网始终优先。内置 IP 规则集通过代理每 24 小时更新,首次下载失败会阻止连接。'
: '组网优先始终生效。全局/直连暂停普通规则;仅组网不接管互联网。',
),
Wrap(
spacing: 8,
runSpacing: 12,
children: [
FilledButton(
onPressed:
disabled ||
(widget.entry == 'system_vpn' && p.feature != 'mesh')
? null
: () => act(widget.connect),
child: Text(widget.running ? '重连使草稿生效' : '连接'),
),
OutlinedButton(
onPressed: disabled ? null : () => act(widget.save),
child: const Text('安全保存配置'),
),
],
),
]),
section('代理节点', [
Wrap(
spacing: 8,
runSpacing: 12,
children: [
OutlinedButton(
onPressed: disabled ? null : () => act(importNodes),
child: const Text('导入与预览'),
),
OutlinedButton(
onPressed: disabled ? null : () => act(() => editNode()),
child: const Text('添加节点'),
),
],
),
if (p.nodes.isEmpty) const Text('尚未添加节点。全局代理或使用代理出口的规则需要选中一个节点。'),
for (final node in p.nodes)
ListTile(
leading: IconButton(
tooltip: '选择出口',
icon: Icon(
p.selectedId == node.id
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
onPressed: disabled
? null
: () => change(() => p.selectedId = node.id),
),
title: Text(node.name),
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) => ProxyNodeDetails(
node: node,
selected: node.id == p.selectedId,
select: () => change(() => p.selectedId = node.id),
edit: () => act(() => editNode(node)),
),
),
),
subtitle: Text(
'${node.options['type']} · ${node.options['server']}:${node.options['server_port']} · ${node.source == 'manual' ? '手动' : '订阅'}',
),
trailing: PopupMenuButton<String>(
enabled: !disabled,
onSelected: (v) => act(() async {
if (v == 'edit') {
await editNode(node);
} else if (await confirm('删除节点', '删除草稿中的节点,不会立即改变正在运行的出口。')) {
change(() {
p.nodes.remove(node);
if (p.selectedId == node.id) p.selectedId = null;
});
}
}),
itemBuilder: (_) => [
PopupMenuItem(
value: 'edit',
child: Text(node.source == 'manual' ? '编辑' : '复制为手动节点'),
),
const PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
),
]),
section('订阅', [
ListTile(
title: const Text('订阅管理'),
subtitle: Text('${p.subscriptions.length} 个来源'),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) =>
LiveDetailPage(title: '订阅管理', builder: subscriptionsBody),
),
),
),
]),
section('分流与 DNS', [
const Text('受管理规则:有效组网地址 → 组网;已失效的已知组网地址 → 拒绝;随后才应用普通规则与默认出口。'),
DropdownButtonFormField<String>(
isExpanded: true,
initialValue: p.defaultAction,
decoration: const InputDecoration(labelText: '规则模式默认出口'),
items: const [
DropdownMenuItem(value: 'proxy', child: Text('所选代理')),
DropdownMenuItem(value: 'direct', child: Text('直连')),
DropdownMenuItem(value: 'reject', child: Text('拒绝')),
],
onChanged: disabled || p.mode != 'rule' || p.feature == 'mesh'
? null
: (v) => change(() => p.defaultAction = v!),
),
Text(
'${p.rules.length} 条普通规则 · ${p.mode == 'rule' && p.feature != 'mesh' ? '规则模式执行' : '已暂停'}',
),
OutlinedButton(
onPressed: disabled
? null
: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) =>
RulesPage(profile: p, changed: widget.changed),
),
),
child: const Text('编辑普通规则'),
),
Text(
'启动 DNS:${p.dnsServer} · 直连 DNS:${p.directDnsServer.isEmpty ? '启动 DNS' : p.directDnsServer} · 代理 DNS:${p.proxyDnsServer.isEmpty ? '待配置 · 代理模式必填' : p.proxyDnsServer}',
),
OutlinedButton(
onPressed: disabled
? null
: () => Navigator.push<void>(
context,
MaterialPageRoute(
builder: (_) =>
DnsPage(profile: p, changed: widget.changed),
),
),
child: const Text('编辑 DNS'),
),
Text('FakeIP:${p.fakeIP ? '开启' : '关闭'} · 组网域名自动排除,解析失败无公共 DNS 回退。'),
]),
],
);
}
}
class _TextEditorDialog extends StatefulWidget {
final String title, initial, hint;
final bool secret;
const _TextEditorDialog({
required this.title,
required this.initial,
required this.hint,
required this.secret,
});
@override
State<_TextEditorDialog> createState() => _TextEditorDialogState();
}
class _TextEditorDialogState extends State<_TextEditorDialog> {
late final controller = TextEditingController(text: widget.initial);
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AlertDialog(
title: Text(widget.title),
content: SizedBox(
width: 520,
child: TextField(
controller: controller,
autofocus: true,
maxLines: widget.secret ? 1 : 8,
obscureText: widget.secret,
decoration: InputDecoration(hintText: widget.hint),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(context, controller.text),
child: const Text('确定'),
),
],
);
}