import 'dart:io'; import 'package:material_ui/material_ui.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 Function() onQuit; const ManagerView({super.key, required this.model, required this.onQuit}); @override State createState() => _ManagerViewState(); } class _ManagerViewState extends State { 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(0xFF14233F), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Padding( padding: EdgeInsets.fromLTRB(24, 30, 24, 8), child: Text( 'ADS', style: TextStyle( color: Colors.white, fontSize: 32, fontWeight: FontWeight.w800, ), ), ), const Padding( padding: EdgeInsets.fromLTRB(24, 0, 16, 36), child: Text( '设备管理中心 / Flutter', style: TextStyle(color: Colors.white60, 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(0xFF29446C), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), leading: Icon(icon, color: Colors.white70, size: 21), title: Text( title, style: const TextStyle( color: Colors.white, 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.white54, height: 1.8, fontSize: 12, ), ), ), TextButton.icon( onPressed: widget.onQuit, icon: const Icon(Icons.logout, size: 16), label: const Text('退出管理中心'), ), const SizedBox(height: 16), ], ), ), ), 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 ? '同步中' : '刷新'), ), ], ), ), if (m.refreshing) const LinearProgressIndicator(minHeight: 2), 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 = {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.toLowerCase().contains(search.toLowerCase())) .toList(); 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: '搜索设备 ID', prefixIcon: Icon(Icons.search), filled: true, fillColor: Colors.white, ), ), ), const SizedBox(width: 16), OutlinedButton( onPressed: m.repository.sessions.isEmpty ? null : () => m.action(() async { for (final id in m.repository.sessions.keys.toList()) { await m.disconnect(id); } }), child: 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) => 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, ), ), 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( onPressed: pending || d.busy ? null : () => m.connect(d), child: 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: true); if (mounted) { setState(() { s.screenPageVisible = true; screenDevice = s.id; page = 6; }); } }), icon: const Icon(Icons.open_in_new, size: 16), label: Text(s.screen == null ? '内嵌投屏' : '查看投屏'), ), OutlinedButton( onPressed: pending ? null : () => m.disconnect(d.id), child: 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( 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(); }), child: 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: [ const Text('最近 500 条 · 仅保存在内存'), const Spacer(), TextButton( onPressed: () => Clipboard.setData(ClipboardData(text: m.logs.join('\n'))), child: 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 Function()? driverInstalled; final Future Function(String, bool)? chooseFile; const SettingsView({ super.key, required this.model, this.driverInstalled, this.chooseFile, }); @override State createState() => _SettingsViewState(); } class _SettingsViewState extends State { late final Map 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 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( 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 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 = 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.exe 路径'), ('adb', 'adb.exe 路径'), ('scrcpy', 'scrcpy.exe 路径(需保留完整发行目录)'), ('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('仅模拟 ADB;修改在下次连接生效。$usbStatus'), onChanged: installingUsb ? null : changeUsb, ), Wrap( spacing: 12, children: [ OutlinedButton( onPressed: installingUsb ? null : () => changeUsb(usbMode, detectOnly: true), child: const Text('检测 USB 组件'), ), TextButton( onPressed: installingUsb ? 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('检查工具'), ), ], ), ], ), ), ), ], ); }