Add cross-platform HarmonyOS Emulator manager
This commit is contained in:
commit
1f6d4322aa
8 files changed
+549
No files matched your search
+309
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user