aisop/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs

337 lines
14 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 partial 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 = "";
private bool _closingDialog;
public string SaveStatus { get => _saveStatus; private set => SetProperty(ref _saveStatus, value); }
public string NameValidationMessage => RecipeWorkspace.GetNameError(Recipe.Name) ?? "";
private BitmapSource? _previewImage;
private string _previewStatus = "选中一个区域后,在图像上拖动画框;Esc 取消本次绘制";
private bool _isCapturing;
private ICameraService? _camera;
private CameraInfo? _cameraInfo;
private Func<CameraInfo?>? _selectedCameraProvider;
private Func<bool> _canUseCamera = () => true;
private Task? _shutdown;
private SopHelper.Training.CameraViewModel? _sopRecording;
public SopHelper.Training.CameraViewModel? SopRecording { get => _sopRecording; private set => SetProperty(ref _sopRecording, value); }
public bool HasSopRecording => SopRecording is not null;
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();
GenerateStepsCommand?.RaiseCanExecuteChanged();
}
}
public DelegateCommand CaptureImageCommand { get; }
public DelegateCommand OpenImageCommand { 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 && !IsAgentBusy && NameValidationMessage.Length == 0);
CloseCommand = new DelegateCommand(async () =>
{
_closingDialog = true; CloseCommand.RaiseCanExecuteChanged();
await ShutdownAsync(); RequestClose.Invoke(ButtonResult.Cancel);
}, () => !IsCapturing && !_closingDialog);
CaptureImageCommand = new DelegateCommand(async () => await CaptureImageAsync(),
() => !IsCapturing && _camera is not null && _cameraInfo is not null);
OpenImageCommand = new DelegateCommand(OpenImage, () => !IsCapturing);
InitializeAgentCommands();
}
/// <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");
_selectedCameraProvider = parameters.GetValue<Func<CameraInfo?>>("selectedCameraProvider") ?? (() => _cameraInfo);
_canUseCamera = parameters.GetValue<Func<bool>>("canUseCamera") ?? (() => true);
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;
InitializeRecipeTools();
LoadAgentSettings();
RefreshWarnings();
}
/// <inheritdoc />
public bool CanCloseDialog() => !IsCapturing;
/// <inheritdoc />
public void OnDialogClosed()
{
_ = ShutdownAsync();
Recipe.Changed -= RefreshWarnings;
foreach (var node in _observedStepNodes) node.PropertyChanged -= StepChanged;
_observedStepNodes.Clear();
_onSaved = null;
}
private void InitializeRecipeTools()
{
if (SopRecording is not null || string.IsNullOrEmpty(_path) || !File.Exists(_path)) return;
// Use a separate camera service so SOP capture cannot dispose the operator page's service.
var recipeDirectory = Path.GetDirectoryName(_path)!;
var root = Path.GetDirectoryName(Path.GetDirectoryName(recipeDirectory)!)!;
SopRecording = new SopHelper.Training.CameraViewModel(new CameraService(), root, Path.GetFileNameWithoutExtension(_path), sopStandard: true, selectedCameraProvider: _selectedCameraProvider);
RaisePropertyChanged(nameof(HasSopRecording));
UpdateAgentDefaultVideo();
}
public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync();
private async Task ShutdownCoreAsync()
{
_agentCancellation?.Cancel();
if (_agentTask is not null) await _agentTask;
ClearAgentDraft();
await ShutdownSopRecordingAsync();
}
public async Task ShutdownSopRecordingAsync()
{
if (SopRecording is null) return;
try { await SopRecording.ShutdownAsync(); }
catch (Exception error) { SaveStatus = "关闭SOP录像时出错:" + error.Message; }
}
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 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 (RecipeWorkspace.GetNameError(Recipe.Name) is { } nameError)
{
SaveStatus = nameError;
return;
}
var fileName = Recipe.Name;
if (!_isNew && fileName != Path.GetFileNameWithoutExtension(_path))
{ SaveStatus = "已有配方名与文件名一致,不可在编辑器中改名"; return; }
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();
config.Sop.Model = null;
var saved = SopConfigLoader.Save(config, path);
_path = path;
_isNew = false;
Recipe.MarkSaved(Path.GetFileNameWithoutExtension(path));
InitializeRecipeTools();
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 = "";
RaisePropertyChanged(nameof(NameValidationMessage));
RaisePropertyChanged(nameof(FileNameText));
SaveCommand.RaiseCanExecuteChanged();
// 步骤和条件字段变化时同步校验,避免方法已选择却仍显示旧的缺失提示。
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();
config.Sop.Model = null;
SopConfigLoader.Validate(config);
foreach (var warning in config.Warnings) Warnings.Add(warning);
}
private void StepChanged(object? sender, PropertyChangedEventArgs e) => RefreshWarnings();
}