Rework emulator UI and add device creation wizard
This commit is contained in:
1 parent
c2084b6cd1
commit
9cf29c11ab
5 files changed
+1028
-176
No files matched your search
@@ -0,0 +1,37 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
internal sealed record DeviceCategory(string Label, string Value, params DeviceCategory[] Children);
|
||||
|
||||
internal static class DeviceCatalog
|
||||
{
|
||||
internal static readonly DeviceCategory[] Categories =
|
||||
[
|
||||
new DeviceCategory("全部", ""),
|
||||
new DeviceCategory("手机", "",
|
||||
new DeviceCategory("手机", "phone"), new DeviceCategory("折叠屏", "foldable"),
|
||||
new DeviceCategory("阔折叠", "widefold"), new DeviceCategory("三折叠", "triplefold")),
|
||||
new DeviceCategory("平板", "", new DeviceCategory("平板", "tablet")),
|
||||
new DeviceCategory("2in1", "", new DeviceCategory("2in1", "2in1"), new DeviceCategory("折叠2in1", "2in1 Foldable")),
|
||||
new DeviceCategory("电视", "", new DeviceCategory("电视", "tv")),
|
||||
new DeviceCategory("穿戴设备", "", new DeviceCategory("智能表", "wearable"), new DeviceCategory("儿童表", "wearablekid")),
|
||||
new DeviceCategory("车机", "", new DeviceCategory("车机", "car"))
|
||||
];
|
||||
|
||||
internal static readonly Dictionary<string, string> TypeNames = Categories
|
||||
.SelectMany(group => new[] { group }.Concat(group.Children))
|
||||
.Where(node => node.Value.Length > 0)
|
||||
.ToDictionary(node => node.Value, node => node.Label);
|
||||
|
||||
internal static TreeViewItem CreateItem(DeviceCategory node)
|
||||
{
|
||||
var item = new TreeViewItem
|
||||
{
|
||||
Header = node.Label,
|
||||
Tag = node,
|
||||
IsExpanded = node.Children.Length > 0
|
||||
};
|
||||
foreach (var child in node.Children)
|
||||
item.Items.Add(CreateItem(child));
|
||||
return item;
|
||||
}
|
||||
}
|
||||
+81
-12
@@ -1,16 +1,24 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
|
||||
internal sealed record EmulatorInstance(string Name, string Type, string Version, string Running)
|
||||
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 Downloaded)
|
||||
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()
|
||||
@@ -50,7 +58,7 @@ internal static class EmulatorCli
|
||||
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 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
|
||||
@@ -89,21 +97,82 @@ internal static class EmulatorCli
|
||||
|
||||
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" => "已停止",
|
||||
_ => "未知"
|
||||
}));
|
||||
Field(row, "os.apiVersion"), Resolution(row), ScreenSize(row),
|
||||
Field(row, "instancePath"), Field(row, "isRunning").Equals("true", StringComparison.OrdinalIgnoreCase)));
|
||||
|
||||
internal static EmulatorImage[] Images(string output) => Parse(output, row => new EmulatorImage(
|
||||
Field(row, "deviceType"), Field(row, "osVersion"),
|
||||
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<EmulatorProfile>();
|
||||
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<T>(string output, Func<JsonElement, T> convert)
|
||||
{
|
||||
|
||||
+431
-160
@@ -1,3 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Templates;
|
||||
@@ -8,53 +9,55 @@ 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 TreeView categories = new();
|
||||
private readonly TreeView imageCategories = new();
|
||||
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 ListBox output = new();
|
||||
private readonly TextBlock status = new()
|
||||
{
|
||||
Text = "就绪", VerticalAlignment = VerticalAlignment.Center,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
TextTrimming = TextTrimming.CharacterEllipsis,
|
||||
Margin = new Thickness(24, 0, 0, 0)
|
||||
};
|
||||
private readonly Button cancel = new() { Content = "取消命令", IsVisible = false };
|
||||
private readonly List<Button> actions = [];
|
||||
private readonly HashSet<(string Executable, string Name)> starting = [];
|
||||
private EmulatorInstance[] allInstances = [];
|
||||
private EmulatorImage[] allImages = [];
|
||||
private readonly bool smokeMode;
|
||||
private Window? imagesWindow;
|
||||
private Window? settingsWindow;
|
||||
private Window? outputWindow;
|
||||
private Window? newEmulatorWindow;
|
||||
private DispatcherTimer? statusTimer;
|
||||
private bool shuttingDown;
|
||||
private CancellationTokenSource? active;
|
||||
|
||||
internal MainWindow(bool smoke, Action<int> shutdown)
|
||||
{
|
||||
smokeMode = smoke;
|
||||
Title = "HarmonyOS Emulator 管理器";
|
||||
Width = 1060;
|
||||
Height = 690;
|
||||
Width = 1280;
|
||||
Height = 820;
|
||||
MinWidth = 780;
|
||||
MinHeight = 570;
|
||||
executable.TextChanged += (_, _) =>
|
||||
{
|
||||
allInstances = [];
|
||||
allImages = [];
|
||||
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) =>
|
||||
{
|
||||
shuttingDown = true;
|
||||
statusTimer?.Stop();
|
||||
imagesWindow?.Close();
|
||||
settingsWindow?.Close();
|
||||
outputWindow?.Close();
|
||||
newEmulatorWindow?.Close();
|
||||
if (active is not null)
|
||||
{
|
||||
args.Cancel = true;
|
||||
@@ -63,120 +66,50 @@ internal sealed class MainWindow : Window
|
||||
}
|
||||
};
|
||||
|
||||
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 settingsButton = new Button { Content = "设置" };
|
||||
settingsButton.Click += (_, _) => OpenSettingsWindow();
|
||||
var heading = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
var title = new StackPanel { Spacing = 3 };
|
||||
title.Children.Add(new TextBlock { Text = "Emulator 管理", FontSize = 26, FontWeight = FontWeight.SemiBold });
|
||||
title.Children.Add(new TextBlock { Text = "管理模拟器实例、系统镜像与 Emulator 命令", FontSize = 13, Opacity = 0.7 });
|
||||
heading.Children.Add(title);
|
||||
settingsButton.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
Grid.SetColumn(settingsButton, 1);
|
||||
heading.Children.Add(settingsButton);
|
||||
|
||||
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);
|
||||
Add(layout, heading, 0);
|
||||
Add(layout, InstancePage(), 1);
|
||||
|
||||
var outputButton = new Button { Content = "命令输出" };
|
||||
outputButton.Click += (_, _) => OpenOutputWindow();
|
||||
var create = Command("创建模拟器", token =>
|
||||
{
|
||||
OpenNewEmulatorWindow();
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
create.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
var middle = new DockPanel();
|
||||
DockPanel.SetDock(cancel, Dock.Right);
|
||||
middle.Children.Add(cancel);
|
||||
middle.Children.Add(status);
|
||||
var footer = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto") };
|
||||
footer.Children.Add(outputButton);
|
||||
Grid.SetColumn(middle, 1);
|
||||
footer.Children.Add(middle);
|
||||
Grid.SetColumn(create, 2);
|
||||
footer.Children.Add(create);
|
||||
Add(layout, footer, 2);
|
||||
Content = layout;
|
||||
|
||||
if (smoke)
|
||||
@@ -203,23 +136,49 @@ internal sealed class MainWindow : Window
|
||||
}
|
||||
else
|
||||
{
|
||||
Opened += async (_, _) => await Execute(RefreshInstances);
|
||||
statusTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
|
||||
statusTimer.Tick += (_, _) => _ = RefreshInstancesSilently();
|
||||
Opened += async (_, _) =>
|
||||
{
|
||||
await Execute(RefreshInstances);
|
||||
statusTimer.Start();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshInstances(CancellationToken token)
|
||||
{
|
||||
var items = await ReadList(token, EmulatorCli.Instances, "-list", "-details");
|
||||
instances.ItemsSource = items;
|
||||
AppendOutput($"已读取 {items.Length} 个模拟器实例。");
|
||||
allInstances = await ReadList(token, EmulatorCli.Instances, "-list", "-details");
|
||||
ApplyCategoryFilter();
|
||||
AppendOutput($"已读取 {allInstances.Length} 个模拟器实例。");
|
||||
}
|
||||
|
||||
private async Task RefreshInstancesSilently()
|
||||
{
|
||||
if (active is not null)
|
||||
return;
|
||||
try
|
||||
{
|
||||
var raw = await EmulatorCli.RunAsync(
|
||||
Required(executable, "Emulator 路径"), ["-list", "-details"], _ => { }, CancellationToken.None);
|
||||
var items = EmulatorCli.Instances(raw);
|
||||
if (active is not null)
|
||||
return;
|
||||
allInstances = items;
|
||||
ApplyCategoryFilter();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshImages(CancellationToken token, bool downloaded)
|
||||
{
|
||||
var items = await ReadList(token, EmulatorCli.Images, downloaded
|
||||
status.Text = downloaded ? "正在读取已下载镜像…" : "正在拉取全部镜像…";
|
||||
allImages = await ReadList(token, EmulatorCli.Images, downloaded
|
||||
? ["-imageList", "-downloaded", "true"] : ["-imageList"]);
|
||||
images.ItemsSource = items;
|
||||
AppendOutput($"已读取 {items.Length} 个镜像。");
|
||||
ApplyImageCategoryFilter();
|
||||
AppendOutput($"已读取 {allImages.Length} 个镜像。");
|
||||
}
|
||||
|
||||
private async Task<T[]> ReadList<T>(CancellationToken token, Func<string, T[]> parse, params string[] args)
|
||||
@@ -236,16 +195,12 @@ internal sealed class MainWindow : Window
|
||||
}
|
||||
}
|
||||
|
||||
private string[] ImageArgs(params string[] prefix) =>
|
||||
[.. prefix, "-deviceType", Required(deviceType, "设备类型"), "-osVersion", Required(version, "镜像版本")];
|
||||
|
||||
private void StartInstance()
|
||||
private void StartInstance(string target, string[] extra)
|
||||
{
|
||||
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];
|
||||
string[] args = ["-start", target, .. extra];
|
||||
AppendOutput($"正在启动「{target}」。可刷新列表查看状态,也可直接停止实例。");
|
||||
_ = ObserveStart(path, target, args);
|
||||
}
|
||||
@@ -266,6 +221,71 @@ internal sealed class MainWindow : Window
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ToggleInstance(EmulatorInstance instance, CancellationToken token)
|
||||
{
|
||||
if (instance.IsRunning)
|
||||
{
|
||||
await Run(token, "-stop", instance.Name);
|
||||
await RefreshInstances(token);
|
||||
}
|
||||
else
|
||||
{
|
||||
StartInstance(instance.Name, []);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DeleteInstance(EmulatorInstance instance, CancellationToken token)
|
||||
{
|
||||
if (!await Confirm($"删除实例「{instance.Name}」及其数据?"))
|
||||
return;
|
||||
await Run(token, "-delete", instance.Name, "-force");
|
||||
await RefreshInstances(token);
|
||||
}
|
||||
|
||||
private async Task GenerateLog(EmulatorInstance instance, CancellationToken token)
|
||||
{
|
||||
ShowOutput();
|
||||
var directory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
await Run(token, "-logZip", instance.Name, "-logPath", directory);
|
||||
AppendOutput($"日志已保存到 {directory}。");
|
||||
}
|
||||
|
||||
private void ShowInDisk(EmulatorInstance instance)
|
||||
{
|
||||
try
|
||||
{
|
||||
Process.Start(new ProcessStartInfo(instance.InstancePath) { UseShellExecute = true });
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
AppendOutput($"无法打开实例目录:{error.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void EditInstance(EmulatorInstance instance)
|
||||
{
|
||||
status.Text = "编辑功能稍后实现。";
|
||||
AppendOutput($"编辑「{instance.Name}」的功能稍后实现。");
|
||||
}
|
||||
|
||||
private void ApplyCategoryFilter()
|
||||
{
|
||||
var node = (categories.SelectedItem as TreeViewItem)?.Tag as DeviceCategory;
|
||||
var type = node?.Value;
|
||||
instances.ItemsSource = string.IsNullOrEmpty(type)
|
||||
? allInstances
|
||||
: allInstances.Where(item => item.Type == type).ToArray();
|
||||
}
|
||||
|
||||
private void ApplyImageCategoryFilter()
|
||||
{
|
||||
var node = (imageCategories.SelectedItem as TreeViewItem)?.Tag as DeviceCategory;
|
||||
var type = node?.Value;
|
||||
images.ItemsSource = string.IsNullOrEmpty(type)
|
||||
? allImages
|
||||
: allImages.Where(item => item.Type == type).ToArray();
|
||||
}
|
||||
|
||||
private Task<string> Run(CancellationToken token, params string[] args) =>
|
||||
EmulatorCli.RunAsync(Required(executable, "Emulator 路径"), args, AppendOutput, token);
|
||||
|
||||
@@ -274,21 +294,18 @@ internal sealed class MainWindow : Window
|
||||
if (output.ItemCount >= 1500)
|
||||
output.Items.RemoveAt(0);
|
||||
output.Items.Add(line);
|
||||
if (output.IsVisible)
|
||||
output.ScrollIntoView(output.ItemCount - 1);
|
||||
ShowOutput();
|
||||
});
|
||||
|
||||
private void ShowLog(bool visible)
|
||||
private void ShowOutput()
|
||||
{
|
||||
output.IsVisible = visible;
|
||||
logToggle.Content = visible ? "收起命令输出" : "展开命令输出";
|
||||
if (visible && output.ItemCount > 0)
|
||||
if (outputWindow?.IsVisible == true && output.ItemCount > 0)
|
||||
output.ScrollIntoView(output.ItemCount - 1);
|
||||
}
|
||||
|
||||
private Button OutputCommand(string label, string argument) => Command(label, token =>
|
||||
{
|
||||
ShowLog(true);
|
||||
ShowOutput();
|
||||
return Run(token, argument);
|
||||
});
|
||||
|
||||
@@ -300,6 +317,122 @@ internal sealed class MainWindow : Window
|
||||
return button;
|
||||
}
|
||||
|
||||
private void OpenImagesWindow()
|
||||
{
|
||||
if (imagesWindow is null)
|
||||
imagesWindow = CreateImagesWindow();
|
||||
imageCategories.SelectedItem = imageCategories.Items[0];
|
||||
imagesWindow.Show(this);
|
||||
if (!smokeMode)
|
||||
_ = Execute(token => RefreshImages(token, false));
|
||||
}
|
||||
|
||||
private void OpenNewEmulatorWindow()
|
||||
{
|
||||
var path = Required(executable, "Emulator 路径");
|
||||
newEmulatorWindow?.Close();
|
||||
newEmulatorWindow = new NewEmulatorWindow(path, AppendOutput, () => _ = Execute(RefreshInstances));
|
||||
newEmulatorWindow.Show(this);
|
||||
}
|
||||
|
||||
private Window CreateImagesWindow()
|
||||
{
|
||||
imageCategories.ItemsSource = DeviceCatalog.Categories.Select(DeviceCatalog.CreateItem).ToArray();
|
||||
imageCategories.SelectionChanged += (_, _) => ApplyImageCategoryFilter();
|
||||
imageCategories.SelectedItem = imageCategories.Items[0];
|
||||
var toolbar = Row(Command("已下载", token => RefreshImages(token, true)),
|
||||
Command("全部镜像", token => RefreshImages(token, false)));
|
||||
var header = new DockPanel();
|
||||
DockPanel.SetDock(toolbar, Dock.Right);
|
||||
header.Children.Add(toolbar);
|
||||
header.Children.Add(Caption("系统镜像"));
|
||||
var body = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
|
||||
Add(body, header, 0);
|
||||
Add(body, Table(images, "0.85*,1.65*,0.7*", ["设备类型", "系统版本", "下载状态"],
|
||||
(EmulatorImage item) => [TypeName(item.Type), item.Version, item.Downloaded]), 1);
|
||||
var page = new Grid
|
||||
{
|
||||
Margin = new Thickness(16),
|
||||
ColumnDefinitions = new ColumnDefinitions("180,*")
|
||||
};
|
||||
page.Children.Add(Card(new ScrollViewer { Content = imageCategories }));
|
||||
var content = Card(body);
|
||||
content.Margin = new Thickness(14, 0, 0, 0);
|
||||
Grid.SetColumn(content, 1);
|
||||
page.Children.Add(content);
|
||||
return NewWindow("系统镜像", page);
|
||||
}
|
||||
|
||||
private void OpenSettingsWindow()
|
||||
{
|
||||
settingsWindow ??= CreateSettingsWindow();
|
||||
settingsWindow.Show(this);
|
||||
}
|
||||
|
||||
private void OpenOutputWindow()
|
||||
{
|
||||
outputWindow ??= CreateOutputWindow();
|
||||
outputWindow.Show(this);
|
||||
ShowOutput();
|
||||
}
|
||||
|
||||
private Window CreateOutputWindow()
|
||||
{
|
||||
var content = new Border
|
||||
{
|
||||
Margin = new Thickness(16),
|
||||
Child = Card(output)
|
||||
};
|
||||
return NewWindow("命令输出", content);
|
||||
}
|
||||
|
||||
private Window CreateSettingsWindow()
|
||||
{
|
||||
var settings = Panel(
|
||||
Caption("Emulator 工具"),
|
||||
Field("可执行文件路径", executable),
|
||||
Row(OutputCommand("查看版本", "-version"), OutputCommand("命令帮助", "--help"),
|
||||
OutputCommand("查看许可协议", "-license"),
|
||||
Command("接受许可", async token =>
|
||||
{
|
||||
if (await Confirm("确认已阅读并接受 Emulator 显示的许可协议?"))
|
||||
{
|
||||
ShowOutput();
|
||||
await Run(token, "-license", "accept");
|
||||
}
|
||||
})));
|
||||
var content = new Border
|
||||
{
|
||||
Margin = new Thickness(16),
|
||||
VerticalAlignment = VerticalAlignment.Top,
|
||||
Child = Card(settings)
|
||||
};
|
||||
return NewWindow("工具设置", content);
|
||||
}
|
||||
|
||||
private Window NewWindow(string title, Control content)
|
||||
{
|
||||
var window = new Window
|
||||
{
|
||||
Title = title,
|
||||
Width = 900,
|
||||
Height = 620,
|
||||
MinWidth = 640,
|
||||
MinHeight = 460,
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner,
|
||||
Content = content
|
||||
};
|
||||
window.Closing += (_, args) =>
|
||||
{
|
||||
if (!shuttingDown)
|
||||
{
|
||||
args.Cancel = true;
|
||||
window.Hide();
|
||||
}
|
||||
};
|
||||
return window;
|
||||
}
|
||||
|
||||
private async Task Execute(Func<CancellationToken, Task> action)
|
||||
{
|
||||
if (active is not null)
|
||||
@@ -324,7 +457,7 @@ internal sealed class MainWindow : Window
|
||||
{
|
||||
status.Text = error.Message;
|
||||
AppendOutput(error.Message);
|
||||
ShowLog(true);
|
||||
ShowOutput();
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -352,9 +485,13 @@ internal sealed class MainWindow : Window
|
||||
panel.Children.Add(new TextBlock { Text = message });
|
||||
panel.Children.Add(Row(no, yes));
|
||||
dialog.Content = panel;
|
||||
return dialog.ShowDialog<bool>(this);
|
||||
return dialog.ShowDialog<bool>(DialogOwner());
|
||||
}
|
||||
|
||||
private Window DialogOwner() =>
|
||||
imagesWindow?.IsVisible == true ? imagesWindow :
|
||||
settingsWindow?.IsVisible == true ? settingsWindow : this;
|
||||
|
||||
private static string Required(TextBox field, string label)
|
||||
{
|
||||
var value = field.Text?.Trim();
|
||||
@@ -374,28 +511,162 @@ internal sealed class MainWindow : Window
|
||||
return panel;
|
||||
}
|
||||
|
||||
private static Control ManagementPage(string title, Control toolbar, Control table, Control controls)
|
||||
private Control InstancePage()
|
||||
{
|
||||
categories.ItemsSource = DeviceCatalog.Categories.Select(DeviceCatalog.CreateItem).ToArray();
|
||||
categories.SelectionChanged += (_, _) => ApplyCategoryFilter();
|
||||
categories.SelectedItem = categories.Items[0];
|
||||
var toolbar = Row(Command("刷新", RefreshInstances));
|
||||
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
|
||||
header.Children.Add(Caption("模拟器实例"));
|
||||
var body = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
|
||||
Add(body, header, 0);
|
||||
Add(body, InstanceTable(), 1);
|
||||
var page = new Grid
|
||||
{
|
||||
Margin = new Thickness(0, 16, 0, 0),
|
||||
ColumnDefinitions = new ColumnDefinitions("*,252")
|
||||
ColumnDefinitions = new ColumnDefinitions("180,*")
|
||||
};
|
||||
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);
|
||||
page.Children.Add(Card(new ScrollViewer { Content = categories }));
|
||||
var content = Card(body);
|
||||
content.Margin = new Thickness(14, 0, 0, 0);
|
||||
Grid.SetColumn(content, 1);
|
||||
page.Children.Add(content);
|
||||
return page;
|
||||
}
|
||||
|
||||
private Control InstanceTable()
|
||||
{
|
||||
instances.ItemTemplate = new FuncDataTemplate<EmulatorInstance>((item, _) =>
|
||||
item is null ? null : InstanceRow(item));
|
||||
instances.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 = InstanceGrid(
|
||||
[
|
||||
HeaderCell("类型"), HeaderCell("名称"), HeaderCell("版本(API)"),
|
||||
HeaderCell("分辨率"), HeaderCell("屏幕尺寸"), HeaderCell("操作")
|
||||
])
|
||||
};
|
||||
DockPanel.SetDock(header, Dock.Top);
|
||||
panel.Children.Add(header);
|
||||
panel.Children.Add(instances);
|
||||
return panel;
|
||||
}
|
||||
|
||||
private Control InstanceRow(EmulatorInstance item)
|
||||
{
|
||||
var row = InstanceGrid(
|
||||
[
|
||||
Cell(TypeName(item.Type)), Cell(item.Name, item.Version),
|
||||
Cell(item.ApiVersion, item.Version), Cell(item.Resolution),
|
||||
Cell(item.ScreenSize), InstanceActions(item)
|
||||
]);
|
||||
row.Margin = new Thickness(0, 2);
|
||||
return row;
|
||||
}
|
||||
|
||||
private Control InstanceActions(EmulatorInstance item)
|
||||
{
|
||||
var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
|
||||
var toggle = new Button
|
||||
{
|
||||
Width = 30, Height = 30, Padding = new Thickness(0),
|
||||
Content = new PathIcon
|
||||
{
|
||||
Data = Geometry.Parse(item.IsRunning ? "M3 3H13V13H3Z" : "M4 2L13 8L4 14Z"),
|
||||
Width = 13, Height = 13
|
||||
}
|
||||
};
|
||||
ToolTip.SetTip(toggle, item.IsRunning ? "停止" : "启动");
|
||||
toggle.Click += async (_, _) => await Execute(token => ToggleInstance(item, token));
|
||||
|
||||
var edit = new Button { Content = "编辑", FontSize = 12, Padding = new Thickness(7, 3) };
|
||||
edit.Click += (_, _) => EditInstance(item);
|
||||
|
||||
var more = new Button { Content = "更多", FontSize = 12, Padding = new Thickness(7, 3) };
|
||||
more.Flyout = InstanceMenu(item);
|
||||
|
||||
panel.Children.Add(toggle);
|
||||
panel.Children.Add(edit);
|
||||
panel.Children.Add(more);
|
||||
return panel;
|
||||
}
|
||||
|
||||
private MenuFlyout InstanceMenu(EmulatorInstance item)
|
||||
{
|
||||
var menu = new MenuFlyout();
|
||||
menu.Items.Add(FlyoutItem("冷启动", () => Execute(token =>
|
||||
{
|
||||
StartInstance(item.Name, ["-bootMode", "coldboot"]);
|
||||
return Task.CompletedTask;
|
||||
})));
|
||||
menu.Items.Add(FlyoutItem("无窗口启动", () => Execute(token =>
|
||||
{
|
||||
StartInstance(item.Name, ["-noWindow"]);
|
||||
return Task.CompletedTask;
|
||||
})));
|
||||
menu.Items.Add(FlyoutItem("擦除用户数据", () => Execute(token =>
|
||||
{
|
||||
StartInstance(item.Name, ["-bootMode", "reset"]);
|
||||
return Task.CompletedTask;
|
||||
})));
|
||||
menu.Items.Add(FlyoutItem("显示在磁盘上", () =>
|
||||
{
|
||||
ShowInDisk(item);
|
||||
return Task.CompletedTask;
|
||||
}));
|
||||
menu.Items.Add(FlyoutItem("生成日志", () => Execute(token => GenerateLog(item, token))));
|
||||
menu.Items.Add(FlyoutItem("删除", () => Execute(token => DeleteInstance(item, token))));
|
||||
return menu;
|
||||
}
|
||||
|
||||
private static MenuItem FlyoutItem(string text, Func<Task> action)
|
||||
{
|
||||
var item = new MenuItem { Header = text };
|
||||
item.Click += async (_, _) => await action();
|
||||
return item;
|
||||
}
|
||||
|
||||
private static Grid InstanceGrid(Control[] cells)
|
||||
{
|
||||
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("70,1.1*,1.35*,100,90,150") };
|
||||
for (var index = 0; index < cells.Length; index++)
|
||||
{
|
||||
Grid.SetColumn(cells[index], index);
|
||||
grid.Children.Add(cells[index]);
|
||||
}
|
||||
return grid;
|
||||
}
|
||||
|
||||
private static TextBlock HeaderCell(string text) => new()
|
||||
{
|
||||
Text = text, FontSize = 12, FontWeight = FontWeight.SemiBold,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
};
|
||||
|
||||
private static TextBlock Cell(string text, string? tooltip = null)
|
||||
{
|
||||
var cell = new TextBlock
|
||||
{
|
||||
Text = text, FontSize = 13, VerticalAlignment = VerticalAlignment.Center,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
};
|
||||
if (!string.IsNullOrEmpty(tooltip))
|
||||
ToolTip.SetTip(cell, tooltip);
|
||||
return cell;
|
||||
}
|
||||
|
||||
private static string TypeName(string type) =>
|
||||
DeviceCatalog.TypeNames.TryGetValue(type, out var label) ? label : type;
|
||||
|
||||
private static Control Table<T>(ListBox list, string columns, string[] headings, Func<T, string[]> cells)
|
||||
where T : class
|
||||
{
|
||||
|
||||
@@ -0,0 +1,475 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Templates;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
|
||||
internal sealed class NewEmulatorWindow : Window
|
||||
{
|
||||
private readonly string executable;
|
||||
private readonly Action<string> log;
|
||||
private readonly Action onCreated;
|
||||
private readonly TreeView deviceTypes = new();
|
||||
private readonly ListBox profiles = new() { MinHeight = 220 };
|
||||
private readonly ListBox images = new() { MinHeight = 220 };
|
||||
private readonly TextBox name = new() { Watermark = "例如 My Phone" };
|
||||
private readonly TextBox memory = new() { Text = "4", Watermark = "GB(2~32)" };
|
||||
private readonly TextBox storage = new() { Text = "8", Watermark = "GB(2~1023)" };
|
||||
private readonly CheckBox hotBoot = new() { Content = "启用快速启动(快照)", IsChecked = true };
|
||||
private readonly TextBlock status = new() { Text = "选择系统镜像", TextTrimming = TextTrimming.CharacterEllipsis };
|
||||
private readonly ContentControl stepHost = new();
|
||||
private readonly Control[] stepPages = new Control[3];
|
||||
private readonly TextBlock selectionSummary = new() { TextWrapping = TextWrapping.Wrap };
|
||||
private readonly Button back = new() { Content = "上一步", IsVisible = false };
|
||||
private readonly Button next = new() { Content = "下一步", IsEnabled = false };
|
||||
private readonly Button finish = new() { Content = "完成", IsVisible = false };
|
||||
private string deviceType = "";
|
||||
private EmulatorImage[] allImages = [];
|
||||
private EmulatorProfile? selectedProfile;
|
||||
private EmulatorImage? selectedImage;
|
||||
private int step;
|
||||
private CancellationTokenSource? active;
|
||||
|
||||
internal NewEmulatorWindow(string executable, Action<string> log, Action onCreated)
|
||||
{
|
||||
this.executable = executable;
|
||||
this.log = log;
|
||||
this.onCreated = onCreated;
|
||||
Title = "新建模拟器";
|
||||
Width = 900;
|
||||
Height = 640;
|
||||
MinWidth = 700;
|
||||
MinHeight = 500;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
|
||||
profiles.ItemTemplate = new FuncDataTemplate<EmulatorProfile>((item, _) =>
|
||||
item is null ? null : ProfileRow(item));
|
||||
images.ItemTemplate = new FuncDataTemplate<EmulatorImage>((item, _) =>
|
||||
item is null ? null : ImageRow(item));
|
||||
deviceTypes.ItemsSource = DeviceCatalog.Categories
|
||||
.Where(node => node.Value.Length > 0 || node.Children.Length > 0)
|
||||
.Select(DeviceCatalog.CreateItem).ToArray();
|
||||
deviceTypes.SelectionChanged += (_, _) => OnDeviceTypeChanged();
|
||||
profiles.SelectionChanged += (_, _) =>
|
||||
{
|
||||
selectedProfile = profiles.SelectedItem as EmulatorProfile;
|
||||
UpdateButtons();
|
||||
};
|
||||
images.SelectionChanged += (_, _) =>
|
||||
{
|
||||
selectedImage = images.SelectedItem as EmulatorImage;
|
||||
UpdateSelectionSummary();
|
||||
UpdateButtons();
|
||||
};
|
||||
name.TextChanged += (_, _) => UpdateButtons();
|
||||
Closing += (_, _) => active?.Cancel();
|
||||
back.Click += (_, _) => GoStep(step - 1);
|
||||
next.Click += (_, _) => GoStep(step + 1);
|
||||
finish.Click += async (_, _) => await CreateAsync();
|
||||
stepPages[0] = SplitPage("选择系统镜像", ImageTable(), new ScrollViewer { Content = deviceTypes }, () => LoadImages());
|
||||
stepPages[1] = SplitPage("选择设备型号", profiles, selectionSummary, () => LoadProfiles());
|
||||
stepPages[2] = ConfigPage();
|
||||
Content = BuildLayout();
|
||||
SelectDeviceType("phone");
|
||||
}
|
||||
|
||||
private Control BuildLayout()
|
||||
{
|
||||
var layout = new Grid
|
||||
{
|
||||
Margin = new Thickness(20),
|
||||
RowDefinitions = new RowDefinitions("Auto,*,Auto,Auto")
|
||||
};
|
||||
layout.Children.Add(new TextBlock
|
||||
{
|
||||
Text = "新建模拟器", FontSize = 22, FontWeight = FontWeight.SemiBold
|
||||
});
|
||||
Grid.SetRow(stepHost, 1);
|
||||
layout.Children.Add(stepHost);
|
||||
Grid.SetRow(status, 2);
|
||||
status.Margin = new Thickness(0, 10, 0, 4);
|
||||
layout.Children.Add(status);
|
||||
var buttons = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
Spacing = 8
|
||||
};
|
||||
var cancel = new Button { Content = "取消" };
|
||||
cancel.Click += (_, _) => Close();
|
||||
buttons.Children.Add(cancel);
|
||||
buttons.Children.Add(back);
|
||||
buttons.Children.Add(next);
|
||||
buttons.Children.Add(finish);
|
||||
Grid.SetRow(buttons, 3);
|
||||
layout.Children.Add(buttons);
|
||||
GoStep(0);
|
||||
return layout;
|
||||
}
|
||||
|
||||
private Control SplitPage(string title, Control list, Control sidebar, Func<Task> loader)
|
||||
{
|
||||
var refresh = new Button { Content = "刷新" };
|
||||
refresh.Click += (_, _) => _ = loader();
|
||||
var header = new DockPanel();
|
||||
DockPanel.SetDock(refresh, Dock.Right);
|
||||
header.Children.Add(refresh);
|
||||
header.Children.Add(Caption(title));
|
||||
var body = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
|
||||
AddRow(body, header, 0);
|
||||
AddRow(body, Card(list), 1);
|
||||
var page = new Grid { ColumnDefinitions = new ColumnDefinitions("180,*") };
|
||||
page.Children.Add(Card(sidebar));
|
||||
var content = Card(body);
|
||||
content.Margin = new Thickness(14, 0, 0, 0);
|
||||
Grid.SetColumn(content, 1);
|
||||
page.Children.Add(content);
|
||||
return page;
|
||||
}
|
||||
|
||||
private Control ConfigPage()
|
||||
{
|
||||
var panel = new StackPanel { Spacing = 12 };
|
||||
panel.Children.Add(Caption("模拟器配置"));
|
||||
panel.Children.Add(Field("实例名称", name));
|
||||
panel.Children.Add(Field("内存(GB)", memory));
|
||||
panel.Children.Add(Field("存储(GB)", storage));
|
||||
panel.Children.Add(hotBoot);
|
||||
var summary = new TextBlock
|
||||
{
|
||||
Text = $"镜像:{selectedImage?.Version ?? "未选择"}\n" +
|
||||
$"型号:{selectedProfile?.Model ?? "未选择"}\n" +
|
||||
$"设备类型:{DeviceCatalog.TypeNames.GetValueOrDefault(selectedImage?.Type ?? deviceType, selectedImage?.Type ?? deviceType)}",
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
Opacity = 0.8
|
||||
};
|
||||
panel.Children.Add(summary);
|
||||
return new Border { Child = Card(panel), VerticalAlignment = VerticalAlignment.Top };
|
||||
}
|
||||
|
||||
private static Control ProfileRow(EmulatorProfile item) => new TextBlock
|
||||
{
|
||||
Text = $"{item.Model} {item.Details.ReplaceLineEndings(" ")}",
|
||||
FontSize = 13,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis,
|
||||
TextWrapping = TextWrapping.NoWrap
|
||||
};
|
||||
|
||||
private Control ImageTable()
|
||||
{
|
||||
images.ItemTemplate = new FuncDataTemplate<EmulatorImage>((item, _) =>
|
||||
item is null ? null : ImageRow(item));
|
||||
images.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 = ImageGrid(
|
||||
[
|
||||
HeaderCell("名称"), HeaderCell("版本(API)"), HeaderCell("操作")
|
||||
])
|
||||
};
|
||||
DockPanel.SetDock(header, Dock.Top);
|
||||
panel.Children.Add(header);
|
||||
panel.Children.Add(images);
|
||||
return panel;
|
||||
}
|
||||
|
||||
private Control ImageRow(EmulatorImage item)
|
||||
{
|
||||
var action = new Button
|
||||
{
|
||||
Content = item.Downloaded == "已下载" ? "删除" : "下载",
|
||||
FontSize = 12,
|
||||
Padding = new Thickness(8, 3),
|
||||
HorizontalAlignment = HorizontalAlignment.Left
|
||||
};
|
||||
action.Click += async (_, _) => await ToggleImageAsync(item, item.Downloaded != "已下载");
|
||||
var row = ImageGrid([ImageCell(item.Version), ImageCell(item.ApiVersion), action]);
|
||||
row.Margin = new Thickness(0, 2);
|
||||
return row;
|
||||
}
|
||||
|
||||
private static Grid ImageGrid(Control[] cells)
|
||||
{
|
||||
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("2*,1*,76") };
|
||||
for (var index = 0; index < cells.Length; index++)
|
||||
{
|
||||
Grid.SetColumn(cells[index], index);
|
||||
grid.Children.Add(cells[index]);
|
||||
}
|
||||
return grid;
|
||||
}
|
||||
|
||||
private static TextBlock HeaderCell(string text) => new()
|
||||
{
|
||||
Text = text, FontSize = 12, FontWeight = FontWeight.SemiBold,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
};
|
||||
|
||||
private static TextBlock ImageCell(string text) => new()
|
||||
{
|
||||
Text = text, FontSize = 13, VerticalAlignment = VerticalAlignment.Center,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis
|
||||
};
|
||||
|
||||
private void SelectDeviceType(string value)
|
||||
{
|
||||
foreach (var item in deviceTypes.Items.Cast<TreeViewItem>())
|
||||
{
|
||||
if (item.Tag is not DeviceCategory group)
|
||||
continue;
|
||||
var match = group.Value == value ? group : group.Children.FirstOrDefault(child => child.Value == value);
|
||||
if (match is null)
|
||||
continue;
|
||||
deviceTypes.SelectedItem = item.Items.OfType<TreeViewItem>()
|
||||
.FirstOrDefault(child => (child.Tag as DeviceCategory)?.Value == value) ?? item;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ToggleImageAsync(EmulatorImage image, bool install)
|
||||
{
|
||||
if (active is not null)
|
||||
return;
|
||||
using var source = new CancellationTokenSource();
|
||||
active = source;
|
||||
status.Text = install ? "正在下载镜像…" : "正在删除镜像…";
|
||||
try
|
||||
{
|
||||
string[] args = install
|
||||
? ["-install", "-deviceType", image.Type, "-osVersion", image.Version]
|
||||
: ["-uninstall", "-deviceType", image.Type, "-osVersion", image.Version, "-force"];
|
||||
await EmulatorCli.RunAsync(executable, args, log, source.Token);
|
||||
active = null;
|
||||
await LoadImages();
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
status.Text = error.Message;
|
||||
log(error.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
active = null;
|
||||
UpdateButtons();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDeviceTypeChanged()
|
||||
{
|
||||
var node = (deviceTypes.SelectedItem as TreeViewItem)?.Tag as DeviceCategory;
|
||||
deviceType = node?.Value ?? "";
|
||||
profiles.ItemsSource = null;
|
||||
selectedProfile = null;
|
||||
selectedImage = null;
|
||||
ApplyImageFilter();
|
||||
UpdateSelectionSummary();
|
||||
UpdateButtons();
|
||||
_ = LoadImages();
|
||||
}
|
||||
|
||||
private void ApplyImageFilter()
|
||||
{
|
||||
var node = (deviceTypes.SelectedItem as TreeViewItem)?.Tag as DeviceCategory;
|
||||
images.ItemsSource = node switch
|
||||
{
|
||||
null => allImages,
|
||||
{ Value.Length: > 0 } => allImages.Where(item => item.Type == node.Value).ToArray(),
|
||||
{ Children.Length: > 0 } => allImages.Where(item =>
|
||||
node.Children.Any(child => child.Value == item.Type)).ToArray(),
|
||||
_ => allImages
|
||||
};
|
||||
}
|
||||
|
||||
private void UpdateSelectionSummary()
|
||||
{
|
||||
var type = selectedImage?.Type ?? deviceType;
|
||||
selectionSummary.Text = $"设备类型:{DeviceCatalog.TypeNames.GetValueOrDefault(type, type)}\n" +
|
||||
$"镜像:{selectedImage?.Version ?? "未选择"}";
|
||||
}
|
||||
|
||||
private async Task LoadProfiles()
|
||||
{
|
||||
var type = selectedImage?.Type ?? deviceType;
|
||||
if (active is not null || type.Length == 0)
|
||||
return;
|
||||
using var source = new CancellationTokenSource();
|
||||
active = source;
|
||||
status.Text = "正在读取设备型号…";
|
||||
try
|
||||
{
|
||||
var raw = await EmulatorCli.RunAsync(executable,
|
||||
["-screenProfileList", "-deviceType", type, "-details"], log, source.Token);
|
||||
var items = EmulatorCli.Profiles(raw);
|
||||
profiles.ItemsSource = items;
|
||||
selectedProfile = null;
|
||||
status.Text = $"已读取 {items.Length} 个设备型号。";
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
status.Text = error.Message;
|
||||
log(error.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
active = null;
|
||||
UpdateButtons();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadImages()
|
||||
{
|
||||
if (active is not null)
|
||||
return;
|
||||
using var source = new CancellationTokenSource();
|
||||
active = source;
|
||||
status.Text = "正在读取系统镜像…";
|
||||
try
|
||||
{
|
||||
var raw = await EmulatorCli.RunAsync(executable, ["-imageList"], log, source.Token);
|
||||
allImages = EmulatorCli.Images(raw);
|
||||
selectedImage = null;
|
||||
ApplyImageFilter();
|
||||
status.Text = $"已读取 {images.Items.Count} 个镜像。";
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
status.Text = error.Message;
|
||||
log(error.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
active = null;
|
||||
UpdateButtons();
|
||||
}
|
||||
}
|
||||
|
||||
private void GoStep(int index)
|
||||
{
|
||||
step = Math.Clamp(index, 0, 2);
|
||||
stepHost.Content = stepPages[step];
|
||||
status.Text = step switch
|
||||
{
|
||||
0 => "选择系统镜像",
|
||||
1 => "选择设备型号",
|
||||
_ => "配置模拟器"
|
||||
};
|
||||
if (step == 1)
|
||||
_ = LoadProfiles();
|
||||
if (step == 2 && string.IsNullOrWhiteSpace(name.Text) && selectedProfile is not null)
|
||||
name.Text = selectedProfile.Model.Replace(" ", "");
|
||||
UpdateButtons();
|
||||
}
|
||||
|
||||
private void UpdateButtons()
|
||||
{
|
||||
back.IsVisible = step > 0;
|
||||
next.IsVisible = step < 2;
|
||||
finish.IsVisible = step == 2;
|
||||
next.IsEnabled = step switch
|
||||
{
|
||||
0 => selectedImage is not null,
|
||||
1 => selectedProfile is not null,
|
||||
_ => false
|
||||
};
|
||||
finish.IsEnabled = step == 2 && selectedProfile is not null && selectedImage is not null
|
||||
&& !string.IsNullOrWhiteSpace(name.Text);
|
||||
}
|
||||
|
||||
private async Task CreateAsync()
|
||||
{
|
||||
if (active is not null)
|
||||
return;
|
||||
var target = name.Text?.Trim();
|
||||
if (string.IsNullOrEmpty(target) || target.StartsWith('-'))
|
||||
{
|
||||
status.Text = "请输入有效的实例名称。";
|
||||
return;
|
||||
}
|
||||
var imageType = selectedImage!.Type;
|
||||
var args = new List<string>
|
||||
{
|
||||
"-create", target, "-deviceType", imageType,
|
||||
"-osVersion", selectedImage.Version,
|
||||
"-screenProfile", selectedProfile!.Model
|
||||
};
|
||||
if (!TryNumber(memory.Text, 2, 32, out var memorySize))
|
||||
{
|
||||
status.Text = "内存需为 2~32 之间的整数。";
|
||||
return;
|
||||
}
|
||||
if (!TryNumber(storage.Text, 2, 1023, out var storageSize))
|
||||
{
|
||||
status.Text = "存储需为 2~1023 之间的整数。";
|
||||
return;
|
||||
}
|
||||
args.AddRange(["-memory", memorySize.ToString(), "-storage", storageSize.ToString()]);
|
||||
if (hotBoot.IsChecked == true)
|
||||
args.AddRange(["-hotBoot", "true"]);
|
||||
|
||||
using var source = new CancellationTokenSource();
|
||||
active = source;
|
||||
status.Text = "正在创建模拟器…";
|
||||
try
|
||||
{
|
||||
if (selectedImage!.Downloaded == "未下载")
|
||||
{
|
||||
status.Text = "正在下载系统镜像…";
|
||||
await EmulatorCli.RunAsync(executable,
|
||||
["-install", "-deviceType", imageType, "-osVersion", selectedImage.Version],
|
||||
log, source.Token);
|
||||
status.Text = "正在创建模拟器…";
|
||||
}
|
||||
await EmulatorCli.RunAsync(executable, [.. args], log, source.Token);
|
||||
onCreated();
|
||||
Close();
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
status.Text = error.Message;
|
||||
log(error.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
active = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryNumber(string? text, int min, int max, out int value) =>
|
||||
int.TryParse(text, out value) && value >= min && value <= max;
|
||||
|
||||
private static TextBlock Caption(string text) => new()
|
||||
{
|
||||
Text = text, FontSize = 15, FontWeight = FontWeight.SemiBold
|
||||
};
|
||||
|
||||
private static StackPanel Field(string label, Control field)
|
||||
{
|
||||
var panel = new StackPanel { Spacing = 4 };
|
||||
panel.Children.Add(new TextBlock { Text = label, FontSize = 12, Opacity = 0.78 });
|
||||
panel.Children.Add(field);
|
||||
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 AddRow(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);
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,11 @@
|
||||
dotnet run --project EmulatorManager.csproj
|
||||
```
|
||||
|
||||
可在「工具设置」中编辑 Emulator 路径,或预先设置环境变量 `HARMONY_EMULATOR`。程序也会尝试 `DEVECO_CLI_CLT_PATH`、常见安装目录和 PATH。Linux 上请按华为要求配置 KVM,必要时勾选无窗口启动。
|
||||
可在「工具设置」中编辑 Emulator 路径,或预先设置环境变量 `HARMONY_EMULATOR`。程序也会尝试 `DEVECO_CLI_CLT_PATH`、常见安装目录和 PATH。Linux 上请按华为要求配置 KVM,必要时从实例行的「更多」中选择无窗口启动。
|
||||
|
||||
- **模拟器实例**支持刷新、启动、停止、删除。
|
||||
- **系统镜像**支持查询全部和已下载镜像、下载、删除,也可用所选镜像创建实例。创建时填入实例名称。
|
||||
- 可在「工具设置」中查看许可并确认接受。底部可展开命令输出。
|
||||
- **模拟器实例**支持刷新、启动、停止、删除;主页每 3 秒自动查询一次运行状态,启停按钮会随状态切换。
|
||||
- **系统镜像**窗口打开时自动拉取在线全部镜像,左侧按设备分类筛选,也可查询已下载镜像。
|
||||
- 主页左下角「命令输出」按钮打开独立输出窗口;右下角「创建模拟器」打开新建向导(默认手机分类;镜像列表含名称/版本(API)/下载或删除操作,选择系统镜像 → 设备型号 → 配置名称/内存/存储,未下载镜像会自动下载),右上角「设置」打开工具设置窗口。可在工具设置中查看许可并确认接受。
|
||||
|
||||
## 构建、运行并同步
|
||||
|
||||
|
||||
Reference in new issue
Block a user