diff --git a/README.md b/README.md
index ad386bf..a643b85 100644
--- a/README.md
+++ b/README.md
@@ -135,6 +135,23 @@ SOP 页配方行的「编辑 / 新建」。表单式,四个 tab:步骤 / 区
"照抄别人的 YAML 拼错一个字母"这种事发生(下拉候选就是 `ConditionMethod` 那几项)。
区域改键名会同步更新所有引用它的步骤;删区域会清掉引用。
+区域页支持图像画框标定:
+
+1. 停止运行,在 SOP 页选好相机,打开「编辑 / 新建」→「区域」。
+2. 已有预览画面会作为背景带入;也可点「从相机取图」获取新的一帧,或「打开图片」载入原图。
+ 取图完成后自动关闭相机,不启动 SOP 判定。
+3. 左侧选中区域(没有则点「加区域」),在图上按住左键拖动画框,松开后更新 X1/Y1/X2/Y2。
+ 支持反方向拖动;超出图像边界会截取到边界;Esc 取消本次绘制。
+4. 重画可直接替换所选区域;下方数字可微调,并同步更新图上的框。点击「保存」写入配方。
+
+图像保持原比例显示,坐标保存为原图像素,不包含预览留白。打开的图片应与现场相机分辨率一致。
+
+区域编辑回归检查(可加 `--hardware` 使用现场海康取图):
+
+```bash
+dotnet run --project tests/RegionEditorSmoke/RegionEditorSmoke.csproj
+```
+
两条要注意的:
- **保存是重写整个文件,注释会丢**(YamlDotNet 不保留注释)。`demo.yaml` 顶上那些说明
diff --git a/src/SopHelper.App/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.App/VVMs/RecipeEditor/EditorNodes.cs
index 1cd3a0c..8b8fbad 100644
--- a/src/SopHelper.App/VVMs/RecipeEditor/EditorNodes.cs
+++ b/src/SopHelper.App/VVMs/RecipeEditor/EditorNodes.cs
@@ -172,6 +172,12 @@ public class RecipeNode : EditorNode
get { return IsNew; }
}
+ internal void MarkSaved(string fileName)
+ {
+ FileName = fileName;
+ IsNew = false;
+ }
+
/// 配方名(sop.name)
public string Name
{
@@ -637,6 +643,14 @@ public class RecipeModelNode : EditorNode
///
public class RegionNode : EditorNode
{
+ /// 整组更新,属性通知发出时四个坐标已一致。
+ public void SetBounds(System.Windows.Int32Rect bounds)
+ {
+ _x1 = bounds.X; _y1 = bounds.Y; _x2 = bounds.X + bounds.Width; _y2 = bounds.Y + bounds.Height;
+ RaisePropertyChanged(nameof(X1)); RaisePropertyChanged(nameof(Y1));
+ RaisePropertyChanged(nameof(X2)); RaisePropertyChanged(nameof(Y2));
+ }
+
private string _key = "";
private int _x1;
private int _y1;
diff --git a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml b/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml
index 81624b5..1a8f460 100644
--- a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml
+++ b/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditor.xaml
@@ -4,7 +4,20 @@
xmlns:prism="http://prismlibrary.com/"
xmlns:ed="clr-namespace:SopHelper.VVMs.RecipeEditor"
prism:ViewModelLocator.AutoWireViewModel="True"
- Width="1020" Height="720" Background="{StaticResource Bg}">
+ Background="{StaticResource Bg}">
+
+
+
+
@@ -344,84 +357,113 @@
-
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -526,6 +568,7 @@
+
@@ -537,7 +580,7 @@
-
+
diff --git a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditorViewModel.cs b/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditorViewModel.cs
index 1eb5e26..9aeae12 100644
--- a/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditorViewModel.cs
+++ b/src/SopHelper.App/VVMs/RecipeEditor/RecipeEditorViewModel.cs
@@ -1,9 +1,14 @@
using System.Collections.ObjectModel;
using System.IO;
+using System.Runtime.InteropServices;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using Microsoft.Win32;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Mvvm;
using SopHelper.Engine.Sop;
+using SopHelper.Engine.Camera;
namespace SopHelper.VVMs.RecipeEditor;
@@ -17,6 +22,32 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
private RecipeNode _recipe = new();
private string _path = "";
private bool _isNew;
+ private Action? _onSaved;
+ private string _saveStatus = "";
+
+ public string SaveStatus { get => _saveStatus; private set => SetProperty(ref _saveStatus, value); }
+ private BitmapSource? _previewImage;
+ private string _previewStatus = "选中一个区域后,在图像上拖动画框;Esc 取消本次绘制";
+ private bool _isCapturing;
+ private ICameraService? _camera;
+ private CameraInfo? _cameraInfo;
+
+ public BitmapSource? PreviewImage { get => _previewImage; private set => SetProperty(ref _previewImage, value); }
+ public string PreviewStatus { get => _previewStatus; private set => SetProperty(ref _previewStatus, value); }
+ public bool IsCapturing
+ {
+ get => _isCapturing;
+ private set
+ {
+ if (!SetProperty(ref _isCapturing, value)) return;
+ CaptureImageCommand.RaiseCanExecuteChanged();
+ OpenImageCommand.RaiseCanExecuteChanged();
+ SaveCommand.RaiseCanExecuteChanged();
+ CloseCommand.RaiseCanExecuteChanged();
+ }
+ }
+ public DelegateCommand CaptureImageCommand { get; }
+ public DelegateCommand OpenImageCommand { get; }
/// 当前编辑的配方目录(configs/sop)
private string _directory = "";
@@ -48,7 +79,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
/// 保存
public DelegateCommand SaveCommand { get; private set; } = null!;
- /// 放弃修改关闭
+ /// 关闭编辑器,未保存的修改不写入文件
public DelegateCommand CloseCommand { get; private set; } = null!;
///
@@ -56,8 +87,11 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
///
public RecipeEditorViewModel()
{
- SaveCommand = new DelegateCommand(Save);
- CloseCommand = new DelegateCommand(() => RequestClose.Invoke(ButtonResult.Cancel));
+ SaveCommand = new DelegateCommand(Save, () => !IsCapturing);
+ CloseCommand = new DelegateCommand(() => RequestClose.Invoke(ButtonResult.Cancel), () => !IsCapturing);
+ CaptureImageCommand = new DelegateCommand(async () => await CaptureImageAsync(),
+ () => !IsCapturing && _camera is not null && _cameraInfo is not null);
+ OpenImageCommand = new DelegateCommand(OpenImage, () => !IsCapturing);
}
///
@@ -66,6 +100,14 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
_directory = parameters.GetValue("directory") ?? "";
_path = parameters.GetValue("path") ?? "";
_isNew = parameters.GetValue("new");
+ _onSaved = parameters.GetValue>("onSaved");
+ SaveStatus = "";
+ _camera = parameters.GetValue("cameraService");
+ _cameraInfo = parameters.GetValue("cameraInfo");
+ PreviewImage = parameters.GetValue("preview");
+ CaptureImageCommand.RaiseCanExecuteChanged();
+ if (PreviewImage is not null) DescribeImage("最近一帧");
+ else if (_cameraInfo is null) PreviewStatus = "请在 SOP 页先选择相机,或打开图片;选中区域后在图上拖动画框";
var config = parameters.GetValue("config") ?? new SopConfig();
@@ -79,15 +121,84 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
}
///
- public bool CanCloseDialog() => true;
+ public bool CanCloseDialog() => !IsCapturing;
///
public void OnDialogClosed()
{
+ Recipe.Changed -= RefreshWarnings;
+ _onSaved = null;
+ }
+
+ private void DescribeImage(string source) => PreviewStatus =
+ $"{source} · {PreviewImage!.PixelWidth} × {PreviewImage.PixelHeight} 像素;选中区域后拖动画框,Esc 取消";
+
+ private void OpenImage()
+ {
+ var dialog = new OpenFileDialog
+ {
+ Title = "选择区域标定图片(使用与相机相同分辨率的原图)",
+ Filter = "图像|*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff|所有文件|*.*",
+ };
+ if (dialog.ShowDialog() != true) return;
+ try
+ {
+ var image = new BitmapImage();
+ image.BeginInit();
+ image.CacheOption = BitmapCacheOption.OnLoad;
+ image.UriSource = new Uri(dialog.FileName, UriKind.Absolute);
+ image.EndInit();
+ image.Freeze();
+ PreviewImage = image;
+ DescribeImage(Path.GetFileName(dialog.FileName));
+ }
+ catch (Exception ex) { PreviewStatus = "打开图片失败:" + ex.Message; }
+ }
+
+ private async Task CaptureImageAsync()
+ {
+ if (IsCapturing || _camera is null || _cameraInfo is null) return;
+ var camera = _camera;
+ IsCapturing = true;
+ PreviewStatus = "正在取图…";
+ var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ void Receive(CameraFrame frame)
+ {
+ if (ready.Task.IsCompleted) return;
+ try
+ {
+ // 不保留相机 Mat;图像在采集线程复制并冻结后再交给 UI。
+ using var copy = frame.Bgr.Clone();
+ var bytes = new byte[checked(copy.Rows * copy.Cols * 3)];
+ Marshal.Copy(copy.Data, bytes, 0, bytes.Length);
+ var bitmap = BitmapSource.Create(copy.Cols, copy.Rows, 96, 96, PixelFormats.Bgr24,
+ null, bytes, copy.Cols * 3);
+ bitmap.Freeze();
+ ready.TrySetResult(bitmap);
+ }
+ catch (Exception ex) { ready.TrySetException(ex); }
+ }
+ try
+ {
+ if (!await camera.ConnectAsync(_cameraInfo)) throw new InvalidOperationException("连接相机失败,请查看 SOP 页日志");
+ camera.FrameArrived += Receive;
+ if (!await camera.StartAsync()) throw new InvalidOperationException("启动采集失败");
+ PreviewImage = await ready.Task.WaitAsync(TimeSpan.FromSeconds(5));
+ DescribeImage(_cameraInfo.Name);
+ }
+ catch (Exception ex) { PreviewStatus = "取图失败:" + ex.Message; }
+ finally
+ {
+ camera.FrameArrived -= Receive;
+ try { await Task.Run(camera.Disconnect); }
+ catch (Exception ex) { PreviewStatus = "关闭相机失败:" + ex.Message; }
+ IsCapturing = false;
+ }
}
private void Save()
{
+ SaveStatus = "";
if (string.IsNullOrWhiteSpace(Recipe.Name))
{
Warnings.Add("配方名(sop.name)不能为空");
@@ -99,17 +210,24 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
// 只取文件名部分,别让人在这儿塞路径
fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars()));
- _path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName + ".yaml") : _path;
+ var path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName + ".yaml") : _path;
try
{
// Save 内部落盘后会回读校验,返回值就是磁盘上那份
- var saved = SopConfigLoader.Save(Recipe.ToConfig(), _path);
+ var saved = SopConfigLoader.Save(Recipe.ToConfig(), path);
+
+ _path = path;
+ _isNew = false;
+ Recipe.MarkSaved(Path.GetFileNameWithoutExtension(path));
+ RaisePropertyChanged(nameof(FileNameText));
+ RaisePropertyChanged(nameof(Title));
Warnings.Clear();
foreach (var warning in saved.Warnings) Warnings.Add(warning);
- RequestClose.Invoke(new DialogParameters { { "path", Path.GetFileName(_path) } }, ButtonResult.OK);
+ SaveStatus = $"已保存 {Path.GetFileName(_path)}";
+ _onSaved?.Invoke(Path.GetFileName(_path));
}
catch (Exception ex)
{
@@ -124,6 +242,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
///
private void RefreshWarnings()
{
+ SaveStatus = "";
Warnings.Clear();
var config = Recipe.ToConfig();
diff --git a/src/SopHelper.App/VVMs/RecipeEditor/RegionCanvas.cs b/src/SopHelper.App/VVMs/RecipeEditor/RegionCanvas.cs
new file mode 100644
index 0000000..c675236
--- /dev/null
+++ b/src/SopHelper.App/VVMs/RecipeEditor/RegionCanvas.cs
@@ -0,0 +1,177 @@
+using System.Collections.ObjectModel;
+using System.Collections.Specialized;
+using System.ComponentModel;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+
+namespace SopHelper.VVMs.RecipeEditor;
+
+/// 图像按比例居中显示;拖动坐标映射到原图像素,留白不参与标定。
+public sealed class RegionCanvas : FrameworkElement
+{
+ public static readonly DependencyProperty ImageProperty = DependencyProperty.Register(
+ nameof(Image), typeof(BitmapSource), typeof(RegionCanvas),
+ new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, CancelOnChange));
+ public static readonly DependencyProperty RegionsProperty = DependencyProperty.Register(
+ nameof(Regions), typeof(ObservableCollection), typeof(RegionCanvas),
+ new FrameworkPropertyMetadata(null, RegionsChanged));
+ public static readonly DependencyProperty SelectedRegionProperty = DependencyProperty.Register(
+ nameof(SelectedRegion), typeof(RegionNode), typeof(RegionCanvas),
+ new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender |
+ FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, CancelOnChange));
+
+ public BitmapSource? Image { get => (BitmapSource?)GetValue(ImageProperty); set => SetValue(ImageProperty, value); }
+ public ObservableCollection? Regions { get => (ObservableCollection?)GetValue(RegionsProperty); set => SetValue(RegionsProperty, value); }
+ public RegionNode? SelectedRegion { get => (RegionNode?)GetValue(SelectedRegionProperty); set => SetValue(SelectedRegionProperty, value); }
+
+ private readonly HashSet _observed = [];
+ private Point? _start;
+ private Point _end;
+ private RegionNode? _drawingRegion;
+
+ public RegionCanvas()
+ {
+ Focusable = true;
+ Cursor = Cursors.Cross;
+ Unloaded += (_, _) => CancelDrag();
+ }
+
+ public static Rect FitImage(Size viewport, Size image)
+ {
+ if (viewport.Width <= 0 || viewport.Height <= 0 || image.Width <= 0 || image.Height <= 0) return Rect.Empty;
+ var scale = Math.Min(viewport.Width / image.Width, viewport.Height / image.Height);
+ var size = new Size(image.Width * scale, image.Height * scale);
+ return new Rect(new Point((viewport.Width - size.Width) / 2, (viewport.Height - size.Height) / 2), size);
+ }
+
+ public static Point ToImage(Point point, Rect display, Size image) => new(
+ Math.Clamp((point.X - display.X) * image.Width / display.Width, 0, image.Width),
+ Math.Clamp((point.Y - display.Y) * image.Height / display.Height, 0, image.Height));
+
+ public static Int32Rect PixelBounds(Point first, Point last, Size image)
+ {
+ var x1 = (int)Math.Clamp(Math.Floor(Math.Min(first.X, last.X)), 0, image.Width);
+ var y1 = (int)Math.Clamp(Math.Floor(Math.Min(first.Y, last.Y)), 0, image.Height);
+ var x2 = (int)Math.Clamp(Math.Ceiling(Math.Max(first.X, last.X)), 0, image.Width);
+ var y2 = (int)Math.Clamp(Math.Ceiling(Math.Max(first.Y, last.Y)), 0, image.Height);
+ return new Int32Rect(x1, y1, x2 - x1, y2 - y1);
+ }
+
+ protected override void OnRender(DrawingContext dc)
+ {
+ dc.DrawRectangle(new SolidColorBrush(Color.FromRgb(10, 16, 22)), null, new Rect(RenderSize));
+ if (Image is null)
+ {
+ var text = new FormattedText("从相机取图,或打开一张图片后画框", CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), 13, Brushes.LightGray,
+ VisualTreeHelper.GetDpi(this).PixelsPerDip);
+ dc.DrawText(text, new Point(Math.Max(8, (ActualWidth - text.Width) / 2), Math.Max(8, ActualHeight / 2 - text.Height / 2)));
+ return;
+ }
+ var size = new Size(Image.PixelWidth, Image.PixelHeight);
+ var display = FitImage(RenderSize, size);
+ if (display.IsEmpty) return;
+ dc.DrawImage(Image, display);
+ var scale = display.Width / size.Width;
+ dc.PushClip(new RectangleGeometry(display));
+ dc.PushTransform(new MatrixTransform(scale, 0, 0, scale, display.X, display.Y));
+ foreach (var region in Regions ?? [])
+ {
+ if (region.X2 <= region.X1 || region.Y2 <= region.Y1) continue;
+ var rect = new Rect(region.X1, region.Y1, region.X2 - region.X1, region.Y2 - region.Y1);
+ var selected = ReferenceEquals(region, SelectedRegion);
+ var pen = new Pen(region.Brush, (selected ? 3 : 1.5) / scale);
+ if (selected) dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(35, 0, 184, 212)), null, rect);
+ dc.DrawRectangle(null, pen, rect);
+ var label = new FormattedText(string.IsNullOrWhiteSpace(region.Name) ? region.Key : region.Name,
+ CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"),
+ 12 / scale, region.Brush, VisualTreeHelper.GetDpi(this).PixelsPerDip);
+ var origin = new Point(Math.Max(0, rect.X), Math.Max(0, rect.Y - label.Height));
+ dc.DrawRectangle(Brushes.Black, null, new Rect(origin, new Size(label.Width, label.Height)));
+ dc.DrawText(label, origin);
+ }
+ if (_start is Point start)
+ {
+ var pen = new Pen(Brushes.Yellow, 2 / scale) { DashStyle = DashStyles.Dash };
+ dc.DrawRectangle(null, pen, new Rect(start, _end));
+ }
+ dc.Pop();
+ dc.Pop();
+ }
+
+ protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
+ {
+ base.OnMouseLeftButtonDown(e);
+ if (Image is null || SelectedRegion is null) return;
+ var display = FitImage(RenderSize, new Size(Image.PixelWidth, Image.PixelHeight));
+ var point = e.GetPosition(this);
+ if (display.IsEmpty || !display.Contains(point)) return;
+ Focus();
+ if (!CaptureMouse()) return;
+ _drawingRegion = SelectedRegion;
+ _start = _end = ToImage(point, display, new Size(Image.PixelWidth, Image.PixelHeight));
+ InvalidateVisual();
+ e.Handled = true;
+ }
+
+ protected override void OnMouseMove(MouseEventArgs e)
+ {
+ base.OnMouseMove(e);
+ if (_start is null || Image is null) return;
+ _end = ToImage(e.GetPosition(this), FitImage(RenderSize, new Size(Image.PixelWidth, Image.PixelHeight)),
+ new Size(Image.PixelWidth, Image.PixelHeight));
+ InvalidateVisual();
+ e.Handled = true;
+ }
+
+ protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
+ {
+ base.OnMouseLeftButtonUp(e);
+ if (_start is not Point start || Image is null) return;
+ var size = new Size(Image.PixelWidth, Image.PixelHeight);
+ var display = FitImage(RenderSize, size);
+ var end = ToImage(e.GetPosition(this), display, size);
+ var bounds = PixelBounds(start, end, size);
+ // 单击不改坐标;拖出图像时按图像边界截取。
+ if (bounds.Width * display.Width / size.Width >= 4 && bounds.Height * display.Height / size.Height >= 4 &&
+ ReferenceEquals(_drawingRegion, SelectedRegion))
+ _drawingRegion?.SetBounds(bounds);
+ CancelDrag();
+ e.Handled = true;
+ }
+
+ protected override void OnKeyDown(KeyEventArgs e)
+ {
+ if (e.Key == Key.Escape && _start is not null) { CancelDrag(); e.Handled = true; }
+ else base.OnKeyDown(e);
+ }
+
+ protected override void OnLostMouseCapture(MouseEventArgs e) { base.OnLostMouseCapture(e); CancelDrag(); }
+ private void CancelDrag()
+ {
+ _start = null;
+ _drawingRegion = null;
+ if (IsMouseCaptured) ReleaseMouseCapture();
+ InvalidateVisual();
+ }
+ private static void CancelOnChange(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((RegionCanvas)d).CancelDrag();
+ private static void RegionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+ {
+ var canvas = (RegionCanvas)d;
+ if (e.OldValue is ObservableCollection old) old.CollectionChanged -= canvas.CollectionChanged;
+ if (e.NewValue is ObservableCollection current) current.CollectionChanged += canvas.CollectionChanged;
+ canvas.ObserveRegions();
+ }
+ private void CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { CancelDrag(); ObserveRegions(); }
+ private void ObserveRegions()
+ {
+ foreach (var node in _observed) node.PropertyChanged -= NodeChanged;
+ _observed.Clear();
+ foreach (var node in Regions ?? []) { _observed.Add(node); node.PropertyChanged += NodeChanged; }
+ InvalidateVisual();
+ }
+ private void NodeChanged(object? sender, PropertyChangedEventArgs e) => InvalidateVisual();
+}
diff --git a/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs
index d497d3e..53e4b9e 100644
--- a/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.App/VVMs/SopPage/SopPageViewModel.cs
@@ -108,10 +108,10 @@ public class SopPageViewModel : ViewModelBase
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
ResetCommand = new DelegateCommand(_engine.Reset, () => IsRunning);
- ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => !IsRunning);
+ ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => !IsRunning && !_isCameraBusy);
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
- NewRecipeCommand = new DelegateCommand(NewRecipe, () => !IsRunning);
+ NewRecipeCommand = new DelegateCommand(NewRecipe, () => !IsRunning && !_isCameraBusy);
StatusText = "选择相机和配方,点开始";
}
@@ -283,7 +283,7 @@ public class SopPageViewModel : ViewModelBase
}
/// 运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用
- private bool CanEditRecipe() => !IsRunning && !string.IsNullOrWhiteSpace(SelectedRecipe);
+ private bool CanEditRecipe() => !IsRunning && !_isCameraBusy && !string.IsNullOrWhiteSpace(SelectedRecipe);
///
/// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
@@ -412,7 +412,7 @@ public class SopPageViewModel : ViewModelBase
}
///
- /// 弹出配方编辑器。保存成功回来的是文件名(可能是新建的,所以列表要重扫)。
+ /// 弹出配方编辑器。每次保存成功后刷新配方列表,编辑窗口保持打开。
///
private void OpenEditor(string path, bool isNew, SopConfig config)
{
@@ -421,13 +421,18 @@ public class SopPageViewModel : ViewModelBase
parameters.Add("path", path);
parameters.Add("new", isNew);
parameters.Add("config", config);
-
- _dialogs.ShowDialog(EditorDialogName, parameters, result =>
+ parameters.Add("onSaved", new Action(fileName =>
+ _dispatcher.BeginInvoke(() => RefreshRecipes(fileName))));
+ parameters.Add("cameraService", _camera);
+ if (SelectedCamera is not null) parameters.Add("cameraInfo", SelectedCamera);
+ if (Frame is BitmapSource image)
{
- if (result.Result != ButtonResult.OK) return;
+ var preview = image.Clone();
+ preview.Freeze();
+ parameters.Add("preview", preview);
+ }
- _dispatcher.BeginInvoke(() => RefreshRecipes(result.Parameters.GetValue("path") ?? ""));
- });
+ _dialogs.ShowDialog(EditorDialogName, parameters, _ => { });
}
private async Task RefreshCamerasAsync()
diff --git a/tests/RegionEditorSmoke/Program.cs b/tests/RegionEditorSmoke/Program.cs
new file mode 100644
index 0000000..3834967
--- /dev/null
+++ b/tests/RegionEditorSmoke/Program.cs
@@ -0,0 +1,213 @@
+using System.IO;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Threading;
+using OpenCvSharp;
+using Prism.Dialogs;
+using SopHelper.Engine.Camera;
+using SopHelper.Engine.Sop;
+using SopHelper.VVMs.RecipeEditor;
+using Point = System.Windows.Point;
+using Rect = System.Windows.Rect;
+using Size = System.Windows.Size;
+
+internal static class Program
+{
+ [STAThread]
+ private static int Main(string[] args)
+ {
+ var app = new Application();
+ app.Resources.MergedDictionaries.Add(new ResourceDictionary
+ {
+ Source = new Uri("pack://application:,,,/SopHelper;component/Themes/Styles.xaml"),
+ });
+ SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
+ var run = CheckAsync(args);
+ _ = run.ContinueWith(_ => app.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background));
+ Dispatcher.Run();
+ try { run.GetAwaiter().GetResult(); return 0; }
+ catch (Exception ex) { Console.Error.WriteLine(ex); return 1; }
+ }
+
+ private static async Task CheckAsync(string[] args)
+ {
+ var imageSize = new Size(4000, 2000);
+ var display = RegionCanvas.FitImage(new Size(800, 600), imageSize);
+ if (display != new Rect(0, 100, 800, 400)) throw new Exception("横向留白计算错误");
+ var first = RegionCanvas.ToImage(new Point(160, 180), display, imageSize);
+ var last = RegionCanvas.ToImage(new Point(640, 420), display, imageSize);
+ var bounds = RegionCanvas.PixelBounds(last, first, imageSize);
+ if (bounds != new Int32Rect(800, 400, 2400, 1200)) throw new Exception("反向画框或像素换算错误");
+ var clipped = RegionCanvas.ToImage(new Point(900, -50), display, imageSize);
+ if (clipped != new Point(4000, 0)) throw new Exception("边界截取错误");
+ var portrait = RegionCanvas.FitImage(new Size(800, 600), new Size(1000, 2000));
+ if (portrait != new Rect(250, 0, 300, 600)) throw new Exception("纵向图像留白计算错误");
+ Console.WriteLine("PASS: 原图像素换算、横竖图留白、反向画框及越界截取");
+
+ var saveDirectory = Path.Combine(Path.GetTempPath(), "SopHelper-save-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(saveDirectory);
+ var savePath = Path.Combine(saveDirectory, "repeat-save.yaml");
+ var notifications = new List();
+ var saveVm = new RecipeEditorViewModel();
+ try
+ {
+ saveVm.OnDialogOpened(new DialogParameters
+ {
+ { "directory", saveDirectory }, { "new", true },
+ { "onSaved", new Action(notifications.Add) },
+ });
+ saveVm.Recipe.Name = "首次保存";
+ saveVm.Recipe.FileName = "repeat-save";
+ var editedRecipe = saveVm.Recipe;
+ // 未注册关闭监听器:保存如果仍尝试关闭弹窗,就不能正常完成。
+ saveVm.SaveCommand.Execute();
+ if (!saveVm.SaveStatus.StartsWith("已保存") || saveVm.Recipe.CanEditFileName ||
+ saveVm.Title != "编辑配方 - repeat-save.yaml" || notifications.Count != 1 ||
+ SopConfigLoader.Load(savePath).Sop.Name != "首次保存")
+ throw new Exception("首次保存后的状态或文件不正确:" + string.Join(";", saveVm.Warnings));
+ saveVm.Recipe.Name = "继续修改并保存";
+ saveVm.SaveCommand.Execute();
+ if (!saveVm.SaveStatus.StartsWith("已保存") || !ReferenceEquals(editedRecipe, saveVm.Recipe) ||
+ notifications.Count != 2 || notifications.Any(name => name != "repeat-save.yaml") ||
+ SopConfigLoader.Load(savePath).Sop.Name != "继续修改并保存" || Directory.GetFiles(saveDirectory).Length != 1)
+ throw new Exception("连续保存未更新原配方文件");
+ Console.WriteLine("PASS: 保存不请求关闭、编辑状态保留、新建转为编辑、连续保存更新同一文件并通知主页");
+ }
+ finally
+ {
+ saveVm.OnDialogClosed();
+ if (File.Exists(savePath)) File.Delete(savePath);
+ Directory.Delete(saveDirectory);
+ }
+
+ var node = new RegionNode();
+ node.PropertyChanged += (_, _) =>
+ {
+ if ((node.X1, node.Y1, node.X2, node.Y2) != (800, 400, 3200, 1600))
+ throw new Exception("坐标更新通知发出时数据不完整");
+ };
+ node.SetBounds(bounds);
+
+ var config = new SopConfig();
+ config.Sop.Name = "画框标定";
+ config.Sop.Regions["work"] = new RegionDef { X1 = 200, Y1 = 150, X2 = 950, Y2 = 650, Name = "操作区域", Color = "#00B8D4" };
+ using var fake = new CaptureCamera();
+ using var real = args.Contains("--hardware") ? new CameraService() : null;
+ var camera = (ICameraService?)real ?? fake;
+ var cameraInfo = real is null ? new CameraInfo { Index = 0, Name = "测试图像" } :
+ (await real.EnumerateAsync()).First(c => c.Kind == CameraKind.Hikvision);
+ var vm = new RecipeEditorViewModel();
+ vm.OnDialogOpened(new DialogParameters
+ {
+ { "config", config }, { "new", true }, { "cameraService", camera }, { "cameraInfo", cameraInfo },
+ });
+ vm.CaptureImageCommand.Execute();
+ var deadline = DateTime.UtcNow.AddSeconds(20);
+ while (vm.IsCapturing && DateTime.UtcNow < deadline) await Task.Delay(20);
+ if (vm.IsCapturing || vm.PreviewImage is null) throw new Exception("取图失败:" + vm.PreviewStatus);
+ if (!vm.PreviewImage.IsFrozen || camera.IsConnected || camera.IsGrabbing) throw new Exception("图像未冻结或取图后未释放相机");
+ if (vm.Recipe.SelectedRegion is null) throw new Exception("区域未自动选中");
+ vm.Recipe.SelectedRegion.SetBounds(new Int32Rect(200, 150, 750, 500));
+ var saved = vm.Recipe.ToConfig().Sop.Regions["work"];
+ if ((saved.X1, saved.Y1, saved.X2, saved.Y2) != (200, 150, 950, 650)) throw new Exception("画框坐标未写入配方");
+ Console.WriteLine($"PASS: {vm.PreviewImage.PixelWidth}x{vm.PreviewImage.PixelHeight} 取图、资源释放和坐标写回配方");
+
+ var view = new RecipeEditor { DataContext = vm };
+ view.Measure(new Size(1020, 720));
+ view.Arrange(new Rect(0, 0, 1020, 720));
+ view.UpdateLayout();
+ var tabs = Descendants(view).OfType().Single();
+ tabs.SelectedIndex = 1;
+ view.UpdateLayout();
+ var canvas = Descendants(view).OfType().Single();
+ if (!ReferenceEquals(canvas.Image, vm.PreviewImage) || !ReferenceEquals(canvas.SelectedRegion, vm.Recipe.SelectedRegion))
+ throw new Exception("画布绑定错误");
+ if (canvas.ActualWidth < 400 || canvas.ActualHeight < 200) throw new Exception("图像预览区域过小");
+ var normalCanvasSize = canvas.RenderSize;
+ var previewSize = new Size(vm.PreviewImage.PixelWidth, vm.PreviewImage.PixelHeight);
+ var normalImage = RegionCanvas.FitImage(normalCanvasSize, previewSize);
+ var dialogStyle = Dialog.GetWindowStyle(view);
+ var host = new DialogWindow { Style = dialogStyle, Content = view, Opacity = 0, ShowActivated = false, ShowInTaskbar = false };
+ if (host.SizeToContent != SizeToContent.Manual || host.ResizeMode != ResizeMode.CanResize ||
+ host.HorizontalContentAlignment != HorizontalAlignment.Stretch ||
+ host.VerticalContentAlignment != VerticalAlignment.Stretch)
+ throw new Exception("配方弹窗未配置为可缩放并拉伸内容");
+ // 用较大的客户区模拟最大化,验证整个弹窗内容链路,而非只检查画布自身。
+ host.Width = 1920;
+ host.Height = 1080;
+ host.Show();
+ host.UpdateLayout();
+ if (view.ActualWidth < host.ActualWidth - 100 || view.ActualHeight < host.ActualHeight - 100 ||
+ canvas.ActualWidth <= normalCanvasSize.Width || canvas.ActualHeight <= normalCanvasSize.Height)
+ throw new Exception($"放大弹窗后编辑内容或图像画布未扩展:内容 {view.RenderSize},画布 {canvas.RenderSize},窗口 {host.RenderSize}");
+ var enlargedImage = RegionCanvas.FitImage(canvas.RenderSize, previewSize);
+ var enlargedCanvasSize = canvas.RenderSize;
+ if (enlargedImage.Width <= normalImage.Width || enlargedImage.Height <= normalImage.Height)
+ throw new Exception("放大弹窗后图像显示尺寸未增大");
+ var enlargedPoint = new Point(enlargedImage.X + enlargedImage.Width / 4,
+ enlargedImage.Y + enlargedImage.Height / 4);
+ var mappedPoint = RegionCanvas.ToImage(enlargedPoint, enlargedImage, previewSize);
+ if ((mappedPoint - new Point(previewSize.Width / 4, previewSize.Height / 4)).Length > 0.001)
+ throw new Exception("放大后的原图坐标换算错误");
+ Console.WriteLine($"PASS: 弹窗内容随尺寸扩展,画布 {normalCanvasSize} → {canvas.RenderSize},图像等比放大且坐标正确");
+ host.Width = 1040;
+ host.Height = 760;
+ host.UpdateLayout();
+ if (canvas.ActualWidth >= enlargedCanvasSize.Width || canvas.ActualHeight >= enlargedCanvasSize.Height)
+ throw new Exception("还原窗口后画布未缩小");
+ if (args.FirstOrDefault(a => a.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) is string output)
+ {
+ var bitmap = new RenderTargetBitmap(1020, 720, 96, 96, PixelFormats.Pbgra32);
+ bitmap.Render(view);
+ var encoder = new PngBitmapEncoder();
+ encoder.Frames.Add(BitmapFrame.Create(bitmap));
+ using var file = File.Create(output);
+ encoder.Save(file);
+ }
+ host.Content = null;
+ host.Close();
+ vm.OnDialogClosed();
+ Console.WriteLine("PASS: 区域页布局、预览与所选区域绑定");
+ }
+
+ private static IEnumerable Descendants(DependencyObject parent)
+ {
+ for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
+ {
+ var child = VisualTreeHelper.GetChild(parent, i);
+ yield return child;
+ foreach (var next in Descendants(child)) yield return next;
+ }
+ }
+}
+
+internal sealed class CaptureCamera : ICameraService
+{
+ public bool IsConnected { get; private set; }
+ public bool IsGrabbing { get; private set; }
+ public event Action? FrameArrived;
+ public event Action? ConnectionChanged;
+#pragma warning disable CS0067
+ public event Action? Error;
+#pragma warning restore CS0067
+ public Task> EnumerateAsync() => Task.FromResult(new List());
+ public Task ConnectAsync(CameraInfo camera) { IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); }
+ public async Task StartAsync()
+ {
+ IsGrabbing = true;
+ await Task.Run(() =>
+ {
+ using var mat = new Mat(900, 1600, MatType.CV_8UC3, new Scalar(48, 41, 34));
+ for (var x = 0; x < mat.Width; x += 100) Cv2.Line(mat, new OpenCvSharp.Point(x, 0), new OpenCvSharp.Point(x, mat.Height), new Scalar(70, 65, 60));
+ for (var y = 0; y < mat.Height; y += 100) Cv2.Line(mat, new OpenCvSharp.Point(0, y), new OpenCvSharp.Point(mat.Width, y), new Scalar(70, 65, 60));
+ using var frame = new CameraFrame { FrameId = 1, Timestamp = DateTime.Now, Bgr = mat.Clone() };
+ FrameArrived?.Invoke(frame);
+ });
+ return true;
+ }
+ public void Stop() => IsGrabbing = false;
+ public void Disconnect() { Stop(); IsConnected = false; ConnectionChanged?.Invoke(false); }
+ public void Dispose() => Disconnect();
+}
diff --git a/tests/RegionEditorSmoke/RegionEditorSmoke.csproj b/tests/RegionEditorSmoke/RegionEditorSmoke.csproj
new file mode 100644
index 0000000..480519f
--- /dev/null
+++ b/tests/RegionEditorSmoke/RegionEditorSmoke.csproj
@@ -0,0 +1,13 @@
+
+
+ Exe
+ net8.0-windows
+ true
+ enable
+ enable
+ x64
+
+
+
+
+