473 lines
17 KiB
C#
473 lines
17 KiB
C#
using Avalonia;
|
||
using Avalonia.Controls;
|
||
using Avalonia.Controls.Templates;
|
||
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 targetName = new() { Watermark = "选择列表中的实例" };
|
||
private readonly TextBox name = new() { Watermark = "例如 My Phone" };
|
||
private readonly TextBox deviceType = new() { Watermark = "例如 phone", Text = "phone" };
|
||
private readonly TextBox version = new() { Watermark = "例如 HarmonyOS 7.0.0(26.0.0)" };
|
||
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() { MaxHeight = 156, MinHeight = 104 };
|
||
private readonly Button logToggle = new() { Content = "展开命令输出" };
|
||
private readonly TextBlock status = new()
|
||
{
|
||
Text = "就绪", VerticalAlignment = VerticalAlignment.Center,
|
||
TextTrimming = TextTrimming.CharacterEllipsis
|
||
};
|
||
private readonly Button cancel = new() { Content = "取消命令", IsVisible = 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 = 1060;
|
||
Height = 690;
|
||
MinWidth = 780;
|
||
MinHeight = 570;
|
||
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)
|
||
targetName.Text = instance.Name;
|
||
};
|
||
cancel.Click += (_, _) => active?.Cancel();
|
||
Closing += (_, args) =>
|
||
{
|
||
if (active is not null)
|
||
{
|
||
args.Cancel = true;
|
||
active.Cancel();
|
||
status.Text = "正在取消命令,请稍后关闭。";
|
||
}
|
||
};
|
||
|
||
var instancePage = ManagementPage(
|
||
"模拟器实例", Row(Command("刷新", RefreshInstances)),
|
||
Table(instances, "1.1*,0.65*,1.55*,0.65*", ["实例名称", "设备类型", "系统版本", "状态"],
|
||
(EmulatorInstance item) => [item.Name, item.Type, item.Version, item.Running]),
|
||
Panel(
|
||
Caption("实例操作"),
|
||
Field("目标实例", targetName),
|
||
headless,
|
||
Row(
|
||
Command("启动", _ =>
|
||
{
|
||
StartInstance();
|
||
return Task.CompletedTask;
|
||
}),
|
||
Command("停止", async token =>
|
||
{
|
||
await Run(token, "-stop", Required(targetName, "目标实例"));
|
||
await RefreshInstances(token);
|
||
})),
|
||
Command("删除实例", async token =>
|
||
{
|
||
var target = Required(targetName, "目标实例");
|
||
if (await Confirm($"删除实例「{target}」及其数据?"))
|
||
{
|
||
await Run(token, "-delete", target, "-force");
|
||
await RefreshInstances(token);
|
||
}
|
||
})));
|
||
|
||
var imagePage = ManagementPage(
|
||
"系统镜像",
|
||
Row(Command("已下载", token => RefreshImages(token, true)),
|
||
Command("全部镜像", token => RefreshImages(token, false))),
|
||
Table(images, "0.85*,1.65*,0.7*", ["设备类型", "系统版本", "下载状态"],
|
||
(EmulatorImage item) => [item.Type, item.Version, item.Downloaded]),
|
||
Panel(
|
||
Caption("镜像操作"),
|
||
Field("设备类型", deviceType),
|
||
Field("系统版本", version),
|
||
Row(
|
||
Command("下载镜像", async token =>
|
||
{
|
||
ShowLog(true);
|
||
await Run(token, ImageArgs("-install"));
|
||
await RefreshImages(token, true);
|
||
}),
|
||
Command("删除镜像", async token =>
|
||
{
|
||
var args = ImageArgs("-uninstall");
|
||
if (await Confirm($"删除镜像 {args[2]} / {args[4]}?"))
|
||
{
|
||
await Run(token, [.. args, "-force"]);
|
||
await RefreshImages(token, true);
|
||
}
|
||
})),
|
||
Caption("创建模拟器"),
|
||
Field("实例名称", name),
|
||
Command("创建实例", async token =>
|
||
{
|
||
await Run(token, ["-create", Required(name, "实例名称"), .. ImageArgs()]);
|
||
await RefreshInstances(token);
|
||
})));
|
||
output.ItemTemplate = new FuncDataTemplate<string>((line, _) => new TextBlock
|
||
{
|
||
Text = line, FontFamily = new FontFamily("monospace"), FontSize = 12,
|
||
TextWrapping = TextWrapping.Wrap
|
||
});
|
||
output.IsVisible = false;
|
||
logToggle.Click += (_, _) => ShowLog(!output.IsVisible);
|
||
|
||
var settings = Panel(
|
||
Caption("Emulator 工具"),
|
||
Field("可执行文件路径", executable),
|
||
Row(OutputCommand("查看版本", "-version"), OutputCommand("命令帮助", "--help"),
|
||
OutputCommand("查看许可协议", "-license"),
|
||
Command("接受许可", async token =>
|
||
{
|
||
if (await Confirm("确认已阅读并接受 Emulator 显示的许可协议?"))
|
||
{
|
||
ShowLog(true);
|
||
await Run(token, "-license", "accept");
|
||
}
|
||
})));
|
||
var tabs = new TabControl
|
||
{
|
||
ItemsSource = new[]
|
||
{
|
||
new TabItem { Header = "模拟器实例", Content = instancePage },
|
||
new TabItem { Header = "系统镜像", Content = imagePage },
|
||
new TabItem { Header = "工具设置", Content = new Border
|
||
{
|
||
Margin = new Thickness(0, 16, 0, 0),
|
||
VerticalAlignment = VerticalAlignment.Top, Child = Card(settings)
|
||
} }
|
||
}
|
||
};
|
||
tabs.SelectionChanged += async (_, args) =>
|
||
{
|
||
if (!smoke && args.Source == tabs && tabs.SelectedIndex == 1 && images.ItemsSource is null)
|
||
await Execute(token => RefreshImages(token, true));
|
||
};
|
||
var layout = new Grid
|
||
{
|
||
Margin = new Thickness(24),
|
||
RowDefinitions = new RowDefinitions("Auto,*,Auto")
|
||
};
|
||
Add(layout, new TextBlock { Text = "Emulator 管理", FontSize = 26, FontWeight = FontWeight.SemiBold }, 0);
|
||
Add(layout, tabs, 1);
|
||
var footer = new DockPanel();
|
||
var controls = Row(logToggle, cancel);
|
||
DockPanel.SetDock(controls, Dock.Right);
|
||
footer.Children.Add(controls);
|
||
footer.Children.Add(status);
|
||
Add(layout, Card(Panel(footer, output)), 2);
|
||
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)
|
||
{
|
||
var items = await ReadList(token, EmulatorCli.Instances, "-list", "-details");
|
||
instances.ItemsSource = items;
|
||
AppendOutput($"已读取 {items.Length} 个模拟器实例。");
|
||
}
|
||
|
||
private async Task RefreshImages(CancellationToken token, bool downloaded)
|
||
{
|
||
var items = await ReadList(token, EmulatorCli.Images, downloaded
|
||
? ["-imageList", "-downloaded", "true"] : ["-imageList"]);
|
||
images.ItemsSource = items;
|
||
AppendOutput($"已读取 {items.Length} 个镜像。");
|
||
}
|
||
|
||
private async Task<T[]> ReadList<T>(CancellationToken token, Func<string, T[]> parse, params string[] args)
|
||
{
|
||
var raw = await Run(token, args);
|
||
try
|
||
{
|
||
return parse(raw);
|
||
}
|
||
catch
|
||
{
|
||
AppendOutput(raw);
|
||
throw;
|
||
}
|
||
}
|
||
|
||
private string[] ImageArgs(params string[] prefix) =>
|
||
[.. prefix, "-deviceType", Required(deviceType, "设备类型"), "-osVersion", Required(version, "镜像版本")];
|
||
|
||
private void StartInstance()
|
||
{
|
||
var path = Required(executable, "Emulator 路径");
|
||
var target = Required(targetName, "目标实例");
|
||
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);
|
||
if (output.IsVisible)
|
||
output.ScrollIntoView(output.ItemCount - 1);
|
||
});
|
||
|
||
private void ShowLog(bool visible)
|
||
{
|
||
output.IsVisible = visible;
|
||
logToggle.Content = visible ? "收起命令输出" : "展开命令输出";
|
||
if (visible && output.ItemCount > 0)
|
||
output.ScrollIntoView(output.ItemCount - 1);
|
||
}
|
||
|
||
private Button OutputCommand(string label, string argument) => Command(label, token =>
|
||
{
|
||
ShowLog(true);
|
||
return Run(token, argument);
|
||
});
|
||
|
||
private Button Command(string label, Func<CancellationToken, Task> action)
|
||
{
|
||
var button = new Button { Content = label, HorizontalAlignment = HorizontalAlignment.Left };
|
||
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.IsVisible = 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;
|
||
AppendOutput(error.Message);
|
||
ShowLog(true);
|
||
}
|
||
finally
|
||
{
|
||
active = null;
|
||
executable.IsEnabled = true;
|
||
cancel.IsVisible = 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 Control ManagementPage(string title, Control toolbar, Control table, Control controls)
|
||
{
|
||
var header = new DockPanel();
|
||
DockPanel.SetDock(toolbar, Dock.Right);
|
||
header.Children.Add(toolbar);
|
||
header.Children.Add(Caption(title));
|
||
var left = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
|
||
Add(left, header, 0);
|
||
Add(left, table, 1);
|
||
var grid = new Grid
|
||
{
|
||
Margin = new Thickness(0, 16, 0, 0),
|
||
ColumnDefinitions = new ColumnDefinitions("*,252")
|
||
};
|
||
grid.Children.Add(Card(left));
|
||
var sidebar = Card(new ScrollViewer { Content = controls });
|
||
sidebar.Margin = new Thickness(14, 0, 0, 0);
|
||
Grid.SetColumn(sidebar, 1);
|
||
grid.Children.Add(sidebar);
|
||
return grid;
|
||
}
|
||
|
||
private static Control Table<T>(ListBox list, string columns, string[] headings, Func<T, string[]> cells)
|
||
where T : class
|
||
{
|
||
list.ItemTemplate = new FuncDataTemplate<T>((item, _) => TableRow(columns, cells(item!), false));
|
||
list.Padding = new Thickness(0);
|
||
var panel = new DockPanel();
|
||
var header = new Border
|
||
{
|
||
Background = new SolidColorBrush(Color.FromArgb(20, 128, 128, 128)),
|
||
CornerRadius = new CornerRadius(6),
|
||
Padding = new Thickness(10, 7),
|
||
Child = TableRow(columns, headings, true)
|
||
};
|
||
DockPanel.SetDock(header, Dock.Top);
|
||
panel.Children.Add(header);
|
||
panel.Children.Add(list);
|
||
return panel;
|
||
}
|
||
|
||
private static Grid TableRow(string columns, string[] values, bool header)
|
||
{
|
||
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions(columns) };
|
||
for (var index = 0; index < values.Length; index++)
|
||
{
|
||
var cell = new TextBlock
|
||
{
|
||
Text = values[index],
|
||
TextTrimming = TextTrimming.CharacterEllipsis,
|
||
FontWeight = header || index == 0 ? FontWeight.SemiBold : FontWeight.Normal,
|
||
FontSize = 13, Margin = new Thickness(0, 0, 8, 0)
|
||
};
|
||
ToolTip.SetTip(cell, values[index]);
|
||
Grid.SetColumn(cell, index);
|
||
grid.Children.Add(cell);
|
||
}
|
||
return grid;
|
||
}
|
||
|
||
private static TextBlock Caption(string text) => new()
|
||
{
|
||
Text = text, FontSize = 16, FontWeight = FontWeight.SemiBold,
|
||
VerticalAlignment = VerticalAlignment.Center
|
||
};
|
||
|
||
private static StackPanel Field(string label, Control field)
|
||
{
|
||
var panel = Panel(new TextBlock { Text = label, FontSize = 12, Opacity = 0.78 }, field);
|
||
panel.Spacing = 5;
|
||
return panel;
|
||
}
|
||
|
||
private static StackPanel Panel(params Control[] controls)
|
||
{
|
||
var panel = new StackPanel { Spacing = 10 };
|
||
foreach (var control in controls)
|
||
panel.Children.Add(control);
|
||
return panel;
|
||
}
|
||
|
||
private static Border Card(Control child) => new()
|
||
{
|
||
BorderThickness = new Thickness(1),
|
||
BorderBrush = new SolidColorBrush(Color.FromArgb(62, 128, 128, 128)),
|
||
Background = new SolidColorBrush(Color.FromArgb(12, 128, 128, 128)),
|
||
CornerRadius = new CornerRadius(10),
|
||
Padding = new Thickness(14),
|
||
Child = child
|
||
};
|
||
|
||
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);
|
||
}
|
||
}
|