diff --git a/EmulatorCli.cs b/EmulatorCli.cs index ee3076d..294d564 100644 --- a/EmulatorCli.cs +++ b/EmulatorCli.cs @@ -3,7 +3,7 @@ using System.Text.Json; internal sealed record EmulatorInstance( string Name, string Type, string Version, string ApiVersion, - string Resolution, string ScreenSize, string InstancePath, bool IsRunning) + string Resolution, string ScreenSize, string InstancePath, string HdcPort, bool IsRunning) { public string Running => IsRunning ? "运行中" : "已停止"; public override string ToString() => $"{Name} | {Type} | {Version} | {Running}"; @@ -41,6 +41,42 @@ internal static class EmulatorCli .FirstOrDefault(path => Path.IsPathFullyQualified(path) && File.Exists(path)) ?? name; } + internal static void StartDetached(string executable, string[] args, Action log) + { + var launchLog = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "emulator-manager-launch.log"); + log($"› Emulator {string.Join(" ", args.Select(arg => JsonSerializer.Serialize(arg)))}(独立进程)"); + + if (OperatingSystem.IsWindows()) + { + var info = new ProcessStartInfo(executable) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = false, + RedirectStandardError = false + }; + foreach (var argument in args) + info.ArgumentList.Add(argument); + using var _ = Process.Start(info); + return; + } + + var command = string.Join(" ", args.Select(Quote)); + var shell = $"setsid {Quote(executable)} {command} >> {Quote(launchLog)} 2>&1 < /dev/null &"; + using var shellProcess = Process.Start(new ProcessStartInfo("/bin/sh") + { + UseShellExecute = false, + CreateNoWindow = true, + ArgumentList = { "-c", shell } + }) ?? throw new InvalidOperationException("无法启动独立进程。"); + shellProcess.WaitForExit(); + log($"模拟器输出写入 {launchLog}"); + } + + private static string Quote(string value) => + "'" + value.Replace("'", "'\\''", StringComparison.Ordinal) + "'"; + internal static async Task RunAsync( string executable, string[] args, Action log, CancellationToken cancellation) { @@ -98,7 +134,8 @@ internal static class EmulatorCli internal static EmulatorInstance[] Instances(string output) => Parse(output, row => new EmulatorInstance( Field(row, "name"), Field(row, "deviceType"), Field(row, "os.osVersion"), Field(row, "os.apiVersion"), Resolution(row), ScreenSize(row), - Field(row, "instancePath"), Field(row, "isRunning").Equals("true", StringComparison.OrdinalIgnoreCase))); + Field(row, "instancePath"), Field(row, "hw.hdc.port"), + Field(row, "isRunning").Equals("true", StringComparison.OrdinalIgnoreCase))); private static string Resolution(JsonElement row) { diff --git a/LanDebugPanel.cs b/LanDebugPanel.cs new file mode 100644 index 0000000..ada40bf --- /dev/null +++ b/LanDebugPanel.cs @@ -0,0 +1,278 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Sockets; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; + +internal sealed class LanDebugPanel +{ + private readonly Action log; + private readonly Func getInstances; + private readonly ComboBox instanceBox = new() { Width = 260 }; + private readonly TextBox port = new() { Width = 150, Text = "10178" }; + private readonly TextBox devicePort = new() { Width = 150, Text = "5555", Watermark = "模拟器 hdc 端口" }; + private readonly TextBox command = new() { IsReadOnly = true, Width = 360 }; + private readonly TextBlock hint = new() { TextWrapping = TextWrapping.Wrap }; + private static readonly string ForwardLogPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "emulator-manager-forward.log"); + private static readonly string ForwardPidPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "emulator-manager-forward.pid"); + private Process? subProcess; + + internal LanDebugPanel(Action log, Func getInstances) + { + this.log = log; + this.getInstances = getInstances; + Content = Build(); + Refresh(); + } + + internal Control Content { get; } + + internal void Refresh() + { + var items = getInstances(); + instanceBox.ItemsSource = items; + if (instanceBox.SelectedItem is not EmulatorInstance && items.Length > 0) + instanceBox.SelectedIndex = 0; + UpdatePort(); + } + + private Control Build() + { + instanceBox.SelectionChanged += (_, _) => UpdatePort(); + port.TextChanged += (_, _) => UpdateCommand(); + + var devices = new Button { Content = "查看 hdc 设备" }; + devices.Click += async (_, _) => await ShowDevices(); + var expose = new Button { Content = "暴露到局域网" }; + expose.Click += (_, _) => Expose(); + var stop = new Button { Content = "停止共享" }; + stop.Click += (_, _) => Stop(); + var copy = new Button { Content = "复制连接命令" }; + copy.Click += async (_, _) => await CopyAsync(); + + var panel = new StackPanel { Spacing = 8 }; + panel.Children.Add(new TextBlock { Text = $"本机局域网 IP:{LocalIp()}", FontSize = 13 }); + panel.Children.Add(Labelled("模拟器实例", instanceBox)); + panel.Children.Add(Labelled("对外端口", port)); + panel.Children.Add(Labelled("模拟器 hdc 端口", devicePort)); + panel.Children.Add(Row(devices, expose, stop)); + panel.Children.Add(Labelled("对端连接命令", command)); + panel.Children.Add(copy); + panel.Children.Add(hint); + return panel; + } + + private static Control Labelled(string label, Control field) + { + var panel = new StackPanel { Spacing = 4 }; + panel.Children.Add(new TextBlock { Text = label, FontSize = 12, Opacity = 0.78 }); + panel.Children.Add(field); + return panel; + } + + private static Control Row(params Control[] children) + { + var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; + foreach (var child in children) + panel.Children.Add(child); + return panel; + } + + private void UpdatePort() + { + if (instanceBox.SelectedItem is EmulatorInstance instance && + !string.IsNullOrWhiteSpace(instance.HdcPort) && instance.HdcPort != "notset") + devicePort.Text = instance.HdcPort; + UpdateCommand(); + } + + private void UpdateCommand() + { + command.Text = $"hdc tconn {LocalIp()}:{port.Text?.Trim()}"; + } + + private async Task ShowDevices() + { + try + { + var output = await RunAsync(["list", "targets", "-v"]); + log(output); + var line = output.Split('\n') + .Select(item => item.Trim()) + .FirstOrDefault(item => item.Length > 0 && !item.StartsWith('[') && !item.StartsWith('-')); + var key = line?.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(); + hint.Text = !string.IsNullOrEmpty(key) && key != "[Empty]" + ? $"检测到设备:{key}(已改用端口转发暴露)" + : "未识别到在线设备,请查看命令输出。"; + } + catch (Exception error) + { + hint.Text = error.Message; + log(error.Message); + } + } + + private void Expose() + { + if ((subProcess is not null && !subProcess.HasExited) || ForwardRunning()) + { + hint.Text = "已有共享进程,请先停止共享。"; + return; + } + if (!int.TryParse(port.Text?.Trim(), out var listenPort) || listenPort is < 1 or > 65535 || + !int.TryParse(devicePort.Text?.Trim(), out var targetPort) || targetPort is < 1 or > 65535) + { + hint.Text = "请填写有效的对外端口和模拟器 hdc 端口。"; + return; + } + + var listen = $"TCP-LISTEN:{listenPort},fork,reuseaddr,bind=0.0.0.0"; + var target = $"TCP:127.0.0.1:{targetPort}"; + if (OperatingSystem.IsWindows()) + { + var info = new ProcessStartInfo(SocatPath()) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = false, + RedirectStandardError = false + }; + info.ArgumentList.Add(listen); + info.ArgumentList.Add(target); + subProcess = Process.Start(info) ?? throw new InvalidOperationException("无法启动 socat。"); + } + else + { + var shell = $"setsid {Quote(SocatPath())} {Quote(listen)} {Quote(target)} " + + $">> {Quote(ForwardLogPath)} 2>&1 < /dev/null & echo $! > {Quote(ForwardPidPath)}"; + using var shellProcess = Process.Start(new ProcessStartInfo("/bin/sh") + { + UseShellExecute = false, + CreateNoWindow = true, + ArgumentList = { "-c", shell } + }) ?? throw new InvalidOperationException("无法启动端口转发。"); + shellProcess.WaitForExit(); + } + UpdateCommand(); + hint.Text = $"已启动端口转发:对端执行 {command.Text}"; + log($"› socat {listen} {target}(独立进程)"); + } + + private void Stop() + { + if (subProcess is not null) + { + try + { + if (!subProcess.HasExited) + subProcess.Kill(entireProcessTree: true); + } + catch (Exception error) + { + hint.Text = error.Message; + } + subProcess = null; + } + if (File.Exists(ForwardPidPath)) + { + try + { + var pid = int.Parse(File.ReadAllText(ForwardPidPath).Trim()); + Process.GetProcessById(pid).Kill(entireProcessTree: true); + } + catch + { + } + File.Delete(ForwardPidPath); + } + hint.Text = "已停止共享。"; + } + + private async Task CopyAsync() + { + UpdateCommand(); + var clipboard = TopLevel.GetTopLevel(Content)?.Clipboard; + if (clipboard is null) + { + hint.Text = "剪贴板不可用,请手动复制命令。"; + return; + } + await clipboard.SetTextAsync(command.Text ?? ""); + hint.Text = "已复制连接命令。"; + } + + private static async Task RunAsync(string[] args) + { + var info = new ProcessStartInfo(HdcPath()) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; + foreach (var arg in args) + info.ArgumentList.Add(arg); + using var process = Process.Start(info) ?? throw new InvalidOperationException("无法启动 hdc。"); + var stdout = await process.StandardOutput.ReadToEndAsync(); + var stderr = await process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync(); + return string.IsNullOrWhiteSpace(stderr) ? stdout : stdout + "\n" + stderr; + } + + private static string LocalIp() + { + try + { + var address = Dns.GetHostAddresses(Dns.GetHostName()) + .FirstOrDefault(item => item.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(item)); + return address?.ToString() ?? "未检测到"; + } + catch + { + return "未检测到"; + } + } + + private static bool ForwardRunning() + { + if (!File.Exists(ForwardPidPath)) + return false; + try + { + _ = Process.GetProcessById(int.Parse(File.ReadAllText(ForwardPidPath).Trim())); + return true; + } + catch + { + File.Delete(ForwardPidPath); + return false; + } + } + + private static string Quote(string value) => + "'" + value.Replace("'", "'\\''", StringComparison.Ordinal) + "'"; + + private static string SocatPath() => + Environment.GetEnvironmentVariable("SOCAT_PATH") is { Length: > 0 } path ? path : "socat"; + + private static string HdcPath() + { + var configured = Environment.GetEnvironmentVariable("HARMONY_HDC"); + if (!string.IsNullOrWhiteSpace(configured)) + return configured; + var name = OperatingSystem.IsWindows() ? "hdc.exe" : "hdc"; + var directory = Path.GetDirectoryName(EmulatorCli.DefaultPath()); + while (!string.IsNullOrEmpty(directory)) + { + var candidate = Path.Combine(directory, "sdk", "default", "openharmony", "toolchains", name); + if (File.Exists(candidate)) + return candidate; + directory = Path.GetDirectoryName(directory); + } + return name; + } +} diff --git a/MainWindow.cs b/MainWindow.cs index 7f67abc..22b56d3 100644 --- a/MainWindow.cs +++ b/MainWindow.cs @@ -30,9 +30,25 @@ internal sealed class MainWindow : Window private Window? settingsWindow; private Window? outputWindow; private Window? newEmulatorWindow; + private LanDebugPanel? lanDebug; private DispatcherTimer? statusTimer; private bool shuttingDown; private CancellationTokenSource? active; + private static readonly string LogPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "emulator-manager.log"); + + private static void WriteLogFile(string line) + { + try + { + if (File.Exists(LogPath) && new FileInfo(LogPath).Length > 5 * 1024 * 1024) + File.Move(LogPath, LogPath + ".1", true); + File.AppendAllText(LogPath, $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {line}{Environment.NewLine}"); + } + catch + { + } + } internal MainWindow(bool smoke, Action shutdown) { @@ -150,6 +166,7 @@ internal sealed class MainWindow : Window { allInstances = await ReadList(token, EmulatorCli.Instances, "-list", "-details"); ApplyCategoryFilter(); + lanDebug?.Refresh(); AppendOutput($"已读取 {allInstances.Length} 个模拟器实例。"); } @@ -166,6 +183,7 @@ internal sealed class MainWindow : Window return; allInstances = items; ApplyCategoryFilter(); + lanDebug?.Refresh(); } catch { @@ -201,23 +219,16 @@ internal sealed class MainWindow : Window if (!starting.Add((path, target))) throw new InvalidOperationException($"「{target}」已有启动进程。"); string[] args = ["-start", target, .. extra]; - AppendOutput($"正在启动「{target}」。可刷新列表查看状态,也可直接停止实例。"); - _ = ObserveStart(path, target, args); - } - - private async Task ObserveStart(string path, string target, string[] args) - { try { - await EmulatorCli.RunAsync(path, args, AppendOutput, CancellationToken.None); + EmulatorCli.StartDetached(path, args, AppendOutput); + AppendOutput($"「{target}」已独立启动,可刷新列表查看状态,也可直接停止实例。"); + _ = Task.Delay(TimeSpan.FromSeconds(5)).ContinueWith(_ => starting.Remove((path, target))); } catch (Exception error) - { - AppendOutput($"「{target}」启动失败:{error.Message}"); - } - finally { starting.Remove((path, target)); + throw new InvalidOperationException($"「{target}」启动失败:{error.Message}", error); } } @@ -230,7 +241,7 @@ internal sealed class MainWindow : Window } else { - StartInstance(instance.Name, []); + StartInstance(instance.Name, ["-bootMode", "snapshot"]); } } @@ -291,6 +302,7 @@ internal sealed class MainWindow : Window private void AppendOutput(string line) => Dispatcher.UIThread.Post(() => { + WriteLogFile(line); if (output.ItemCount >= 1500) output.Items.RemoveAt(0); output.Items.Add(line); @@ -401,6 +413,27 @@ internal sealed class MainWindow : Window await Run(token, "-license", "accept"); } }))); + lanDebug ??= new LanDebugPanel(AppendOutput, () => allInstances); + settings.Children.Add(Caption("局域网调试")); + settings.Children.Add(lanDebug.Content); + settings.Children.Add(Caption("日志")); + settings.Children.Add(new TextBlock + { + Text = LogPath, FontSize = 12, Opacity = 0.78, TextWrapping = TextWrapping.Wrap + }); + var openLog = new Button { Content = "打开日志文件" }; + openLog.Click += (_, _) => + { + try + { + Process.Start(new ProcessStartInfo(LogPath) { UseShellExecute = true }); + } + catch (Exception error) + { + AppendOutput(error.Message); + } + }; + settings.Children.Add(openLog); var content = new Border { Margin = new Thickness(16), diff --git a/README.md b/README.md index 91e64f6..3e1b65f 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,9 @@ dotnet run --project EmulatorManager.csproj 可在「工具设置」中编辑 Emulator 路径,或预先设置环境变量 `HARMONY_EMULATOR`。程序也会尝试 `DEVECO_CLI_CLT_PATH`、常见安装目录和 PATH。Linux 上请按华为要求配置 KVM,必要时从实例行的「更多」中选择无窗口启动。 -- **模拟器实例**支持刷新、启动、停止、删除;主页每 3 秒自动查询一次运行状态,启停按钮会随状态切换。 +- **模拟器实例**支持刷新、启动、停止、删除;行内启动使用热启动(snapshot,实例需启用快速启动);模拟器以独立进程启动,关闭本程序不会退出模拟器,其输出写入 `~/.emulator-manager-launch.log`。主页每 3 秒自动查询一次运行状态,启停按钮会随状态切换。 - **系统镜像**窗口打开时自动拉取在线全部镜像,左侧按设备分类筛选,也可查询已下载镜像。 -- 主页左下角「命令输出」按钮打开独立输出窗口;右下角「创建模拟器」打开新建向导(默认手机分类;镜像列表含名称/版本(API)/下载或删除操作,选择系统镜像 → 设备型号 → 配置名称/内存/存储,未下载镜像会自动下载),右上角「设置」打开工具设置窗口。可在工具设置中查看许可并确认接受。 +- 主页左下角「命令输出」按钮打开独立输出窗口,所有输出同时带时间戳写入 `~/.emulator-manager.log`(超过 5MB 轮转);右下角「创建模拟器」打开新建向导(默认手机分类;镜像列表含名称/版本(API)/下载或删除操作,选择系统镜像 → 设备型号 → 配置名称/内存/存储,未下载镜像会自动下载),右上角「设置」打开工具设置窗口。可在工具设置中查看许可并确认接受。「局域网调试」可查看 hdc 设备、通过 `socat` 端口转发把模拟器 hdc 端口暴露到局域网(需安装 socat,或以 `SOCAT_PATH` 指定路径);转发进程独立运行,关闭程序不会中断,并生成对端 `hdc tconn` 命令。 ## 构建、运行并同步