334 lines
14 KiB
C#
334 lines
14 KiB
C#
using System.Collections.ObjectModel;
|
||
using System.ComponentModel;
|
||
using System.IO;
|
||
using System.Runtime.InteropServices;
|
||
using Avalonia.Media;
|
||
using SopHelper.Presentation.Imaging;
|
||
using SopHelper.Presentation;
|
||
using Prism.Commands;
|
||
using Prism.Dialogs;
|
||
using Prism.Mvvm;
|
||
using SopHelper.Engine.Sop;
|
||
using SopHelper.Engine.Camera;
|
||
using SopHelper.Engine.Training;
|
||
|
||
namespace SopHelper.VVMs.RecipeEditor;
|
||
|
||
/// <summary>
|
||
/// 配方编辑器(SOP 页「编辑」按钮弹出)。表单在 EditorNodes 那一侧,
|
||
/// 保存时整体映射回 SopConfig 交给 SopConfigLoader 写 YAML。
|
||
/// 类名必须是"视图全名 + ViewModel",Prism 的 ViewModelLocator 按这个约定绑定(见 App)。
|
||
/// </summary>
|
||
public class RecipeEditorViewModel : BindableBase, IDialogAware
|
||
{
|
||
private RecipeNode _recipe = new();
|
||
private string _path = "";
|
||
private bool _isNew;
|
||
private Action<string>? _onSaved;
|
||
private readonly HashSet<EditorNode> _observedStepNodes = [];
|
||
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();
|
||
BrowseModelCommand.RaiseCanExecuteChanged();
|
||
SaveCommand.RaiseCanExecuteChanged();
|
||
CloseCommand.RaiseCanExecuteChanged();
|
||
}
|
||
}
|
||
public DelegateCommand CaptureImageCommand { get; }
|
||
public DelegateCommand OpenImageCommand { get; }
|
||
public DelegateCommand BrowseModelCommand { get; }
|
||
|
||
/// <summary>当前编辑的配方目录(configs/sop)</summary>
|
||
private string _directory = "";
|
||
|
||
/// <inheritdoc />
|
||
public string Title => _isNew ? "新建配方" : $"编辑配方 - {FileNameText}";
|
||
|
||
/// <inheritdoc />
|
||
public DialogCloseListener RequestClose { get; } = new();
|
||
|
||
/// <summary>标题栏显示的文件名</summary>
|
||
public string FileNameText => string.IsNullOrEmpty(_path) ? $"{_recipe.FileName}.yaml(新建)" : Path.GetFileName(_path);
|
||
|
||
/// <summary>编辑中的配方</summary>
|
||
public RecipeNode Recipe
|
||
{
|
||
get { return _recipe; }
|
||
private set
|
||
{
|
||
if (!SetProperty(ref _recipe, value)) return;
|
||
RaisePropertyChanged(nameof(FileNameText));
|
||
RaisePropertyChanged(nameof(Title));
|
||
}
|
||
}
|
||
|
||
/// <summary>保存前的校验提醒(不阻止保存——现场常见"先存草稿再补区域")</summary>
|
||
public ObservableCollection<string> Warnings { get; } = [];
|
||
|
||
/// <summary>保存</summary>
|
||
public DelegateCommand SaveCommand { get; private set; } = null!;
|
||
|
||
/// <summary>关闭编辑器,未保存的修改不写入文件</summary>
|
||
public DelegateCommand CloseCommand { get; private set; } = null!;
|
||
|
||
/// <summary>
|
||
/// 配方编辑器
|
||
/// </summary>
|
||
public RecipeEditorViewModel()
|
||
{
|
||
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);
|
||
BrowseModelCommand = new DelegateCommand(BrowseModel, () => !IsCapturing);
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
public void OnDialogOpened(IDialogParameters parameters)
|
||
{
|
||
_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();
|
||
|
||
// 新建时文件名还没定,用配方名兜底;已存在的文件名不可改(SOP 页按文件名选配方)
|
||
var fileName = string.IsNullOrEmpty(_path) ? config.Sop.Name : Path.GetFileNameWithoutExtension(_path);
|
||
|
||
Recipe = RecipeNode.From(config, fileName, _isNew);
|
||
Recipe.Changed += RefreshWarnings;
|
||
|
||
RefreshWarnings();
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
public bool CanCloseDialog() => !IsCapturing;
|
||
|
||
/// <inheritdoc />
|
||
public void OnDialogClosed()
|
||
{
|
||
Recipe.Changed -= RefreshWarnings;
|
||
foreach (var node in _observedStepNodes) node.PropertyChanged -= StepChanged;
|
||
_observedStepNodes.Clear();
|
||
_onSaved = null;
|
||
}
|
||
|
||
private void DescribeImage(string source) => PreviewStatus =
|
||
$"{source} · {PreviewImage!.PixelWidth} × {PreviewImage.PixelHeight} 像素;选中区域后拖动画框,Esc 取消";
|
||
|
||
private async void OpenImage()
|
||
{
|
||
var dialog = new OpenFileDialog
|
||
{
|
||
Title = "选择区域标定图片(使用与相机相同分辨率的原图)",
|
||
Filter = "图像|*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff|所有文件|*.*",
|
||
};
|
||
if (await dialog.ShowDialogAsync() != 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 void BrowseModel()
|
||
{
|
||
if (Recipe.Model is null) return;
|
||
var dialog = new OpenFileDialog
|
||
{
|
||
Title = "选择 ONNX 检测模型",
|
||
Filter = "ONNX 模型 (*.onnx)|*.onnx",
|
||
DefaultExt = ".onnx",
|
||
CheckFileExists = true,
|
||
Multiselect = false,
|
||
InitialDirectory = AppContext.BaseDirectory,
|
||
};
|
||
try
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(Recipe.Model.Path))
|
||
{
|
||
var currentPath = Path.GetFullPath(Recipe.Model.Path, string.IsNullOrEmpty(_path) ? AppContext.BaseDirectory : Path.GetDirectoryName(_path)!);
|
||
var directory = Path.GetDirectoryName(currentPath);
|
||
if (Directory.Exists(directory)) dialog.InitialDirectory = directory;
|
||
if (File.Exists(currentPath)) dialog.FileName = Path.GetFileName(currentPath);
|
||
}
|
||
}
|
||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||
{
|
||
// 手填路径无效时,仍可从程序目录重新选择。
|
||
}
|
||
if (await dialog.ShowDialogAsync() != true) return;
|
||
Recipe.Model.Path = dialog.FileName;
|
||
RefreshWarnings();
|
||
}
|
||
|
||
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 页日志");
|
||
if (Recipe.Settings.ExposureTimeUs is { } exposure)
|
||
{
|
||
if (!double.IsFinite(exposure) || exposure <= 0)
|
||
throw new InvalidOperationException("相机曝光必须大于 0(微秒),或留空保留相机设置");
|
||
await camera.SetExposureTimeAsync(exposure);
|
||
}
|
||
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 (Recipe.Settings.ExposureTimeUs is { } exposure && (!double.IsFinite(exposure) || exposure <= 0))
|
||
{
|
||
Warnings.Add("相机曝光必须大于 0(微秒),或留空保留相机设置");
|
||
return;
|
||
}
|
||
if (string.IsNullOrWhiteSpace(Recipe.Name))
|
||
{
|
||
Warnings.Add("配方名(sop.name)不能为空");
|
||
return;
|
||
}
|
||
|
||
var fileName = string.IsNullOrWhiteSpace(Recipe.FileName) ? Recipe.Name : Recipe.FileName;
|
||
|
||
// 只取文件名部分,别让人在这儿塞路径
|
||
fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars()));
|
||
|
||
var path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName, fileName + ".yaml") : _path;
|
||
|
||
try
|
||
{
|
||
// Save 内部落盘后会回读校验,返回值就是磁盘上那份
|
||
if (_isNew && File.Exists(path)) throw new IOException("同名配方已存在,请使用其他配方名");
|
||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||
var config = Recipe.ToConfig();
|
||
if (config.Sop.Model is { Path.Length: > 0 } model)
|
||
{
|
||
var source = Path.GetFullPath(model.Path, string.IsNullOrEmpty(_path) ? AppContext.BaseDirectory : Path.GetDirectoryName(_path)!);
|
||
var workspace = new RecipeWorkspace(Path.GetDirectoryName(_directory)!);
|
||
if (File.Exists(source))
|
||
{
|
||
var imported = workspace.ImportFile(fileName, source, "models");
|
||
model.Path = Path.GetRelativePath(Path.GetDirectoryName(path)!, imported);
|
||
}
|
||
}
|
||
var saved = SopConfigLoader.Save(config, path);
|
||
if (Recipe.Model is not null && config.Sop.Model is not null) Recipe.Model.Path = config.Sop.Model.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);
|
||
|
||
SaveStatus = $"已保存 {Path.GetFileName(_path)}";
|
||
_onSaved?.Invoke(Path.GetFileName(_path));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
// 写盘失败(文件被占用/只读)留给用户看,别让整个编辑器跟着炸
|
||
Warnings.Clear();
|
||
Warnings.Add("保存失败:" + ex.Message);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 用当前编辑结果跑一遍加载器校验(就是"这一步永远不推进"那类问题)
|
||
/// </summary>
|
||
private void RefreshWarnings()
|
||
{
|
||
SaveStatus = "";
|
||
// 步骤和条件字段变化时同步校验,避免方法已选择却仍显示旧的缺失提示。
|
||
var current = new HashSet<EditorNode>(Recipe.Steps);
|
||
foreach (var step in Recipe.Steps)
|
||
if (step.Detection is not null) current.Add(step.Detection);
|
||
foreach (var removed in _observedStepNodes.Except(current).ToArray())
|
||
{
|
||
removed.PropertyChanged -= StepChanged;
|
||
_observedStepNodes.Remove(removed);
|
||
}
|
||
foreach (var added in current.Except(_observedStepNodes))
|
||
{
|
||
added.PropertyChanged += StepChanged;
|
||
_observedStepNodes.Add(added);
|
||
}
|
||
Warnings.Clear();
|
||
|
||
var config = Recipe.ToConfig();
|
||
SopConfigLoader.Validate(config);
|
||
|
||
foreach (var warning in config.Warnings) Warnings.Add(warning);
|
||
}
|
||
|
||
private void StepChanged(object? sender, PropertyChangedEventArgs e) => RefreshWarnings();
|
||
}
|