782 lines
27 KiB
C#
782 lines
27 KiB
C#
using System.Diagnostics;
|
|
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 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();
|
|
private readonly TextBlock status = new()
|
|
{
|
|
Text = "就绪", VerticalAlignment = VerticalAlignment.Center,
|
|
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 LanDebugPanel? lanDebug;
|
|
private DispatcherTimer? statusTimer;
|
|
private bool shuttingDown;
|
|
private CancellationTokenSource? active;
|
|
private static readonly string LogPath = Path.Combine(
|
|
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "emulator-manager.log");
|
|
|
|
private static void WriteLogFile(string line)
|
|
{
|
|
try
|
|
{
|
|
if (File.Exists(LogPath) && new FileInfo(LogPath).Length > 5 * 1024 * 1024)
|
|
File.Move(LogPath, LogPath + ".1", true);
|
|
File.AppendAllText(LogPath, $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {line}{Environment.NewLine}");
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
}
|
|
|
|
internal MainWindow(bool smoke, Action<int> shutdown)
|
|
{
|
|
smokeMode = smoke;
|
|
Title = "HarmonyOS Emulator 管理器";
|
|
Width = 1280;
|
|
Height = 820;
|
|
MinWidth = 780;
|
|
MinHeight = 570;
|
|
executable.TextChanged += (_, _) =>
|
|
{
|
|
allInstances = [];
|
|
allImages = [];
|
|
instances.ItemsSource = null;
|
|
images.ItemsSource = null;
|
|
};
|
|
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;
|
|
active.Cancel();
|
|
status.Text = "正在取消命令,请稍后关闭。";
|
|
}
|
|
};
|
|
|
|
output.ItemTemplate = new FuncDataTemplate<string>((line, _) => new TextBlock
|
|
{
|
|
Text = line, FontFamily = new FontFamily("monospace"), FontSize = 12,
|
|
TextWrapping = TextWrapping.Wrap
|
|
});
|
|
|
|
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, 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)
|
|
{
|
|
Opened += async (_, _) =>
|
|
{
|
|
try
|
|
{
|
|
// Recycling a visible row asks its template to build null content.
|
|
instances.ItemTemplate?.Build(null);
|
|
images.ItemTemplate?.Build(null);
|
|
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);
|
|
Dispatcher.UIThread.Post(() => shutdown(1));
|
|
}
|
|
};
|
|
}
|
|
else
|
|
{
|
|
statusTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
|
|
statusTimer.Tick += (_, _) => _ = RefreshInstancesSilently();
|
|
Opened += async (_, _) =>
|
|
{
|
|
await Execute(RefreshInstances);
|
|
statusTimer.Start();
|
|
};
|
|
}
|
|
}
|
|
|
|
private async Task RefreshInstances(CancellationToken token)
|
|
{
|
|
allInstances = await ReadList(token, EmulatorCli.Instances, "-list", "-details");
|
|
ApplyCategoryFilter();
|
|
lanDebug?.Refresh();
|
|
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();
|
|
lanDebug?.Refresh();
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
}
|
|
|
|
private async Task RefreshImages(CancellationToken token, bool downloaded)
|
|
{
|
|
status.Text = downloaded ? "正在读取已下载镜像…" : "正在拉取全部镜像…";
|
|
allImages = await ReadList(token, EmulatorCli.Images, downloaded
|
|
? ["-imageList", "-downloaded", "true"] : ["-imageList"]);
|
|
ApplyImageCategoryFilter();
|
|
AppendOutput($"已读取 {allImages.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 void StartInstance(string target, string[] extra)
|
|
{
|
|
var path = Required(executable, "Emulator 路径");
|
|
if (!starting.Add((path, target)))
|
|
throw new InvalidOperationException($"「{target}」已有启动进程。");
|
|
string[] args = ["-start", target, .. extra];
|
|
try
|
|
{
|
|
EmulatorCli.StartDetached(path, args, AppendOutput);
|
|
AppendOutput($"「{target}」已独立启动,可刷新列表查看状态,也可直接停止实例。");
|
|
_ = Task.Delay(TimeSpan.FromSeconds(5)).ContinueWith(_ => starting.Remove((path, target)));
|
|
}
|
|
catch (Exception error)
|
|
{
|
|
starting.Remove((path, target));
|
|
throw new InvalidOperationException($"「{target}」启动失败:{error.Message}", error);
|
|
}
|
|
}
|
|
|
|
private async Task ToggleInstance(EmulatorInstance instance, CancellationToken token)
|
|
{
|
|
if (instance.IsRunning)
|
|
{
|
|
await Run(token, "-stop", instance.Name);
|
|
await RefreshInstances(token);
|
|
}
|
|
else
|
|
{
|
|
StartInstance(instance.Name, ["-bootMode", "snapshot"]);
|
|
}
|
|
}
|
|
|
|
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);
|
|
|
|
private void AppendOutput(string line) => Dispatcher.UIThread.Post(() =>
|
|
{
|
|
WriteLogFile(line);
|
|
if (output.ItemCount >= 1500)
|
|
output.Items.RemoveAt(0);
|
|
output.Items.Add(line);
|
|
ShowOutput();
|
|
});
|
|
|
|
private void ShowOutput()
|
|
{
|
|
if (outputWindow?.IsVisible == true && output.ItemCount > 0)
|
|
output.ScrollIntoView(output.ItemCount - 1);
|
|
}
|
|
|
|
private Button OutputCommand(string label, string argument) => Command(label, token =>
|
|
{
|
|
ShowOutput();
|
|
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 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");
|
|
}
|
|
})));
|
|
lanDebug ??= new LanDebugPanel(AppendOutput, () => allInstances);
|
|
settings.Children.Add(Caption("局域网调试"));
|
|
settings.Children.Add(lanDebug.Content);
|
|
settings.Children.Add(Caption("日志"));
|
|
settings.Children.Add(new TextBlock
|
|
{
|
|
Text = LogPath, FontSize = 12, Opacity = 0.78, TextWrapping = TextWrapping.Wrap
|
|
});
|
|
var openLog = new Button { Content = "打开日志文件" };
|
|
openLog.Click += (_, _) =>
|
|
{
|
|
try
|
|
{
|
|
Process.Start(new ProcessStartInfo(LogPath) { UseShellExecute = true });
|
|
}
|
|
catch (Exception error)
|
|
{
|
|
AppendOutput(error.Message);
|
|
}
|
|
};
|
|
settings.Children.Add(openLog);
|
|
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)
|
|
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);
|
|
ShowOutput();
|
|
}
|
|
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>(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();
|
|
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 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("模拟器实例"));
|
|
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("180,*")
|
|
};
|
|
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
|
|
{
|
|
// Avalonia clears the content to null before reusing a virtualized row.
|
|
list.ItemTemplate = new FuncDataTemplate<T>((item, _) =>
|
|
item is null ? null : 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);
|
|
}
|
|
}
|