using System.Diagnostics; using System.Text.Json; internal sealed record EmulatorInstance( string Name, string Type, string Version, string ApiVersion, string Resolution, string ScreenSize, string InstancePath, bool IsRunning) { public string Running => IsRunning ? "运行中" : "已停止"; public override string ToString() => $"{Name} | {Type} | {Version} | {Running}"; } internal sealed record EmulatorImage(string Type, string Version, string ApiVersion, string Downloaded) { public override string ToString() => $"{Type} | {Version} | {Downloaded}"; } internal sealed record EmulatorProfile(string Model, string Details) { public override string ToString() => $"{Model} | {Details.ReplaceLineEndings(" ")}"; } internal static class EmulatorCli { internal static string DefaultPath() { var name = OperatingSystem.IsWindows() ? "Emulator.exe" : "Emulator"; var configured = Environment.GetEnvironmentVariable("HARMONY_EMULATOR"); if (!string.IsNullOrWhiteSpace(configured)) return configured; var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string?[] candidates = [ Environment.GetEnvironmentVariable("DEVECO_CLI_CLT_PATH"), Path.Combine(home, "harmonyos", "command-line-tools"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Huawei", "DevEco Studio", "tools"), "/Applications/DevEco-Studio.app/Contents/tools" ]; return candidates.Where(path => !string.IsNullOrWhiteSpace(path)) .Select(path => Path.Combine(path!, "emulator", name)) .FirstOrDefault(path => Path.IsPathFullyQualified(path) && File.Exists(path)) ?? name; } internal static async Task RunAsync( string executable, string[] args, Action log, CancellationToken cancellation) { var info = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, CreateNoWindow = true }; foreach (var argument in args) info.ArgumentList.Add(argument); log($"› Emulator {string.Join(" ", args.Select(arg => JsonSerializer.Serialize(arg)))}"); using var process = Process.Start(info) ?? throw new InvalidOperationException("无法启动 Emulator。"); process.StandardInput.Close(); var capture = args[0] is "-list" or "-imageList" or "-screenProfileList"; var stdout = ReadAsync(process.StandardOutput, capture ? null : log, capture, cancellation); var stderr = ReadAsync(process.StandardError, log, false, cancellation); try { await Task.WhenAll(process.WaitForExitAsync(cancellation), stdout, stderr); } catch (OperationCanceledException) { if (!process.HasExited) process.Kill(entireProcessTree: true); await process.WaitForExitAsync(); throw; } if (process.ExitCode != 0) { if (capture) log(await stdout); throw new InvalidOperationException($"Emulator 退出码 {process.ExitCode}。请查看命令输出。"); } return await stdout; } private static async Task ReadAsync( StreamReader reader, Action? log, bool capture, CancellationToken cancellation) { var output = new System.Text.StringBuilder(); while (await reader.ReadLineAsync(cancellation) is { } line) { log?.Invoke(line); if (capture) output.AppendLine(line); } return output.ToString(); } 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))); private static string Resolution(JsonElement row) { var width = Field(row, "hw.lcd.single.width"); var height = Field(row, "hw.lcd.single.height"); return width.Length > 0 && height.Length > 0 ? $"{width}×{height}" : ""; } private static string ScreenSize(JsonElement row) { var size = Field(row, "hw.lcd.single.diagonalSize"); return size.Length > 0 ? $"{size}\"" : ""; } internal static EmulatorImage[] Images(string output) => Parse(output, row => { var version = Field(row, "osVersion"); return new EmulatorImage( Field(row, "deviceType"), version, ApiVersion(version), Field(row, "downloaded").ToLowerInvariant() switch { "true" => "已下载", "false" => "未下载", _ => "未知" }); }); private static string ApiVersion(string version) { var open = version.IndexOf('('); var close = version.LastIndexOf(')'); return open >= 0 && close > open ? version[(open + 1)..close] : ""; } internal static EmulatorProfile[] Profiles(string output) { var result = new List(); string? model = null; var details = new System.Text.StringBuilder(); void AddCurrent() { if (model is not null) result.Add(new EmulatorProfile(model, details.ToString().Trim())); } foreach (var raw in output.Split('\n')) { var line = raw.Trim(); if (line.Length == 0) continue; if (line.StartsWith("- ", StringComparison.Ordinal)) { AddCurrent(); model = line[2..].Trim(); details.Clear(); } else { var separator = line.IndexOf(" - ", StringComparison.Ordinal); if (separator >= 0) { AddCurrent(); model = line[(separator + 3)..].Trim(); details.Clear(); } else if (model is not null) { details.AppendLine(line); } } } AddCurrent(); return result.ToArray(); } private static T[] Parse(string output, Func convert) { var first = output.IndexOf('['); var last = output.LastIndexOf(']'); if (first < 0 || last <= first) throw new InvalidOperationException("未收到 Emulator 的 JSON 列表。请查看命令输出。"); using var document = JsonDocument.Parse(output[first..(last + 1)]); return document.RootElement.EnumerateArray().Select(convert).ToArray(); } private static string Field(JsonElement row, string name) => row.TryGetProperty(name, out var value) ? value.ToString() : ""; }