commit 1f6d4322aa4f5fdc8d3c2ec3f69fc742fd0d7d65 Author: TongTongStudio Date: Sat Nov 28 04:57:39 2026 +0800 Add cross-platform HarmonyOS Emulator manager diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..547a964 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +bin/ +obj/ +.vs/ +*.user diff --git a/EmulatorCli.cs b/EmulatorCli.cs new file mode 100644 index 0000000..109e36f --- /dev/null +++ b/EmulatorCli.cs @@ -0,0 +1,117 @@ +using System.Diagnostics; +using System.Text.Json; + +internal sealed record EmulatorInstance(string Name, string Type, string Version, string Running) +{ + public override string ToString() => $"{Name} | {Type} | {Version} | {Running}"; +} + +internal sealed record EmulatorImage(string Type, string Version, string Downloaded) +{ + public override string ToString() => $"{Type} | {Version} | {Downloaded}"; +} + +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"; + var stdout = ReadAsync(process.StandardOutput, 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) + 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(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, "isRunning").ToLowerInvariant() switch + { + "true" => "运行中", + "false" => "已停止", + _ => "未知" + })); + + internal static EmulatorImage[] Images(string output) => Parse(output, row => new EmulatorImage( + Field(row, "deviceType"), Field(row, "osVersion"), + Field(row, "downloaded").ToLowerInvariant() switch + { + "true" => "已下载", + "false" => "未下载", + _ => "未知" + })); + + 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() : ""; +} diff --git a/EmulatorManager.csproj b/EmulatorManager.csproj new file mode 100644 index 0000000..803c89d --- /dev/null +++ b/EmulatorManager.csproj @@ -0,0 +1,12 @@ + + + WinExe + net10.0 + enable + enable + + + + + + diff --git a/MainWindow.cs b/MainWindow.cs new file mode 100644 index 0000000..be0c0dd --- /dev/null +++ b/MainWindow.cs @@ -0,0 +1,309 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; + +internal sealed class MainWindow : Window +{ + private readonly TextBox executable = new() { Text = EmulatorCli.DefaultPath(), Watermark = "Emulator 可执行文件路径" }; + private readonly TextBox name = new() { Watermark = "实例名称", Width = 210 }; + private readonly TextBox deviceType = new() { Watermark = "设备类型,如 phone", Width = 170, Text = "phone" }; + private readonly TextBox version = new() { Watermark = "HarmonyOS 镜像版本", Width = 270 }; + private readonly CheckBox headless = new() { Content = "无窗口启动" }; + private readonly ListBox instances = new() { MinHeight = 120 }; + private readonly ListBox images = new() { MinHeight = 120 }; + private readonly ListBox output = new(); + private readonly TextBlock status = new() { Text = "就绪", VerticalAlignment = VerticalAlignment.Center }; + private readonly Button cancel = new() { Content = "取消命令", IsEnabled = false }; + private readonly List