Files
AndroidDeviceStreaming/flutter_manager/lib/ui/manager_view.dart
T

913 lines
33 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:io';
import 'app_widgets.dart';
import 'package:flutter/services.dart';
import '../data/windows_usb.dart';
import '../data/manager_repository.dart';
import 'manager_model.dart';
import 'agent_view.dart';
import 'embedded_screen.dart';
import 'path_picker.dart';
class ManagerView extends StatefulWidget {
final ManagerModel model;
final Future<void> Function() onQuit;
const ManagerView({super.key, required this.model, required this.onQuit});
@override
State<ManagerView> createState() => _ManagerViewState();
}
class _ManagerViewState extends State<ManagerView> {
int page = 0;
String? screenDevice;
String search = '';
ManagerModel get m => widget.model;
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: m,
builder: (context, _) {
return Scaffold(
body: Row(
children: [
SizedBox(
width: 204,
child: Material(
color: const Color(0xFFF0F2F7),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Padding(
padding: EdgeInsets.fromLTRB(24, 30, 24, 8),
child: Text(
'ADS',
style: TextStyle(
color: Color(0xFF182235),
fontSize: 32,
fontWeight: FontWeight.w800,
),
),
),
const Padding(
padding: EdgeInsets.fromLTRB(24, 0, 16, 36),
child: Text(
'设备管理中心 / Flutter',
style: TextStyle(color: Colors.blueGrey, fontSize: 12),
),
),
for (final (i, title, icon) in [
(0, '设备工作台', Icons.devices_rounded),
(1, '中继节点', Icons.hub_outlined),
(2, '本机 ADB', Icons.terminal_rounded),
(3, '连接配置', Icons.tune_rounded),
(4, '运行日志', Icons.receipt_long_outlined),
(5, 'Agent 管理', Icons.computer_outlined),
])
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 4,
),
child: ListTile(
selected: page == i,
selectedTileColor: const Color(0xFFE4ECFF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
leading: Icon(
icon,
color: page == i
? const Color(0xFF305DDB)
: Colors.blueGrey,
size: 21,
),
title: Text(
title,
style: const TextStyle(
color: Color(0xFF182235),
fontSize: 14,
),
),
onTap: () {
for (final session
in m.repository.sessions.values) {
session.screenPageVisible = false;
}
setState(() => page = i);
},
),
),
const Spacer(),
const Padding(
padding: EdgeInsets.all(20),
child: Text(
'Windows · 网络 ADB\n关闭窗口后保留在托盘',
style: TextStyle(
color: Colors.blueGrey,
height: 1.8,
fontSize: 12,
),
),
),
TextButton.icon(
onPressed: widget.onQuit,
icon: const Icon(Icons.logout, size: 16),
label: const Text('退出管理中心'),
),
const SizedBox(height: 16),
],
),
),
),
Container(
width: 1,
decoration: const BoxDecoration(
color: Color(0xFFD5DCE8),
boxShadow: [
BoxShadow(
color: Color(0x1A000000),
blurRadius: 6,
offset: Offset(1, 0),
),
],
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
color: Colors.white,
padding: const EdgeInsets.symmetric(
horizontal: 28,
vertical: 20,
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
[
'设备工作台',
'中继节点',
'本机 ADB',
'连接配置',
'运行日志',
'Agent 管理',
'内嵌投屏',
][page],
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 5),
Text(
m.notice,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Color(0xFF66758D),
fontSize: 12,
),
),
],
),
),
const SizedBox(width: 12),
OutlinedButton.icon(
onPressed: m.refreshing ? null : m.refresh,
icon: const Icon(Icons.refresh, size: 18),
label: Text(m.refreshing ? '同步中' : '刷新'),
),
],
),
),
SizedBox(
height: 3,
child: m.refreshing
? const LinearProgressIndicator(minHeight: 3)
: null,
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(24),
child: switch (page) {
0 => devices(),
1 => nodes(),
2 => adb(),
3 => SettingsView(model: m),
5 => AgentView(model: m.agents),
6 => ScreenPage(
busy: m.pending.contains(screenDevice),
onToggle: () =>
m.deviceAction(screenDevice!, () async {
final s = m.repository.sessions[screenDevice];
if (s != null) {
await m.repository.screen(
s,
embedded: !s.screenEmbedded,
);
}
}),
session: m.repository.sessions[screenDevice],
onBack: () {
m
.repository
.sessions[screenDevice]
?.screenPageVisible =
false;
setState(() => page = 0);
},
onStop: () => m.deviceAction(screenDevice!, () async {
final s = m.repository.sessions[screenDevice];
if (s != null) {
await m.repository.stopScreen(s);
}
}),
),
_ => logs(),
},
),
),
],
),
),
],
),
);
},
);
Widget stat(String label, String value, IconData icon) => Expanded(
child: Card(
child: Padding(
padding: const EdgeInsets.all(20),
child: Row(
children: [
Icon(icon, color: const Color(0xFF305DDB), size: 26),
const SizedBox(width: 16),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
value,
style: const TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
Text(
label,
style: const TextStyle(color: Colors.blueGrey, fontSize: 12),
),
],
),
],
),
),
),
);
Widget devices() {
final all = <String, Device>{for (final d in m.devices) d.id: d};
for (final id in m.repository.sessions.keys) {
all.putIfAbsent(id, () => Device(id, false));
}
final rows = all.values
.where(
(d) => '${d.id} ${d.computerName} ${d.agentId}'
.toLowerCase()
.contains(search.toLowerCase()),
)
.toList();
rows.sort((a, b) {
final host = '${a.computerName} ${a.agentId}'.compareTo(
'${b.computerName} ${b.agentId}',
);
return host != 0 ? host : a.id.compareTo(b.id);
});
return Column(
children: [
Row(
children: [
stat('网关在线设备', '${m.devices.length}', Icons.phone_android),
const SizedBox(width: 16),
stat('本机连接', '${m.repository.sessions.length}', Icons.link),
const SizedBox(width: 16),
stat(
'ADB 已就绪',
'${m.repository.sessions.values.where((s) => s.ready).length}',
Icons.check_circle_outline,
),
],
),
const SizedBox(height: 20),
Row(
children: [
Expanded(
child: TextField(
onChanged: (v) => setState(() => search = v),
decoration: const InputDecoration(
hintText: '搜索手机或电脑名',
prefixIcon: Icon(Icons.search),
filled: true,
fillColor: Colors.white,
),
),
),
const SizedBox(width: 16),
OutlinedButton.icon(
onPressed: m.repository.sessions.isEmpty
? null
: () => m.action(() async {
for (final id in m.repository.sessions.keys.toList()) {
await m.disconnect(id);
}
}),
icon: const Icon(Icons.link_off, size: 16),
label: const Text('断开全部'),
),
],
),
const SizedBox(height: 16),
Expanded(
child: rows.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.devices_other,
size: 52,
color: Colors.blueGrey,
),
const SizedBox(height: 16),
const Text('暂无设备'),
TextButton(
onPressed: () => setState(() => page = 3),
child: const Text('检查服务地址与客户端凭据'),
),
],
),
)
: ListView.separated(
itemCount: rows.length,
separatorBuilder: (_, index) => const SizedBox(height: 12),
itemBuilder: (context, i) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (i == 0 || rows[i].agentId != rows[i - 1].agentId)
Padding(
padding: const EdgeInsets.only(top: 6, bottom: 10),
child: Text(
'电脑 · ${rows[i].computerName.isEmpty ? "未上报电脑名" : rows[i].computerName}${rows[i].agentId.isEmpty ? "" : " / ${rows[i].agentId}"}',
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: Colors.blueGrey,
),
),
),
deviceCard(rows[i]),
],
),
),
),
],
);
}
Widget deviceCard(Device d) {
final s = m.repository.sessions[d.id];
final pending = m.pending.contains(d.id);
return Card(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFFEDF2FF),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.phone_android,
color: Color(0xFF305DDB),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
d.id,
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 17,
),
),
Text(
'电脑:${d.computerName.isEmpty ? "旧 Agent(未上报电脑名)" : d.computerName}${d.agentId.isEmpty ? "" : " · ${d.agentId}"}',
style: const TextStyle(
fontSize: 12,
color: Colors.blueGrey,
),
),
const SizedBox(height: 5),
Text(
s?.state ?? (d.busy ? '其他客户端占用' : '空闲 · 可连接'),
style: TextStyle(
color: s?.ready == true
? Colors.teal
: Colors.blueGrey,
fontSize: 12,
),
),
],
),
),
if (pending)
const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 12),
if (s == null)
FilledButton.icon(
onPressed: pending || d.busy ? null : () => m.connect(d),
icon: const Icon(Icons.add_link, size: 16),
label: const Text('连接设备'),
)
else
Wrap(
spacing: 8,
children: [
FilledButton.icon(
onPressed: pending || !s.ready
? null
: () => m.deviceAction(d.id, () async {
await m.repository.screen(
s,
embedded: Platform.isWindows,
);
if (mounted && Platform.isWindows) {
setState(() {
s.screenPageVisible = true;
screenDevice = s.id;
page = 6;
});
}
}),
icon: const Icon(Icons.open_in_new, size: 16),
label: Text(
Platform.isWindows
? (s.screen == null ? '内嵌投屏' : '查看投屏')
: '独立窗口投屏',
),
),
OutlinedButton.icon(
onPressed: pending ? null : () => m.disconnect(d.id),
icon: const Icon(Icons.link_off, size: 16),
label: const Text('断开'),
),
],
),
],
),
if (s != null) ...[
const Divider(height: 28),
Row(
children: [
Expanded(
child: Text(
'${s.mode} ${s.endpoint} · ${s.route}',
style: const TextStyle(fontSize: 12),
),
),
IconButton(
tooltip: '复制 ADB 地址',
onPressed: () =>
Clipboard.setData(ClipboardData(text: s.endpoint)),
icon: const Icon(Icons.copy, size: 16),
),
],
),
],
],
),
),
);
}
Widget nodes() => m.nodes.isEmpty
? const Center(child: Text('暂无中继节点,或服务尚未启用 v2 节点接口'))
: ListView.separated(
itemCount: m.nodes.length,
separatorBuilder: (_, index) => const SizedBox(height: 12),
itemBuilder: (_, i) {
final n = m.nodes[i];
return Card(
child: ListTile(
contentPadding: const EdgeInsets.all(20),
leading: Icon(
Icons.hub,
color: n['healthy'] == true ? Colors.teal : Colors.grey,
),
title: Text('${n["id"]}'),
subtitle: Text(n['healthy'] == true ? '在线' : '不可用'),
trailing: Text('通道 ${n["sessions"]} / ${n["capacity"]}'),
),
);
},
);
Widget adb() => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'使用本机 ADB Server,显示本地 USB 设备和网络设备。',
style: TextStyle(color: Colors.blueGrey),
),
const SizedBox(height: 16),
Wrap(
spacing: 12,
children: [
FilledButton.icon(
onPressed: m.localAdb,
icon: const Icon(Icons.refresh),
label: const Text('读取设备列表'),
),
OutlinedButton.icon(
onPressed: () => m.action(() async {
final result = await m.repository.run(m.repository.settings.adb, [
'start-server',
]);
m.log(result.isEmpty ? 'ADB Server 已启动' : result);
await m.localAdb();
}),
icon: const Icon(Icons.play_arrow, size: 16),
label: const Text('启动 ADB Server'),
),
],
),
const SizedBox(height: 20),
Expanded(
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: const Color(0xFF14233F),
borderRadius: BorderRadius.circular(12),
),
child: SingleChildScrollView(
child: SelectableText(
m.adbListing.isEmpty ? '点击“读取设备列表”检查本机设备。' : m.adbListing,
style: const TextStyle(
color: Colors.white,
fontFamily: 'Consolas',
height: 1.8,
),
),
),
),
),
],
);
Widget logs() => Column(
children: [
Row(
children: [
Expanded(
child: Text(
'最近 500 条 · 按天保存,单文件 5 MiB,保留 14 天\n${m.logDirectory}${m.diskLog.error == null ? "" : "\n日志写入失败:${m.diskLog.error}"}',
style: const TextStyle(fontSize: 12),
),
),
const Spacer(),
TextButton.icon(
onPressed: m.openLogDirectory,
icon: const Icon(Icons.folder_open, size: 16),
label: const Text('打开日志文件夹'),
),
TextButton.icon(
onPressed: () =>
Clipboard.setData(ClipboardData(text: m.logs.join('\n'))),
icon: const Icon(Icons.copy, size: 16),
label: const Text('复制日志'),
),
],
),
Expanded(
child: ListView.builder(
itemCount: m.logs.length,
itemBuilder: (_, i) => Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: SelectableText(
m.logs[i],
style: const TextStyle(fontSize: 12),
),
),
),
),
],
);
}
class SettingsView extends StatefulWidget {
final ManagerModel model;
final Future<bool> Function()? driverInstalled;
final Future<String?> Function(String, bool)? chooseFile;
const SettingsView({
super.key,
required this.model,
this.driverInstalled,
this.chooseFile,
});
@override
State<SettingsView> createState() => _SettingsViewState();
}
class _SettingsViewState extends State<SettingsView> {
late final Map<String, TextEditingController> fields;
bool relayOnly = false, usbMode = false, installingUsb = false;
String usbStatus = '尚未检测';
@override
void initState() {
super.initState();
final s = widget.model.repository.settings;
fields = {
for (final entry in {
'server': s.server,
'origin': s.origin,
'credential': s.credential,
'client': s.client,
'adb': s.adb,
'scrcpy': s.scrcpy,
'usbip': s.usbip,
}.entries)
entry.key: TextEditingController(text: entry.value),
};
relayOnly = s.relayOnly;
usbMode = s.usbMode;
}
Future<void> changeUsb(bool value, {bool detectOnly = false}) async {
if (!value && !detectOnly) {
setState(() => usbMode = false);
return;
}
await widget.model.action(() async {
final repo = widget.model.repository;
final driver =
await (widget.driverInstalled?.call() ??
UsbDriver.installed(repo.run));
if (!mounted) {
return;
}
if (!driver) {
setState(() {
usbMode = false;
usbStatus = '未安装 USBip 虚拟控制器';
});
final install = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('需要安装 USBip 驱动'),
content: const Text(
'USB 挂载需要已签名的 USBip 虚拟控制器。安装会请求管理员权限,可能短暂重启 USB 集线器并要求重启 Windows。安装后请重新检测;网络 ADB 仍可使用。',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('暂不安装'),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('安装驱动'),
),
],
),
);
if (install == true && mounted) {
await installUsb();
}
return;
}
if (!await File(fields['usbip']!.text.trim()).exists()) {
throw StateError('驱动已安装,但找不到 usbip.exe,请检查路径');
}
await repo.run(repo.findTool('ads-usb'), ['--version']);
if (mounted) {
setState(() {
usbStatus = '组件可用';
if (!detectOnly) {
usbMode = value;
}
});
}
});
}
Future<void> installUsb() async {
if (installingUsb) {
return;
}
setState(() => installingUsb = true);
await widget.model.action(() async {
final repo = widget.model.repository;
final code = await UsbDriver.install(
UsbDriver.installer(repo.root?.path),
);
if (mounted) {
setState(
() => usbStatus = code == 3010
? '安装完成,需要重启 Windows 后检测'
: '安装程序已结束,请重新检测组件',
);
}
widget.model.notice = usbStatus;
});
if (mounted) {
setState(() => installingUsb = false);
}
}
void apply() {
final s = widget.model.repository.settings;
s.server = fields['server']!.text.trim();
s.origin = fields['origin']!.text.trim();
s.credential = fields['credential']!.text.trim();
s.client = fields['client']!.text.trim();
s.adb = fields['adb']!.text.trim();
s.scrcpy = fields['scrcpy']!.text.trim();
s.relayOnly = relayOnly;
s.usbMode = Platform.isWindows && usbMode;
s.usbip = fields['usbip']!.text.trim();
}
@override
void dispose() {
for (final c in fields.values) {
c.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) => ListView(
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'控制中心与工具',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
const Text(
'修改后点击保存;已连接设备继续使用连接时的配置。令牌仅保存在内存。',
style: TextStyle(color: Colors.blueGrey, fontSize: 12),
),
const SizedBox(height: 24),
for (final (key, label) in [
('server', '控制中心 WSS 地址'),
('origin', '直连服务器(可留空)'),
('credential', '客户端凭据文件 client.env'),
('client', 'ads-client 路径'),
('adb', 'adb 路径'),
('scrcpy', 'scrcpy 路径(需保留完整发行目录)'),
if (Platform.isWindows) ('usbip', 'usbip.exe 路径'),
])
Padding(
padding: const EdgeInsets.only(bottom: 18),
child: TextField(
controller: fields[key],
decoration: InputDecoration(
labelText: label,
suffixIcon: ['server', 'origin'].contains(key)
? null
: IconButton(
tooltip: '选择文件并保存',
icon: const Icon(Icons.folder_open),
onPressed: () => widget.model.action(() async {
final selected =
await (widget.chooseFile?.call(
fields[key]!.text,
key != "credential",
) ??
pickPath(
fields[key]!.text,
executable: key != 'credential',
));
if (selected == null || !mounted) {
return;
}
fields[key]!.text = selected;
apply();
await widget.model.repository.save();
widget.model.notice = '文件位置已保存';
}),
),
),
),
),
SwitchListTile(
contentPadding: EdgeInsets.zero,
value: usbMode,
title: const Text('挂载为 USB 设备 · Windows'),
subtitle: Text(
Platform.isWindows
? '仅模拟 ADB;修改在下次连接生效。$usbStatus'
: 'Linux 当前使用网络 ADB;USB 模拟可在终端使用 ads-usb。',
),
onChanged: installingUsb || !Platform.isWindows
? null
: changeUsb,
),
Wrap(
spacing: 12,
children: [
OutlinedButton(
onPressed: installingUsb || !Platform.isWindows
? null
: () => changeUsb(usbMode, detectOnly: true),
child: const Text('检测 USB 组件'),
),
TextButton(
onPressed: installingUsb || !Platform.isWindows
? null
: installUsb,
child: Text(installingUsb ? '等待驱动安装完成…' : '安装 USBip 驱动'),
),
],
),
const SizedBox(height: 12),
SwitchListTile(
contentPadding: EdgeInsets.zero,
value: relayOnly,
title: const Text('仅使用中继'),
subtitle: const Text('关闭时优先尝试 P2P 直连'),
onChanged: (v) => setState(() => relayOnly = v),
),
const SizedBox(height: 16),
Wrap(
spacing: 12,
runSpacing: 12,
children: [
FilledButton(
onPressed: () => widget.model.action(() async {
apply();
widget.model.repository.settings.uri('v1/devices');
await widget.model.repository.save();
widget.model.notice = '配置已保存';
}),
child: const Text('保存配置'),
),
OutlinedButton(
onPressed: () => widget.model.action(() async {
apply();
await widget.model.repository.importCredential();
fields['origin']!.text =
widget.model.repository.settings.origin;
widget.model.notice = '客户端凭据已导入';
await widget.model.refresh();
}),
child: const Text('导入凭据并同步'),
),
OutlinedButton(
onPressed: () => widget.model.action(() async {
apply();
for (final (exe, args) in [
(fields['client']!.text, ['--version']),
(fields['adb']!.text, ['version']),
(fields['scrcpy']!.text, ['--version']),
]) {
widget.model.log(
await widget.model.repository.run(exe, args),
);
}
widget.model.notice = '工具检查完成';
}),
child: const Text('检查工具'),
),
],
),
],
),
),
),
],
);
}