Improve recipe region editor layout and keep editor open after saving
This commit is contained in:
parent
9e51dea52d
commit
e739dcf35c
17
README.md
17
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` 顶上那些说明
|
||||
|
||||
@ -172,6 +172,12 @@ public class RecipeNode : EditorNode
|
||||
get { return IsNew; }
|
||||
}
|
||||
|
||||
internal void MarkSaved(string fileName)
|
||||
{
|
||||
FileName = fileName;
|
||||
IsNew = false;
|
||||
}
|
||||
|
||||
/// <summary>配方名(sop.name)</summary>
|
||||
public string Name
|
||||
{
|
||||
@ -637,6 +643,14 @@ public class RecipeModelNode : EditorNode
|
||||
/// </summary>
|
||||
public class RegionNode : EditorNode
|
||||
{
|
||||
/// <summary>整组更新,属性通知发出时四个坐标已一致。</summary>
|
||||
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;
|
||||
|
||||
@ -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}">
|
||||
|
||||
<prism:Dialog.WindowStyle>
|
||||
<Style TargetType="Window">
|
||||
<Setter Property="Width" Value="1040" />
|
||||
<Setter Property="Height" Value="760" />
|
||||
<Setter Property="MinWidth" Value="1040" />
|
||||
<Setter Property="MinHeight" Value="760" />
|
||||
<Setter Property="SizeToContent" Value="Manual" />
|
||||
<Setter Property="ResizeMode" Value="CanResize" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Stretch" />
|
||||
</Style>
|
||||
</prism:Dialog.WindowStyle>
|
||||
|
||||
<UserControl.Resources>
|
||||
<BooleanToVisibilityConverter x:Key="BoolToVis" />
|
||||
@ -344,84 +357,113 @@
|
||||
<TabItem Header="区域">
|
||||
<Grid Margin="10">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="270" />
|
||||
<ColumnDefinition Width="180" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="230" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<DockPanel>
|
||||
<Button DockPanel.Dock="Bottom" Content="加区域" Margin="0,8,0,0" Padding="0,6"
|
||||
Command="{Binding Recipe.AddRegionCommand}" />
|
||||
|
||||
<ListBox Style="{StaticResource Pick}" ItemContainerStyle="{StaticResource PickItem}"
|
||||
ItemTemplate="{StaticResource RegionRow}"
|
||||
ItemsSource="{Binding Recipe.Regions}"
|
||||
SelectedItem="{Binding Recipe.SelectedRegion}" />
|
||||
</DockPanel>
|
||||
|
||||
<StackPanel Grid.Column="1" Margin="12,0,0,0" DataContext="{Binding Recipe.SelectedRegion}">
|
||||
<TextBlock Text="绝对像素坐标(相机原始分辨率),必须在现场画面上标定,别照抄别人的配方"
|
||||
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,10" />
|
||||
<Grid Grid.Column="1" Margin="12,0,12,0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" MinHeight="210" />
|
||||
</Grid.RowDefinitions>
|
||||
<WrapPanel Margin="0,0,0,6">
|
||||
<Button Content="从相机取图" Style="{StaticResource Mini}" Command="{Binding CaptureImageCommand}" />
|
||||
<Button Content="打开图片" Style="{StaticResource Mini}" Command="{Binding OpenImageCommand}" Margin="8,0,0,0" />
|
||||
</WrapPanel>
|
||||
<TextBlock Grid.Row="1" Text="选中左侧区域,再在图上拖动画框" TextWrapping="Wrap"
|
||||
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
|
||||
<TextBlock Grid.Row="2" Text="{Binding PreviewStatus}" TextWrapping="Wrap"
|
||||
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
|
||||
<Border Grid.Row="3" Padding="0" CornerRadius="4" ClipToBounds="True">
|
||||
<ed:RegionCanvas Image="{Binding PreviewImage}" Regions="{Binding Recipe.Regions}"
|
||||
SelectedRegion="{Binding Recipe.SelectedRegion, Mode=TwoWay}" />
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="键名" Style="{StaticResource Field}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Key, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<TextBlock Grid.Column="2" Text="显示名" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
|
||||
<TextBox Grid.Column="3" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
|
||||
</Grid>
|
||||
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="X1 / Y1" Style="{StaticResource Field}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding X1}" />
|
||||
<TextBlock Grid.Column="2" Text="Y1" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
|
||||
<TextBox Grid.Column="3" Text="{Binding Y1}" />
|
||||
</Grid>
|
||||
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="X2 / Y2" Style="{StaticResource Field}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding X2}" />
|
||||
<TextBlock Grid.Column="2" Text="Y2" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
|
||||
<TextBox Grid.Column="3" Text="{Binding Y2}" />
|
||||
</Grid>
|
||||
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="160" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="颜色" Style="{StaticResource Field}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Color, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" />
|
||||
<Rectangle Grid.Column="1" Width="18" Height="18" Fill="{Binding Brush}"
|
||||
HorizontalAlignment="Right" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="2" Text="说明" Style="{StaticResource Field}" Margin="16,0,8,0" Width="Auto" />
|
||||
<TextBox Grid.Column="3" Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Text="改键名会同步更新所有步骤里对它的引用" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,8,0,0" />
|
||||
</StackPanel>
|
||||
<ScrollViewer x:Name="RegionParameters" Grid.Column="2" VerticalScrollBarVisibility="Auto"
|
||||
HorizontalScrollBarVisibility="Disabled">
|
||||
<StackPanel DataContext="{Binding Recipe.SelectedRegion}">
|
||||
<TextBlock Text="区域参数" Style="{StaticResource Title}" FontSize="13" Margin="0,0,0,10" />
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="54" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="键名" Foreground="{StaticResource FgDim}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Key, UpdateSourceTrigger=PropertyChanged}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="54" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="显示名" Foreground="{StaticResource FgDim}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="54" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="X1" Foreground="{StaticResource FgDim}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding X1, UpdateSourceTrigger=PropertyChanged}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="54" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="Y1" Foreground="{StaticResource FgDim}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Y1, UpdateSourceTrigger=PropertyChanged}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="54" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="X2" Foreground="{StaticResource FgDim}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding X2, UpdateSourceTrigger=PropertyChanged}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="54" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="Y2" Foreground="{StaticResource FgDim}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Y2, UpdateSourceTrigger=PropertyChanged}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Row}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="54" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="颜色" Foreground="{StaticResource FgDim}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Color, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<Rectangle Grid.Column="2" Width="18" Height="18" Fill="{Binding Brush}" Margin="6,0,0,0"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<TextBlock Text="说明" Foreground="{StaticResource FgDim}" Margin="0,4,0,6" />
|
||||
<TextBox Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap"
|
||||
AcceptsReturn="True" Height="72" VerticalScrollBarVisibility="Auto" />
|
||||
<TextBlock Text="坐标使用原图像素;画框更新右侧数值,也可手动微调。" TextWrapping="Wrap"
|
||||
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,12,0,0" />
|
||||
<TextBlock Text="改键名会同步更新所有步骤里对它的引用" TextWrapping="Wrap"
|
||||
Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,8,0,0" />
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
|
||||
@ -526,6 +568,7 @@
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding SaveStatus}" Foreground="{StaticResource Ok}" FontSize="12" />
|
||||
<TextBlock Text="校验提醒(不阻止保存;现场常见先存草稿再补区域)" Foreground="{StaticResource FgDim}" FontSize="12" />
|
||||
<ItemsControl ItemsSource="{Binding Warnings}" MaxHeight="66">
|
||||
<ItemsControl.ItemTemplate>
|
||||
@ -537,7 +580,7 @@
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Bottom">
|
||||
<Button Content="取消" Command="{Binding CloseCommand}" Margin="0,0,8,0" />
|
||||
<Button Content="关闭" Command="{Binding CloseCommand}" Margin="0,0,8,0" />
|
||||
<Button Content="保存" Command="{Binding SaveCommand}"
|
||||
Background="{StaticResource Panel}" BorderBrush="{StaticResource Accent}" />
|
||||
</StackPanel>
|
||||
|
||||
@ -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<string>? _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; }
|
||||
|
||||
/// <summary>当前编辑的配方目录(configs/sop)</summary>
|
||||
private string _directory = "";
|
||||
@ -48,7 +79,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
/// <summary>保存</summary>
|
||||
public DelegateCommand SaveCommand { get; private set; } = null!;
|
||||
|
||||
/// <summary>放弃修改关闭</summary>
|
||||
/// <summary>关闭编辑器,未保存的修改不写入文件</summary>
|
||||
public DelegateCommand CloseCommand { get; private set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
@ -56,8 +87,11 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@ -66,6 +100,14 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
_directory = parameters.GetValue<string>("directory") ?? "";
|
||||
_path = parameters.GetValue<string>("path") ?? "";
|
||||
_isNew = parameters.GetValue<bool>("new");
|
||||
_onSaved = parameters.GetValue<Action<string>>("onSaved");
|
||||
SaveStatus = "";
|
||||
_camera = parameters.GetValue<ICameraService>("cameraService");
|
||||
_cameraInfo = parameters.GetValue<CameraInfo>("cameraInfo");
|
||||
PreviewImage = parameters.GetValue<BitmapSource>("preview");
|
||||
CaptureImageCommand.RaiseCanExecuteChanged();
|
||||
if (PreviewImage is not null) DescribeImage("最近一帧");
|
||||
else if (_cameraInfo is null) PreviewStatus = "请在 SOP 页先选择相机,或打开图片;选中区域后在图上拖动画框";
|
||||
|
||||
var config = parameters.GetValue<SopConfig>("config") ?? new SopConfig();
|
||||
|
||||
@ -79,15 +121,84 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanCloseDialog() => true;
|
||||
public bool CanCloseDialog() => !IsCapturing;
|
||||
|
||||
/// <inheritdoc />
|
||||
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<BitmapSource>(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
|
||||
/// </summary>
|
||||
private void RefreshWarnings()
|
||||
{
|
||||
SaveStatus = "";
|
||||
Warnings.Clear();
|
||||
|
||||
var config = Recipe.ToConfig();
|
||||
|
||||
177
src/SopHelper.App/VVMs/RecipeEditor/RegionCanvas.cs
Normal file
177
src/SopHelper.App/VVMs/RecipeEditor/RegionCanvas.cs
Normal file
@ -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;
|
||||
|
||||
/// <summary>图像按比例居中显示;拖动坐标映射到原图像素,留白不参与标定。</summary>
|
||||
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<RegionNode>), 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<RegionNode>? Regions { get => (ObservableCollection<RegionNode>?)GetValue(RegionsProperty); set => SetValue(RegionsProperty, value); }
|
||||
public RegionNode? SelectedRegion { get => (RegionNode?)GetValue(SelectedRegionProperty); set => SetValue(SelectedRegionProperty, value); }
|
||||
|
||||
private readonly HashSet<RegionNode> _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<RegionNode> old) old.CollectionChanged -= canvas.CollectionChanged;
|
||||
if (e.NewValue is ObservableCollection<RegionNode> 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();
|
||||
}
|
||||
@ -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
|
||||
}
|
||||
|
||||
/// <summary>运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用</summary>
|
||||
private bool CanEditRecipe() => !IsRunning && !string.IsNullOrWhiteSpace(SelectedRecipe);
|
||||
private bool CanEditRecipe() => !IsRunning && !_isCameraBusy && !string.IsNullOrWhiteSpace(SelectedRecipe);
|
||||
|
||||
/// <summary>
|
||||
/// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
|
||||
@ -412,7 +412,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 弹出配方编辑器。保存成功回来的是文件名(可能是新建的,所以列表要重扫)。
|
||||
/// 弹出配方编辑器。每次保存成功后刷新配方列表,编辑窗口保持打开。
|
||||
/// </summary>
|
||||
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<string>(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<string>("path") ?? ""));
|
||||
});
|
||||
_dialogs.ShowDialog(EditorDialogName, parameters, _ => { });
|
||||
}
|
||||
|
||||
private async Task RefreshCamerasAsync()
|
||||
|
||||
213
tests/RegionEditorSmoke/Program.cs
Normal file
213
tests/RegionEditorSmoke/Program.cs
Normal file
@ -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<string>();
|
||||
var saveVm = new RecipeEditorViewModel();
|
||||
try
|
||||
{
|
||||
saveVm.OnDialogOpened(new DialogParameters
|
||||
{
|
||||
{ "directory", saveDirectory }, { "new", true },
|
||||
{ "onSaved", new Action<string>(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<TabControl>().Single();
|
||||
tabs.SelectedIndex = 1;
|
||||
view.UpdateLayout();
|
||||
var canvas = Descendants(view).OfType<RegionCanvas>().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<DependencyObject> 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<CameraFrame>? FrameArrived;
|
||||
public event Action<bool>? ConnectionChanged;
|
||||
#pragma warning disable CS0067
|
||||
public event Action<string>? Error;
|
||||
#pragma warning restore CS0067
|
||||
public Task<List<CameraInfo>> EnumerateAsync() => Task.FromResult(new List<CameraInfo>());
|
||||
public Task<bool> ConnectAsync(CameraInfo camera) { IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); }
|
||||
public async Task<bool> 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();
|
||||
}
|
||||
13
tests/RegionEditorSmoke/RegionEditorSmoke.csproj
Normal file
13
tests/RegionEditorSmoke/RegionEditorSmoke.csproj
Normal file
@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Loading…
Reference in New Issue
Block a user