步骤界面增加配置导入导出并保护区域引用及现有编辑内容
This commit is contained in:
parent
2575d6ac8e
commit
3d6169a400
@ -111,6 +111,13 @@
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<DockPanel>
|
||||
<StackPanel DockPanel.Dock="Top" Spacing="6" Margin="0,0,0,8">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" IsEnabled="{Binding CanTransferSteps}">
|
||||
<Button Content="导入步骤" Click="ImportStepsFile" ToolTip.Tip="从步骤文件或完整配方导入,可选择追加或替换" />
|
||||
<Button Content="导出步骤" Click="ExportStepsFile" ToolTip.Tip="导出全部步骤及关联区域,保留触发、AI判定与复检设置" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding StepTransferStatus}" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
|
||||
</StackPanel>
|
||||
<Button DockPanel.Dock="Bottom" Content="加步骤" Margin="0,8,0,0" Padding="0,6" Command="{Binding Recipe.AddStepCommand}" />
|
||||
<ListBox ItemTemplate="{StaticResource StepRow}" ItemsSource="{Binding Recipe.Steps}" SelectedItem="{Binding Recipe.SelectedStep}" Classes="Pick" />
|
||||
</DockPanel>
|
||||
|
||||
@ -111,6 +111,10 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
OpenImageCommand = new DelegateCommand(OpenImage, () => !IsCapturing);
|
||||
CaptureStandardVideoImageCommand = new DelegateCommand(async () => await CaptureStandardVideoImageAsync(), () => !IsCapturing);
|
||||
InitializeAgentCommands();
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName is nameof(IsAgentBusy) or nameof(IsCapturing)) RaisePropertyChanged(nameof(CanTransferSteps));
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@ -286,6 +290,7 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
foreach (var warning in saved.Warnings) Warnings.Add(warning);
|
||||
|
||||
SaveStatus = $"已保存 {Path.GetFileName(_path)}";
|
||||
StepTransferStatus = "";
|
||||
_onSaved?.Invoke(Path.GetFileName(_path));
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
86
src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTransferView.cs
Normal file
86
src/SopHelper.Avalonia/VVMs/RecipeEditor/StepTransferView.cs
Normal file
@ -0,0 +1,86 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Platform.Storage;
|
||||
using SopHelper.Engine.Sop;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace SopHelper.VVMs.RecipeEditor;
|
||||
|
||||
public partial class RecipeEditor
|
||||
{
|
||||
private bool _stepTransferInProgress;
|
||||
private async void ImportStepsFile(object? sender, RoutedEventArgs args)
|
||||
{
|
||||
if (_stepTransferInProgress || _model is not { CanTransferSteps: true } model || TopLevel.GetTopLevel(this) is not Window owner) return;
|
||||
_stepTransferInProgress = true;
|
||||
try
|
||||
{
|
||||
var files = await owner.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "导入步骤或配方文件", AllowMultiple = false,
|
||||
FileTypeFilter = [new("SOP步骤 / 配方") { Patterns = ["*.yaml", "*.yml", "*.json"] }]
|
||||
});
|
||||
if (files.Count == 0 || _closing || !ReferenceEquals(model, _model)) return;
|
||||
var path = files[0].TryGetLocalPath() ?? throw new IOException("请选择本地步骤文件");
|
||||
if (new FileInfo(path).Length > 8 * 1024 * 1024) throw new IOException("步骤文件超过8MB");
|
||||
var incoming = SopStepTransfer.Read(await File.ReadAllTextAsync(path));
|
||||
var mode = model.Recipe.Steps.Count == 0 ? "replace" : await ChooseStepImportMode(incoming.Sop.Steps.Count, model.Recipe.Steps.Count);
|
||||
if (mode is null || _closing || !ReferenceEquals(model, _model)) return;
|
||||
model.ImportSteps(incoming, mode == "append");
|
||||
}
|
||||
catch (Exception error) { await ShowNotice("导入步骤失败", error.Message, false); }
|
||||
finally { _stepTransferInProgress = false; }
|
||||
}
|
||||
|
||||
private async void ExportStepsFile(object? sender, RoutedEventArgs args)
|
||||
{
|
||||
if (_stepTransferInProgress || _model is not { CanTransferSteps: true } model || TopLevel.GetTopLevel(this) is not Window owner) return;
|
||||
_stepTransferInProgress = true;
|
||||
string? temporary = null;
|
||||
try
|
||||
{
|
||||
var text = model.ExportStepsText();
|
||||
var count = model.Recipe.Steps.Count;
|
||||
var name = string.Concat(model.Recipe.Name.Select(c => Path.GetInvalidFileNameChars().Contains(c) ? '_' : c));
|
||||
var file = await owner.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
|
||||
{
|
||||
Title = "导出全部步骤", SuggestedFileName = name + ".steps.yaml", DefaultExtension = "yaml", ShowOverwritePrompt = true,
|
||||
FileTypeChoices = [new("SOP步骤文件") { Patterns = ["*.yaml"] }]
|
||||
});
|
||||
if (file is null || _closing || !ReferenceEquals(model, _model)) return;
|
||||
var path = file.TryGetLocalPath() ?? throw new IOException("请选择本地保存位置");
|
||||
if (model.IsCurrentRecipeFile(path)) throw new IOException("步骤导出不能覆盖当前配方文件,请选择其他文件名");
|
||||
temporary = Path.Combine(Path.GetDirectoryName(path)!, ".steps-export-" + Guid.NewGuid().ToString("N") + ".tmp");
|
||||
await File.WriteAllTextAsync(temporary, text, new UTF8Encoding(false));
|
||||
File.Move(temporary, path, overwrite: true);
|
||||
model.StepTransferStatus = $"已导出 {count} 个步骤:{Path.GetFileName(path)}";
|
||||
}
|
||||
catch (Exception error) { await ShowNotice("导出步骤失败", error.Message, false); }
|
||||
finally
|
||||
{
|
||||
try { if (temporary is not null && File.Exists(temporary)) File.Delete(temporary); }
|
||||
catch (Exception cleanup) when (cleanup is IOException or UnauthorizedAccessException) { }
|
||||
_stepTransferInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string?> ChooseStepImportMode(int incoming, int current)
|
||||
{
|
||||
if (_closing || _dialog is not null || TopLevel.GetTopLevel(this) is not Window owner) return null;
|
||||
var actions = new StackPanel { Orientation = Avalonia.Layout.Orientation.Horizontal, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right, Spacing = 8 };
|
||||
var dialog = new Window { Title = "导入步骤", Width = 500, SizeToContent = SizeToContent.Height, CanResize = false, WindowStartupLocation = WindowStartupLocation.CenterOwner,
|
||||
Content = new StackPanel { Margin = new Avalonia.Thickness(20), Spacing = 18, Children =
|
||||
{
|
||||
new TextBlock { Text = $"文件含 {incoming} 个步骤,当前有 {current} 个步骤。\n请选择追加或替换。关联区域将一并导入,同名但坐标不同的区域会自动改名。导入后可继续编辑,点击“保存”才写入配方。", TextWrapping = Avalonia.Media.TextWrapping.Wrap }, actions
|
||||
} } };
|
||||
foreach (var (label, mode) in new[] { ("取消", ""), ("追加步骤", "append"), ("替换步骤", "replace") })
|
||||
{
|
||||
var button = new Button { Content = label, IsCancel = mode.Length == 0, IsDefault = mode.Length == 0 };
|
||||
button.Click += (_, _) => dialog.Close(mode); actions.Children.Add(button);
|
||||
}
|
||||
_dialog = dialog;
|
||||
try { var result = await dialog.ShowDialog<object?>(owner); return result is string mode && mode.Length > 0 ? mode : null; }
|
||||
finally { _dialog = null; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,36 @@
|
||||
using SopHelper.Engine.Sop;
|
||||
|
||||
namespace SopHelper.VVMs.RecipeEditor;
|
||||
|
||||
public partial class RecipeEditorViewModel
|
||||
{
|
||||
private string _stepTransferStatus = "";
|
||||
public string StepTransferStatus { get => _stepTransferStatus; set => SetProperty(ref _stepTransferStatus, value); }
|
||||
public bool CanTransferSteps => !IsAgentBusy && !IsCapturing && !_closingDialog;
|
||||
|
||||
public string ExportStepsText() => SopStepTransfer.Export(Recipe.ToConfig());
|
||||
|
||||
public void ImportSteps(SopConfig incoming, bool append)
|
||||
{
|
||||
if (!CanTransferSteps) throw new InvalidOperationException("请等待当前分析或图像采集结束后再导入步骤");
|
||||
var firstImported = append ? Recipe.Steps.Count : 0;
|
||||
var merged = SopStepTransfer.Merge(Recipe.ToConfig(), incoming, append);
|
||||
var prepared = RecipeNode.From(merged, Recipe.FileName, Recipe.IsNew);
|
||||
// 所有解析、引用校验和节点转换先完成,失败时不改编辑中的内容。
|
||||
ClearAgentDraft();
|
||||
foreach (var region in prepared.Regions)
|
||||
if (!Recipe.Regions.Any(r => r.Key.Equals(region.Key, StringComparison.OrdinalIgnoreCase)))
|
||||
Recipe.AddRegion(region.Key).CopyFrom(merged.Sop.Regions[region.Key]);
|
||||
Recipe.Steps.Clear();
|
||||
foreach (var step in prepared.Steps) Recipe.Steps.Add(step);
|
||||
foreach (var part in prepared.Parts.Items)
|
||||
if (!Recipe.Parts.Items.Any(p => p.Text.Equals(part.Text, StringComparison.OrdinalIgnoreCase)))
|
||||
Recipe.Parts.Items.Add(new TextItem { Text = part.Text, RemoveCommand = Recipe.Parts.RemoveCommand });
|
||||
Recipe.SelectedStep = Recipe.Steps.ElementAtOrDefault(firstImported);
|
||||
RefreshWarnings();
|
||||
StepTransferStatus = $"已{(append ? "追加" : "替换导入")} {incoming.Sop.Steps.Count} 个步骤,当前共 {Recipe.Steps.Count} 步;点击“保存”后写入配方。";
|
||||
}
|
||||
|
||||
public bool IsCurrentRecipeFile(string path) => !string.IsNullOrEmpty(_path)
|
||||
&& System.IO.Path.GetFullPath(path).Equals(System.IO.Path.GetFullPath(_path), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
|
||||
}
|
||||
128
src/SopHelper.CrossPlatform.Engine/Sop/SopStepTransfer.cs
Normal file
128
src/SopHelper.CrossPlatform.Engine/Sop/SopStepTransfer.cs
Normal file
@ -0,0 +1,128 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using YamlDotNet.Serialization;
|
||||
using YamlDotNet.Serialization.NamingConventions;
|
||||
|
||||
namespace SopHelper.Engine.Sop;
|
||||
|
||||
/// <summary>使用现有配方格式交换步骤;只合并步骤、关联区域及零件名称。</summary>
|
||||
public static class SopStepTransfer
|
||||
{
|
||||
private static T Copy<T>(T value) => JsonSerializer.Deserialize<T>(JsonSerializer.Serialize(value))!;
|
||||
|
||||
public static string Export(SopConfig current)
|
||||
{
|
||||
Check(current);
|
||||
var document = new SopConfig();
|
||||
document.Sop.Name = current.Sop.Name;
|
||||
document.Sop.Description = "步骤导出:导入时仅读取步骤、关联区域和零件名称";
|
||||
document.Sop.Steps = current.Sop.Steps.Select(Copy).ToList();
|
||||
document.Sop.Parts = PartNames(document.Sop.Steps).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
foreach (var key in References(document.Sop.Steps).Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var region = Find(current.Sop.Regions, key);
|
||||
if (region is null) throw new FormatException($"步骤引用的区域“{key}”不存在,请先补全区域");
|
||||
document.Sop.Regions[key] = Copy(region);
|
||||
}
|
||||
return SopConfigLoader.ToYaml(document);
|
||||
}
|
||||
|
||||
public static SopConfig Read(string text)
|
||||
{
|
||||
if (text.Length > 8 * 1024 * 1024) throw new FormatException("步骤文件超过8MB");
|
||||
SopConfig? document;
|
||||
// JSON兼容下划线、camelCase及PascalCase;区域字典的自定义键原样保留。
|
||||
if (text.TrimStart().StartsWith('{'))
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = JsonNode.Parse(text);
|
||||
document = NormalizeJson(json)?.Deserialize<SopConfig>(new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||
}
|
||||
catch (JsonException) { document = ParseYaml(text); }
|
||||
}
|
||||
else document = ParseYaml(text);
|
||||
if (document is null) throw new FormatException("文件中没有步骤配置");
|
||||
Check(document);
|
||||
return document;
|
||||
}
|
||||
|
||||
private static SopConfig? ParseYaml(string text) => new DeserializerBuilder()
|
||||
.WithNamingConvention(UnderscoredNamingConvention.Instance).WithCaseInsensitivePropertyMatching()
|
||||
.IgnoreUnmatchedProperties().Build().Deserialize<SopConfig>(text);
|
||||
|
||||
private static JsonNode? NormalizeJson(JsonNode? node, bool dictionary = false)
|
||||
{
|
||||
if (node is JsonArray array) return new JsonArray(array.Select(n => NormalizeJson(n)).ToArray());
|
||||
if (node is not JsonObject obj) return node?.DeepClone();
|
||||
var result = new JsonObject();
|
||||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var pair in obj)
|
||||
{
|
||||
var key = dictionary ? pair.Key : pair.Key.Replace("_", "");
|
||||
if (!names.Add(key)) throw new FormatException($"重复配置字段:{pair.Key}");
|
||||
result[key] = NormalizeJson(pair.Value, !dictionary && key.Equals("regions", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static SopConfig Merge(SopConfig current, SopConfig incoming, bool append)
|
||||
{
|
||||
Check(incoming);
|
||||
var result = Copy(current);
|
||||
var existingParts = result.Sop.Parts ?? PartNames(result.Sop.Steps).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
var steps = incoming.Sop.Steps.OrderBy(s => s.Id).Select(Copy).ToList();
|
||||
var mapped = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var key in References(steps).Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var source = Find(incoming.Sop.Regions, key);
|
||||
var existingKey = result.Sop.Regions.Keys.FirstOrDefault(k => k.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||||
if (source is null)
|
||||
{
|
||||
if (existingKey is null) throw new FormatException($"步骤引用的区域“{key}”未包含在文件中,当前配方也不存在该区域");
|
||||
mapped[key] = existingKey;
|
||||
continue;
|
||||
}
|
||||
if (existingKey is not null && SameArea(result.Sop.Regions[existingKey], source)) { mapped[key] = existingKey; continue; }
|
||||
var reusable = result.Sop.Regions.FirstOrDefault(p => p.Key.StartsWith(key + "_import", StringComparison.OrdinalIgnoreCase) && SameArea(p.Value, source));
|
||||
if (reusable.Value is not null) { mapped[key] = reusable.Key; continue; }
|
||||
var target = key;
|
||||
for (var suffix = 2; result.Sop.Regions.Keys.Any(k => k.Equals(target, StringComparison.OrdinalIgnoreCase)); suffix++)
|
||||
target = $"{key}_import{suffix}";
|
||||
result.Sop.Regions[target] = Copy(source);
|
||||
mapped[key] = target;
|
||||
}
|
||||
string Map(string key) => string.IsNullOrEmpty(key) ? "" : mapped[key];
|
||||
foreach (var step in steps)
|
||||
{
|
||||
if (step.Detection is { } condition)
|
||||
{ condition.Region = Map(condition.Region); condition.FromRegion = Map(condition.FromRegion); condition.ToRegion = Map(condition.ToRegion); }
|
||||
if (step.AiConfirmation is { } ai && mapped.TryGetValue(ai.ImageRegion ?? "", out var imageRegion)) ai.ImageRegion = imageRegion;
|
||||
}
|
||||
if (!append) result.Sop.Steps.Clear();
|
||||
result.Sop.Steps.AddRange(steps);
|
||||
for (var index = 0; index < result.Sop.Steps.Count; index++) result.Sop.Steps[index].Id = index + 1;
|
||||
result.Sop.Parts = existingParts.Concat(PartNames(steps)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
return result;
|
||||
}
|
||||
|
||||
private static IEnumerable<string> References(IEnumerable<StepDef> steps) => steps.SelectMany(s => new[]
|
||||
{ s.Detection?.Region, s.Detection?.FromRegion, s.Detection?.ToRegion, s.AiConfirmation is { } ai && VisionImageMode.Resolve(ai) == VisionImageMode.FixedRegion ? ai.ImageRegion : null })
|
||||
.Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k!);
|
||||
private static IEnumerable<string> PartNames(IEnumerable<StepDef> steps) => steps.SelectMany(s => s.MustKeep.Concat(s.RequiredObjects).Append(s.Detection?.TargetObject ?? "")).Where(n => !string.IsNullOrWhiteSpace(n));
|
||||
private static RegionDef? Find(Dictionary<string, RegionDef> regions, string key)
|
||||
=> regions.FirstOrDefault(p => p.Key.Equals(key, StringComparison.OrdinalIgnoreCase)).Value;
|
||||
private static bool SameArea(RegionDef a, RegionDef b) => a.X1 == b.X1 && a.Y1 == b.Y1 && a.X2 == b.X2 && a.Y2 == b.Y2;
|
||||
private static void Check(SopConfig document)
|
||||
{
|
||||
if (document.Sop?.Steps is not { Count: > 0 and <= 1000 } steps)
|
||||
throw new FormatException("文件须包含 sop.steps(1至1000个步骤),请选择步骤导出文件或完整配方文件");
|
||||
if (steps.Any(s => s is null || string.IsNullOrWhiteSpace(s.Name) || s.MustKeep is null || s.RequiredObjects is null
|
||||
|| s.ViolationRules is null || s.ViolationRules.Any(r => r is null)))
|
||||
throw new FormatException("步骤名称或列表字段无效,未修改当前步骤");
|
||||
document.Sop.Regions ??= new();
|
||||
if (document.Sop.Regions.Any(p => string.IsNullOrWhiteSpace(p.Key) || p.Value is null)
|
||||
|| document.Sop.Regions.Keys.Distinct(StringComparer.OrdinalIgnoreCase).Count() != document.Sop.Regions.Count)
|
||||
throw new FormatException("区域名称重复或区域内容无效");
|
||||
}
|
||||
}
|
||||
@ -34,6 +34,7 @@ internal static class Program
|
||||
if (args.Contains("--live")) { LiveVideoFlowChecks.Run(args); return; }
|
||||
CheckAiFlow();
|
||||
CheckSequenceEditor();
|
||||
StepTransferChecks.Run(root);
|
||||
AgentDraftVerificationChecks.Run(root);
|
||||
StandardVideoImportChecks.Run(root);
|
||||
CheckVideoPage(root);
|
||||
|
||||
79
tests/VideoFlowTest.Smoke/StepTransferChecks.cs
Normal file
79
tests/VideoFlowTest.Smoke/StepTransferChecks.cs
Normal file
@ -0,0 +1,79 @@
|
||||
using System.Text.Json;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.VisualTree;
|
||||
using Prism.Dialogs;
|
||||
using SopHelper.Engine.Sop;
|
||||
using SopHelper.VVMs.RecipeEditor;
|
||||
|
||||
internal static class StepTransferChecks
|
||||
{
|
||||
public static void Run(string root)
|
||||
{
|
||||
var source = new SopConfig(); source.Sop.Name = "来源";
|
||||
foreach (var key in new[] { "start", "finish", "inspect_area", "unused" })
|
||||
source.Sop.Regions[key] = new() { Name = key, X1 = 10, Y1 = 20, X2 = 100, Y2 = 120 };
|
||||
source.Sop.Steps = [new() { Id = 8, Name = "移动并确认", Description = "完整可见结果", Timeout = 17, StandardDurationMs = 3200,
|
||||
CompletionImageDirectory = "custom-images", SaveCompletionImage = false, RequiredObjects = ["零件"], MustKeep = ["工具"],
|
||||
ViolationRules = [new() { Type = "object_removed", Description = "工具移除", Severity = 3 }],
|
||||
Detection = new() { Method = "hand_move", FromRegion = "start", ToRegion = "finish", Hand = "left", StableFrames = 7, Tolerance = 9, MinConfidence = .81f },
|
||||
AiConfirmation = new() { EvidenceMode = "sequence", ImageMode = "fixed_region", ImageRegion = "inspect_area", CheckWindowMs = 32900,
|
||||
MaxChecks = 4, CheckSettleMs = 550, ObservationMaxFrames = 26, ObservationRequestMaxFrames = 9, MinConfidence = .94,
|
||||
TimeoutSeconds = 25, RetryDelayMs = 1700, HandPadding = 180, HandMemoryMs = 2400 } }];
|
||||
var original = JsonSerializer.Serialize(source);
|
||||
var text = SopStepTransfer.Export(source);
|
||||
var incoming = SopStepTransfer.Read(text);
|
||||
Check(JsonSerializer.Serialize(incoming.Sop.Steps) == JsonSerializer.Serialize(source.Sop.Steps), "YAML往返须完整保留触发、AI时序预算、阈值、结束图及违规规则");
|
||||
Check(incoming.Sop.Regions.Count == 3 && !incoming.Sop.Regions.ContainsKey("unused"), "仅导出步骤引用区域");
|
||||
var pascalJson = SopStepTransfer.Read(JsonSerializer.Serialize(source));
|
||||
Check(pascalJson.Sop.Steps[0].AiConfirmation!.ObservationRequestMaxFrames == 9, "可读取完整配方JSON");
|
||||
Check(SopStepTransfer.Read("{sop: {steps: [{id: 1, name: 流式步骤}]}}").Sop.Steps.Count == 1, "可读取合法流式YAML");
|
||||
|
||||
foreach (var naming in new[] { JsonNamingPolicy.CamelCase, JsonNamingPolicy.SnakeCaseLower })
|
||||
{
|
||||
var json = JsonSerializer.Serialize(source, new JsonSerializerOptions { PropertyNamingPolicy = naming });
|
||||
var read = SopStepTransfer.Read(json);
|
||||
Check(JsonSerializer.Serialize(read.Sop.Steps) == JsonSerializer.Serialize(source.Sop.Steps) && read.Sop.Regions.ContainsKey("inspect_area"),
|
||||
"JSON命名风格兼容不能丢失AI或触发参数,也不能改变自定义区域键");
|
||||
}
|
||||
var target = new SopConfig(); target.Sop.Name = "当前配方"; target.Sop.Settings.FrameStride = 7;
|
||||
target.Sop.Regions["start"] = new() { X1 = 200, Y1 = 200, X2 = 300, Y2 = 300 };
|
||||
target.Sop.Steps = [new() { Id = 1, Name = "已有步骤", Detection = new() { Method = "hand_in_region", Region = "start" } }];
|
||||
var before = JsonSerializer.Serialize(target);
|
||||
var merged = SopStepTransfer.Merge(target, incoming, append: true);
|
||||
Check(merged.Sop.Steps.Count == 2 && merged.Sop.Steps[1].Id == 2 && merged.Sop.Steps[0].Detection!.Region == "start"
|
||||
&& merged.Sop.Steps[1].Detection!.FromRegion == "start_import2" && merged.Sop.Regions["start"].X1 == 200,
|
||||
"追加须连续编号并重映射同名异坐标区域,不能改变旧步骤及标定");
|
||||
Check(merged.Sop.Steps[1].AiConfirmation!.ImageRegion == "inspect_area" && merged.Sop.Settings.FrameStride == 7 && merged.Sop.Name == "当前配方",
|
||||
"保留独立送检区及当前配方全局设置");
|
||||
Check(JsonSerializer.Serialize(target) == before && JsonSerializer.Serialize(source) == original, "合并和导出不得修改输入对象");
|
||||
var second = SopStepTransfer.Merge(merged, incoming, append: false);
|
||||
Check(second.Sop.Steps.Count == 1 && second.Sop.Regions.Count == merged.Sop.Regions.Count, "替换步骤不会清除当前区域,已有同坐标区域可复用");
|
||||
|
||||
var model = new RecipeEditorViewModel();
|
||||
model.OnDialogOpened(new DialogParameters { { "config", target }, { "directory", root }, { "new", true } });
|
||||
model.ImportSteps(incoming, append: true);
|
||||
Check(model.Recipe.Steps.Count == 2 && model.Recipe.SelectedStep is not null && model.StepTransferStatus.Contains("保存"), "导入更新编辑列表和选中项,明确需保存");
|
||||
var rendered = new RecipeEditor { DataContext = model };
|
||||
var window = new Window { Content = rendered, Width = 1040, Height = 900 }; window.Show(); window.UpdateLayout();
|
||||
var tabs = rendered.GetVisualDescendants().OfType<TabControl>().Single();
|
||||
tabs.SelectedItem = tabs.Items.OfType<TabItem>().Single(t => t.Header?.ToString() == "步骤"); window.UpdateLayout();
|
||||
Check(rendered.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "导入步骤")
|
||||
&& rendered.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "导出步骤"), "步骤页显示导入和导出入口");
|
||||
var edited = model.Recipe.ToConfig();
|
||||
var exported = SopStepTransfer.Read(model.ExportStepsText());
|
||||
Check(JsonSerializer.Serialize(edited.Sop.Steps) == JsonSerializer.Serialize(exported.Sop.Steps), "界面导入后再次导出须保留全部步骤配置");
|
||||
model.ImportSteps(incoming, append: false);
|
||||
Check(model.Recipe.Steps.Count == 1 && model.Recipe.Steps[0].AiObservationRequestMaxFrames == 9 && model.Recipe.Steps[0].AiMinConfidence == .94,
|
||||
"界面替换须使用导入的时序参数和完成阈值");
|
||||
var stable = JsonSerializer.Serialize(model.Recipe.ToConfig());
|
||||
var invalid = SopStepTransfer.Read(text); invalid.Sop.Steps[0].Detection!.ToRegion = "missing";
|
||||
try { model.ImportSteps(invalid, append: false); throw new Exception("缺少区域不应导入"); }
|
||||
catch (FormatException) { }
|
||||
Check(JsonSerializer.Serialize(model.Recipe.ToConfig()) == stable, "无效导入须保持当前编辑内容完整");
|
||||
foreach (var bad in new[] { "sop: { steps: [] }", "{}", "sop:\n steps: [null]", "not: a-sop" })
|
||||
{ try { SopStepTransfer.Read(bad); throw new Exception("无效文件不应被接受"); } catch (FormatException) { } }
|
||||
window.Close(); model.OnDialogClosed();
|
||||
Console.WriteLine("PASS: 步骤导入导出全字段往返、追加替换、区域冲突映射、全局设置隔离、非法输入原子保护及界面入口");
|
||||
}
|
||||
private static void Check(bool value, string message) { if (!value) throw new Exception(message); }
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user