From 87e888af6932658f08aa61d281157201985757d7 Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Thu, 12 Nov 2026 14:42:42 +0800 Subject: [PATCH] Add initial Avalonia desktop device workbench --- .gitignore | 3 ++ README.md | 4 ++ desktop/Ads.Desktop/Ads.Desktop.csproj | 5 ++ desktop/Ads.Desktop/App.axaml | 3 ++ desktop/Ads.Desktop/App.axaml.cs | 40 ++++++++++++++++ desktop/Ads.Desktop/Assets/app.png | Bin 0 -> 200 bytes desktop/Ads.Desktop/MainViewModel.cs | 61 ++++++++++++++++++++++++ desktop/Ads.Desktop/MainWindow.axaml | 54 +++++++++++++++++++++ desktop/Ads.Desktop/MainWindow.axaml.cs | 6 +++ desktop/Ads.Desktop/Program.cs | 7 +++ desktop/README.md | 37 ++++++++++++++ desktop/global.json | 1 + 12 files changed, 221 insertions(+) create mode 100644 desktop/Ads.Desktop/Ads.Desktop.csproj create mode 100644 desktop/Ads.Desktop/App.axaml create mode 100644 desktop/Ads.Desktop/App.axaml.cs create mode 100644 desktop/Ads.Desktop/Assets/app.png create mode 100644 desktop/Ads.Desktop/MainViewModel.cs create mode 100644 desktop/Ads.Desktop/MainWindow.axaml create mode 100644 desktop/Ads.Desktop/MainWindow.axaml.cs create mode 100644 desktop/Ads.Desktop/Program.cs create mode 100644 desktop/README.md create mode 100644 desktop/global.json diff --git a/.gitignore b/.gitignore index 361ab7e..2cdfb02 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,6 @@ __pycache__/ *.log *.env /config/private/ + +/desktop/**/bin/ +/desktop/**/obj/ diff --git a/README.md b/README.md index 48fcc47..ba402ad 100644 --- a/README.md +++ b/README.md @@ -172,3 +172,7 @@ python tests/real_device.py --adb-server 192.168.5.222:5037 --serial 192.168.100 - 当前 WebSocket 关闭会结束整个 TCP 通道,不保留半关闭语义;已覆盖常规双向流量,额外工具的特殊连接语义需单独测试。 协议说明见 `docs/protocol.md`。此前的 Python 局域网桥接保留在 `adb_bridge.py`,说明在 `docs/local-bridge.md`,与新三端实现独立。 + +## 桌面客户端(Avalonia) + +设备列表、配置、连接管理、托盘、运行日志及 scrcpy 独立窗口手机控制现已放在 `desktop/`。启动和工具路径配置见 [桌面客户端说明](desktop/README.md)。 diff --git a/desktop/Ads.Desktop/Ads.Desktop.csproj b/desktop/Ads.Desktop/Ads.Desktop.csproj new file mode 100644 index 0000000..b0714aa --- /dev/null +++ b/desktop/Ads.Desktop/Ads.Desktop.csproj @@ -0,0 +1,5 @@ + + WinExenet8.0enableenable + + + diff --git a/desktop/Ads.Desktop/App.axaml b/desktop/Ads.Desktop/App.axaml new file mode 100644 index 0000000..67615d4 --- /dev/null +++ b/desktop/Ads.Desktop/App.axaml @@ -0,0 +1,3 @@ + + + diff --git a/desktop/Ads.Desktop/App.axaml.cs b/desktop/Ads.Desktop/App.axaml.cs new file mode 100644 index 0000000..6f6c3dc --- /dev/null +++ b/desktop/Ads.Desktop/App.axaml.cs @@ -0,0 +1,40 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using Avalonia.Media.Imaging; +using CommunityToolkit.Mvvm.Input; +namespace Ads.Desktop; +public partial class App : Application +{ + private bool quitting; + public override void Initialize() => AvaloniaXamlLoader.Load(this); + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + var vm = new MainViewModel(); + var window = new MainWindow { DataContext = vm }; + desktop.MainWindow = window; + desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown; + void Show() { window.Show(); window.WindowState = WindowState.Normal; window.Activate(); } + var menu = new NativeMenu(); + var show = new NativeMenuItem("打开设备工作台"); show.Click += (_, _) => Show(); menu.Items.Add(show); + var quit = new NativeMenuItem("退出并断开连接"); + quit.Click += async (_, _) => { quitting = true; await vm.ShutdownAsync(); desktop.Shutdown(); }; + menu.Items.Add(quit); + using var stream = Avalonia.Platform.AssetLoader.Open(new Uri("avares://Ads.Desktop/Assets/app.png")); + var tray = new TrayIcon { ToolTipText = "ADS · Android 设备工作台", Icon = new WindowIcon(stream), Menu = menu, Command = new RelayCommand(Show) }; + TrayIcon.SetIcons(this, new TrayIcons { tray }); + window.Closing += async (_, e) => { + if (quitting) return; + e.Cancel = true; + if (vm.MinimizeToTray) window.Hide(); + else { quitting = true; await vm.ShutdownAsync(); desktop.Shutdown(); } + }; + desktop.Exit += (_, _) => { tray.Dispose(); vm.Dispose(); }; + } + base.OnFrameworkInitializationCompleted(); + } +} + diff --git a/desktop/Ads.Desktop/Assets/app.png b/desktop/Ads.Desktop/Assets/app.png new file mode 100644 index 0000000000000000000000000000000000000000..3d1f7be4310068c7358dfbec3f6de327ad348d0d GIT binary patch literal 200 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1|*BCs=fdz#^NA%Cx&(BWL^R}Ea{HEjtmSN z`?>!lvI6;>1s;*b3=DjSL74G){)!Z!V63N$V@QPi+e^M&3<4sqiMI{5GOga^cYA}B zo7Z~vde2up=Z^I5V@#fVUZ2^3rA4Iw^1Zc;5lk7?>u**AwL`$|hHo)>Mbo3D8}|P@ kkaughDTDKYw{pxidcRI8Yx(eqCxDcBy85}Sb4q9e05VfP7ytkO literal 0 HcmV?d00001 diff --git a/desktop/Ads.Desktop/MainViewModel.cs b/desktop/Ads.Desktop/MainViewModel.cs new file mode 100644 index 0000000..36b4c4c --- /dev/null +++ b/desktop/Ads.Desktop/MainViewModel.cs @@ -0,0 +1,61 @@ +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Avalonia.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +namespace Ads.Desktop; +public record Device(string Id,bool Busy) { public string Description=>Busy?"在线 · 已占用":"在线 · 可连接"; } +public partial class MainViewModel:ObservableObject,IDisposable +{ + [ObservableProperty] private string server="wss://ads.ttstd.com"; + [ObservableProperty] private string token=Environment.GetEnvironmentVariable("ADS_CLIENT_TOKEN")??""; + [ObservableProperty] private string clientPath=FindClient(); + [ObservableProperty] private string adbPath="adb"; + [ObservableProperty] private string scrcpyPath="scrcpy"; + [ObservableProperty] private int port=15555; + [ObservableProperty] private int maxSize=1920; + [ObservableProperty] private int maxFps=60; + [ObservableProperty] private bool audio; + [ObservableProperty] private bool viewOnly; + [ObservableProperty] private bool minimizeToTray=true; + [ObservableProperty] private Device? selectedDevice; + [ObservableProperty] private string status="尚未连接"; + [ObservableProperty] private string activeEndpoint="请选择在线设备"; + [ObservableProperty] private string notice="填写客户端令牌,然后刷新设备。"; + [ObservableProperty] private string deviceSummary="尚未刷新"; + public ObservableCollection Devices {get;}=new(); + public ObservableCollection Logs {get;}=new(); + private Process? client,scrcpy; + private string? endpoint,activeAdb,activeId; + private bool probing,stopping; + private readonly DispatcherTimer timer; + private readonly HttpClient http=new(new HttpClientHandler{AllowAutoRedirect=false}){Timeout=TimeSpan.FromSeconds(10)}; + private static readonly string Folder=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"TTSTD","ADS"); + private static string FindClient() { var name=OperatingSystem.IsWindows()?"ads-client.exe":"ads-client"; for(var d=new DirectoryInfo(AppContext.BaseDirectory);d!=null;d=d.Parent){var p=Path.Combine(d.FullName,"bin",name);if(File.Exists(p))return p;}return name; } + public MainViewModel() { + try {var p=Path.Combine(Folder,"settings.json"); if(File.Exists(p)){var s=JsonSerializer.Deserialize(File.ReadAllText(p));if(s!=null){Server=s.Server;ClientPath=s.Client;AdbPath=s.Adb;ScrcpyPath=s.Scrcpy;Port=s.Port;MaxSize=s.Size;MaxFps=s.Fps;Audio=s.Audio;ViewOnly=s.ViewOnly;MinimizeToTray=s.Tray;}}}catch(Exception e){Log(e.Message);} + timer=new DispatcherTimer{Interval=TimeSpan.FromSeconds(3)};timer.Tick+=async(_,_)=>await ProbeAsync();timer.Start(); + } + private void Log(string s)=>Dispatcher.UIThread.Post(()=>{if(Token.Length>0)s=s.Replace(Token,"[REDACTED]");Logs.Add($"{DateTime.Now:HH:mm:ss} {s}");while(Logs.Count>1000)Logs.RemoveAt(0);}); + private async Task Guard(Func f){try{await f();}catch(Exception e){Notice=e.Message;Log(e.Message);}} + private Uri Validate(){if(!Uri.TryCreate(Server,UriKind.Absolute,out var u)||u.Scheme!="wss"||string.IsNullOrEmpty(u.Host)||u.AbsolutePath!="/"||u.Query!=""||u.Fragment!=""||u.UserInfo!="")throw new InvalidOperationException("请输入根路径 WSS 中继地址。");if(Token.Length<32)throw new InvalidOperationException("客户端令牌至少需要 32 个字符。");return u;} + [RelayCommand] private Task RefreshAsync()=>Guard(async()=>{var u=Validate();using var req=new HttpRequestMessage(HttpMethod.Get,new UriBuilder(u){Scheme="https",Path="/v1/devices"}.Uri);req.Headers.Authorization=new AuthenticationHeaderValue("Bearer",Token);using var res=await http.SendAsync(req);res.EnsureSuccessStatusCode();var rows=await res.Content.ReadFromJsonAsync()??[];var id=SelectedDevice?.Id;Devices.Clear();foreach(var d in rows.OrderBy(d=>d.Id))Devices.Add(d);SelectedDevice=Devices.FirstOrDefault(d=>d.Id==id)??Devices.FirstOrDefault();DeviceSummary=$"{Devices.Count} 台在线设备";Notice="设备列表已更新";}); + private ProcessStartInfo Info(string exe,IEnumerable args){var i=new ProcessStartInfo(exe){UseShellExecute=false,CreateNoWindow=true,RedirectStandardOutput=true,RedirectStandardError=true};foreach(var a in args)i.ArgumentList.Add(a);foreach(var k in new[]{"ADB_SERVER_SOCKET","ANDROID_ADB_SERVER_ADDRESS","ANDROID_ADB_SERVER_PORT","ADS_CLIENT_TOKEN"})i.Environment.Remove(k);i.Environment["NO_COLOR"]="1";return i;} + private Process Start(ProcessStartInfo i){var p=new Process{StartInfo=i};p.OutputDataReceived+=(_,e)=>{if(e.Data!=null)Log(e.Data);};p.ErrorDataReceived+=(_,e)=>{if(e.Data!=null)Log(e.Data);};try{p.Start();p.BeginOutputReadLine();p.BeginErrorReadLine();return p;}catch{p.Dispose();throw;}} + [RelayCommand] private Task ConnectAsync()=>Guard(async()=>{Validate();var d=SelectedDevice??throw new InvalidOperationException("请选择设备。");if(client!=null)throw new InvalidOperationException("请先断开当前连接。");if(d.Busy)throw new InvalidOperationException("设备已被其他客户端占用。");if(Port is <1024 or >65535)throw new InvalidOperationException("端口范围 1024–65535。");var ep=$"127.0.0.1:{Port}";var i=Info(ClientPath,["--server",Server,"--device",d.Id,"--listen",ep,"--adb",AdbPath]);i.Environment["ADS_CLIENT_TOKEN"]=Token;client=Start(i);endpoint=ep;activeAdb=AdbPath;activeId=d.Id;ActiveEndpoint=$"{d.Id} → {ep}";Status="连接中 · 等待租约与调试授权";await Task.CompletedTask;}); + private async Task AdbAsync(params string[] args){using var p=Process.Start(Info(activeAdb??AdbPath,args))??throw new InvalidOperationException("无法启动 ADB");var o=p.StandardOutput.ReadToEndAsync();var e=p.StandardError.ReadToEndAsync();using var c=new CancellationTokenSource(TimeSpan.FromSeconds(8));try{await p.WaitForExitAsync(c.Token);}catch{if(!p.HasExited)p.Kill(true);throw;}var text=await o;var err=await e;if(p.ExitCode!=0)throw new InvalidOperationException("ADB:"+err.Trim());return text;} + private async Task ProbeAsync(){if(probing||stopping||client==null)return;probing=true;var current=client;try{if(current.HasExited){Notice=$"守护程序退出码:{current.ExitCode}";await DisconnectAsync();return;}var text=await AdbAsync("devices");if(client!=current||stopping)return;var row=text.Split('\n').Select(l=>l.Trim().Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries)).FirstOrDefault(a=>a.Length>=2&&a[0]==endpoint);Status=row?[1] switch{"device"=>"已连接 · 可调试 / 控制","unauthorized"=>"等待手机允许 USB 调试","offline"=>"ADB 离线 · 正在恢复",_=>"连接中 · 等待设备 / 租约 / 网络恢复"};}catch(Exception e){Notice=e.Message;}finally{probing=false;}} + [RelayCommand] private Task StartScrcpyAsync()=>Guard(async()=>{if(client==null||client.HasExited||endpoint==null)throw new InvalidOperationException("请先连接设备。");if(scrcpy!=null&&!scrcpy.HasExited)throw new InvalidOperationException("控制窗口已打开。");if(MaxSize is <256 or >8192||MaxFps is <1 or >240)throw new InvalidOperationException("分辨率范围 256–8192,帧率范围 1–240。");var ep=endpoint;var state=await AdbAsync("-s",ep,"get-state");if(state.Trim()!="device"||endpoint!=ep)throw new InvalidOperationException("设备尚未就绪,请先完成手机调试授权。");var args=new List{"--serial",ep,"--force-adb-forward","--window-title",$"ADS · {activeId}","--max-size",MaxSize.ToString(),"--max-fps",MaxFps.ToString()};if(!Audio)args.Add("--no-audio");if(ViewOnly)args.Add("--no-control");scrcpy?.Dispose();var i=Info(ScrcpyPath,args);i.Environment["ADB"]=activeAdb??AdbPath;scrcpy=Start(i);Notice="手机控制已启动,详情见日志。";}); + private static async Task StopAsync(Process? p){if(p==null)return;try{if(!p.HasExited){p.Kill(true);await p.WaitForExitAsync();}}finally{p.Dispose();}} + [RelayCommand] private async Task StopScrcpyAsync(){var p=scrcpy;scrcpy=null;await StopAsync(p);} + [RelayCommand] private async Task DisconnectAsync(){if(stopping)return;stopping=true;try{await StopScrcpyAsync();var p=client;client=null;await StopAsync(p);if(endpoint!=null){try{await AdbAsync("disconnect",endpoint);}catch(Exception e){Log(e.Message);}}endpoint=null;activeAdb=null;activeId=null;Status="已断开";ActiveEndpoint="本地 ADB 通道已释放";}finally{stopping=false;}} + private record Settings(string Server,string Client,string Adb,string Scrcpy,int Port,int Size,int Fps,bool Audio,bool ViewOnly,bool Tray); + [RelayCommand] private void Save(){try{Directory.CreateDirectory(Folder);File.WriteAllText(Path.Combine(Folder,"settings.json"),JsonSerializer.Serialize(new Settings(Server,ClientPath,AdbPath,ScrcpyPath,Port,MaxSize,MaxFps,Audio,ViewOnly,MinimizeToTray),new JsonSerializerOptions{WriteIndented=true}));Notice="配置已保存,不包含令牌";}catch(Exception e){Notice=e.Message;}} + [RelayCommand] private void ClearLogs()=>Logs.Clear(); + [RelayCommand] private void ExportLogs(){try{Directory.CreateDirectory(Folder);var p=Path.Combine(Folder,$"ads-{DateTime.Now:yyyyMMdd-HHmmss}.log");File.WriteAllLines(p,Logs);Notice="日志已导出:"+p;}catch(Exception e){Notice=e.Message;}} + public async Task ShutdownAsync(){timer.Stop();await DisconnectAsync();} + public void Dispose(){timer.Stop();http.Dispose();foreach(var p in new[]{scrcpy,client}){try{if(p!=null&&!p.HasExited)p.Kill(true);}catch{}p?.Dispose();}} +} diff --git a/desktop/Ads.Desktop/MainWindow.axaml b/desktop/Ads.Desktop/MainWindow.axaml new file mode 100644 index 0000000..63863d2 --- /dev/null +++ b/desktop/Ads.Desktop/MainWindow.axaml @@ -0,0 +1,54 @@ + + + + + + + + + +