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; } }