diff --git a/AGENTS.md b/AGENTS.md index 1f17ff6..c27429c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,7 +23,7 @@ | `crates/` | Rust 工作区共享库容器 | Rust、TOML | | `crates/ads-management/` | Agent 配置及管理协议、Windows 命名管道/Unix socket、私有文件与系统服务操作;源码在 `src/` | Rust、TOML | | `crates/ads-core/` | 共用网络与协议代码,包括 WSS、WebRTC P2P、节点回退、ADB smart socket 和流式转发;源码在 `src/` | Rust、TOML | -| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、Agent 管理、多设备连接、本机 ADB、托盘与独立 scrcpy 窗口 | Dart、C++、CMake、YAML、ICO | +| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、Agent 管理、多设备连接、本机 ADB、可选虚拟 USB、托盘与 Windows 内嵌 scrcpy 投屏 | Dart、C++、CMake、YAML、ICO | | `desktop/` | 跨平台桌面客户端及其测试项目、.NET SDK 配置与使用说明 | C#、Avalonia XAML(AXAML)、JSON、Markdown | | `desktop/Ads.Desktop/` | Avalonia 多设备工作台,管理独立连接、自动端口分配、USB 模拟、多个 scrcpy 窗口及托盘;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG | | `desktop/Ads.Desktop.Tests/` | 桌面客户端单元测试 | C#、XML(csproj) | diff --git a/README.md b/README.md index c761ed1..3829e0a 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络 | `crates/` | Rust 工作区共享库容器 | Rust、TOML | | `crates/ads-management/` | Agent 配置及管理协议、Windows 命名管道/Unix socket、私有文件与系统服务操作;源码在 `src/` | Rust、TOML | | `crates/ads-core/` | 共用网络与协议代码,包括 WSS、WebRTC P2P、节点回退、ADB smart socket 和流式转发;源码在 `src/` | Rust、TOML | -| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、Agent 管理、多设备连接、本机 ADB、托盘与独立 scrcpy 窗口 | Dart、C++、CMake、YAML、ICO | +| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、Agent 管理、多设备连接、本机 ADB、可选虚拟 USB、托盘与 Windows 内嵌 scrcpy 投屏 | Dart、C++、CMake、YAML、ICO | | `desktop/` | 跨平台桌面客户端及其测试项目、.NET SDK 配置与使用说明 | C#、Avalonia XAML(AXAML)、JSON、Markdown | | `desktop/Ads.Desktop/` | Avalonia 多设备工作台,管理独立连接、自动端口分配、USB 模拟、多个 scrcpy 窗口及托盘;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG | | `desktop/Ads.Desktop.Tests/` | 桌面客户端单元测试 | C#、XML(csproj) | diff --git a/deploy/windows/README.md b/deploy/windows/README.md index a012e05..6eb7e3c 100644 --- a/deploy/windows/README.md +++ b/deploy/windows/README.md @@ -76,3 +76,5 @@ The managed log buffer is in memory; the old runner log is historical. See [Agen Run `scripts/build-installers.ps1` from the repository root to build separate Avalonia and Flutter Windows x64 installers. Requires Inno Setup 6/7 (`-Compiler` selects ISCC.exe). Build Rust binaries first with `scripts/build.ps1`; `-SkipBuild` packages existing release folders. `-Edition Avalonia` or `Flutter` selects one client. Outputs and SHA-256 sidecars are in `bin/installers/`. Installers use per-user installation, Start menu entries, optional desktop shortcuts, and Windows uninstall registration. Editions have separate install identities and can coexist; installing the same edition upgrades it in place. Close the client and stop any Agent hosted from its installation folder before upgrading. Credentials, local settings and device configuration are excluded; import credentials after installation. Uninstall retains settings in user data and does not remove separately installed Agent tasks or USB drivers. USB driver installation remains an explicit optional step. Setup executables are currently unsigned; distribution signing requires the publisher certificate. + +Windows desktop packages now include the unmodified signed USBip 0.9.8.1 x64 installer under drivers/. Packaging verifies its pinned SHA-256 and publisher signature using scripts/install-windows-usb.ps1. The ADS installer only copies the optional installer; Flutter prompts to install it when USB mode is selected without the controller. Driver installation is interactive and requires the user's UAC approval; no automatic reboot occurs. diff --git a/desktop/Ads.Desktop/App.axaml.cs b/desktop/Ads.Desktop/App.axaml.cs index cb3097e..a4da58b 100644 --- a/desktop/Ads.Desktop/App.axaml.cs +++ b/desktop/Ads.Desktop/App.axaml.cs @@ -23,6 +23,7 @@ public partial class App : Application desktop.MainWindow = window; desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown; void Show() { window.Show(); window.WindowState = WindowState.Normal; window.Activate(); } + Program.Instance?.Listen(() => Avalonia.Threading.Dispatcher.UIThread.Post(Show)); async Task QuitAsync() { if (quitting) return; @@ -59,4 +60,3 @@ public partial class App : Application base.OnFrameworkInitializationCompleted(); } } - diff --git a/desktop/Ads.Desktop/DesktopInstance.cs b/desktop/Ads.Desktop/DesktopInstance.cs new file mode 100644 index 0000000..fca44b2 --- /dev/null +++ b/desktop/Ads.Desktop/DesktopInstance.cs @@ -0,0 +1,39 @@ +using System.Runtime.InteropServices; + +namespace Ads.Desktop; + +/// Shares the Windows desktop UI lease with Flutter, including tray mode. +internal sealed class DesktopInstance : IDisposable +{ + private readonly Mutex mutex; + private readonly EventWaitHandle activation; + private RegisteredWaitHandle? registration; + public bool Primary { get; } + + public DesktopInstance() + { + activation = new EventWaitHandle(false, EventResetMode.AutoReset, @"Local\TTSTD.ADS.Desktop.Activate"); + mutex = new Mutex(true, @"Local\TTSTD.ADS.Desktop.Instance", out var primary); + Primary = primary; + } + + public void Activate() + { + AllowSetForegroundWindow(uint.MaxValue); + activation.Set(); + } + + public void Listen(Action show) => + registration = ThreadPool.RegisterWaitForSingleObject(activation, (_, _) => show(), null, Timeout.Infinite, false); + + public void Dispose() + { + registration?.Unregister(null); + if (Primary) mutex.ReleaseMutex(); + mutex.Dispose(); + activation.Dispose(); + } + + [DllImport("user32.dll")] + private static extern bool AllowSetForegroundWindow(uint processId); +} diff --git a/desktop/Ads.Desktop/Program.cs b/desktop/Ads.Desktop/Program.cs index 4da9a81..3800704 100644 --- a/desktop/Ads.Desktop/Program.cs +++ b/desktop/Ads.Desktop/Program.cs @@ -2,6 +2,16 @@ using Avalonia; namespace Ads.Desktop; internal static class Program { - [STAThread] public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + public static DesktopInstance? Instance { get; private set; } + [STAThread] + public static void Main(string[] args) + { + if (!OperatingSystem.IsWindows()) { BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); return; } + using var instance = new DesktopInstance(); + Instance = instance; + if (!instance.Primary) { instance.Activate(); return; } + try { BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); } + finally { Instance = null; } + } public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure().UsePlatformDetect().LogToTrace(); } diff --git a/desktop/README.md b/desktop/README.md index 811fecc..8f5f414 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -76,3 +76,7 @@ ADB、USB/IP 和 scrcpy 转发端口分别自动分配,避开其他连接和 ## Agent 管理 工作台新增 Agent 管理页,与 Flutter 共用控制中心 v3 接口。支持多 Agent/多手机、本机私有 IPC、配置与日志、受监督重启;`--agent-tray` 可单独打开本机 Agent 管理窗口。发行包同时包含 adsctl 和 ads-agent,后台运行不依赖 GUI。完整安装及 CLI 示例见 [Agent 管理](../docs/agent-management.md)。 + +## Windows 单实例 + +Windows 桌面入口与 Flutter 共用同一会话级单实例锁(包括 --agent-tray 入口和不同安装路径)。重复启动会唤起正在运行的桌面窗口并退出新进程,避免重复托盘及重复设备管理。后台 Agent 和设备连接进程不受该 UI 锁限制。DesktopInstance.cs 使用 Windows 命名事件通知,由 Avalonia UI 线程恢复窗口。非 Windows 暂保留原启动行为。 diff --git a/docs/windows-usb.md b/docs/windows-usb.md index 8b04bd4..ce91152 100644 --- a/docs/windows-usb.md +++ b/docs/windows-usb.md @@ -35,7 +35,7 @@ ads-client → P2P / WSS 中继 → ads-agent → 手机 TCP adbd - 发布者:Cloudyne Systems (Scheibling Consulting AB) - 证书指纹:9AC56B6C76141395D74FFF6652818376E80B9C95 -安装会短暂重启 USB 集线器;安装器可能要求随后重启 Windows。脚本不会强制重启、打开测试签名或关闭 Secure Boot。升级版本时需重新核验发布资产、签名及驱动兼容性。第三方安装包不进入 Git 或桌面分发包。 +安装会短暂重启 USB 集线器;安装器可能要求随后重启 Windows。脚本不会强制重启、打开测试签名或关闭 Secure Boot。升级版本时需重新核验发布资产、签名及驱动兼容性。第三方安装包不进入 Git;Windows 客户端分发包附带经固定哈希及签名校验的原版安装器,由用户选择安装。 2026-11-12 已在当前 Windows 安装驱动,usbip2_ude 与 usbip2_filter 均运行。安装器报告需要重启,但未自动重启;重启前的虚拟 USB 枚举、远程 shell 已通过。 @@ -70,3 +70,11 @@ dotnet run --project Ads.Desktop.Smoke -c Debug -- --live --screen --usb 桌面 USB 模式实测通过:P2P 路线状态、USB 序列号选择、设备型号、真实 scrcpy 视频、重新连接、断开后释放租约、清理本机隧道端口时一并移除虚拟 USB,以及凭据不写入配置/日志。结束后 USBip 控制器导入数量为 0,物理 USB 手机保持在线。 多设备工作台中,切换当前设备不会断开其他 USB 设备;清理所选设备的隧道端口只释放该设备。退出和“断开全部”释放本工作台的全部虚拟 USB 设备,不卸载驱动或操作物理 USB 手机。 + +## Flutter Windows + +“连接配置”勾选“挂载为 USB 设备 · Windows”,先检测 USBip 控制器、usbip.exe 和 ads-usb。未安装控制器时弹出安装提示;选择安装后验证随包安装器的 SHA-256 和发布者签名,启动交互安装器请求 UAC,不静默安装、不重启 Windows。安装完成后重新检测并勾选、保存配置,再连接设备。 + +Flutter 连接会等待租约状态为 true,禁用网络 adb connect,分配独立回环 USB/IP 端口并挂载;设备列表和投屏使用 ADS- 序列号。断开/退出停止本次 ads-usb,借助 --once 与 TCP EOF 移除本设备,不按可能复用的控制器端口 detach。 + +Windows 包在 drivers/ 下附带原版 USBip-0.9.8.1-x64.exe 及来源说明;ADS 主安装器只复制该文件,不自动安装驱动。 diff --git a/flutter_manager/README.md b/flutter_manager/README.md index 5697b09..a2b5baf 100644 --- a/flutter_manager/README.md +++ b/flutter_manager/README.md @@ -21,14 +21,14 @@ flutter build windows --release - 设备工作台:显示网关在线设备和租约占用,搜索设备,同时连接多台设备,自动分配回环端口,断开与复制地址。 - 中继节点:显示控制中心 /v2/nodes 的健康与通道使用情况;旧服务器无该接口时为空。 - 本机 ADB:启动本地 ADB Server、读取 devices -l,包括本机 USB 及网络设备。 -- 投屏:ADB 就绪后以独立 scrcpy 窗口运行,使用 --force-adb-forward。当前默认最大边长 1920、60 FPS、关闭音频。 +- 投屏:Windows 下点击“内嵌投屏”,将官方 scrcpy 窗口嵌入管理端,鼠标键盘直接控制;返回设备页后隐藏画面,点击“查看投屏”恢复。可停止投屏而保留设备连接。使用 --force-adb-forward,最大边长 1920、60 FPS、关闭音频。 - 托盘:关闭主窗口后保留连接,托盘打开窗口、断开全部、退出。完全退出会停止本应用启动的进程并断开所属 ADB 地址。 - 配置:保存非敏感设置、导入 client.env、检查三个可执行程序;凭据不写入设置,子进程通过环境变量接收令牌。 - 自动每 12 秒同步控制中心,每 3 秒检查 ADB 状态,连接重试由 ads-client 负责。 开发环境自动向上查找仓库,使用 bin/ads-client.exe、bin/tools/scrcpy/ 中的工具与 config/private/client.env。发行时请在应用旁放置 ads-client.exe、tools/scrcpy/ 完整发行目录,或在配置页填写绝对路径,并导入自己的凭据文件。配置在 %LOCALAPPDATA%/TTSTD/ADS-Flutter/settings.json,与原客户端分开。 -服务地址支持 /ads 路径前缀和可选直连源站地址,HTTPS 仍按原域名校验证书。令牌仅使用 client 角色。Agent 管理使用独立 admin.env 管理角色,支持多 Agent/多手机、配置、日志及受监督重启;本机使用 adsctl 私有 IPC。用户账号和角色编辑不在此版本范围。USB 模拟未在本工程接入。 +服务地址支持 /ads 路径前缀和可选直连源站地址,HTTPS 仍按原域名校验证书。令牌仅使用 client 角色。Agent 管理使用独立 admin.env 管理角色,支持多 Agent/多手机、配置、日志及受监督重启;本机使用 adsctl 私有 IPC。用户账号和角色编辑不在此版本范围。Windows 支持可选虚拟 USB ADB;连接配置中勾选启用。 ## 目录 @@ -38,7 +38,7 @@ flutter build windows --release | lib/data/ | 配置、HTTP API、工具发现、ADB 与子进程生命周期 | Dart | | lib/ui/ | ChangeNotifier 状态与管理界面 | Dart | | assets/ | 托盘图标资源 | ICO,无业务源码 | -| windows/ | Flutter Windows 原生宿主与插件注册 | C++、CMake、资源文件;部分自动生成 | +| windows/ | Flutter Windows 原生宿主、scrcpy 子窗口承载与插件注册 | C++、CMake、资源文件;部分自动生成 | | test/ | 凭据、URL 与不同窗口宽度的界面验证 | Dart | | build/ | Flutter 生成的 Windows 发行与缓存(忽略) | 构建产物,无业务源码 | | .dart_tool/ | Dart/Flutter 生成缓存(忽略) | JSON 等,无业务源码 | @@ -68,3 +68,48 @@ dart run test/live_smoke.dart --connect --screen 导航“Agent 管理”可选择多台被控电脑,添加/移除/启停手机,修改配置、跟随日志和重启。也可管理本机 Agent,初始化并安装无界面开机任务。发行包旁放置 adsctl.exe 和 ads-agent.exe;两者与 Avalonia 共用同一配置和后台,不应重复启动。详见 [Agent 管理](../docs/agent-management.md)。 `lib/data/agent_models.dart` 使用 Freezed 生成不可变快照(生成文件一并提交);`agent_service.dart` 封装 HTTP/本机 CLI,`agent_repository.dart` 解析数据,`lib/ui/agent_model.dart` 持有页面状态。模型变化后运行 `dart run build_runner build`。`test/agent_test.dart` 验证选择范围、日志脱敏、响应竞争和布局;`agent_live_smoke.dart` 仅面向显式提供的隔离测试 Agent。 + + +## Windows 内嵌投屏 + +使用本机官方 scrcpy 5.0.1,以独立进程运行,画面窗口通过原生平台通道 ads/scrcpy_host 挂到 Flutter 视图。lib/ui/embedded_screen.dart 按设备像素比同步画面矩形;windows/runner/scrcpy_host.cpp 按 PID 发现、挂载、隐藏及释放窗口。不修改手机端、隧道或 scrcpy 源码。 + +一次在页面中显示一台设备的画面,其他投屏进程可保留。返回设备页切换另一台;关闭主窗口后,画面随父窗口隐藏。退出会停止本应用启动的 scrcpy。布局采用原生子窗口,Flutter 控件放在画面外;暂不支持画面上叠加 Flutter 弹窗、原生画面全屏快捷键及其他系统的窗口嵌入。首版采用已验证的软件解码和软件渲染路径;硬件加速尚未验收。高 DPI 使用 Flutter 实际设备像素比,多显示器不同 DPI 的迁移仍需专门验收。 + +原生自动冒烟(使用已授权设备,会临时投屏,不操作手机应用): + +```powershell +flutter run -d windows --release -t test/windows_embed_smoke.dart --dart-define=ADS_EMBED_SERIAL= +# 冒烟产物会覆盖同一输出目录,完成后重新构建正式入口 +flutter build windows --release -t lib/main.dart +``` + +验证报告位于仓库 work/flutter-embed-smoke.json,检查原生父窗口、画面尺寸同步、页面隐藏、主窗口隐藏/恢复和释放。不等同于鼠标键盘与输入法的人工交互验收。 + +2026-11-12 Windows 真机内嵌验证通过:scrcpy 5.0.1,H.264 1920×1200;原生子窗口挂载、窗口缩放、切页隐藏、主窗口隐藏/恢复和释放均通过。内嵌模式使用本轮验证通过的软件解码及 software 渲染器,硬件加速路径尚未验收。鼠标键盘直接交给原生 scrcpy,输入法、全屏快捷键和多显示器混合 DPI 未完成自动交互验收。 + +## Windows 便携包 + +在本目录执行 .\package-windows.ps1,自动分析、测试、构建正式 lib/main.dart 入口,并输出带北京时间戳的 bin/flutter-win-x64-YYYYMMDD-HHmmss/ 与对应 ZIP、SHA-256 文件。该脚本为 PowerShell,无新增源码目录。 + +包内包含 Flutter 运行资源、现有 bin/ 中的 ads-client/ads-agent/adsctl、完整 scrcpy 工具目录、已安装 Visual Studio 的 x64 C++ 可再分发运行库,以及逐文件校验清单 manifest.json。不会覆盖已运行的旧包;不包含凭据或用户设置。解压整个目录后运行 ads_manager.exe,无需 Flutter SDK、Rust 工具链或 .NET。目标机器需自行导入凭据。 + +## 可选虚拟 USB 与驱动安装 + +连接配置勾选“挂载为 USB 设备 · Windows”;缺少驱动时提示安装,点击安装后验证 SHA-256 与发布者签名,再由 Windows 请求管理员确认。安装可能短暂重启 USB 集线器并要求重启 Windows,应用不强制重启。重新检测组件后勾选并保存,对下一次连接生效。默认 usbip.exe 路径为 C:\Program Files\USBip\usbip.exe。 + +Windows 便携包和安装器包含 ads-usb.exe 及 drivers/ 下的原版已签名 USBip 安装器,主安装器不自动安装驱动;drivers/ 为分发产物目录(EXE、TXT,无业务源码)。lib/data/windows_usb.dart 封装组件检测、校验、安装启动及每台设备的 USB 生命周期(Dart)。 + +USB 模式禁用网络 adb connect,等待租约后挂载,ADB 与 scrcpy 使用 ADS-设备ID 序列号。每台设备独立分配回环端口,断开只移除本次虚拟 USB,不操作物理 USB 手机或卸载驱动。仅支持 ADB,不包含 MTP/fastboot。Linux、macOS 后端未实现。 + +真机验证:dart run test/live_smoke.dart --connect --usb --screen,仅连接空闲设备,验证原版 ADB 的 -d USB 专用筛选、远程 shell、scrcpy 进程及断开后的设备移除与端口回收。 + +2026-11-12 Flutter USB 验证:16 项自动测试通过,包含缺少驱动时的安装提示与取消行为。真实远端 ADS-home-phone 的原版 ADB USB 筛选、远程 shell、scrcpy 与断开回收通过;USB 模式下的 Windows 内嵌画面、缩放、切页隐藏、主窗口隐藏恢复及释放亦通过。本机驱动已预装,未为测试卸载/重装驱动;真实 UAC 安装交互仍由用户完成。 + +## 投屏窗口切换与单实例 + +内嵌投屏页提供“独立投屏”,切换后提供“返回内嵌”。切换仅重启该设备的 scrcpy 进程,保留网络隧道、租约和可选虚拟 USB;停止投屏同样保留设备连接。虚拟 USB 的驱动检测与安装提示保持可用。 + +Windows 下 Flutter 和 Avalonia 两个桌面入口共享会话级单实例锁,安装版、便携版和 Agent 托盘入口都不能重复启动第二个 ADS 桌面实例。重复启动会退出新进程并唤起已有窗口(包括托盘隐藏或最小化状态)。仅限制桌面管理 UI,不限制无界面 Agent/client 或多个设备的 scrcpy 子进程。非 Windows 平台尚未接入此单实例机制。 + +本轮验证:Flutter 17 项测试与 Avalonia 20 项测试通过。真实虚拟 USB 上验证内嵌转独立窗口实际显示、USB 连接与桥接进程保持不变;重复启动退出并恢复隐藏主窗口通过。Avalonia 作为主实例时,重复启动 Avalonia 或 Flutter 均退出,主实例正常保留。 diff --git a/flutter_manager/lib/data/manager_repository.dart b/flutter_manager/lib/data/manager_repository.dart index e217fd1..a459f83 100644 --- a/flutter_manager/lib/data/manager_repository.dart +++ b/flutter_manager/lib/data/manager_repository.dart @@ -4,12 +4,15 @@ import 'dart:io'; import 'package:path/path.dart' as p; +import 'windows_usb.dart'; + class Settings { String server = 'wss://ttstd.com/ads'; String origin = '175.178.213.60:443'; String credential = ''; String client = '', adb = '', scrcpy = ''; - bool relayOnly = false; + bool relayOnly = false, usbMode = false; + String usbip = UsbDriver.defaultUsbip(); Map toJson() => { 'server': server, 'origin': origin, @@ -18,6 +21,8 @@ class Settings { 'adb': adb, 'scrcpy': scrcpy, 'relayOnly': relayOnly, + 'usbMode': usbMode, + 'usbip': usbip, }; void load(Map j) { server = j['server'] as String? ?? server; @@ -27,6 +32,8 @@ class Settings { adb = j['adb'] as String? ?? adb; scrcpy = j['scrcpy'] as String? ?? scrcpy; relayOnly = j['relayOnly'] == true; + usbMode = j['usbMode'] == true; + usbip = j['usbip'] as String? ?? usbip; } Uri uri(String suffix) { @@ -52,12 +59,17 @@ class Device { } class Session { - final String id, endpoint, adb, statusFile; + final String id, tunnel, adb, statusFile; + String? leaseFile; + WindowsUsbSession? usb; + String get endpoint => usb?.serial ?? tunnel; + String get mode => usb == null ? "网络 ADB" : "虚拟 USB"; final Process process; Process? screen; + bool screenEmbedded = false; String state = '连接中', route = '协商中'; bool ready = false, stopping = false, exited = false; - Session(this.id, this.endpoint, this.adb, this.statusFile, this.process); + Session(this.id, this.tunnel, this.adb, this.statusFile, this.process); } class ManagerRepository { @@ -300,73 +312,141 @@ class ManagerRepository { if (token.length < 32) { throw const FormatException('请先导入凭据'); } - var port = 15555; - while (port < 18000) { - if (reservedPorts.contains(port) || - sessions.values.any((s) => s.endpoint.endsWith(':$port'))) { - port++; + final usbMode = settings.usbMode; + final usbip = settings.usbip; + if (usbMode) { + if (!await UsbDriver.installed(run)) { + throw StateError('未安装 USBip 虚拟控制器,请在连接配置中安装驱动'); + } + if (!await File(usbip).exists()) { + throw StateError('找不到 usbip.exe,请检查配置路径'); + } + await run(findTool('ads-usb'), ['--version']); + } + final port = await allocatePort(15555, 18000); + int? usbPort; + Session? session; + try { + if (usbMode) { + usbPort = await allocateUsbPort(); + } + final endpoint = '127.0.0.1:$port'; + final status = p.join( + storage.path, + 'transport-$id-${DateTime.now().microsecondsSinceEpoch}.json', + ); + final lease = usbMode ? "$status.lease" : null; + final proc = await Process.start( + settings.client, + [ + '--server', + settings.server.trim(), + '--device', + id, + '--listen', + endpoint, + '--adb', + settings.adb, + '--transport', + settings.relayOnly ? 'relay' : 'auto', + '--status-file', + status, + if (lease != null) ...[ + '--no-auto-connect', + '--lease-status-file', + lease, + ], + if (settings.origin.trim().isNotEmpty) ...[ + '--connect-address', + settings.origin.trim(), + ], + ], + environment: environment()..['ADS_CLIENT_TOKEN'] = token, + includeParentEnvironment: false, + ); + watch(proc, id); + session = Session(id, endpoint, settings.adb, status, proc); + final current = session; + sessions[id] = current; + current.leaseFile = lease; + unawaited( + proc.exitCode.then((code) { + current.exited = true; + current.ready = false; + current.state = '连接程序已退出 ($code)'; + }), + ); + if (usbMode) { + final usb = WindowsUsbSession(id, usbPort!); + current.usb = usb; + current.state = '等待设备租约并挂载 USB'; + await usb.start( + leaseFile: lease!, + upstream: current.tunnel, + executable: findTool('ads-usb'), + usbip: usbip, + environment: environment(), + run: run, + watch: watch, + cancelled: () => current.exited || current.stopping, + ); + log('USB 已挂载:${usb.serial}'); + } + return current; + } catch (_) { + if (session != null) { + await disconnect(id); + } else { + reservedPorts.remove(port); + if (usbPort != null) { + reservedPorts.remove(usbPort); + } + } + rethrow; + } + } + + Future allocateUsbPort() async { + // A new OS-selected endpoint also avoids a previous controller's delayed + // teardown reconnecting to the next export at a reused fixed port. + while (true) { + final probe = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final port = probe.port; + final reserved = reservedPorts.add(port); + await probe.close(); + if (reserved) { + return port; + } + } + } + + Future allocatePort(int start, int end) async { + for (var port = start; port < end; port++) { + if (!reservedPorts.add(port)) { continue; } try { - final socket = await ServerSocket.bind( + final probe = await ServerSocket.bind( InternetAddress.loopbackIPv4, port, ); - reservedPorts.add(port); - await socket.close(); - break; + await probe.close(); + return port; } on SocketException { - port++; + reservedPorts.remove(port); } } - if (port == 18000) { - throw const SocketException('没有空闲本地端口'); - } - final endpoint = '127.0.0.1:$port'; - final status = p.join( - storage.path, - 'transport-$id-${DateTime.now().microsecondsSinceEpoch}.json', - ); - final proc = await Process.start( - settings.client, - [ - '--server', - settings.server.trim(), - '--device', - id, - '--listen', - endpoint, - '--adb', - settings.adb, - '--transport', - settings.relayOnly ? 'relay' : 'auto', - '--status-file', - status, - if (settings.origin.trim().isNotEmpty) ...[ - '--connect-address', - settings.origin.trim(), - ], - ], - environment: environment()..['ADS_CLIENT_TOKEN'] = token, - includeParentEnvironment: false, - ); - watch(proc, id); - final session = Session(id, endpoint, settings.adb, status, proc); - sessions[id] = session; - unawaited( - proc.exitCode.then((code) { - session.exited = true; - session.ready = false; - session.state = '连接程序已退出 ($code)'; - }), - ); - return session; + throw const SocketException('没有空闲的本地端口'); } Future monitor() async { final listings = {}; for (final s in sessions.values.toList()) { - if (s.stopping || s.exited) { + if (!s.stopping && (s.exited || s.usb?.exited == true)) { + await disconnect(s.id); + continue; + } + if (s.stopping) { continue; } try { @@ -393,29 +473,25 @@ class ManagerRepository { } } - Future screen(Session s) async { - if (!s.ready || s.screen != null) { + Future screen(Session s, {bool embedded = false}) async { + if (!s.ready) { return; } - final proc = await Process.start( - settings.scrcpy, - [ - '--serial', - s.endpoint, - '--force-adb-forward', - '--window-title', - 'ADS Flutter · ${s.id}', - '--max-size', - '1920', - '--max-fps', - '60', - '--no-audio', - ], - workingDirectory: p.dirname(p.absolute(settings.scrcpy)), - environment: environment()..['ADB'] = s.adb, - includeParentEnvironment: false, + if (s.screen != null) { + if (s.screenEmbedded == embedded) { + return; + } + await stop(s.screen); + s.screen = null; + } + final proc = await launchScreen( + s.endpoint, + s.adb, + s.id, + embedded: embedded, ); s.screen = proc; + s.screenEmbedded = embedded; watch(proc, 'scrcpy ${s.id}'); unawaited( proc.exitCode.then((code) { @@ -427,6 +503,38 @@ class ManagerRepository { ); } + Future launchScreen( + String endpoint, + String adb, + String id, { + bool embedded = false, + }) { + return Process.start( + settings.scrcpy, + [ + '--serial', + endpoint, + '--force-adb-forward', + '--window-title', + 'ADS Flutter · $id', + if (embedded) ...[ + '--window-borderless', + '--hwdec=disabled', + '--render-driver=software', + '--no-window-aspect-ratio-lock', + ], + '--max-size', + '1920', + '--max-fps', + '60', + '--no-audio', + ], + workingDirectory: p.dirname(p.absolute(settings.scrcpy)), + environment: environment()..['ADB'] = adb, + includeParentEnvironment: false, + ); + } + Future stop(Process? proc) async { if (proc == null) { return; @@ -441,20 +549,51 @@ class ManagerRepository { return; } s.stopping = true; - try { + for (final proc in [s.screen, s.usb?.bridge, s.process]) { try { - await stop(s.screen); + await stop(proc); } catch (e) { - log("停止投屏:$e"); + log('停止设备进程:$e'); } - await stop(s.process); - await run(s.adb, ['disconnect', s.endpoint]); + } + try { + if (s.usb == null) { + await run(s.adb, ['disconnect', s.tunnel]); + } else { + final deadline = DateTime.now().add(const Duration(seconds: 8)); + while (true) { + final listing = await run(s.adb, ['devices']); + if (!listing + .split('\n') + .any((line) => line.startsWith('${s.endpoint}\t'))) { + break; + } + if (DateTime.now().isAfter(deadline)) { + throw StateError('虚拟 USB 正在由 Windows 回收,请稍后重连'); + } + await Future.delayed(const Duration(milliseconds: 200)); + } + } + } catch (e) { + log('断开 ADB:$e'); } finally { sessions.remove(id); - reservedPorts.remove(int.parse(s.endpoint.split(':').last)); - final file = File(s.statusFile); - if (await file.exists()) { - await file.delete(); + reservedPorts.remove(int.parse(s.tunnel.split(':').last)); + if (s.usb != null) { + reservedPorts.remove(s.usb!.port); + } + for (final path in [s.statusFile, s.leaseFile]) { + if (path == null) { + continue; + } + final file = File(path); + try { + if (await file.exists()) { + await file.delete(); + } + } on FileSystemException catch (e) { + log('$e'); + } } } } diff --git a/flutter_manager/lib/data/windows_usb.dart b/flutter_manager/lib/data/windows_usb.dart new file mode 100644 index 0000000..ab817f2 --- /dev/null +++ b/flutter_manager/lib/data/windows_usb.dart @@ -0,0 +1,171 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:path/path.dart' as p; + +typedef UsbRun = Future Function(String exe, List args); + +class UsbDriver { + static const filename = 'USBip-0.9.8.1-x64.exe'; + static const hash = + '38cad6d4432b52d5bb9409d9ad03b72fdffc4ada4cd3a48fbeca1a2752a8518a'; + static String defaultUsbip() => p.join( + Platform.environment['ProgramFiles'] ?? r'C:Program Files', + 'USBip', + 'usbip.exe', + ); + static Future installed(UsbRun run) async { + if (!Platform.isWindows) { + return false; + } + try { + await run('sc.exe', ['query', 'usbip2_ude']); + return true; + } on ProcessException { + return false; + } + } + + static String installer(String? root) { + final adjacent = p.join( + p.dirname(Platform.resolvedExecutable), + 'drivers', + filename, + ); + if (File(adjacent).existsSync()) { + return adjacent; + } + return root == null ? adjacent : p.join(root, 'work', filename); + } + + static Future validHash(File file) async => + (await sha256.bind(file.openRead()).first).toString() == hash; + + /// Only invoked after the user selects Install in the missing-driver dialog. + static Future install(String file) async { + if (!Platform.isWindows) { + throw UnsupportedError('USB 模拟目前仅支持 Windows'); + } + if (!await File(file).exists() || !await validHash(File(file))) { + throw StateError('USBip 安装包缺失或 SHA-256 校验失败,请重新获取完整 Windows 安装包'); + } + const script = r""" +$ErrorActionPreference='Stop' +$f=$env:ADS_USB_INSTALLER +$s=Get-AuthenticodeSignature -LiteralPath $f +if ($s.Status -ne 'Valid' -or $s.SignerCertificate.Thumbprint -ne '9AC56B6C76141395D74FFF6652818376E80B9C95') { throw 'USBip signature verification failed' } +$p=Start-Process -FilePath $f -ArgumentList '/NORESTART' -Verb RunAs -PassThru -Wait +exit $p.ExitCode +"""; + final result = await Process.run( + 'powershell.exe', + ['-NoProfile', '-NonInteractive', '-Command', script], + environment: Map.of(Platform.environment) + ..removeWhere((key, value) => key.startsWith('ADS_')) + ..['ADS_USB_INSTALLER'] = p.absolute(file), + includeParentEnvironment: false, + ); + if (result.exitCode != 0 && result.exitCode != 3010) { + throw StateError( + 'USBip 安装未完成(可能已取消 UAC),退出码 ${result.exitCode}:${result.stderr}', + ); + } + return result.exitCode; + } +} + +class WindowsUsbSession { + final String serial; + final int port; + Process? bridge; + bool exited = false; + WindowsUsbSession(String device, this.port) : serial = serialFor(device); + static String serialFor(String device) => + 'ADS-${device.length <= 116 ? device : sha256.convert(utf8.encode(device)).toString().substring(0, 24).toUpperCase()}'; + + Future start({ + required String leaseFile, + required String upstream, + required String executable, + required String usbip, + required Map environment, + required UsbRun run, + required void Function(Process, String) watch, + required bool Function() cancelled, + Duration leaseTimeout = const Duration(seconds: 40), + }) async { + final deadline = DateTime.now().add(leaseTimeout); + while (true) { + if (cancelled()) { + throw StateError('USB 连接已取消或客户端已退出'); + } + final file = File(leaseFile); + try { + if (await file.exists() && + (await file.readAsString()).trim() == 'true') { + break; + } + } on FileSystemException { + /* publisher is replacing its readiness file */ + } + if (DateTime.now().isAfter(deadline)) { + throw StateError('等待 USB 设备租约超时'); + } + await Future.delayed(const Duration(milliseconds: 150)); + } + bridge = await Process.start( + executable, + [ + '--listen', + '127.0.0.1:$port', + '--upstream', + upstream, + '--serial', + serial, + ], + environment: environment, + includeParentEnvironment: false, + ); + watch(bridge!, serial); + unawaited(bridge!.exitCode.then((_) => exited = true)); + final readyDeadline = DateTime.now().add(const Duration(seconds: 5)); + while (true) { + if (exited || cancelled()) { + throw StateError('虚拟 USB 设备进程已退出'); + } + try { + final probe = await Socket.connect( + InternetAddress.loopbackIPv4, + port, + timeout: const Duration(milliseconds: 250), + ); + probe.destroy(); + break; + } on SocketException { + if (DateTime.now().isAfter(readyDeadline)) { + rethrow; + } + await Future.delayed(const Duration(milliseconds: 100)); + } + } + final output = await run(usbip, [ + '--tcp-port', + '$port', + 'attach', + '--remote', + '127.0.0.1', + '--bus-id', + '1-1', + '--terse', + '--once', + ]); + final imported = int.tryParse(output.trim()); + if (imported == null || imported < 1 || imported > 127) { + throw StateError('无法确认 USBip 挂载成功:$output'); + } + // --once has no persistent retry. Closing only our bridge removes only our + // device; do not detach by a hub number that might have been reused. + } +} diff --git a/flutter_manager/lib/ui/embedded_screen.dart b/flutter_manager/lib/ui/embedded_screen.dart new file mode 100644 index 0000000..20ddaae --- /dev/null +++ b/flutter_manager/lib/ui/embedded_screen.dart @@ -0,0 +1,188 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../data/manager_repository.dart'; + +/// A native child window occupies this rectangle; controls stay outside it. +class EmbeddedScreen extends StatefulWidget { + final int pid; + const EmbeddedScreen({super.key, required this.pid}); + static const channel = MethodChannel('ads/scrcpy_host'); + @override + State createState() => _EmbeddedScreenState(); +} + +class _EmbeddedScreenState extends State { + final area = GlobalKey(); + Timer? timer; + bool attached = false, updating = false; + String? error; + int attempts = 0; + @override + void initState() { + super.initState(); + timer = Timer.periodic(const Duration(milliseconds: 150), (_) => update()); + WidgetsBinding.instance.addPostFrameCallback((_) => update()); + } + + Future update() async { + if (!mounted || updating || error != null) { + return; + } + updating = true; + try { + if (!attached) { + attached = + await EmbeddedScreen.channel.invokeMethod('attach', { + 'pid': widget.pid, + }) ?? + false; + if (!mounted) { + await EmbeddedScreen.channel.invokeMethod('hide', { + 'pid': widget.pid, + }); + return; + } + if (!attached) { + if (++attempts > 100) { + throw StateError('等待 scrcpy 窗口超时,请检查运行日志'); + } + return; + } + setState(() {}); + } + final box = area.currentContext?.findRenderObject(); + if (box is! RenderBox || !box.hasSize) { + return; + } + final point = box.localToGlobal(Offset.zero); + final scale = MediaQuery.devicePixelRatioOf(context); + await EmbeddedScreen.channel.invokeMethod('layout', { + 'pid': widget.pid, + 'x': (point.dx * scale).round(), + 'y': (point.dy * scale).round(), + 'width': (box.size.width * scale).floor(), + 'height': (box.size.height * scale).floor(), + }); + } catch (e) { + await EmbeddedScreen.channel + .invokeMethod('hide', {'pid': widget.pid}) + .catchError((Object _) {}); + if (mounted) { + setState(() => error = e.toString()); + } + } finally { + updating = false; + } + } + + @override + void dispose() { + timer?.cancel(); + unawaited( + EmbeddedScreen.channel + .invokeMethod('hide', {'pid': widget.pid}) + .catchError((Object _) {}), + ); + super.dispose(); + } + + @override + Widget build(BuildContext context) => ColoredBox( + key: area, + color: const Color(0xFF111827), + child: Center( + child: error != null + ? Padding( + padding: const EdgeInsets.all(24), + child: Text( + '投屏嵌入失败\n$error\n请停止投屏后重试。', + style: const TextStyle(color: Colors.white70), + ), + ) + : attached + ? const SizedBox.expand() + : const Column( + mainAxisSize: MainAxisSize.min, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text( + '正在连接 scrcpy 画面…', + style: TextStyle(color: Colors.white70), + ), + ], + ), + ), + ); +} + +class ScreenPage extends StatelessWidget { + final Session? session; + final VoidCallback onBack; + final Future Function() onStop; + final Future Function() onToggle; + final bool busy; + const ScreenPage({ + super.key, + required this.session, + required this.onBack, + required this.onStop, + required this.onToggle, + this.busy = false, + }); + @override + Widget build(BuildContext context) { + final s = session; + final pid = s?.screen?.pid; + return Column( + children: [ + Row( + children: [ + OutlinedButton.icon( + onPressed: onBack, + icon: const Icon(Icons.arrow_back), + label: const Text('返回设备'), + ), + const SizedBox(width: 16), + Expanded( + child: Text( + s == null ? '设备连接已释放' : '${s.id} · ${s.endpoint}', + overflow: TextOverflow.ellipsis, + ), + ), + OutlinedButton.icon( + onPressed: pid == null || busy ? null : onToggle, + icon: Icon( + s?.screenEmbedded == true + ? Icons.open_in_new + : Icons.picture_in_picture_alt, + ), + label: Text(s?.screenEmbedded == true ? '独立投屏' : '返回内嵌'), + ), + const SizedBox(width: 8), + TextButton( + onPressed: pid == null || busy ? null : onStop, + child: const Text('停止投屏'), + ), + ], + ), + const SizedBox(height: 12), + Expanded( + child: pid == null + ? const Center(child: Text('投屏已停止,请返回设备重新打开。')) + : s?.screenEmbedded == true + ? EmbeddedScreen(key: ValueKey(pid), pid: pid) + : const Center(child: Text('投屏已在独立窗口运行,设备连接保持不变。')), + ), + const SizedBox(height: 8), + const Text( + '点击画面后可用鼠标和键盘控制 · 切换页面后投屏保留 · 暂不支持在内嵌画面使用全屏快捷键', + style: TextStyle(fontSize: 11, color: Colors.blueGrey), + ), + ], + ); + } +} diff --git a/flutter_manager/lib/ui/manager_view.dart b/flutter_manager/lib/ui/manager_view.dart index 75979da..f234261 100644 --- a/flutter_manager/lib/ui/manager_view.dart +++ b/flutter_manager/lib/ui/manager_view.dart @@ -1,9 +1,14 @@ +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'; class ManagerView extends StatefulWidget { final ManagerModel model; @@ -15,6 +20,7 @@ class ManagerView extends StatefulWidget { class _ManagerViewState extends State { int page = 0; + String? screenDevice; String search = ''; ManagerModel get m => widget.model; @override @@ -125,6 +131,7 @@ class _ManagerViewState extends State { '连接配置', '运行日志', 'Agent 管理', + '内嵌投屏', ][page], style: const TextStyle( fontSize: 24, @@ -163,6 +170,28 @@ class _ManagerViewState extends State { 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: () => setState(() => page = 0), + onStop: () => m.deviceAction(screenDevice!, () async { + final s = m.repository.sessions[screenDevice]; + if (s != null) { + await m.repository.stop(s.screen); + s.screen = null; + } + }), + ), _ => logs(), }, ), @@ -349,14 +378,19 @@ class _ManagerViewState extends State { spacing: 8, children: [ FilledButton.icon( - onPressed: pending || !s.ready || s.screen != null + onPressed: pending || !s.ready ? null - : () => m.deviceAction( - d.id, - () => m.repository.screen(s), - ), + : () => m.deviceAction(d.id, () async { + await m.repository.screen(s, embedded: true); + if (mounted) { + setState(() { + screenDevice = s.id; + page = 6; + }); + } + }), icon: const Icon(Icons.open_in_new, size: 16), - label: Text(s.screen == null ? '打开 scrcpy' : '投屏运行中'), + label: Text(s.screen == null ? '内嵌投屏' : '查看投屏'), ), OutlinedButton( onPressed: pending ? null : () => m.disconnect(d.id), @@ -372,7 +406,7 @@ class _ManagerViewState extends State { children: [ Expanded( child: Text( - '网络 ADB ${s.endpoint} · ${s.route}', + '${s.mode} ${s.endpoint} · ${s.route}', style: const TextStyle(fontSize: 12), ), ), @@ -494,14 +528,16 @@ class _ManagerViewState extends State { class SettingsView extends StatefulWidget { final ManagerModel model; - const SettingsView({super.key, required this.model}); + final Future Function()? driverInstalled; + const SettingsView({super.key, required this.model, this.driverInstalled}); @override State createState() => _SettingsViewState(); } class _SettingsViewState extends State { late final Map fields; - bool relayOnly = false; + bool relayOnly = false, usbMode = false, installingUsb = false; + String usbStatus = '尚未检测'; @override void initState() { super.initState(); @@ -514,10 +550,93 @@ class _SettingsViewState extends State { '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() { @@ -529,6 +648,8 @@ class _SettingsViewState extends State { 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 @@ -565,6 +686,7 @@ class _SettingsViewState extends State { ('client', 'ads-client.exe 路径'), ('adb', 'adb.exe 路径'), ('scrcpy', 'scrcpy.exe 路径(需保留完整发行目录)'), + ('usbip', 'usbip.exe 路径'), ]) Padding( padding: const EdgeInsets.only(bottom: 18), @@ -573,6 +695,29 @@ class _SettingsViewState extends State { decoration: InputDecoration(labelText: label), ), ), + 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, diff --git a/flutter_manager/package-windows.ps1 b/flutter_manager/package-windows.ps1 new file mode 100644 index 0000000..19b63ff --- /dev/null +++ b/flutter_manager/package-windows.ps1 @@ -0,0 +1,82 @@ +param([switch]$SkipChecks) +$ErrorActionPreference = 'Stop' +$projectRoot = Split-Path $PSScriptRoot -Parent +Push-Location $PSScriptRoot +try { + if (-not $SkipChecks) { + flutter analyze + if ($LASTEXITCODE -ne 0) { throw 'Flutter analysis failed' } + flutter test + if ($LASTEXITCODE -ne 0) { throw 'Flutter tests failed' } + } + # Always select the production entry, even after running native smoke tests. + flutter build windows --release -t lib/main.dart + if ($LASTEXITCODE -ne 0) { throw 'Flutter Windows build failed' } + + $stamp = [TimeZoneInfo]::ConvertTimeBySystemTimeZoneId([DateTimeOffset]::UtcNow, 'China Standard Time').ToString('yyyyMMdd-HHmmss') + $packageName = "flutter-win-x64-$stamp" + $packageDir = Join-Path $projectRoot "bin/$packageName" + if (Test-Path -LiteralPath $packageDir) { throw "Package already exists: $packageDir" } + New-Item -ItemType Directory -Path $packageDir | Out-Null + Copy-Item -Path (Join-Path $PSScriptRoot 'build/windows/x64/runner/Release/*') -Destination $packageDir -Recurse + foreach ($name in @('ads-client','ads-agent','adsctl','ads-usb')) { + $source = Join-Path $projectRoot "bin/$name.exe" + if (-not (Test-Path -LiteralPath $source)) { throw "Missing bundled tool: $name" } + Copy-Item -LiteralPath $source -Destination $packageDir + } + $scrcpy = Join-Path $projectRoot 'bin/tools/scrcpy' + foreach ($name in @('scrcpy.exe','scrcpy-server','adb.exe','SDL3.dll','LICENSE.txt')) { + if (-not (Test-Path -LiteralPath (Join-Path $scrcpy $name))) { throw "Missing scrcpy asset: $name" } + } + $tools = Join-Path $packageDir 'tools/scrcpy' + New-Item -ItemType Directory -Path $tools -Force | Out-Null + Copy-Item -Path (Join-Path $scrcpy '*') -Destination $tools -Recurse + + & (Join-Path $projectRoot 'scripts/copy-windows-usb-driver.ps1') -Destination $packageDir + # Use the latest installed desktop x64 CRT, never the onecore/ARM variant. + $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/vswhere.exe' + $vsRoot = & $vswhere -latest -products '*' -property installationPath + if ($LASTEXITCODE -ne 0 -or -not $vsRoot) { throw 'Visual Studio installation not found' } + $crt = Get-ChildItem -Path (Join-Path $vsRoot 'VC/Redist/MSVC/*/x64/Microsoft.VC*.CRT') -Directory | + Sort-Object { [version]$_.Parent.Parent.Name } -Descending | Select-Object -First 1 + if (-not $crt) { throw 'Visual C++ x64 redistributable libraries not found' } + Copy-Item -Path (Join-Path $crt.FullName '*.dll') -Destination $packageDir + foreach ($name in @('ads_manager.exe','flutter_windows.dll','vcruntime140.dll','msvcp140.dll','data/app.so','data/icudtl.dat','data/flutter_assets/assets/tray.ico')) { + if (-not (Test-Path -LiteralPath (Join-Path $packageDir $name))) { throw "Package missing: $name" } + } + $forbidden = Get-ChildItem -LiteralPath $packageDir -Recurse -File | + Where-Object { $_.Extension -in @('.env','.pem','.key','.pfx') -or $_.Name -in @('settings.json','admin.env','client.env','agent.env') } + if ($forbidden) { throw 'Private configuration detected in package' } + + @( + 'ADS Flutter Windows x64', + 'Extract the entire ZIP and launch ads_manager.exe. Do not copy only the EXE.', + 'Includes Flutter runtime, Microsoft Visual C++ x64 CRT, ads-client, ads-agent, adsctl, ads-usb, scrcpy and the optional signed USBip installer.', + 'No Flutter SDK, Rust toolchain or .NET runtime is required on the target PC.', + 'Import your own client.env in connection settings; Agent administration uses your own admin.env.', + 'Credentials are not included. Existing non-secret settings remain in %LOCALAPPDATA%/TTSTD/ADS-Flutter.', + 'Connect a device, then select the embedded screen button for Windows scrcpy mirroring.', + 'Closing the main window keeps the app in the tray. Use the tray menu to exit.', + 'Embedded mirroring currently uses software decoding/rendering. Mixed-monitor DPI and IME require further validation.' + ) | Set-Content -LiteralPath (Join-Path $packageDir 'README-Windows.txt') -Encoding utf8 + + $revision = git -C $projectRoot rev-parse HEAD + $dirty = [bool](git -C $projectRoot status --porcelain) + $files = @(Get-ChildItem -LiteralPath $packageDir -File -Recurse | ForEach-Object { + [ordered]@{ path = [IO.Path]::GetRelativePath($packageDir, $_.FullName).Replace('\','/'); bytes = $_.Length; sha256 = (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash } + }) + [ordered]@{ + builtAt = $stamp; target = 'windows-x64'; entrypoint = 'lib/main.dart'; + sourceRevision = $revision; sourceHasLocalChanges = $dirty; + backendSource = 'Existing project bin executables'; crtVersion = $crt.Parent.Parent.Name; + files = $files + } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $packageDir 'manifest.json') -Encoding utf8 + + $zip = "$packageDir.zip" + Compress-Archive -LiteralPath $packageDir -DestinationPath $zip -CompressionLevel Optimal + $hash = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash + "$hash $packageName.zip" | Set-Content -LiteralPath "$zip.sha256" -Encoding ascii + Write-Host "PACKAGE=$packageDir" + Write-Host "ZIP=$zip" + Write-Host "SHA256=$hash" +} finally { Pop-Location } diff --git a/flutter_manager/pubspec.lock b/flutter_manager/pubspec.lock index 44433ee..187a83f 100644 --- a/flutter_manager/pubspec.lock +++ b/flutter_manager/pubspec.lock @@ -138,7 +138,7 @@ packages: source: hosted version: "3.1.2" crypto: - dependency: transitive + dependency: "direct main" description: name: crypto sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4 diff --git a/flutter_manager/pubspec.yaml b/flutter_manager/pubspec.yaml index e0094d0..83efb48 100644 --- a/flutter_manager/pubspec.yaml +++ b/flutter_manager/pubspec.yaml @@ -39,6 +39,7 @@ dependencies: window_manager: 0.5.1 path: ^1.9.1 freezed_annotation: ^3.1.0 + crypto: ^3.0.8 dev_dependencies: flutter_test: diff --git a/flutter_manager/test/embedded_test.dart b/flutter_manager/test/embedded_test.dart new file mode 100644 index 0000000..6495c39 --- /dev/null +++ b/flutter_manager/test/embedded_test.dart @@ -0,0 +1,145 @@ +import 'dart:io'; + +import 'package:ads_manager/data/manager_repository.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:ads_manager/ui/embedded_screen.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + testWidgets( + 'screen page switches between embedded and standalone without disconnecting', + (tester) async { + tester.view.physicalSize = const Size(1280, 820); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + EmbeddedScreen.channel, + (call) async => call.method == 'attach' ? true : null, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + EmbeddedScreen.channel, + null, + ), + ); + final process = ScreenProcess(); + final session = + Session('phone', '127.0.0.1:15555', 'adb', 'status', process) + ..screen = process + ..screenEmbedded = true + ..ready = true; + var switches = 0; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) => ScreenPage( + session: session, + onBack: () {}, + onStop: () async {}, + onToggle: () async { + setState(() { + session.screenEmbedded = !session.screenEmbedded; + switches++; + }); + }, + ), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 200)); + await tester.tap(find.text('独立投屏')); + await tester.pumpAndSettle(); + expect(find.byType(EmbeddedScreen), findsNothing); + expect(find.textContaining('独立窗口运行'), findsOneWidget); + expect(session.ready, true); + expect(session.endpoint, '127.0.0.1:15555'); + await tester.tap(find.text('返回内嵌')); + await tester.pump(const Duration(milliseconds: 200)); + expect(find.byType(EmbeddedScreen), findsOneWidget); + expect(switches, 2); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + }, + ); + testWidgets('native screen scales its bounds and hides on removal', ( + tester, + ) async { + tester.view.physicalSize = const Size(1600, 1200); + tester.view.devicePixelRatio = 2; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final calls = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + EmbeddedScreen.channel, + (call) async { + calls.add(call); + return call.method == 'attach' ? true : null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + EmbeddedScreen.channel, + null, + ), + ); + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: Padding( + padding: EdgeInsets.all(20), + child: EmbeddedScreen(pid: 123), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 200)); + await tester.pump(); + final layout = + calls.lastWhere((c) => c.method == 'layout').arguments + as Map; + expect(layout['pid'], 123); + expect(layout['x'], 40); + expect(layout['width'], 1520); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + expect(calls.last.method, 'hide'); + expect(tester.takeException(), isNull); + }); + testWidgets('attach failure shows an error and hides the child', ( + tester, + ) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + EmbeddedScreen.channel, + (call) async { + if (call.method == 'attach') { + throw PlatformException(code: 'set_parent', message: 'test failure'); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + EmbeddedScreen.channel, + null, + ), + ); + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: EmbeddedScreen(pid: 234))), + ); + await tester.pump(const Duration(milliseconds: 200)); + await tester.pump(); + expect(find.textContaining('投屏嵌入失败'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + }); +} + +class ScreenProcess extends Fake implements Process { + @override + int get pid => 123; +} diff --git a/flutter_manager/test/live_smoke.dart b/flutter_manager/test/live_smoke.dart index 0145d81..4d14b0a 100644 --- a/flutter_manager/test/live_smoke.dart +++ b/flutter_manager/test/live_smoke.dart @@ -6,6 +6,7 @@ Future main(List args) async { final repo = ManagerRepository(stdout.writeln); try { await repo.init(); + repo.settings.usbMode = args.contains('--usb'); final devices = await repo.devices(); stdout.writeln( 'API devices: ${devices.map((d) => "${d.id} busy=${d.busy}").join(", ")}', @@ -40,6 +41,33 @@ Future main(List args) async { } stdout.writeln('scrcpy process alive: ${s.screen!.pid}'); } + if (args.contains('--usb')) { + final path = await repo.run(s.adb, ['-s', s.endpoint, 'get-devpath']); + // Windows ADB may return "unknown" for get-devpath. USB-only selection + // must either select this virtual serial or report multiple USB devices. + try { + final selected = await repo.run(s.adb, ['-d', 'get-serialno']); + if (selected.trim() != s.endpoint) { + throw StateError('USB-only selection did not include virtual device'); + } + } on ProcessException catch (error) { + if (!error.message.contains('more than one')) { + rethrow; + } + } + stdout.writeln('Native USB-only selection verified; get-devpath=$path'); + await repo.disconnect(s.id); + await Future.delayed(const Duration(seconds: 2)); + final listing = await repo.run(s.adb, ['devices']); + if (listing + .split('\n') + .any((line) => line.startsWith('${s.endpoint}\t'))) { + throw StateError('USB transport was not removed'); + } + if (repo.reservedPorts.isNotEmpty) { + throw StateError('Ports leaked after USB disconnect'); + } + } stdout.writeln('LIVE PASS'); } finally { await repo.shutdown(); diff --git a/flutter_manager/test/windows_embed_smoke.dart b/flutter_manager/test/windows_embed_smoke.dart new file mode 100644 index 0000000..65efe31 --- /dev/null +++ b/flutter_manager/test/windows_embed_smoke.dart @@ -0,0 +1,196 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:material_ui/material_ui.dart'; +import 'package:window_manager/window_manager.dart'; +import 'package:ads_manager/data/manager_repository.dart'; +import 'package:ads_manager/ui/embedded_screen.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + await windowManager.ensureInitialized(); + final repo = ManagerRepository(stdout.writeln); + Process? screen; + Session? usbSession; + final report = {}; + try { + await repo.init(); + var serial = const String.fromEnvironment('ADS_EMBED_SERIAL'); + if (const bool.fromEnvironment('ADS_EMBED_USB')) { + repo.settings.usbMode = true; + final idle = (await repo.devices()) + .where((device) => !device.busy) + .firstOrNull; + if (idle == null) { + throw StateError('No idle device for USB embedding smoke'); + } + final session = await repo.connect(idle.id); + usbSession = session; + for (var i = 0; i < 20 && !session.ready; i++) { + await Future.delayed(const Duration(seconds: 3)); + await repo.monitor(); + } + if (!session.ready) { + throw StateError('Virtual USB ADB did not become ready'); + } + serial = session.endpoint; + } + if (serial.isEmpty) { + throw StateError('Specify --dart-define=ADS_EMBED_SERIAL=...'); + } + screen = await repo.launchScreen( + serial, + repo.settings.adb, + 'native-smoke', + embedded: true, + ); + if (usbSession != null) { + usbSession.screen = screen; + usbSession.screenEmbedded = true; + } + repo.watch(screen, 'native-smoke'); + unawaited( + screen.exitCode.then((code) => stdout.writeln("SCRCPY EXIT=$code")), + ); + final pid = screen.pid; + stdout.writeln("SCRCPY PID=$pid"); + final show = ValueNotifier(true); + runApp( + MaterialApp( + home: Scaffold( + body: Padding( + padding: const EdgeInsets.fromLTRB(220, 80, 24, 24), + child: ValueListenableBuilder( + valueListenable: show, + builder: (_, visible, child) => visible + ? EmbeddedScreen(key: ValueKey(pid), pid: pid) + : const SizedBox(), + ), + ), + ), + ), + ); + await windowManager.waitUntilReadyToShow( + const WindowOptions(size: Size(1280, 820), title: 'ADS Embedded Smoke'), + () async { + await windowManager.show(); + }, + ); + Future> state() async => Map.from( + await EmbeddedScreen.channel.invokeMethod>( + 'state', + {'pid': pid}, + ) ?? + {}, + ); + for (var i = 0; i < 60; i++) { + await Future.delayed(const Duration(milliseconds: 500)); + if ((await state())['visible'] == true) { + break; + } + } + report['initial'] = await state(); + if (report['initial']['embedded'] != true || + report['initial']['visible'] != true) { + throw StateError('Embedding failed: $report'); + } + await windowManager.setSize(const Size(1080, 720)); + await Future.delayed(const Duration(seconds: 2)); + report['resized'] = await state(); + if (report['resized']['width'] == report['initial']['width']) { + throw StateError('Resize did not reach child'); + } + show.value = false; + await Future.delayed(const Duration(seconds: 1)); + report['pageHidden'] = await state(); + if (report['pageHidden']['visible'] != false) { + throw StateError('Page hide failed'); + } + show.value = true; + await Future.delayed(const Duration(seconds: 1)); + await windowManager.hide(); + await Future.delayed(const Duration(seconds: 1)); + report['trayHidden'] = await state(); + if (report['trayHidden']['visible'] != false) { + throw StateError('Host hide failed'); + } + final duplicate = await Process.start(Platform.resolvedExecutable, []); + final duplicateExit = await duplicate.exitCode.timeout( + const Duration(seconds: 10), + ); + if (duplicateExit != 0) { + throw StateError('Duplicate instance failed to exit'); + } + await Future.delayed(const Duration(seconds: 1)); + report['duplicateExited'] = duplicateExit; + if (!await windowManager.isVisible()) { + throw StateError('Duplicate did not restore existing tray window'); + } + report['restored'] = await state(); + if (report['restored']['visible'] != true) { + throw StateError('Restore failed'); + } + await EmbeddedScreen.channel.invokeMethod('release', {'pid': pid}); + report['released'] = await state(); + if (report['released']['embedded'] != false) { + throw StateError('Release failed'); + } + if (usbSession != null) { + final tunnelPid = usbSession.process.pid; + final bridgePid = usbSession.usb!.bridge!.pid; + await repo.screen(usbSession, embedded: false); + var standaloneVisible = false; + for (var i = 0; i < 30; i++) { + await Future.delayed(const Duration(milliseconds: 500)); + final child = usbSession.screen; + if (child == null) { + throw StateError('Standalone scrcpy exited'); + } + standaloneVisible = + await EmbeddedScreen.channel.invokeMethod( + 'standaloneVisible', + {'pid': child.pid}, + ) ?? + false; + if (standaloneVisible) { + break; + } + } + if (!standaloneVisible) { + throw StateError('Standalone window did not appear'); + } + report['standaloneVisible'] = true; + if (usbSession.screenEmbedded || usbSession.screen?.pid == pid) { + throw StateError('Standalone mode did not restart scrcpy'); + } + if (usbSession.process.pid != tunnelPid || + usbSession.usb!.bridge!.pid != bridgePid) { + throw StateError('Screen switch changed device connection'); + } + final state = await repo.run(usbSession.adb, [ + '-s', + usbSession.endpoint, + 'get-state', + ]); + if (state.trim() != 'device') { + throw StateError('USB connection lost during screen switch'); + } + report['standalonePreservesUsb'] = true; + } + report['passed'] = true; + } catch (e, stack) { + report['passed'] = false; + report['error'] = '$e'; + stderr.writeln('$e\n$stack'); + } finally { + await repo.stop(screen); + await repo.shutdown(); + final root = repo.root?.path ?? Directory.current.parent.path; + await File('$root/work/flutter-embed-smoke.json') + .writeAsString(const JsonEncoder.withIndent(' ').convert(report)); + stdout.writeln(jsonEncode(report)); + await windowManager.destroy(); + exit(report['passed'] == true ? 0 : 1); + } +} diff --git a/flutter_manager/test/windows_usb_test.dart b/flutter_manager/test/windows_usb_test.dart new file mode 100644 index 0000000..8c41b39 --- /dev/null +++ b/flutter_manager/test/windows_usb_test.dart @@ -0,0 +1,105 @@ +import 'dart:io'; + +import 'package:material_ui/material_ui.dart'; +import 'package:ads_manager/ui/manager_model.dart'; +import 'package:ads_manager/ui/manager_view.dart'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:ads_manager/data/windows_usb.dart'; +import 'package:ads_manager/data/manager_repository.dart'; + +void main() { + testWidgets('enabling USB without driver prompts before installation', ( + tester, + ) async { + tester.view.physicalSize = const Size(1280, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final model = ManagerModel(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SettingsView(model: model, driverInstalled: () async => false), + ), + ), + ); + final toggle = find.widgetWithText(SwitchListTile, '挂载为 USB 设备 · Windows'); + await tester.ensureVisible(toggle); + await tester.tap(toggle); + await tester.pumpAndSettle(); + expect(find.text('需要安装 USBip 驱动'), findsOneWidget); + expect(find.text('安装驱动'), findsOneWidget); + await tester.tap(find.text('暂不安装')); + await tester.pumpAndSettle(); + expect(tester.widget(toggle).value, false); + expect(model.repository.settings.usbMode, false); + await tester.pumpWidget(const SizedBox()); + model.dispose(); + }); + test( + 'USB defaults off, persists explicitly and maps stable ASCII serials', + () { + final settings = Settings(); + expect(settings.usbMode, false); + settings.usbMode = true; + settings.usbip = 'C:/USBip/usbip.exe'; + final restored = Settings()..load(settings.toJson()); + expect(restored.usbMode, true); + expect(restored.usbip, settings.usbip); + expect(WindowsUsbSession.serialFor('home-phone'), 'ADS-home-phone'); + final serial = WindowsUsbSession.serialFor('a' * 128); + expect(serial.length, 28); + expect(serial, WindowsUsbSession.serialFor('a' * 128)); + expect(RegExp(r'^ADS-[A-F0-9]{24}$').hasMatch(serial), true); + }, + ); + test('missing driver is reported without installing anything', () async { + final installed = await UsbDriver.installed((exe, args) async { + expect(exe, 'sc.exe'); + expect(args, ['query', 'usbip2_ude']); + throw const ProcessException('sc.exe', [], 'missing', 1060); + }); + expect(installed, false); + }); + test( + 'USB and tunnel ports avoid each other and external listeners', + () async { + final listener = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final repo = ManagerRepository((_) {}); + try { + final a = await repo.allocatePort(listener.port, listener.port + 4); + final b = await repo.allocatePort(listener.port, listener.port + 4); + expect(a, isNot(listener.port)); + expect(b, isNot(a)); + expect(b, isNot(listener.port)); + } finally { + await listener.close(); + } + }, + ); + test('USB lease timeout does not start a bridge or attach', () async { + final usb = WindowsUsbSession('test', 3240); + final directory = await Directory.systemTemp.createTemp('ads-usb-test'); + try { + await expectLater( + usb.start( + leaseFile: '${directory.path}/lease', + upstream: '127.0.0.1:15555', + executable: 'must-not-run.exe', + usbip: 'must-not-run.exe', + environment: {}, + run: (exe, args) async => + throw StateError('Must not attach before lease'), + watch: (process, label) => fail('Must not start before lease'), + cancelled: () => false, + leaseTimeout: Duration.zero, + ), + throwsStateError, + ); + expect(usb.bridge, isNull); + } finally { + await directory.delete(); + } + }); +} diff --git a/flutter_manager/windows/runner/CMakeLists.txt b/flutter_manager/windows/runner/CMakeLists.txt index 394917c..7c09a77 100644 --- a/flutter_manager/windows/runner/CMakeLists.txt +++ b/flutter_manager/windows/runner/CMakeLists.txt @@ -8,6 +8,7 @@ project(runner LANGUAGES CXX) # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" + "scrcpy_host.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" diff --git a/flutter_manager/windows/runner/desktop_instance.h b/flutter_manager/windows/runner/desktop_instance.h new file mode 100644 index 0000000..ac39e7b --- /dev/null +++ b/flutter_manager/windows/runner/desktop_instance.h @@ -0,0 +1,40 @@ +#ifndef RUNNER_DESKTOP_INSTANCE_H_ +#define RUNNER_DESKTOP_INSTANCE_H_ +#include + +// Shared with the Avalonia entry point, across installed/portable copies in +// the same interactive Windows session. +class DesktopInstance { + public: + DesktopInstance() { + event_ = CreateEventW(nullptr, FALSE, FALSE, L"Local\\TTSTD.ADS.Desktop.Activate"); + mutex_ = CreateMutexW(nullptr, TRUE, L"Local\\TTSTD.ADS.Desktop.Instance"); + primary_ = mutex_ && GetLastError() != ERROR_ALREADY_EXISTS; + } + ~DesktopInstance() { + if (wait_) UnregisterWaitEx(wait_, INVALID_HANDLE_VALUE); + if (primary_) ReleaseMutex(mutex_); + if (mutex_) CloseHandle(mutex_); + if (event_) CloseHandle(event_); + } + bool valid() const { return event_ && mutex_; } + bool primary() const { return primary_; } + void Activate() { + AllowSetForegroundWindow(ASFW_ANY); + SetEvent(event_); + } + bool Listen(HWND window) { + return RegisterWaitForSingleObject(&wait_, event_, Wake, + reinterpret_cast(window), INFINITE, WT_EXECUTEDEFAULT) != FALSE; + } + static UINT ActivationMessage() { + return RegisterWindowMessageW(L"TTSTD.ADS.Desktop.Activate"); + } + private: + static void CALLBACK Wake(void* context, BOOLEAN) { + PostMessageW(reinterpret_cast(context), ActivationMessage(), 0, 0); + } + HANDLE event_ = nullptr, mutex_ = nullptr, wait_ = nullptr; + bool primary_ = false; +}; +#endif diff --git a/flutter_manager/windows/runner/flutter_window.cpp b/flutter_manager/windows/runner/flutter_window.cpp index 955ee30..46c28b5 100644 --- a/flutter_manager/windows/runner/flutter_window.cpp +++ b/flutter_manager/windows/runner/flutter_window.cpp @@ -1,4 +1,5 @@ #include "flutter_window.h" +#include "desktop_instance.h" #include @@ -26,6 +27,7 @@ bool FlutterWindow::OnCreate() { } RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); + scrcpy_host_ = std::make_unique(flutter_controller_->engine()->messenger(), flutter_controller_->view()->GetNativeWindow()); flutter_controller_->engine()->SetNextFrameCallback([&]() { this->Show(); @@ -40,6 +42,7 @@ bool FlutterWindow::OnCreate() { } void FlutterWindow::OnDestroy() { + scrcpy_host_.reset(); if (flutter_controller_) { flutter_controller_ = nullptr; } @@ -51,6 +54,11 @@ LRESULT FlutterWindow::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { + if (message == DesktopInstance::ActivationMessage()) { + ShowWindow(hwnd, IsIconic(hwnd) ? SW_RESTORE : SW_SHOW); + SetForegroundWindow(hwnd); + return 0; + } // Give Flutter, including plugins, an opportunity to handle window messages. if (flutter_controller_) { std::optional result = diff --git a/flutter_manager/windows/runner/flutter_window.h b/flutter_manager/windows/runner/flutter_window.h index 6da0652..cc7ae82 100644 --- a/flutter_manager/windows/runner/flutter_window.h +++ b/flutter_manager/windows/runner/flutter_window.h @@ -7,6 +7,7 @@ #include #include "win32_window.h" +#include "scrcpy_host.h" // A window that does nothing but host a Flutter view. class FlutterWindow : public Win32Window { @@ -23,6 +24,7 @@ class FlutterWindow : public Win32Window { LPARAM const lparam) noexcept override; private: + std::unique_ptr scrcpy_host_; // The project to run. flutter::DartProject project_; diff --git a/flutter_manager/windows/runner/main.cpp b/flutter_manager/windows/runner/main.cpp index 902718c..8835032 100644 --- a/flutter_manager/windows/runner/main.cpp +++ b/flutter_manager/windows/runner/main.cpp @@ -4,9 +4,16 @@ #include "flutter_window.h" #include "utils.h" +#include "desktop_instance.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) { + DesktopInstance desktop_instance; + if (!desktop_instance.valid()) return EXIT_FAILURE; + if (!desktop_instance.primary()) { + desktop_instance.Activate(); + return EXIT_SUCCESS; + } // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { @@ -30,6 +37,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, if (!window.Create(L"ads_manager", origin, size)) { return EXIT_FAILURE; } + if (!desktop_instance.Listen(window.GetHandle())) return EXIT_FAILURE; window.SetQuitOnClose(true); ::MSG msg; diff --git a/flutter_manager/windows/runner/scrcpy_host.cpp b/flutter_manager/windows/runner/scrcpy_host.cpp new file mode 100644 index 0000000..e68a75c --- /dev/null +++ b/flutter_manager/windows/runner/scrcpy_host.cpp @@ -0,0 +1,170 @@ +#include "scrcpy_host.h" +#include +#include +#include + +namespace { +using flutter::EncodableMap; +using flutter::EncodableValue; +int64_t Number(const EncodableMap& map, const char* key) { + const auto it = map.find(EncodableValue(key)); + if (it == map.end()) return 0; + if (const auto* n = std::get_if(&it->second)) return *n; + if (const auto* n = std::get_if(&it->second)) return *n; + if (const auto* n = std::get_if(&it->second)) return static_cast(std::lround(*n)); + return 0; +} +struct Search { DWORD pid; HWND found = nullptr; }; +BOOL CALLBACK FindWindowForProcess(HWND window, LPARAM data) { + auto* search = reinterpret_cast(data); + DWORD pid = 0; + GetWindowThreadProcessId(window, &pid); + if (pid != search->pid || !IsWindowVisible(window)) return TRUE; + wchar_t title[256] = {}; + GetWindowTextW(window, title, 256); + if (std::wstring(title).find(L"ADS Flutter") != 0) return TRUE; + search->found = window; + return FALSE; +} +} +ScrcpyHost::ScrcpyHost(flutter::BinaryMessenger* messenger, HWND parent) + : parent_(parent) { + SetWindowLongPtr(parent_, GWL_STYLE, GetWindowLongPtr(parent_, GWL_STYLE) | WS_CLIPCHILDREN); + channel_ = std::make_unique>( + messenger, "ads/scrcpy_host", &flutter::StandardMethodCodec::GetInstance()); + channel_->SetMethodCallHandler([this](const auto& call, auto result) { + Handle(call, std::move(result)); + }); +} +ScrcpyHost::~ScrcpyHost() { + channel_->SetMethodCallHandler(nullptr); + // Dart normally stops owned processes first. Never leave an embedded orphan + // visible if the native host is destroyed unexpectedly. + while (!windows_.empty()) { + const auto pid = windows_.begin()->first; + const auto window = windows_.begin()->second.window; + Release(pid); + if (IsWindow(window)) PostMessage(window, WM_CLOSE, 0, 0); + } +} +void ScrcpyHost::Release(DWORD pid) { + auto it = windows_.find(pid); + if (it == windows_.end()) return; + const auto entry = it->second; + DWORD actual = 0; + GetWindowThreadProcessId(entry.window, &actual); + if (IsWindow(entry.window) && actual == pid) { + ShowWindow(entry.window, SW_HIDE); + SetParent(entry.window, nullptr); + SetWindowLongPtr(entry.window, GWL_STYLE, entry.style); + SetWindowLongPtr(entry.window, GWL_EXSTYLE, entry.extended); + SetWindowPos(entry.window, nullptr, entry.rect.left, entry.rect.top, + entry.rect.right-entry.rect.left, entry.rect.bottom-entry.rect.top, + SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_ASYNCWINDOWPOS); + } + windows_.erase(it); +} +void ScrcpyHost::Handle(const flutter::MethodCall& call, + std::unique_ptr> result) { + const auto* args = call.arguments() ? std::get_if(call.arguments()) : nullptr; + if (!args) { result->Error("arguments", "Expected a map"); return; } + // HWNDs may be recycled after a process exits. Validate ownership before + // every operation, including hiding sessions on pages that are no longer open. + for (auto it = windows_.begin(); it != windows_.end();) { + DWORD actual = 0; + GetWindowThreadProcessId(it->second.window, &actual); + if (!IsWindow(it->second.window) || actual != it->first) it = windows_.erase(it); + else ++it; + } + const auto pid = static_cast(Number(*args, "pid")); + if (call.method_name() == "attach") { + if (!windows_.count(pid)) { + Search search{pid}; + EnumWindows(FindWindowForProcess, reinterpret_cast(&search)); + if (!search.found) { result->Success(EncodableValue(false)); return; } + Entry entry{search.found, GetWindowLongPtr(search.found, GWL_STYLE), + GetWindowLongPtr(search.found, GWL_EXSTYLE), {}}; + GetWindowRect(search.found, &entry.rect); + ShowWindow(search.found, SW_HIDE); + SetWindowLongPtr(search.found, GWL_STYLE, + (entry.style & ~(WS_POPUP | WS_CAPTION | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU)) + | WS_CHILD | WS_CLIPSIBLINGS); + SetWindowLongPtr(search.found, GWL_EXSTYLE, + (entry.extended & ~WS_EX_APPWINDOW) | WS_EX_TOOLWINDOW); + SetLastError(0); + const auto previous = SetParent(search.found, parent_); + if (!previous && GetLastError() != 0) { + const auto error = GetLastError(); + SetWindowLongPtr(search.found, GWL_STYLE, entry.style); + SetWindowLongPtr(search.found, GWL_EXSTYLE, entry.extended); + ShowWindow(search.found, SW_SHOWNOACTIVATE); + result->Error("set_parent", "Windows embedding failed: " + std::to_string(error)); + return; + } + windows_.emplace(pid, entry); + } + result->Success(EncodableValue(true)); return; + } + if (call.method_name() == "release") { + Release(pid); result->Success(); return; + } + if (call.method_name() == "hide") { + auto it = windows_.find(pid); + if (it != windows_.end()) ShowWindow(it->second.window, SW_HIDE); + result->Success(); return; + } + if (call.method_name() == "layout") { + auto it = windows_.find(pid); + DWORD actual = 0; + if (it != windows_.end()) GetWindowThreadProcessId(it->second.window, &actual); + if (it == windows_.end() || !IsWindow(it->second.window) || actual != pid) { + windows_.erase(pid); result->Error("window_closed", "scrcpy window closed"); return; + } + RECT client{}; + GetClientRect(parent_, &client); + const int x = static_cast(Number(*args, "x")); + const int y = static_cast(Number(*args, "y")); + const int width = static_cast(Number(*args, "width")); + const int height = static_cast(Number(*args, "height")); + // Hide stale geometry while Flutter catches up to a resize/DPI change. + if (x < 0 || y < 0 || width <= 0 || height <= 0 || + x + width > client.right + 1 || y + height > client.bottom + 1) { + ShowWindow(it->second.window, SW_HIDE); result->Success(); return; + } + for (const auto& pair : windows_) { + if (pair.first != pid) ShowWindow(pair.second.window, SW_HIDE); + } + RECT previous{}; + GetWindowRect(it->second.window, &previous); + MapWindowPoints(HWND_DESKTOP, parent_, reinterpret_cast(&previous), 2); + if (previous.left == x && previous.top == y && + previous.right - previous.left == width && + previous.bottom - previous.top == height && + IsWindowVisible(it->second.window)) { + result->Success(); return; + } + SetWindowPos(it->second.window, HWND_TOP, x, y, width, height, + SWP_NOACTIVATE | SWP_FRAMECHANGED | SWP_SHOWWINDOW | SWP_ASYNCWINDOWPOS); + result->Success(); return; + } + if (call.method_name() == "standaloneVisible") { + Search search{pid}; + EnumWindows(FindWindowForProcess, reinterpret_cast(&search)); + result->Success(EncodableValue(search.found != nullptr)); + return; + } + if (call.method_name() == "state") { + auto it = windows_.find(pid); +RECT rect{}; + const bool exists = it != windows_.end() && IsWindow(it->second.window); + if (exists) GetWindowRect(it->second.window, &rect); + result->Success(EncodableValue(EncodableMap{ + {EncodableValue("embedded"), EncodableValue(exists && GetParent(it->second.window) == parent_)}, + {EncodableValue("visible"), EncodableValue(exists && IsWindowVisible(it->second.window) != FALSE)}, + {EncodableValue("width"), EncodableValue(static_cast(rect.right-rect.left))}, + {EncodableValue("height"), EncodableValue(static_cast(rect.bottom-rect.top))} + })); + return; + } + result->NotImplemented(); +} diff --git a/flutter_manager/windows/runner/scrcpy_host.h b/flutter_manager/windows/runner/scrcpy_host.h new file mode 100644 index 0000000..958d03e --- /dev/null +++ b/flutter_manager/windows/runner/scrcpy_host.h @@ -0,0 +1,27 @@ +#ifndef RUNNER_SCRCPY_HOST_H_ +#define RUNNER_SCRCPY_HOST_H_ +#include +#include +#include +#include +#include + +class ScrcpyHost { + public: + ScrcpyHost(flutter::BinaryMessenger* messenger, HWND parent); + ~ScrcpyHost(); + private: + struct Entry { + HWND window; + LONG_PTR style; + LONG_PTR extended; + RECT rect; + }; + HWND parent_; + std::map windows_; + std::unique_ptr> channel_; + void Release(DWORD pid); + void Handle(const flutter::MethodCall& call, + std::unique_ptr> result); +}; +#endif diff --git a/scripts/build-flutter.ps1 b/scripts/build-flutter.ps1 index faf774d..b9dc55d 100644 --- a/scripts/build-flutter.ps1 +++ b/scripts/build-flutter.ps1 @@ -3,12 +3,12 @@ $projectRoot = Split-Path $PSScriptRoot -Parent $output = Join-Path $projectRoot 'bin/flutter-win-x64' Push-Location (Join-Path $projectRoot 'flutter_manager') try { - flutter build windows --release + flutter build windows --release -t lib/main.dart if ($LASTEXITCODE -ne 0) { throw 'Flutter publish failed' } } finally { Pop-Location } New-Item -ItemType Directory -Force -Path $output | Out-Null Copy-Item -Path (Join-Path $projectRoot 'flutter_manager/build/windows/x64/runner/Release/*') -Destination $output -Recurse -Force -foreach ($name in @('ads-client','ads-agent','adsctl')) { +foreach ($name in @('ads-client','ads-agent','adsctl','ads-usb')) { $tool = Join-Path $projectRoot "bin/$name.exe" if (-not (Test-Path -LiteralPath $tool)) { throw "先运行 scripts/build.ps1:缺少 $name" } Copy-Item -LiteralPath $tool -Destination $output -Force @@ -16,5 +16,6 @@ foreach ($name in @('ads-client','ads-agent','adsctl')) { $tools = Join-Path $output 'tools/scrcpy' New-Item -ItemType Directory -Force -Path $tools | Out-Null Copy-Item -Path (Join-Path $projectRoot 'bin/tools/scrcpy/*') -Destination $tools -Recurse -Force +& (Join-Path $PSScriptRoot 'copy-windows-usb-driver.ps1') -Destination $output # Private credentials are deliberately excluded from distributable artifacts. Write-Host "Flutter published to $output (credentials excluded)" diff --git a/scripts/build-installers.ps1 b/scripts/build-installers.ps1 index 7ff0782..2d4ca40 100644 --- a/scripts/build-installers.ps1 +++ b/scripts/build-installers.ps1 @@ -31,6 +31,8 @@ foreach ($name in @('Avalonia','Flutter')) { if (-not (Test-Path -LiteralPath (Join-Path $source $runtime))) { throw "Missing redistributable C++ runtime: $runtime" } } } + & (Join-Path $PSScriptRoot 'copy-windows-usb-driver.ps1') -Destination $source + if (-not (Test-Path -LiteralPath (Join-Path $source 'ads-usb.exe'))) { Copy-Item -LiteralPath (Join-Path $root 'bin/ads-usb.exe') -Destination $source } foreach ($file in @($exe,'adsctl.exe','ads-agent.exe','ads-client.exe','tools/scrcpy/adb.exe','tools/scrcpy/scrcpy.exe')) { if (-not (Test-Path -LiteralPath (Join-Path $source $file))) { throw "Missing payload: $folder/$file" } } diff --git a/scripts/copy-windows-usb-driver.ps1 b/scripts/copy-windows-usb-driver.ps1 new file mode 100644 index 0000000..fe9b6b2 --- /dev/null +++ b/scripts/copy-windows-usb-driver.ps1 @@ -0,0 +1,17 @@ +param([Parameter(Mandatory)][string]$Destination) +$ErrorActionPreference = 'Stop' +$root = Split-Path $PSScriptRoot -Parent +# Reuse the pinned upstream SHA-256 and publisher signature checks. This does +# not install the driver and never requests elevation during packaging. +& (Join-Path $PSScriptRoot 'install-windows-usb.ps1') +if (-not $?) { throw 'USBip installer verification failed' } +$drivers = Join-Path $Destination 'drivers' +New-Item -ItemType Directory -Path $drivers -Force | Out-Null +Copy-Item -LiteralPath (Join-Path $root 'work/USBip-0.9.8.1-x64.exe') -Destination $drivers -Force +@( + 'USBip 0.9.8.1 x64, upstream usbip-win2 by Cloudyne Systems (Scheibling Consulting AB).', + 'Source: https://github.com/vadimgrn/usbip-win2/releases/tag/v.0.9.8.1', + 'This is an unmodified, signed optional installer. It is not installed by the ADS installer.', + 'Select USB mode in ADS, then confirm driver installation and the Windows UAC prompt.', + 'Driver installation can briefly restart USB hubs and may require a Windows reboot.' +) | Set-Content -LiteralPath (Join-Path $drivers 'README.txt') -Encoding utf8