Add cross-platform HarmonyOS Emulator manager

This commit is contained in:
tongtong committed 2026-11-28 04:57:39 +08:00
commit 1f6d4322aa
8 files changed
+549

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
bin/
obj/
.vs/
*.user
+117
View File
@@ -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<string> RunAsync(
string executable, string[] args, Action<string> 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<string> ReadAsync(
StreamReader reader, Action<string> 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<T>(string output, Func<JsonElement, T> 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() : "";
}
+12
View File
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" Version="11.2.6" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.6" />
</ItemGroup>
</Project>
+309
View File
@@ -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<Button> actions = [];
private readonly HashSet<(string Executable, string Name)> starting = [];
private CancellationTokenSource? active;
internal MainWindow(bool smoke, Action<int> shutdown)
{
Title = "HarmonyOS Emulator 管理器";
Width = 990;
Height = 730;
MinWidth = 740;
MinHeight = 580;
executable.TextChanged += (_, _) =>
{
instances.ItemsSource = null;
images.ItemsSource = null;
};
images.SelectionChanged += (_, _) =>
{
if (images.SelectedItem is EmulatorImage image)
{
deviceType.Text = image.Type;
version.Text = image.Version;
}
};
instances.SelectionChanged += (_, _) =>
{
if (instances.SelectedItem is EmulatorInstance instance)
name.Text = instance.Name;
};
cancel.Click += (_, _) => active?.Cancel();
Closing += (_, args) =>
{
if (active is not null)
{
args.Cancel = true;
active.Cancel();
status.Text = "正在取消命令,请稍后关闭。";
}
};
var instancePage = Page(
Row(headless, Command("刷新", RefreshInstances),
Command("启动", _ =>
{
StartInstance();
return Task.CompletedTask;
}),
Command("停止", async token =>
{
await Run(token, "-stop", Required(name, "实例名称"));
await RefreshInstances(token);
}),
Command("删除实例", async token =>
{
var target = Required(name, "实例名称");
if (await Confirm($"删除实例「{target}」及其数据?"))
{
await Run(token, "-delete", target, "-force");
await RefreshInstances(token);
}
})),
instances);
var imagePage = Page(
Row(Command("已下载", token => RefreshImages(token, true)),
Command("全部镜像", token => RefreshImages(token, false)),
Command("下载镜像", async token =>
{
await Run(token, ImageArgs("-install"));
await RefreshImages(token, true);
}),
Command("创建实例", async token =>
{
await Run(token, ["-create", Required(name, "实例名称"), .. ImageArgs()]);
await RefreshInstances(token);
}),
Command("删除镜像", async token =>
{
var args = ImageArgs("-uninstall");
if (await Confirm($"删除镜像 {args[2]} / {args[4]}?"))
{
await Run(token, [.. args, "-force"]);
await RefreshImages(token, true);
}
})),
images);
// The inputs stay visible while switching between instances and images.
var tabs = new TabControl
{
ItemsSource = new[]
{
new TabItem { Header = "模拟器实例", Content = instancePage },
new TabItem { Header = "系统镜像", Content = imagePage }
}
};
var layout = new Grid
{
Margin = new Thickness(24),
RowDefinitions = new RowDefinitions("Auto,Auto,Auto,*,Auto,170,Auto")
};
Add(layout, new TextBlock { Text = "Emulator 管理", FontSize = 28, FontWeight = FontWeight.SemiBold }, 0);
var tools = new DockPanel { LastChildFill = true };
var help = Row(Command("版本", token => Run(token, "-version")),
Command("帮助", token => Run(token, "--help")),
Command("许可协议", token => Run(token, "-license")),
Command("接受许可", async token =>
{
if (await Confirm("确认已阅读并接受 Emulator 显示的许可协议?"))
await Run(token, "-license", "accept");
}));
DockPanel.SetDock(help, Dock.Right);
tools.Children.Add(help);
tools.Children.Add(executable);
Add(layout, tools, 1);
Add(layout, Row(name, deviceType, version), 2);
Add(layout, tabs, 3);
Add(layout, new TextBlock { Text = "命令输出", FontWeight = FontWeight.SemiBold }, 4);
Add(layout, output, 5);
Add(layout, Row(cancel, status), 6);
Content = layout;
if (smoke)
{
Opened += async (_, _) =>
{
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
await RefreshInstances(timeout.Token);
await RefreshImages(timeout.Token, true);
Console.WriteLine($"Emulator smoke passed: {instances.ItemCount} instances, {images.ItemCount} downloaded images.");
shutdown(0);
}
catch (Exception error)
{
Console.Error.WriteLine(error);
shutdown(1);
}
};
}
else
{
Opened += async (_, _) => await Execute(RefreshInstances);
}
}
private async Task RefreshInstances(CancellationToken token) =>
instances.ItemsSource = EmulatorCli.Instances(await Run(token, "-list", "-details"));
private async Task RefreshImages(CancellationToken token, bool downloaded) =>
images.ItemsSource = EmulatorCli.Images(await Run(token, downloaded
? ["-imageList", "-downloaded", "true"] : ["-imageList"]));
private string[] ImageArgs(params string[] prefix) =>
[.. prefix, "-deviceType", Required(deviceType, "设备类型"), "-osVersion", Required(version, "镜像版本")];
private void StartInstance()
{
var path = Required(executable, "Emulator 路径");
var target = Required(name, "实例名称");
if (!starting.Add((path, target)))
throw new InvalidOperationException($"「{target}」已有启动进程。");
string[] args = headless.IsChecked == true ? ["-start", target, "-noWindow"] : ["-start", target];
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);
}
catch (Exception error)
{
AppendOutput($"「{target}」启动失败:{error.Message}");
}
finally
{
starting.Remove((path, target));
}
}
private Task<string> Run(CancellationToken token, params string[] args) =>
EmulatorCli.RunAsync(Required(executable, "Emulator 路径"), args, AppendOutput, token);
private void AppendOutput(string line) => Dispatcher.UIThread.Post(() =>
{
if (output.ItemCount >= 1500)
output.Items.RemoveAt(0);
output.Items.Add(line);
output.ScrollIntoView(line);
});
private Button Command(string label, Func<CancellationToken, Task> action)
{
var button = new Button { Content = label };
button.Click += async (_, _) => await Execute(action);
actions.Add(button);
return button;
}
private async Task Execute(Func<CancellationToken, Task> action)
{
if (active is not null)
return;
using var source = new CancellationTokenSource();
active = source;
executable.IsEnabled = false;
cancel.IsEnabled = true;
actions.ForEach(button => button.IsEnabled = false);
status.Text = "正在执行…";
try
{
await action(source.Token);
status.Text = "就绪";
}
catch (OperationCanceledException)
{
status.Text = "命令已取消";
}
catch (Exception error)
{
status.Text = error.Message;
}
finally
{
active = null;
executable.IsEnabled = true;
cancel.IsEnabled = false;
actions.ForEach(button => button.IsEnabled = true);
}
}
private Task<bool> Confirm(string message)
{
var dialog = new Window
{
Title = "确认操作",
SizeToContent = SizeToContent.WidthAndHeight,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
CanResize = false
};
var yes = new Button { Content = "确认" };
var no = new Button { Content = "取消", IsCancel = true };
yes.Click += (_, _) => dialog.Close(true);
no.Click += (_, _) => dialog.Close(false);
var panel = new StackPanel { Margin = new Thickness(24), Spacing = 16 };
panel.Children.Add(new TextBlock { Text = message });
panel.Children.Add(Row(no, yes));
dialog.Content = panel;
return dialog.ShowDialog<bool>(this);
}
private static string Required(TextBox field, string label)
{
var value = field.Text?.Trim();
if (string.IsNullOrEmpty(value) || value.StartsWith('-'))
throw new InvalidOperationException($"请输入有效的{label}。");
return value;
}
private static WrapPanel Row(params Control[] children)
{
var panel = new WrapPanel();
foreach (var child in children)
{
child.Margin = new Thickness(0, 0, 8, 4);
panel.Children.Add(child);
}
return panel;
}
private static DockPanel Page(Control toolbar, Control list)
{
var panel = new DockPanel { Margin = new Thickness(0, 8, 0, 0) };
DockPanel.SetDock(toolbar, Dock.Top);
panel.Children.Add(toolbar);
panel.Children.Add(list);
return panel;
}
private static void Add(Grid grid, Control control, int row)
{
if (row > 0)
control.Margin = new Thickness(0, 10, 0, 0);
Grid.SetRow(control, row);
grid.Children.Add(control);
}
}
+23
View File
@@ -0,0 +1,23 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Themes.Fluent;
internal static class Program
{
[STAThread]
public static int Main(string[] args) =>
AppBuilder.Configure<App>().UsePlatformDetect()
.StartWithClassicDesktopLifetime(args);
}
public sealed class App : Application
{
public override void Initialize() => Styles.Add(new FluentTheme());
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
desktop.MainWindow = new MainWindow(desktop.Args?.Contains("--smoke") == true, desktop.Shutdown);
base.OnFrameworkInitializationCompleted();
}
}
+27
View File
@@ -0,0 +1,27 @@
# HarmonyOS Emulator 管理器
使用 C#、.NET 10 和 Avalonia 的桌面应用,调用本机华为 Emulator CLI。
## 运行
安装 .NET 10 SDK,以及含 Emulator 的 DevEco Studio 或 Command Line Tools。
```sh
dotnet run --project EmulatorManager.csproj
```
可在窗口顶部编辑 Emulator 路径,或预先设置环境变量 `HARMONY_EMULATOR`。程序也会尝试 `DEVECO_CLI_CLT_PATH`、常见安装目录和 PATH。Linux 上请按华为要求配置 KVM,必要时勾选无窗口启动。
- **模拟器实例**支持刷新、启动、停止、删除。
- **系统镜像**支持查询全部和已下载镜像、下载、删除,也可用所选镜像创建实例。创建时填入实例名称。
- 首次使用可在界面中查看许可并确认接受。命令输出区显示官方工具返回的信息。
## 构建、运行并同步
在已配置指定 Gitea 仓库为 `origin` 的工作区运行:
```sh
pwsh -File sync.ps1 -Message "说明本次变更"
```
脚本先编译 Release 并打开应用。应用正常退出后,脚本显示待提交改动,经确认后提交并推送当前分支。传入 `-Smoke` 会运行桌面启动、实例列表和已下载镜像列表检查,然后自动退出。若 SDK 不在 PATH,使用 `-Dotnet` 指定可执行文件。
+6
View File
@@ -0,0 +1,6 @@
{
"sdk": {
"version": "10.0.100",
"rollForward": "latestFeature"
}
}
+51
View File
@@ -0,0 +1,51 @@
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $Message,
[string] $Dotnet = 'dotnet',
[switch] $Smoke
)
$ErrorActionPreference = 'Stop'
function Invoke-Checked {
param([string] $Executable, [string[]] $Arguments)
& $Executable @Arguments
if ($LASTEXITCODE -ne 0) {
throw "$Executable $($Arguments[0]) 退出码 $LASTEXITCODE"
}
}
Push-Location -LiteralPath $PSScriptRoot
try {
$expectedRemote = 'ssh://git@gitea.ttstd.com:2222/tt/TTSTDHarmonyOSCommandLineToolsUI.git'
$pushRemote = Invoke-Checked git @('remote', 'get-url', '--push', '--all', 'origin')
if (@($pushRemote).Count -ne 1 -or $pushRemote -cne $expectedRemote) {
throw "origin 推送地址必须是 $expectedRemote"
}
$branch = Invoke-Checked git @('symbolic-ref', '--short', 'HEAD')
Invoke-Checked $Dotnet @('build', 'EmulatorManager.csproj', '-c', 'Release')
$runArguments = @('run', '--project', 'EmulatorManager.csproj', '-c', 'Release', '--no-build')
if ($Smoke) {
$runArguments += @('--', '--smoke')
}
Invoke-Checked $Dotnet $runArguments
Invoke-Checked git @('status', '--short')
$answer = Read-Host '将以上工作区变更提交并推送到 origin。输入 yes 确认'
if ($answer -cne 'yes') {
return
}
Invoke-Checked git @('add', '-A')
& git diff --cached --quiet --exit-code
switch ($LASTEXITCODE) {
0 { }
1 { Invoke-Checked git @('commit', '-m', $Message) }
default { throw "git diff 退出码 $LASTEXITCODE" }
}
Invoke-Checked git @('push', '--set-upstream', 'origin', "HEAD:refs/heads/$branch")
}
finally {
Pop-Location
}