From ae79ff3a986944ec8f3436cc84a29fac1f94829b Mon Sep 17 00:00:00 2001
From: sophelper <123211521@163.com>
Date: Sun, 8 Nov 2026 19:55:05 +0800
Subject: [PATCH] Port the full Windows workflow to one shared Avalonia desktop
application
---
SopHelper.Avalonia.slnx | 6 +
src/SopHelper.Avalonia/App.axaml | 9 +
src/SopHelper.Avalonia/App.axaml.cs | 76 ++
.../Assets/BellwetherLogo.axaml | 165 +++
.../Core/Prism/CoreAttribute.cs | 39 +
.../Core/Prism/MessageEvent.cs | 61 +
.../Core/Prism/ModelBase.cs | 48 +
.../Core/Prism/NavigateItem.cs | 31 +
.../Core/Prism/ViewModelBase.cs | 17 +
.../Diagnostics/RuntimeCheck.cs | 28 +
.../Models/NavigationModel.cs | 80 ++
.../Presentation/DesktopPlatform.cs | 62 +
.../Presentation/Imaging.cs | 81 ++
.../Presentation/SelectionConverter.cs | 13 +
.../Presentation/Threading.cs | 28 +
src/SopHelper.Avalonia/Program.cs | 12 +
.../SopHelper.Avalonia.csproj | 27 +
src/SopHelper.Avalonia/Themes/Styles.axaml | 101 ++
.../Training/AnnotationCanvas.cs | 43 +
.../Training/CameraViewModel.cs | 286 +++++
.../Training/CameraWindow.axaml | 64 ++
.../Training/CameraWindow.axaml.cs | 16 +
.../Training/MainViewModel.cs | 367 ++++++
src/SopHelper.Avalonia/Training/Styles.axaml | 73 ++
.../Training/TrainingPage.axaml | 155 +++
.../Training/TrainingPage.axaml.cs | 57 +
.../VVMs/MainWindow/MainWindow.axaml | 37 +
.../VVMs/MainWindow/MainWindow.axaml.cs | 4 +
.../VVMs/MainWindow/MainWindowViewModel.cs | 39 +
.../VVMs/RecipeEditor/EditorNodes.cs | 1011 +++++++++++++++++
.../VVMs/RecipeEditor/RecipeDialogWindow.cs | 15 +
.../VVMs/RecipeEditor/RecipeEditor.axaml | 440 +++++++
.../VVMs/RecipeEditor/RecipeEditor.axaml.cs | 4 +
.../RecipeEditor/RecipeEditorViewModel.cs | 318 ++++++
.../VVMs/RecipeEditor/RegionCanvas.cs | 96 ++
.../VVMs/SopPage/DetectionOverlay.cs | 35 +
.../VVMs/SopPage/HandOverlay.cs | 30 +
.../VVMs/SopPage/SopPage.axaml | 203 ++++
.../VVMs/SopPage/SopPage.axaml.cs | 5 +
.../VVMs/SopPage/SopPageViewModel.cs | 846 ++++++++++++++
.../MvsNativeBindings.cs | 28 +
.../SopHelper.CrossPlatform.Engine.csproj | 4 +
tests/Avalonia.Smoke/Avalonia.Smoke.csproj | 7 +
tests/Avalonia.Smoke/Program.cs | 166 +++
44 files changed, 5233 insertions(+)
create mode 100644 SopHelper.Avalonia.slnx
create mode 100644 src/SopHelper.Avalonia/App.axaml
create mode 100644 src/SopHelper.Avalonia/App.axaml.cs
create mode 100644 src/SopHelper.Avalonia/Assets/BellwetherLogo.axaml
create mode 100644 src/SopHelper.Avalonia/Core/Prism/CoreAttribute.cs
create mode 100644 src/SopHelper.Avalonia/Core/Prism/MessageEvent.cs
create mode 100644 src/SopHelper.Avalonia/Core/Prism/ModelBase.cs
create mode 100644 src/SopHelper.Avalonia/Core/Prism/NavigateItem.cs
create mode 100644 src/SopHelper.Avalonia/Core/Prism/ViewModelBase.cs
create mode 100644 src/SopHelper.Avalonia/Diagnostics/RuntimeCheck.cs
create mode 100644 src/SopHelper.Avalonia/Models/NavigationModel.cs
create mode 100644 src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs
create mode 100644 src/SopHelper.Avalonia/Presentation/Imaging.cs
create mode 100644 src/SopHelper.Avalonia/Presentation/SelectionConverter.cs
create mode 100644 src/SopHelper.Avalonia/Presentation/Threading.cs
create mode 100644 src/SopHelper.Avalonia/Program.cs
create mode 100644 src/SopHelper.Avalonia/SopHelper.Avalonia.csproj
create mode 100644 src/SopHelper.Avalonia/Themes/Styles.axaml
create mode 100644 src/SopHelper.Avalonia/Training/AnnotationCanvas.cs
create mode 100644 src/SopHelper.Avalonia/Training/CameraViewModel.cs
create mode 100644 src/SopHelper.Avalonia/Training/CameraWindow.axaml
create mode 100644 src/SopHelper.Avalonia/Training/CameraWindow.axaml.cs
create mode 100644 src/SopHelper.Avalonia/Training/MainViewModel.cs
create mode 100644 src/SopHelper.Avalonia/Training/Styles.axaml
create mode 100644 src/SopHelper.Avalonia/Training/TrainingPage.axaml
create mode 100644 src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/MainWindow/MainWindow.axaml
create mode 100644 src/SopHelper.Avalonia/VVMs/MainWindow/MainWindow.axaml.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/MainWindow/MainWindowViewModel.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeDialogWindow.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
create mode 100644 src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/RecipeEditor/RegionCanvas.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/SopPage/DetectionOverlay.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/SopPage/HandOverlay.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
create mode 100644 src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml.cs
create mode 100644 src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
create mode 100644 src/SopHelper.CrossPlatform.Engine/MvsNativeBindings.cs
create mode 100644 tests/Avalonia.Smoke/Avalonia.Smoke.csproj
create mode 100644 tests/Avalonia.Smoke/Program.cs
diff --git a/SopHelper.Avalonia.slnx b/SopHelper.Avalonia.slnx
new file mode 100644
index 0000000..e57f17b
--- /dev/null
+++ b/SopHelper.Avalonia.slnx
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/src/SopHelper.Avalonia/App.axaml b/src/SopHelper.Avalonia/App.axaml
new file mode 100644
index 0000000..e6164b9
--- /dev/null
+++ b/src/SopHelper.Avalonia/App.axaml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
diff --git a/src/SopHelper.Avalonia/App.axaml.cs b/src/SopHelper.Avalonia/App.axaml.cs
new file mode 100644
index 0000000..b0ad003
--- /dev/null
+++ b/src/SopHelper.Avalonia/App.axaml.cs
@@ -0,0 +1,76 @@
+using System.Reflection;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.ApplicationLifetimes;
+using Avalonia.Markup.Xaml;
+using Prism.DryIoc;
+using Prism.Ioc;
+using Prism.Mvvm;
+using SopHelper.Core.Prism;
+using SopHelper.Engine.Camera;
+using SopHelper.Engine.Pipeline;
+using SopHelper.Engine.Sop;
+using SopHelper.Models;
+using SopHelper.VVMs.MainWindow;
+using SopHelper.VVMs.RecipeEditor;
+using SopHelper.VVMs.SopPage;
+
+namespace SopHelper;
+public partial class App : PrismApplication
+{
+ private ICameraService? _camera;
+ private DetectionPipeline? _pipeline;
+ private Engine.Training.WorkerClient? _worker;
+ public App() { }
+ public App(ICameraService camera) { _camera=camera; }
+ public override void Initialize() { AvaloniaXamlLoader.Load(this); base.Initialize(); }
+ protected override void RegisterTypes(IContainerRegistry containerRegistry)
+ {
+ AppDomain.CurrentDomain.UnhandledException+=(_,e)=>Log(e.ExceptionObject as Exception,"AppDomain");
+ Avalonia.Threading.Dispatcher.UIThread.UnhandledException+=(_,e)=>{Log(e.Exception,"Dispatcher");e.Handled=true;};
+ foreach(var model in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute()!=null))
+ containerRegistry.RegisterSingleton(model);
+ foreach(var view in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute()!=null))
+ containerRegistry.RegisterForNavigation(view,view.Name);
+ containerRegistry.RegisterSingleton();
+ _camera??=new CameraService();_pipeline=new DetectionPipeline(_camera);
+ containerRegistry.RegisterInstance(_camera);
+ containerRegistry.RegisterInstance(_pipeline);
+ containerRegistry.RegisterSingleton();
+ containerRegistry.RegisterSingleton();
+ _worker=new Engine.Training.WorkerClient();containerRegistry.RegisterInstance(_worker);
+ containerRegistry.RegisterSingleton();
+ containerRegistry.RegisterDialog("RecipeEditorDialog");
+ containerRegistry.RegisterDialogWindow();
+ }
+ protected override AvaloniaObject CreateShell()
+ {
+ var navigation=Container.Resolve();
+ foreach(var type in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute()!=null)
+ .OrderBy(t=>t.GetCustomAttribute()!.Index))
+ {
+ var page=type.GetCustomAttribute()!;
+ var item=Container.Resolve();item.ViewName=page.ViewName;item.DisplayName=page.DisplayName;navigation.Pages.Add(item);
+ }
+ var window=Container.Resolve();
+ window.Opened+=(_,_)=> { if(navigation.Pages.Count>0) navigation.SelectedIndex=0; };
+ window.Closed+=(_,_)=>
+ {
+ _worker?.Dispose();
+ try{_camera?.Dispose();}catch(Exception ex){Log(ex,"Exit.Camera");}
+ try{_pipeline?.Dispose();}catch(Exception ex){Log(ex,"Exit.Pipeline");}
+ };
+ return window;
+ }
+ protected override void ConfigureViewModelLocator()
+ {
+ base.ConfigureViewModelLocator();
+ ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver(t=>Type.GetType($"{t.FullName}ViewModel, {t.Assembly.FullName}"));
+ }
+ private static void Log(Exception? exception,string from)
+ {
+ if(exception is null)return;
+ var line=$"[{DateTime.Now:HH:mm:ss.fff}] [{from}] {exception.Message}";Console.WriteLine(line);
+ try{Directory.CreateDirectory("logs");File.AppendAllText(Path.Combine("logs","error.log"),line+Environment.NewLine);}catch{ }
+ }
+}
diff --git a/src/SopHelper.Avalonia/Assets/BellwetherLogo.axaml b/src/SopHelper.Avalonia/Assets/BellwetherLogo.axaml
new file mode 100644
index 0000000..b5e4b46
--- /dev/null
+++ b/src/SopHelper.Avalonia/Assets/BellwetherLogo.axaml
@@ -0,0 +1,165 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/SopHelper.Avalonia/Core/Prism/CoreAttribute.cs b/src/SopHelper.Avalonia/Core/Prism/CoreAttribute.cs
new file mode 100644
index 0000000..29ab00c
--- /dev/null
+++ b/src/SopHelper.Avalonia/Core/Prism/CoreAttribute.cs
@@ -0,0 +1,39 @@
+namespace SopHelper.Core.Prism;
+
+///
+/// 标志此特性的类会被注册为单例(照搬 plcsharp 约定)
+///
+[AttributeUsage(AttributeTargets.Class)]
+public class ModelAttribute : Attribute
+{
+}
+
+///
+/// 标志此特性的 View 会被注册到导航列表
+///
+[AttributeUsage(AttributeTargets.Class)]
+public class NavigationPageAttribute : Attribute
+{
+ ///
+ /// 视图名称(导航用)
+ ///
+ public string ViewName { get; set; } = "";
+
+ ///
+ /// Display名称
+ ///
+ public string DisplayName { get; set; } = "";
+
+ ///
+ /// 排序序号
+ ///
+ public int Index { get; set; }
+}
+
+///
+/// 标志此特性的类会被注册为弹出窗口
+///
+[AttributeUsage(AttributeTargets.Class)]
+public class DialogAttribute : Attribute
+{
+}
diff --git a/src/SopHelper.Avalonia/Core/Prism/MessageEvent.cs b/src/SopHelper.Avalonia/Core/Prism/MessageEvent.cs
new file mode 100644
index 0000000..b0b9370
--- /dev/null
+++ b/src/SopHelper.Avalonia/Core/Prism/MessageEvent.cs
@@ -0,0 +1,61 @@
+using Prism.Events;
+
+namespace SopHelper.Core.Prism;
+
+///
+/// 全局消息事件(照搬 plcsharp:模块间解耦都走事件聚合器)
+///
+public class MessageEvent : PubSubEvent
+{
+}
+
+///
+/// 消息内容
+///
+public struct Message
+{
+ ///
+ /// 消息目标
+ ///
+ public string Target { get; set; }
+
+ ///
+ /// 消息
+ ///
+ public string Content { get; set; }
+
+ ///
+ /// 消息类型 1 记录 2 弹出 3 弹出并记录
+ ///
+ public ShowType Type { get; set; }
+
+ ///
+ /// 级别
+ ///
+ public MsgLevel Level { get; set; }
+}
+
+///
+/// 显示方式
+///
+public enum ShowType
+{
+ /// 仅记录日志
+ Log = 1,
+
+ /// 仅提示
+ Show = 2,
+
+ /// 提示并记录
+ Both = 3,
+}
+
+///
+/// 消息级别
+///
+public enum MsgLevel
+{
+ Info,
+ Warn,
+ Error,
+}
diff --git a/src/SopHelper.Avalonia/Core/Prism/ModelBase.cs b/src/SopHelper.Avalonia/Core/Prism/ModelBase.cs
new file mode 100644
index 0000000..1562226
--- /dev/null
+++ b/src/SopHelper.Avalonia/Core/Prism/ModelBase.cs
@@ -0,0 +1,48 @@
+using Prism.Events;
+using Prism.Ioc;
+using Prism.Mvvm;
+
+namespace SopHelper.Core.Prism;
+
+///
+/// 模型Base
+///
+public class ModelBase : BindableBase
+{
+ ///
+ /// 事件聚合器
+ ///
+ protected readonly IEventAggregator _eventAggregator;
+
+ ///
+ /// DI 容器
+ ///
+ protected readonly IContainerExtension _container;
+
+ ///
+ /// 模型Base
+ ///
+ public ModelBase(IContainerExtension container, IEventAggregator ea)
+ {
+ _container = container;
+ _eventAggregator = ea;
+
+ _eventAggregator.GetEvent().Subscribe(OnMessage, ThreadOption.PublisherThread, true);
+
+ AppDomain.CurrentDomain.ProcessExit += OnExit;
+ }
+
+ ///
+ /// 收到消息(子类覆写做本模块的落库/统计)
+ ///
+ protected virtual void OnMessage(Message message)
+ {
+ }
+
+ ///
+ /// 进程退出(子类覆写做释放)
+ ///
+ protected virtual void OnExit(object? sender, EventArgs e)
+ {
+ }
+}
diff --git a/src/SopHelper.Avalonia/Core/Prism/NavigateItem.cs b/src/SopHelper.Avalonia/Core/Prism/NavigateItem.cs
new file mode 100644
index 0000000..4af4c70
--- /dev/null
+++ b/src/SopHelper.Avalonia/Core/Prism/NavigateItem.cs
@@ -0,0 +1,31 @@
+using Prism.Mvvm;
+
+namespace SopHelper.Core.Prism;
+
+///
+/// Navigate项
+///
+public class NavigateItem : BindableBase
+{
+ private string _viewName = "";
+
+ ///
+ /// 视图名称
+ ///
+ public string ViewName
+ {
+ get { return _viewName; }
+ set { SetProperty(ref _viewName, value); }
+ }
+
+ private string _displayName = "";
+
+ ///
+ /// Display名称
+ ///
+ public string DisplayName
+ {
+ get { return _displayName; }
+ set { SetProperty(ref _displayName, value); }
+ }
+}
diff --git a/src/SopHelper.Avalonia/Core/Prism/ViewModelBase.cs b/src/SopHelper.Avalonia/Core/Prism/ViewModelBase.cs
new file mode 100644
index 0000000..40777ed
--- /dev/null
+++ b/src/SopHelper.Avalonia/Core/Prism/ViewModelBase.cs
@@ -0,0 +1,17 @@
+using Prism.Mvvm;
+using Prism.Navigation;
+
+namespace SopHelper.Core.Prism;
+
+///
+/// 视图模型Base
+///
+public abstract class ViewModelBase : BindableBase, IDestructible
+{
+ ///
+ /// Destroy
+ ///
+ public virtual void Destroy()
+ {
+ }
+}
diff --git a/src/SopHelper.Avalonia/Diagnostics/RuntimeCheck.cs b/src/SopHelper.Avalonia/Diagnostics/RuntimeCheck.cs
new file mode 100644
index 0000000..da513ae
--- /dev/null
+++ b/src/SopHelper.Avalonia/Diagnostics/RuntimeCheck.cs
@@ -0,0 +1,28 @@
+using System.Text.Json;
+using OpenCvSharp;
+using SopHelper.Engine.Common;
+using SopHelper.Engine.Inference;
+using SopHelper.Engine.Sop;
+
+namespace SopHelper.Diagnostics;
+
+internal static class RuntimeCheck
+{
+ public static int Run()
+ {
+ try
+ {
+ var root=AppContext.BaseDirectory;
+ using var yolo=new YoloDetector();using var hand=new MediaPipeHandDetector();
+ yolo.Load(Path.Combine(root,"models/yolo11n.onnx"),[],preferGpu:false);
+ hand.Load(Path.Combine(root,"models/palm_detection_full_Nx3x192x192_post.onnx"),Path.Combine(root,"models/hand_landmark_sparse_Nx3x224x224.onnx"),false);
+ if(!yolo.IsReady||!hand.IsReady)throw new InvalidOperationException("模型未加载");
+ using var frame=new Mat(480,640,MatType.CV_8UC3,Scalar.Black);yolo.Detect(frame);hand.Detect(frame);
+ var config=SopConfigLoader.Parse("sop:\n name: runtime-check\n settings:\n auto_reset_on_complete: false\n steps:\n - id: 1\n name: timer\n detection:\n method: time_elapsed\n duration_ms: 1\n");
+ var engine=new SopEngine();engine.Load(config);engine.Start();Thread.Sleep(10);engine.ProcessFrame(new FrameResult());
+ if(engine.State!=EngineState.Completed)throw new Exception("SOP 状态机测试失败");
+ Console.WriteLine(JsonSerializer.Serialize(new{passed=true,opencv=Cv2.GetVersionString(),classes=yolo.ClassNames.Count,hand=hand.IsReady,sop=engine.State.ToString()}));return 0;
+ }
+ catch(Exception error){Console.Error.WriteLine(error);return 1;}
+ }
+}
diff --git a/src/SopHelper.Avalonia/Models/NavigationModel.cs b/src/SopHelper.Avalonia/Models/NavigationModel.cs
new file mode 100644
index 0000000..06027e9
--- /dev/null
+++ b/src/SopHelper.Avalonia/Models/NavigationModel.cs
@@ -0,0 +1,80 @@
+using System.Collections.ObjectModel;
+using Prism.Events;
+using Prism.Ioc;
+using Prism.Navigation.Regions;
+using SopHelper.Core.Prism;
+
+namespace SopHelper.Models;
+
+///
+/// Navigate模型
+///
+[Model]
+public class NavigationModel : ModelBase
+{
+ private readonly IRegionManager _regionManager;
+
+ ///
+ /// Navigate模型
+ ///
+ public NavigationModel(IContainerExtension container, IEventAggregator ea, IRegionManager regionManager)
+ : base(container, ea)
+ {
+ _regionManager = regionManager;
+ }
+
+ private ObservableCollection _pages = [];
+
+ ///
+ /// 导航页列表(shell 侧栏绑定)
+ ///
+ public ObservableCollection Pages
+ {
+ get { return _pages; }
+ set { SetProperty(ref _pages, value); }
+ }
+
+ private NavigateItem? _target;
+
+ ///
+ /// 当前页
+ ///
+ public NavigateItem? Target
+ {
+ get { return _target; }
+ set { SetProperty(ref _target, value); }
+ }
+
+ private int _selectedIndex = -1;
+
+ ///
+ /// 侧栏选中索引
+ ///
+ public int SelectedIndex
+ {
+ get { return _selectedIndex; }
+ set
+ {
+ if (!SetProperty(ref _selectedIndex, value)) return;
+ if (value >= 0 && value < Pages.Count) Navigate(Pages[value].ViewName);
+ }
+ }
+
+ ///
+ /// 导航到指定页
+ ///
+ public void Navigate(string viewName)
+ {
+ if (string.IsNullOrEmpty(viewName)) return;
+
+ Target = Pages.FirstOrDefault(n => n.ViewName == viewName);
+ if (Target is null) return;
+
+ _regionManager.RequestNavigate(ContentRegion, viewName);
+ }
+
+ ///
+ /// 内容区名(shell 与导航的唯一约定)
+ ///
+ public const string ContentRegion = "ContentRegion";
+}
diff --git a/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs
new file mode 100644
index 0000000..fd259c0
--- /dev/null
+++ b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs
@@ -0,0 +1,62 @@
+using System.Diagnostics;
+using Avalonia.Controls;
+using Avalonia.Controls.ApplicationLifetimes;
+using Avalonia.Platform.Storage;
+
+namespace SopHelper.Presentation;
+
+internal static class DesktopPlatform
+{
+ public static Window Owner => ((IClassicDesktopStyleApplicationLifetime)Avalonia.Application.Current!.ApplicationLifetime!).MainWindow!;
+ public static string PythonPath
+ {
+ get
+ {
+ var relative=OperatingSystem.IsWindows()?Path.Combine("python","python.exe"):Path.Combine("python","bin","python3");
+ var bundled=Path.Combine(AppContext.BaseDirectory,relative);
+ if(File.Exists(bundled))return bundled;
+ // Source-tree builds use the same repository-managed runtime; published apps bundle it.
+ for(var directory=new DirectoryInfo(AppContext.BaseDirectory);directory is not null;directory=directory.Parent)
+ if(File.Exists(Path.Combine(directory.FullName,"SopHelper.Avalonia.slnx")))return Path.Combine(directory.FullName,relative);
+ return bundled;
+ }
+ }
+ public static void Reveal(string path)
+ {
+ var directory=File.Exists(path)?Path.GetDirectoryName(path)!:path;
+ var info=new ProcessStartInfo(OperatingSystem.IsWindows()?"explorer.exe":"xdg-open") { UseShellExecute=false };
+ info.ArgumentList.Add(directory); Process.Start(info);
+ }
+}
+public sealed class OpenFileDialog
+{
+ public string Title { get; set; } = "选择文件";
+ public string Filter { get; set; } = "所有文件|*.*";
+ public string DefaultExt { get; set; } = "";
+ public bool CheckFileExists { get; set; } = true;
+ public bool Multiselect { get; set; }
+ public string InitialDirectory { get; set; } = "";
+ public string FileName { get; set; } = "";
+ public async Task ShowDialogAsync()
+ {
+ var storage=DesktopPlatform.Owner.StorageProvider;
+ var filters=Filter.Split('|');var types=new List();
+ for(var i=0;i+1 ShowDialogAsync()
+ {
+ var storage=DesktopPlatform.Owner.StorageProvider;
+ var folders=await storage.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title=Title,AllowMultiple=false,
+ SuggestedStartLocation=Directory.Exists(InitialDirectory)?await storage.TryGetFolderFromPathAsync(InitialDirectory):null });
+ if(folders.Count==0)return false; FolderName=folders[0].TryGetLocalPath()??throw new IOException("请选择本地文件夹");return true;
+ }
+}
diff --git a/src/SopHelper.Avalonia/Presentation/Imaging.cs b/src/SopHelper.Avalonia/Presentation/Imaging.cs
new file mode 100644
index 0000000..1cda070
--- /dev/null
+++ b/src/SopHelper.Avalonia/Presentation/Imaging.cs
@@ -0,0 +1,81 @@
+using System.Runtime.InteropServices;
+using Avalonia;
+using Avalonia.Media;
+using Avalonia.Platform;
+using NativeBitmap = Avalonia.Media.Imaging.Bitmap;
+using NativeWritableBitmap = Avalonia.Media.Imaging.WriteableBitmap;
+
+namespace SopHelper.Presentation.Imaging;
+
+// Keeps the original acquisition/rendering ownership contract while using Avalonia bitmaps.
+// Immutable snapshots can be created by acquisition threads; mutable previews are UI-thread owned.
+public class BitmapSource : IImage, IDisposable
+{
+ protected NativeBitmap? Native;
+ public int PixelWidth => Native?.PixelSize.Width ?? 0;
+ public int PixelHeight => Native?.PixelSize.Height ?? 0;
+ public Size Size => Native?.Size ?? default;
+ public void Draw(DrawingContext context, Rect sourceRect, Rect destRect)
+ { if (Native is not null) context.DrawImage(Native,sourceRect,destRect); }
+ public BitmapSource Clone()
+ {
+ using var stream = new MemoryStream(); Native!.Save(stream); stream.Position=0;
+ return new BitmapSource { Native = new NativeBitmap(stream) };
+ }
+ public void Freeze() { /* Avalonia Bitmap snapshots are immutable already. */ }
+ public void Save(string path) => Native!.Save(path);
+ public void Dispose() { Native?.Dispose(); Native=null; GC.SuppressFinalize(this); }
+ public static BitmapSource Create(int width,int height,double dpiX,double dpiY,PixelFormat format,object? palette,
+ IntPtr data,int bufferSize,int stride)
+ {
+ if (bufferSize < checked(stride*height)) throw new ArgumentException("图像缓冲不足");
+ var input=new byte[bufferSize];Marshal.Copy(data,input,0,bufferSize);
+ using var converted=new WriteableBitmap(width,height,dpiX,dpiY,format,palette);
+ converted.WritePixels(new PixelRect(0,0,width,height),input,stride,0);
+ return converted.Snapshot();
+ }
+ public static unsafe BitmapSource Create(int width,int height,double dpiX,double dpiY,PixelFormat format,object? palette,byte[] bytes,int stride)
+ {fixed(byte* data=bytes)return Create(width,height,dpiX,dpiY,format,palette,(IntPtr)data,bytes.Length,stride);}
+}
+public enum BitmapCacheOption { OnLoad }
+public sealed class BitmapImage : BitmapSource
+{
+ public Uri? UriSource { get; set; }
+ public BitmapCacheOption CacheOption { get; set; }
+ public void BeginInit() { }
+ public void EndInit() { Native?.Dispose(); Native = new NativeBitmap(UriSource!.LocalPath); }
+}
+public sealed class WriteableBitmap : BitmapSource
+{
+ public WriteableBitmap(int width,int height,double dpiX,double dpiY,PixelFormat format,object? palette)
+ { Native = new NativeWritableBitmap(new PixelSize(width,height),new Vector(dpiX,dpiY),format,AlphaFormat.Opaque); }
+ public void WritePixels(PixelRect rect,byte[] bytes,int stride,int offset)
+ {
+ using var framebuffer=((NativeWritableBitmap)Native!).Lock();
+ if (rect.X!=0 || rect.Y!=0 || rect.Width!=PixelWidth || rect.Height!=PixelHeight) throw new ArgumentException("预览需写入完整帧");
+ var rowBytes=new byte[rect.Width*4];
+ for(var row=0;row
+ new OwnedSnapshot(address,width,height,stride);
+ private sealed class OwnedSnapshot : BitmapSource
+ {
+ public OwnedSnapshot(IntPtr address,int width,int height,int stride)
+ {Native=new NativeBitmap(PixelFormat.Bgra8888,AlphaFormat.Opaque,address,new PixelSize(width,height),new Vector(96,96),stride);}
+ }
+}
+public static class PixelFormats
+{
+ // Public acquisition buffers are BGR24; the adapter expands them to Avalonia's BGRA surface.
+ public static PixelFormat Bgr24 => PixelFormat.Bgra8888;
+}
diff --git a/src/SopHelper.Avalonia/Presentation/SelectionConverter.cs b/src/SopHelper.Avalonia/Presentation/SelectionConverter.cs
new file mode 100644
index 0000000..4438c00
--- /dev/null
+++ b/src/SopHelper.Avalonia/Presentation/SelectionConverter.cs
@@ -0,0 +1,13 @@
+using System.Globalization;
+using Avalonia.Data;
+using Avalonia.Data.Converters;
+
+namespace SopHelper.Presentation;
+
+public sealed class SelectionConverter : IValueConverter
+{
+ public object? Convert(object? value,Type targetType,object? parameter,CultureInfo culture)=>value;
+ // Avalonia clears selection while attaching/replacing an ItemsSource. That transient
+ // null must not erase a recipe field. Selecting the explicit empty-string item still works.
+ public object? ConvertBack(object? value,Type targetType,object? parameter,CultureInfo culture)=>value??BindingOperations.DoNothing;
+}
diff --git a/src/SopHelper.Avalonia/Presentation/Threading.cs b/src/SopHelper.Avalonia/Presentation/Threading.cs
new file mode 100644
index 0000000..e7bbc52
--- /dev/null
+++ b/src/SopHelper.Avalonia/Presentation/Threading.cs
@@ -0,0 +1,28 @@
+namespace SopHelper.Presentation.Threading;
+
+// UI scheduling is shared by both targets. No Win32/WPF dispatcher is involved.
+public enum DispatcherPriority { Normal, Background }
+public sealed class Dispatcher
+{
+ public static Dispatcher CurrentDispatcher { get; } = new();
+ public bool HasShutdownStarted => Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime { MainWindow: null };
+ public void BeginInvoke(Action action, DispatcherPriority priority = DispatcherPriority.Normal) =>
+ Avalonia.Threading.Dispatcher.UIThread.Post(action, priority == DispatcherPriority.Background
+ ? Avalonia.Threading.DispatcherPriority.Background : Avalonia.Threading.DispatcherPriority.Normal);
+ public void Invoke(Action action)
+ {
+ if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) action();
+ else Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(action).GetAwaiter().GetResult();
+ }
+}
+public sealed class DispatcherTimer
+{
+ private readonly Avalonia.Threading.DispatcherTimer _timer = new();
+ public TimeSpan Interval { get => _timer.Interval; set => _timer.Interval = value; }
+ public event EventHandler? Tick { add => _timer.Tick += value; remove => _timer.Tick -= value; }
+ public DispatcherTimer() { }
+ public DispatcherTimer(TimeSpan interval, DispatcherPriority priority, EventHandler tick, Dispatcher dispatcher)
+ { Interval = interval; Tick += tick; Start(); }
+ public void Start() => _timer.Start();
+ public void Stop() => _timer.Stop();
+}
diff --git a/src/SopHelper.Avalonia/Program.cs b/src/SopHelper.Avalonia/Program.cs
new file mode 100644
index 0000000..eea8a6a
--- /dev/null
+++ b/src/SopHelper.Avalonia/Program.cs
@@ -0,0 +1,12 @@
+using Avalonia;
+
+namespace SopHelper;
+internal static class Program
+{
+ [STAThread]
+ public static int Main(string[] args)
+ {
+ if(args.Contains("--check-runtime"))return Diagnostics.RuntimeCheck.Run();
+ return AppBuilder.Configure().UsePlatformDetect().LogToTrace().StartWithClassicDesktopLifetime(args);
+ }
+}
diff --git a/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj b/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj
new file mode 100644
index 0000000..39095ba
--- /dev/null
+++ b/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj
@@ -0,0 +1,27 @@
+
+
+ WinExe
+ net8.0
+ enable
+ enable
+ true
+ SopHelper
+ false
+
+ $(NoWarn);AVLN3001
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/SopHelper.Avalonia/Themes/Styles.axaml b/src/SopHelper.Avalonia/Themes/Styles.axaml
new file mode 100644
index 0000000..81cc095
--- /dev/null
+++ b/src/SopHelper.Avalonia/Themes/Styles.axaml
@@ -0,0 +1,101 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs b/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs
new file mode 100644
index 0000000..e62d584
--- /dev/null
+++ b/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs
@@ -0,0 +1,43 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+using SopHelper.Presentation.Imaging;
+
+namespace SopHelper.Training;
+public sealed class AnnotationCanvas : Control
+{
+ public static readonly StyledProperty SourceProperty=AvaloniaProperty.Register(nameof(Source));
+ public static readonly StyledProperty BoxProperty=AvaloniaProperty.Register(nameof(Box));
+ public BitmapSource? Source {get=>GetValue(SourceProperty);set=>SetValue(SourceProperty,value);}
+ public double[]? Box {get=>GetValue(BoxProperty);set=>SetValue(BoxProperty,value);}
+ public event Action? BoxDrawn;
+ private Point? _start;private Point _end;private IPointer? _pointer;
+ static AnnotationCanvas(){AffectsRender(SourceProperty,BoxProperty);}
+ public AnnotationCanvas(){ClipToBounds=true;Cursor=new Cursor(StandardCursorType.Cross);Focusable=true;}
+ private Rect ImageRect=>Source is null?default:VVMs.RecipeEditor.RegionCanvas.FitImage(Bounds.Size,new Size(Source.PixelWidth,Source.PixelHeight));
+ public override void Render(DrawingContext dc)
+ {
+ dc.DrawRectangle(Brushes.Transparent,null,new Rect(Bounds.Size));var image=ImageRect;if(Source is null||image.Width<=0)return;
+ dc.DrawImage(Source,image);var pen=new Pen(new SolidColorBrush(Color.FromRgb(0,220,220)),2);
+ if(Box is { Length:4 } b)
+ {var scale=image.Width/Source.PixelWidth;dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(30,0,220,220)),pen,new Rect(image.X+b[0]*scale,image.Y+b[1]*scale,(b[2]-b[0])*scale,(b[3]-b[1])*scale));}
+ if(_start is {} start)dc.DrawRectangle(null,new Pen(Brushes.Yellow,2),DragRect(start,_end));
+ }
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if(!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed||!IsEnabled||Source is null||!ImageRect.Contains(e.GetPosition(this)))return;
+ Focus();_start=_end=e.GetPosition(this);_pointer=e.Pointer;_pointer.Capture(this);InvalidateVisual();e.Handled=true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {if(_start is null)return;var p=e.GetPosition(this);var image=ImageRect;_end=new Point(Math.Clamp(p.X,image.Left,image.Right),Math.Clamp(p.Y,image.Top,image.Bottom));InvalidateVisual();}
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if(_start is not {} start||Source is null)return;
+ var rectangle=DragRect(start,_end);var image=ImageRect;_start=null;_pointer?.Capture(null);_pointer=null;InvalidateVisual();
+ if(rectangle.Width<3||rectangle.Height<3||image.Width<=0)return;
+ var scale=Source.PixelWidth/image.Width;BoxDrawn?.Invoke([(rectangle.Left-image.Left)*scale,(rectangle.Top-image.Top)*scale,Math.Min(Source.PixelWidth,(rectangle.Right-image.Left)*scale),Math.Min(Source.PixelHeight,(rectangle.Bottom-image.Top)*scale)]);
+ }
+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e){_start=null;_pointer=null;InvalidateVisual();base.OnPointerCaptureLost(e);}
+ private static Rect DragRect(Point a,Point b)=>new(Math.Min(a.X,b.X),Math.Min(a.Y,b.Y),Math.Abs(a.X-b.X),Math.Abs(a.Y-b.Y));
+}
diff --git a/src/SopHelper.Avalonia/Training/CameraViewModel.cs b/src/SopHelper.Avalonia/Training/CameraViewModel.cs
new file mode 100644
index 0000000..a594a58
--- /dev/null
+++ b/src/SopHelper.Avalonia/Training/CameraViewModel.cs
@@ -0,0 +1,286 @@
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.IO;
+using System.Text.Json;
+using Avalonia;
+using SopHelper.Presentation;
+using Avalonia.Media;
+using SopHelper.Presentation.Imaging;
+using SopHelper.Presentation.Threading;
+using OpenCvSharp;
+using SopHelper.Engine.Camera;
+using Prism.Commands;
+using Prism.Mvvm;
+
+namespace SopHelper.Training;
+
+public sealed class CameraViewModel : BindableBase
+{
+ private readonly ICameraService _camera;
+ private readonly VideoRecorder _recorder = new();
+ private readonly object _frames = new();
+ private readonly Dispatcher _dispatcher;
+ private readonly DispatcherTimer _timer;
+ private readonly string _settingsPath;
+ private readonly Stopwatch _previewClock = Stopwatch.StartNew();
+ private Mat? _latest;
+ private int _previewPending;
+ private int _generation;
+ private long _lastFrameTick;
+ private volatile bool _closing;
+ private bool _busy, _previewing, _recording;
+ private string _status = "刷新设备列表,选择相机后开启预览";
+ private string _directory;
+ private string _lastRecording = "";
+ private string _recordingInfo = "未录像";
+ private CameraInfo? _selected;
+ private BitmapSource? _preview;
+ private Task _operation = Task.CompletedTask;
+ private Task? _shutdown;
+ private readonly List _commands = [];
+
+ public ObservableCollection Cameras { get; } = [];
+ public CameraInfo? SelectedCamera { get => _selected; set { SetProperty(ref _selected, value); UpdateCommands(); } }
+ public BitmapSource? Preview { get => _preview; private set => SetProperty(ref _preview, value); }
+ public string Status { get => _status; private set => SetProperty(ref _status, value); }
+ public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); StateChanged(); } }
+ public bool IsPreviewing { get => _previewing; private set { SetProperty(ref _previewing, value); StateChanged(); } }
+ public bool IsRecording { get => _recording; private set { SetProperty(ref _recording, value); StateChanged(); } }
+ public bool CanChooseCamera => !IsBusy && !IsPreviewing && !_closing;
+ public bool CanChangeDirectory => !IsBusy && !IsRecording && !_closing;
+ public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览";
+ public string RecordButtonText => IsRecording ? "停止录像" : "开始录像";
+ public string RecordingInfo { get => _recordingInfo; private set => SetProperty(ref _recordingInfo, value); }
+ public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, value); }
+ public string LastRecording { get => _lastRecording; private set { SetProperty(ref _lastRecording, value); UpdateCommands(); } }
+ public double RecordingFps { get; set; } = 30;
+ public DelegateCommand RefreshCommand { get; }
+ public DelegateCommand PreviewCommand { get; }
+ public DelegateCommand RecordCommand { get; }
+ public DelegateCommand BrowseCommand { get; }
+ public DelegateCommand RevealCommand { get; }
+
+ public CameraViewModel(ICameraService camera, string root)
+ {
+ _camera = camera; _dispatcher = Dispatcher.CurrentDispatcher;
+ _directory = Path.Combine(root, "workspace", "recordings");
+ _settingsPath = Path.Combine(root, "workspace", "camera-settings.json");
+ try
+ {
+ if (File.Exists(_settingsPath))
+ {
+ using var json = JsonDocument.Parse(File.ReadAllText(_settingsPath));
+ SaveDirectory = json.RootElement.GetProperty("directory").GetString() ?? _directory;
+ }
+ }
+ catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; }
+ RefreshCommand = Command(RefreshAsync, () => CanChooseCamera);
+ PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && (IsPreviewing || SelectedCamera != null));
+ RecordCommand = Command(ToggleRecordingAsync, () => !IsBusy && !_closing && (IsRecording || (IsPreviewing && Preview != null && HasRecentFrame)));
+ BrowseCommand = Command(async () =>
+ {
+ var picker = new OpenFolderDialog { Title = "选择录像保存目录" };
+ if (Directory.Exists(SaveDirectory)) picker.InitialDirectory = SaveDirectory;
+ if (await picker.ShowDialogAsync() == true) { SaveDirectory = picker.FolderName; SaveSettings(); }
+ }, () => CanChangeDirectory);
+ RevealCommand = Command(() =>
+ {
+ if (!string.IsNullOrEmpty(LastRecording) && File.Exists(LastRecording))
+ {
+ DesktopPlatform.Reveal(LastRecording);
+ }
+ else
+ {
+ Directory.CreateDirectory(SaveDirectory);
+ var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true };
+ info.ArgumentList.Add(Path.GetFullPath(SaveDirectory)); Process.Start(info);
+ }
+ return Task.CompletedTask;
+ }, () => !IsBusy && !_closing);
+ _camera.FrameArrived += OnFrame;
+ _camera.ConnectionChanged += OnConnection;
+ _camera.Error += OnError;
+ _timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Tick(), _dispatcher);
+ _timer.Start();
+ }
+
+ private DelegateCommand Command(Func action, Func canExecute)
+ {
+ var command = new DelegateCommand(() => _operation = PerformAsync(action), canExecute);
+ _commands.Add(command); return command;
+ }
+ private async Task PerformAsync(Func action)
+ {
+ if (IsBusy || _closing) return;
+ IsBusy = true;
+ try { await action(); }
+ catch (Exception e) { Status = e.Message; }
+ finally { IsBusy = false; }
+ }
+ private void UpdateCommands() { foreach (var command in _commands) command.RaiseCanExecuteChanged(); }
+ private void StateChanged()
+ {
+ RaisePropertyChanged(nameof(CanChooseCamera)); RaisePropertyChanged(nameof(CanChangeDirectory));
+ RaisePropertyChanged(nameof(PreviewButtonText)); RaisePropertyChanged(nameof(RecordButtonText)); UpdateCommands();
+ }
+ private async Task RefreshAsync()
+ {
+ Status = "正在枚举 UVC / 海康相机…";
+ var devices = await _camera.EnumerateAsync();
+ if (_closing) return;
+ Cameras.Clear(); foreach (var device in devices) Cameras.Add(device);
+ SelectedCamera = Cameras.FirstOrDefault();
+ Status = Cameras.Count == 0 ? "未找到相机,请检查连接;海康设备需要 MVS x64 运行时" : $"找到 {Cameras.Count} 台相机";
+ }
+ private async Task TogglePreviewAsync()
+ {
+ if (IsPreviewing)
+ {
+ StopRecording();
+ await Task.Run(_camera.Disconnect);
+ ClearPreview(); IsPreviewing = false; Status = "相机已关闭";
+ return;
+ }
+ var selected = SelectedCamera ?? throw new InvalidOperationException("请选择相机");
+ Status = "正在连接 " + selected.Name;
+ if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用");
+ if (_closing) return;
+ if (!await _camera.StartAsync())
+ {
+ await Task.Run(_camera.Disconnect);
+ throw new IOException("相机已连接,但采集启动失败");
+ }
+ IsPreviewing = true; Status = "相机预览中,可开始录像";
+ }
+ private Task ToggleRecordingAsync()
+ {
+ if (IsRecording) { StopRecording(); return Task.CompletedTask; }
+ if (string.IsNullOrWhiteSpace(SaveDirectory)) throw new ArgumentException("请选择录像保存目录");
+ var directory = Path.GetFullPath(SaveDirectory.Trim());
+ SaveDirectory = directory; SaveSettings();
+ lock (_frames)
+ {
+ if (_latest == null || !_camera.IsGrabbing) throw new InvalidOperationException("尚未收到相机画面,请先开启预览");
+ if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像");
+ LastRecording = _recorder.Start(directory, _latest, RecordingFps);
+ }
+ IsRecording = true; Status = "正在录像,点击“停止录像”保存文件"; Tick();
+ return Task.CompletedTask;
+ }
+ private void StopRecording()
+ {
+ RecordingResult? result;
+ lock (_frames) result = _recorder.Stop();
+ IsRecording = false;
+ if (result != null)
+ {
+ LastRecording = result.Path;
+ RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧";
+ Status = "录像已保存,可在主窗口导入视频继续标注";
+ }
+ }
+ private void OnFrame(CameraFrame frame)
+ {
+ if (_closing) return;
+ BitmapSource? preview = null;
+ string? recordingError = null;
+ var generation = Volatile.Read(ref _generation);
+ lock (_frames)
+ {
+ if (_closing) return;
+ Interlocked.Exchange(ref _lastFrameTick, Stopwatch.GetTimestamp());
+ if (_latest == null) _latest = frame.Bgr.Clone(); else frame.Bgr.CopyTo(_latest);
+ try { _recorder.Write(frame.Bgr); }
+ catch (Exception e) { recordingError = "录像中断:" + e.Message + ";已写入内容保存在 " + _recorder.CurrentPath; }
+ if (_previewClock.ElapsedMilliseconds >= 66 && Interlocked.CompareExchange(ref _previewPending, 1, 0) == 0)
+ {
+ try
+ {
+ var stride = checked((int)frame.Bgr.Step());
+ preview = BitmapSource.Create(frame.Bgr.Width, frame.Bgr.Height, 96, 96, PixelFormats.Bgr24,
+ null, frame.Bgr.Data, checked(stride * frame.Bgr.Height), stride);
+ preview.Freeze(); _previewClock.Restart();
+ }
+ catch { Interlocked.Exchange(ref _previewPending, 0); throw; }
+ }
+ }
+ if (recordingError != null)
+ {
+ var error = recordingError;
+ Post(() => { IsRecording = false; Status = error; RecordingInfo = "录像中断,请检查日志提示"; });
+ }
+ if (preview != null)
+ {
+ var bitmap = preview;
+ Post(() =>
+ {
+ try
+ {
+ if (generation == Volatile.Read(ref _generation)) { Preview = bitmap; UpdateCommands(); }
+ }
+ finally { Interlocked.Exchange(ref _previewPending, 0); }
+ });
+ }
+ }
+ private void OnConnection(bool connected)
+ {
+ if (!connected) Post(() =>
+ {
+ if (_camera.IsConnected) return; // Ignore a queued disconnect from the previous connection.
+ StopRecording(); IsPreviewing = false; ClearPreview();
+ });
+ }
+ private void OnError(string message) => Post(() => Status = message);
+ private void Post(Action action)
+ {
+ if (!_closing && !_dispatcher.HasShutdownStarted)
+ _dispatcher.BeginInvoke(() => { if (!_closing) action(); }, DispatcherPriority.Background);
+ }
+ private void Tick()
+ {
+ if (_closing) return;
+ if (IsRecording)
+ {
+ if (Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds > 2)
+ {
+ StopRecording(); Status = "超过2秒未收到相机画面,录像已结束,请检查相机连接";
+ }
+ else if (!_recorder.IsRecording) IsRecording = false;
+ else RecordingInfo = $"● 正在录像 {_recorder.Elapsed:hh\\:mm\\:ss} · {RecordingFps:F0} fps";
+ }
+ if (IsPreviewing && !_camera.IsGrabbing && !IsBusy)
+ {
+ StopRecording(); IsPreviewing = false; ClearPreview(); Status = "相机采集已中断,请重新连接";
+ }
+ }
+ private bool HasRecentFrame => Interlocked.Read(ref _lastFrameTick) != 0 &&
+ Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds <= 2;
+ private void ClearPreview()
+ {
+ Interlocked.Increment(ref _generation);
+ lock (_frames) { _latest?.Dispose(); _latest = null; }
+ Preview = null;
+ }
+ private void SaveSettings()
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(_settingsPath)!);
+ File.WriteAllText(_settingsPath, JsonSerializer.Serialize(new { directory = SaveDirectory }));
+ }
+ public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync();
+ private async Task ShutdownCoreAsync()
+ {
+ _closing = true; _timer.Stop(); StateChanged();
+ await _operation;
+ try { await Task.Run(_camera.Dispose); }
+ finally
+ {
+ try { StopRecording(); }
+ finally
+ {
+ ClearPreview();
+ _camera.FrameArrived -= OnFrame; _camera.ConnectionChanged -= OnConnection; _camera.Error -= OnError;
+ IsPreviewing = false;
+ }
+ }
+ }
+}
diff --git a/src/SopHelper.Avalonia/Training/CameraWindow.axaml b/src/SopHelper.Avalonia/Training/CameraWindow.axaml
new file mode 100644
index 0000000..55163ba
--- /dev/null
+++ b/src/SopHelper.Avalonia/Training/CameraWindow.axaml
@@ -0,0 +1,64 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/SopHelper.Avalonia/Training/CameraWindow.axaml.cs b/src/SopHelper.Avalonia/Training/CameraWindow.axaml.cs
new file mode 100644
index 0000000..b704467
--- /dev/null
+++ b/src/SopHelper.Avalonia/Training/CameraWindow.axaml.cs
@@ -0,0 +1,16 @@
+using Avalonia.Controls;
+using Avalonia.Threading;
+
+namespace SopHelper.Training;
+public partial class CameraWindow : Window
+{
+ public CameraViewModel Model { get; }
+ private bool _closedSafely,_closeRequested;
+ public CameraWindow(CameraViewModel model){InitializeComponent();Model=model;DataContext=model;Closing+=OnSafeClosing;}
+ private async void OnSafeClosing(object? sender,WindowClosingEventArgs e)
+ {
+ if(_closedSafely)return;e.Cancel=true;if(_closeRequested)return;_closeRequested=true;IsEnabled=false;
+ try{await Model.ShutdownAsync();}catch(Exception error){System.Diagnostics.Trace.TraceError("关闭相机时出错:"+error);}
+ _closedSafely=true;Dispatcher.UIThread.Post(Close);
+ }
+}
diff --git a/src/SopHelper.Avalonia/Training/MainViewModel.cs b/src/SopHelper.Avalonia/Training/MainViewModel.cs
new file mode 100644
index 0000000..269e62c
--- /dev/null
+++ b/src/SopHelper.Avalonia/Training/MainViewModel.cs
@@ -0,0 +1,367 @@
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.IO;
+using System.Text.Json;
+using Avalonia;
+using SopHelper.Presentation.Threading;
+using SopHelper.Presentation;
+using SopHelper.Presentation.Imaging;
+using SopHelper.Engine.Training;
+using Prism.Commands;
+using Prism.Mvvm;
+
+namespace SopHelper.Training;
+
+public sealed class MainViewModel : BindableBase
+{
+ private readonly WorkerClient _worker;
+ private CancellationTokenSource? _cancellation;
+ private TaskCompletionSource? _completion;
+ private TrainingProject? _project;
+ private FrameAnnotation? _selected;
+ private BitmapImage? _preview;
+ private bool _busy;
+ private double _progress;
+ private string _status = "新建项目:导入视频,在任意清晰帧拖动画框";
+ private string _logs = "";
+ private bool _isTraining;
+ private string _trainingStatus = "打开已复核项目后即可开始训练";
+ private string _trainingMetrics = "尚无训练指标";
+ private string _latestWeights = "";
+ private string _trainingRunDirectory = "";
+ public bool IsTraining { get => _isTraining; private set => SetProperty(ref _isTraining, value); }
+ public string TrainingStatus { get => _trainingStatus; private set => SetProperty(ref _trainingStatus, value); }
+ public string TrainingMetrics { get => _trainingMetrics; private set => SetProperty(ref _trainingMetrics, value); }
+ public string LatestWeights { get => _latestWeights; private set => SetProperty(ref _latestWeights, value); }
+ public string TrainingRunDirectory { get => _trainingRunDirectory; private set => SetProperty(ref _trainingRunDirectory, value); }
+ public string TrainingOutputDirectory { get; set; } = "";
+ public string Root { get; }
+ public TrainingProject? Project => _project;
+ public ObservableCollection Frames { get; } = [];
+ public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); RaisePropertyChanged(nameof(IsIdle)); Commands.ForEach(c => c.RaiseCanExecuteChanged()); } }
+ public bool IsIdle => !IsBusy;
+ public double Progress { get => _progress; set => SetProperty(ref _progress, value); }
+ public string Status { get => _status; set => SetProperty(ref _status, value); }
+ public string Logs { get => _logs; set => SetProperty(ref _logs, value); }
+ public string Summary => _project == null ? "尚未导入视频" : $"{_project.Width} × {_project.Height} · {Frames.Count} 帧 · 已复核 {Frames.Count(f => f.Status is "reviewed" or "absent")} · 待复核 {Frames.Count(f => f.Status == "auto")}";
+ public string FrameInfo => _selected == null || _project == null ? "拖动画框以标记零件" : $"第 {_selected.Index + 1} 帧 · 原视频帧 {_selected.SourceIndex} · {(_project.Fps > 0 ? (_selected.SourceIndex / _project.Fps).ToString("F2") + " 秒" : "时间未知")} · {_selected.Display}";
+ public string ProjectPath => _project?.FilePath ?? "项目会自动保存到你选择的文件夹";
+ public BitmapImage? Preview { get => _preview; private set => SetProperty(ref _preview, value); }
+ public double[]? CurrentBox => _selected?.Box;
+ public FrameAnnotation? SelectedFrame
+ {
+ get => _selected;
+ set
+ {
+ if (!SetProperty(ref _selected, value)) return;
+ try
+ {
+ if (value != null && _project != null)
+ {
+ var bitmap = new BitmapImage();
+ bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad;
+ bitmap.UriSource = new Uri(Path.Combine(_project.DirectoryPath, value.Image));
+ bitmap.EndInit(); bitmap.Freeze(); Preview = bitmap;
+ }
+ }
+ catch (Exception e) { Status = "图像读取失败:" + e.Message; Preview = null; }
+ RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo));
+ }
+ }
+ // Configuration is saved locally, except the API key which is passed only through the worker environment.
+ private static string PythonPath => DesktopPlatform.PythonPath;
+ public string Label { get; set; } = "零件";
+ public int ExtractStride { get; set; } = 1;
+ public int MaxFrames { get; set; } = 600;
+ public string Checkpoint { get; set; } = "";
+ public string SamConfig { get; set; } = "configs/sam2.1/sam2.1_hiera_t.yaml";
+ public string Device { get; set; } = "auto";
+ public int ExportEvery { get; set; } = 5;
+ public int Epochs { get; set; } = 50;
+ public int Batch { get; set; } = 4;
+ public int ImageSize { get; set; } = 640;
+ public string Model { get; set; } = "yolo11n.pt";
+ public string Endpoint { get; set; } = "https://api.example.com/v1";
+ public string ApiModel { get; set; } = "";
+ public string Description { get; set; } = "";
+ public Func? ReadApiKey { get; set; }
+ public DelegateCommand ImportCommand { get; }
+ public DelegateCommand OpenCommand { get; }
+ public DelegateCommand DoctorCommand { get; }
+ public DelegateCommand PropagateCommand { get; }
+ public DelegateCommand ExportCommand { get; }
+ public DelegateCommand TrainCommand { get; }
+ public DelegateCommand PickTrainingModelCommand { get; }
+ public DelegateCommand PickTrainingOutputCommand { get; }
+ public DelegateCommand OpenTrainingResultsCommand { get; }
+ public DelegateCommand OnnxCommand { get; }
+ public DelegateCommand SuggestCommand { get; }
+ public DelegateCommand ApproveCommand { get; }
+ public DelegateCommand ApproveAllCommand { get; }
+ public DelegateCommand AbsentCommand { get; }
+ public DelegateCommand ExcludeCommand { get; }
+ public DelegateCommand PreviousCommand { get; }
+ public DelegateCommand NextCommand { get; }
+ public DelegateCommand CancelCommand { get; }
+ public DelegateCommand RevealCommand { get; }
+ private List Commands { get; } = [];
+
+ public MainViewModel(WorkerClient worker)
+ {
+ _worker = worker;
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory.Parent != null && !File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx"))) directory = directory.Parent;
+ Root = File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx")) ? directory.FullName : AppContext.BaseDirectory;
+ LoadSettings();
+ ImportCommand = Command(Import);
+ OpenCommand = Command(async () =>
+ {
+ var dialog = new OpenFileDialog { Filter = "标注项目|project.json" };
+ if (await dialog.ShowDialogAsync() == true) Load(dialog.FileName);
+ });
+ DoctorCommand = Command(async () => await Run(new { action = "doctor" }, reload: false));
+ PropagateCommand = Command(async () => { SaveLabel(); await Run(new { action = "propagate", project = RequireProject().FilePath, checkpoint = Checkpoint, config = SamConfig, device = Device }); });
+ ExportCommand = Command(async () => { SaveLabel(); await Run(Request("export")); });
+ TrainCommand = Command(async () => { SaveLabel(); await Run(Request("train")); });
+ PickTrainingModelCommand = Command(async () =>
+ {
+ var dialog = new OpenFileDialog { Filter = "YOLO模型|*.pt;*.yaml;*.yml" };
+ if (await dialog.ShowDialogAsync() == true) { Model = dialog.FileName; RaisePropertyChanged(nameof(Model)); }
+ });
+ PickTrainingOutputCommand = Command(async () =>
+ {
+ var dialog = new OpenFolderDialog { Title = "选择训练结果保存目录" };
+ if (await dialog.ShowDialogAsync() == true) { TrainingOutputDirectory = dialog.FolderName; RaisePropertyChanged(nameof(TrainingOutputDirectory)); }
+ });
+ OpenTrainingResultsCommand = Command(() =>
+ {
+ var directory = TrainingRunDirectory;
+ if (!Directory.Exists(directory)) throw new DirectoryNotFoundException("尚无训练结果目录,请先完成一次训练");
+ DesktopPlatform.Reveal(directory);
+ });
+ OnnxCommand = Command(async () => await Run(Request("onnx")));
+ SuggestCommand = Command(async () =>
+ {
+ SaveLabel();
+ if (SelectedFrame == null) throw new InvalidOperationException("请先选择帧");
+ await Run(new { action = "suggest", project = RequireProject().FilePath, index = SelectedFrame.Index,
+ endpoint = Endpoint, apiModel = ApiModel, description = Description }, apiKey: ReadApiKey?.Invoke());
+ });
+ ApproveCommand = Command(() => Update("reviewed"));
+ ApproveAllCommand = Command(ApproveAll);
+ AbsentCommand = Command(() => Update("absent"));
+ ExcludeCommand = Command(() => Update("excluded"));
+ PreviousCommand = Command(() => Move(-1));
+ NextCommand = Command(() => Move(1));
+ CancelCommand = new DelegateCommand(() => _cancellation?.Cancel());
+ RevealCommand = Command(() => DesktopPlatform.Reveal(_project?.DirectoryPath ?? Root));
+ }
+ private DelegateCommand Command(Action action)
+ {
+ var command = new DelegateCommand(() => { try { action(); } catch (Exception e) { Status = e.Message; Append(e.Message); } }, () => !IsBusy);
+ Commands.Add(command); return command;
+ }
+ private DelegateCommand Command(Func action)
+ {
+ var command = new DelegateCommand(async () =>
+ {
+ try { await action(); }
+ catch (Exception e) { Status = e.Message; Append(e.Message); }
+ }, () => !IsBusy);
+ Commands.Add(command); return command;
+ }
+ // Async operations catch their own exceptions inside Run. Import does synchronous validation before awaiting.
+ private object Request(string action) => new { action, project = RequireProject().FilePath, every = ExportEvery,
+ valRatio = 0.2, epochs = Epochs, imageSize = ImageSize, batch = Batch, model = Model, device = Device,
+ outputDirectory = TrainingOutputDirectory };
+ private TrainingProject RequireProject() => _project ?? throw new InvalidOperationException("请先导入视频或打开项目");
+ private void SaveLabel()
+ {
+ var project = RequireProject();
+ if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
+ project.Name = Label.Trim(); project.Save();
+ }
+ private async void Import()
+ {
+ try
+ {
+ var video = new OpenFileDialog { Filter = "视频|*.mp4;*.avi;*.mov;*.mkv;*.wmv|所有文件|*.*" };
+ if (await video.ShowDialogAsync() != true) return;
+ var folder = new OpenFolderDialog { Title = "选择项目保存的父文件夹(会自动新建子文件夹)" };
+ if (await folder.ShowDialogAsync() != true) return;
+ if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
+ var output = Path.Combine(folder.FolderName, "part-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N")[..4]);
+ if (await Run(new { action = "extract", video = video.FileName, output, name = Label.Trim(), stride = ExtractStride, maxFrames = MaxFrames }, reload: false))
+ Load(Path.Combine(output, "project.json"));
+ }
+ catch (Exception e) { Status = e.Message; Append(e.Message); }
+ }
+ public void Load(string path, int index = 0)
+ {
+ _project = TrainingProject.Load(path);
+ Label = _project.Name; RaisePropertyChanged(nameof(Label));
+ _selected = null; Frames.Clear();
+ foreach (var frame in _project.Frames) Frames.Add(frame);
+ SelectedFrame = Frames[Math.Clamp(index, 0, Frames.Count - 1)];
+ RaisePropertyChanged(nameof(Summary)); RaisePropertyChanged(nameof(ProjectPath));
+ LoadTrainingResult();
+ if (!IsBusy) Status = "项目已打开;拖动画框或选择帧进行复核";
+ }
+ public void DrawBox(double[] box)
+ {
+ if (IsBusy || SelectedFrame == null || _project == null) return;
+ try
+ {
+ _project.ValidateBox(box); SelectedFrame.Box = box; SelectedFrame.Prompt = true;
+ SelectedFrame.Status = "reviewed"; _project.Save(); Refresh();
+ Status = "关键帧已保存;可再选其他角度画框,或开始 SAM2 传播";
+ }
+ catch (Exception e) { Status = e.Message; }
+ }
+ private void Update(string status)
+ {
+ if (SelectedFrame == null) return;
+ if (status == "reviewed" && SelectedFrame.Box == null) throw new InvalidOperationException("该帧没有目标框,请画框或标记无目标");
+ SelectedFrame.Status = status;
+ if (status != "reviewed") { SelectedFrame.Box = null; SelectedFrame.Prompt = false; }
+ RequireProject().Save(); Refresh();
+ Status = "当前帧已保存";
+ }
+ private void ApproveAll()
+ {
+ var project = RequireProject();
+ var pending = project.Frames.Where(frame => frame.Status == "auto" && frame.Box != null).ToList();
+ // Validate the whole batch before changing any annotation status.
+ foreach (var frame in pending) project.ValidateBox(frame.Box!);
+ if (pending.Count == 0) { Status = "没有带目标框的待复核帧"; return; }
+ var selectedIndex = SelectedFrame?.Index ?? 0;
+ foreach (var frame in pending) frame.Status = "reviewed";
+ try { project.Save(); }
+ catch
+ {
+ foreach (var frame in pending) frame.Status = "auto";
+ throw;
+ }
+ Load(project.FilePath, selectedIndex);
+ Status = $"一键复核完成:已确认 {pending.Count} 帧并保存";
+ }
+ private void Refresh()
+ {
+ var frame = SelectedFrame;
+ if (frame == null) return;
+ var index = Frames.IndexOf(frame); Frames[index] = frame;
+ SelectedFrame = frame;
+ RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo)); RaisePropertyChanged(nameof(Summary));
+ }
+ private void Move(int delta)
+ {
+ if (Frames.Count > 0) SelectedFrame = Frames[Math.Clamp(Frames.IndexOf(SelectedFrame!) + delta, 0, Frames.Count - 1)];
+ }
+ private void Append(string line)
+ {
+ Dispatcher.CurrentDispatcher.Invoke(() =>
+ {
+ Logs += line + Environment.NewLine;
+ if (Logs.Length > 40000) Logs = Logs[^30000..];
+ });
+ }
+ private async Task Run(object request, bool reload = true, string? apiKey = null)
+ {
+ if (IsBusy) return false;
+ IsTraining = JsonSerializer.SerializeToElement(request).GetProperty("action").GetString() == "train";
+ if (IsTraining) { TrainingStatus = "正在准备数据与模型…"; TrainingMetrics = "等待首轮训练指标"; }
+ IsBusy = true; Progress = 0; Status = "任务运行中…";
+ _cancellation = new CancellationTokenSource();
+ _completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var path = _project?.FilePath; var index = SelectedFrame?.Index ?? 0;
+ try
+ {
+ SaveSettings();
+ if (!File.Exists(PythonPath))
+ throw new FileNotFoundException("缺少内置 Python 环境,请运行 tools/Setup-Python.ps1 -Sam2 后重新构建程序。", PythonPath);
+ await _worker.RunAsync(PythonPath, Path.Combine(Root, "tools", "worker.py"), request, line =>
+ {
+ try
+ {
+ using var json = JsonDocument.Parse(line);
+ var item = json.RootElement;
+ var message = item.TryGetProperty("message", out var m) ? m.GetString() ?? line : line;
+ Append(message);
+ Dispatcher.CurrentDispatcher.Invoke(() =>
+ {
+ Status = message;
+ if (item.TryGetProperty("progress", out var progress) && (!IsTraining || item.TryGetProperty("event", out _))) Progress = Math.Clamp(progress.GetDouble(), 0, 1) * 100;
+ if (IsTraining)
+ {
+ TrainingStatus = message;
+ if (item.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
+ if (item.TryGetProperty("runDirectory", out var directory)) TrainingRunDirectory = directory.GetString() ?? "";
+ if (item.TryGetProperty("weights", out var weights)) LatestWeights = weights.GetString() ?? "";
+ }
+ });
+ if (item.TryGetProperty("modules", out var modules)) Append(modules.ToString());
+ if (item.TryGetProperty("output", out var output)) Append(output.GetString() ?? "");
+ }
+ catch (Exception e) when (e is JsonException or InvalidOperationException or FormatException) { Append(line); }
+ }, _cancellation.Token, apiKey);
+ Progress = 100; return true;
+ }
+ catch (OperationCanceledException) { Status = "任务已取消;已保存的标注保留"; if (IsTraining) TrainingStatus = "训练已停止;已写入的日志与检查点保留在结果目录"; Append(Status); return false; }
+ catch (Exception e) { Status = e.Message; if (IsTraining) TrainingStatus = "训练失败,请查看运行日志:" + e.Message; Append(e.Message); return false; }
+ finally
+ {
+ if (reload && path != null)
+ {
+ try { Load(path, index); } catch (Exception e) { Append("重新读取项目失败:" + e.Message); }
+ }
+ _cancellation.Dispose(); _cancellation = null; IsBusy = false; IsTraining = false;
+ _completion.TrySetResult();
+ }
+ }
+ public void Cancel() => _cancellation?.Cancel();
+ public async Task StopAsync()
+ {
+ Cancel();
+ if (_completion != null) await _completion.Task;
+ }
+ private static string FormatMetrics(JsonElement metrics) => string.Join(Environment.NewLine,
+ metrics.EnumerateObject().Where(m => m.Value.ValueKind == JsonValueKind.Number)
+ .Select(m => $"{m.Name}: {m.Value.GetDouble():F4}"));
+ private void LoadTrainingResult()
+ {
+ if (IsTraining) return;
+ LatestWeights = ""; TrainingRunDirectory = ""; TrainingMetrics = "尚无训练指标";
+ var file = Path.Combine(RequireProject().DirectoryPath, "latest-model.json");
+ if (!File.Exists(file)) return;
+ try
+ {
+ using var result = JsonDocument.Parse(File.ReadAllText(file));
+ LatestWeights = result.RootElement.GetProperty("weights").GetString() ?? "";
+ TrainingRunDirectory = result.RootElement.TryGetProperty("runDirectory", out var directory) ? directory.GetString() ?? "" : Path.GetDirectoryName(Path.GetDirectoryName(LatestWeights)) ?? "";
+ if (result.RootElement.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
+ }
+ catch (Exception e) { Append("读取训练结果失败:" + e.Message); }
+ }
+ private void SaveSettings()
+ {
+ Directory.CreateDirectory(Path.Combine(Root, "workspace"));
+ File.WriteAllText(Path.Combine(Root, "workspace", "settings.json"), JsonSerializer.Serialize(new
+ { Checkpoint, SamConfig, Device, ExportEvery, Epochs, Batch, ImageSize, Model, TrainingOutputDirectory, Endpoint, ApiModel, Description, ExtractStride, MaxFrames }));
+ }
+ private void LoadSettings()
+ {
+ var path = Path.Combine(Root, "workspace", "settings.json");
+ if (!File.Exists(path)) return;
+ try
+ {
+ using var settings = JsonDocument.Parse(File.ReadAllText(path));
+ foreach (var item in settings.RootElement.EnumerateObject())
+ {
+ var property = GetType().GetProperty(item.Name);
+ if (property?.CanWrite == true && property.PropertyType == typeof(string)) property.SetValue(this, item.Value.GetString());
+ else if (property?.CanWrite == true && property.PropertyType == typeof(int)) property.SetValue(this, item.Value.GetInt32());
+ }
+ }
+ catch (Exception) { Status = "设置文件不可读,已使用默认配置"; }
+ }
+}
diff --git a/src/SopHelper.Avalonia/Training/Styles.axaml b/src/SopHelper.Avalonia/Training/Styles.axaml
new file mode 100644
index 0000000..5656bd4
--- /dev/null
+++ b/src/SopHelper.Avalonia/Training/Styles.axaml
@@ -0,0 +1,73 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/SopHelper.Avalonia/Training/TrainingPage.axaml b/src/SopHelper.Avalonia/Training/TrainingPage.axaml
new file mode 100644
index 0000000..7f9c9e4
--- /dev/null
+++ b/src/SopHelper.Avalonia/Training/TrainingPage.axaml
@@ -0,0 +1,155 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs b/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs
new file mode 100644
index 0000000..28d82c4
--- /dev/null
+++ b/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs
@@ -0,0 +1,57 @@
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Interactivity;
+using Avalonia.Threading;
+using SopHelper.Core.Prism;
+using SopHelper.Engine.Camera;
+using SopHelper.VVMs.SopPage;
+
+namespace SopHelper.Training;
+
+[NavigationPage(ViewName=nameof(TrainingPage),DisplayName="零件标注与训练",Index=1)]
+public partial class TrainingPage : UserControl
+{
+ private readonly MainViewModel _model;
+ private readonly SopPageViewModel? _sop;
+ private CameraWindow? _cameraWindow;
+ private Window? _host;
+ private bool _closing,_closedSafely;
+ public TrainingPage(MainViewModel model,SopPageViewModel? sop)
+ {
+ InitializeComponent();_model=model;_sop=sop;DataContext=model;
+ Canvas.BoxDrawn+=model.DrawBox;
+ model.ReadApiKey=()=>ApiKey.Text??"";
+ AttachedToVisualTree+=(_,_)=>
+ {
+ if(_host!=null || TopLevel.GetTopLevel(this) is not Window host)return;
+ _host=host;host.Closing+=HostClosing;
+ };
+ AddHandler(KeyDownEvent,(_,e)=>
+ {
+ if(model.IsBusy || TopLevel.GetTopLevel(this)?.FocusManager?.GetFocusedElement() is TextBox)return;
+ if(e.Key==Key.Left){model.PreviousCommand.Execute();e.Handled=true;}
+ else if(e.Key==Key.Right){model.NextCommand.Execute();e.Handled=true;}
+ else if(e.Key==Key.Enter && model.SelectedFrame?.Box!=null)
+ {model.ApproveCommand.Execute();model.NextCommand.Execute();e.Handled=true;}
+ },RoutingStrategies.Tunnel);
+ }
+ private async void OpenCameraClicked(object? sender,RoutedEventArgs e)
+ {
+ if(_sop is { CanSelectCamera:false } || _sop is { IsConnected:true })
+ {_model.Status="请先停止 SOP 采集并等待相机操作完成,再打开录像";return;}
+ if(TopLevel.GetTopLevel(this) is not Window owner)return;
+ _cameraWindow=new CameraWindow(new CameraViewModel(new CameraService(),_model.Root));
+ try { await _cameraWindow.ShowDialog(owner); }
+ finally { _cameraWindow=null; }
+ }
+ public async Task ShutdownAsync()
+ {await _model.StopAsync();if(_cameraWindow!=null)await _cameraWindow.Model.ShutdownAsync();}
+ private async void HostClosing(object? sender,WindowClosingEventArgs e)
+ {
+ if(_closedSafely)return;e.Cancel=true;if(_closing)return;_closing=true;_host!.IsEnabled=false;
+ try{await ShutdownAsync();}catch(Exception error){_model.Status="关闭训练任务时出错:"+error.Message;}
+ _closedSafely=true;Dispatcher.UIThread.Post(()=>_host.Close());
+ }
+ private void LogChanged(object? sender,TextChangedEventArgs e)
+ {if(sender is TextBox box)box.CaretIndex=box.Text?.Length??0;}
+}
diff --git a/src/SopHelper.Avalonia/VVMs/MainWindow/MainWindow.axaml b/src/SopHelper.Avalonia/VVMs/MainWindow/MainWindow.axaml
new file mode 100644
index 0000000..11ae1f1
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/MainWindow/MainWindow.axaml
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/SopHelper.Avalonia/VVMs/MainWindow/MainWindow.axaml.cs b/src/SopHelper.Avalonia/VVMs/MainWindow/MainWindow.axaml.cs
new file mode 100644
index 0000000..9cf3f03
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/MainWindow/MainWindow.axaml.cs
@@ -0,0 +1,4 @@
+using Avalonia.Controls;
+namespace SopHelper.VVMs.MainWindow;
+public partial class MainWindow : Window
+{ public MainWindow() { InitializeComponent(); } }
diff --git a/src/SopHelper.Avalonia/VVMs/MainWindow/MainWindowViewModel.cs b/src/SopHelper.Avalonia/VVMs/MainWindow/MainWindowViewModel.cs
new file mode 100644
index 0000000..5eac70b
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/MainWindow/MainWindowViewModel.cs
@@ -0,0 +1,39 @@
+using Prism.Commands;
+using Prism.Mvvm;
+using SopHelper.Models;
+
+namespace SopHelper.VVMs.MainWindow;
+
+///
+/// Main窗口视图模型
+///
+public class MainWindowViewModel : BindableBase
+{
+ private readonly NavigationModel _navigation;
+
+ ///
+ /// Main窗口视图模型
+ ///
+ public MainWindowViewModel(NavigationModel navigation)
+ {
+ _navigation = navigation;
+ }
+
+ private string _title = "SopHelper";
+
+ ///
+ /// 标题
+ ///
+ public string Title
+ {
+ get { return _title; }
+ set { SetProperty(ref _title, value); }
+ }
+
+ ///
+ /// 导航模型(侧栏绑定)
+ ///
+ public NavigationModel Navigation => _navigation;
+
+
+}
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
new file mode 100644
index 0000000..7300aca
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs
@@ -0,0 +1,1011 @@
+using System.Collections.ObjectModel;
+using System.Windows.Input;
+using Avalonia.Media;
+using Prism.Commands;
+using SopHelper.Core.Prism;
+using SopHelper.Engine.Sop;
+
+namespace SopHelper.VVMs.RecipeEditor;
+
+///
+/// 编辑器自己的可观察节点。配方模型(SopHelper.Engine)是纯数据类、不带 INPC,
+/// 引擎层不该为 UI 引这套接口,所以绑定层在这一侧,保存时整体映射回 SopConfig。
+///
+public abstract class EditorNode : BindableBase
+{
+}
+
+///
+/// 可被"可编辑列表"删除的行
+///
+public interface IRemovable
+{
+ /// 删除自己(由所属列表注入)
+ ICommand? RemoveCommand { get; set; }
+}
+
+///
+/// 字符串列表项(YAML 的 classes / must_keep / required_objects)。
+/// 不能直接绑 string——string 不实现 INPC,TwoWay 写不回集合项。
+///
+public class TextItem : EditorNode, IRemovable
+{
+ private string _text = "";
+
+ /// 文本
+ public string Text
+ {
+ get { return _text; }
+ set { SetProperty(ref _text, value); }
+ }
+
+ ///
+ public ICommand? RemoveCommand { get; set; }
+
+ ///
+ public override string ToString() => Text;
+}
+
+///
+/// 可增删的行列表(类别名、必在物料、违规规则都用它)
+///
+public class EditableList : EditorNode where T : EditorNode, IRemovable, new()
+{
+ /// 列表标题
+ public string Title { get; init; } = "";
+
+ /// 行
+ public ObservableCollection Items { get; } = [];
+
+ /// 加一行
+ public DelegateCommand AddCommand { get; }
+
+ /// 删一行
+ public DelegateCommand RemoveCommand { get; }
+
+ ///
+ /// 可增删的行列表
+ ///
+ public EditableList()
+ {
+ AddCommand = new DelegateCommand(() =>
+ {
+ var item = new T { RemoveCommand = RemoveCommand };
+ Items.Add(item);
+ });
+
+ RemoveCommand = new DelegateCommand(item =>
+ {
+ if (item is not null) Items.Remove(item);
+ });
+ }
+}
+
+///
+/// sop 根节点
+///
+public class RecipeNode : EditorNode
+{
+ private string _fileName = "";
+ private bool _isNew;
+ private string _name = "";
+ private string _version = "1.0";
+ private string _description = "";
+ private bool _hasModel;
+ private RecipeModelNode? _model;
+ private RegionNode? _selectedRegion;
+ private StepNode? _selectedStep;
+
+ ///
+ /// 配方根节点
+ ///
+ public RecipeNode()
+ {
+ Methods =
+ [
+ "",
+ ConditionMethod.TimeElapsed,
+ ConditionMethod.HandInRegion,
+ ConditionMethod.HandMove,
+ ConditionMethod.HandNearObject,
+ ConditionMethod.ObjectPresent,
+ ConditionMethod.ObjectInZone,
+ ConditionMethod.PersonPresent,
+ ];
+
+ Hands = ["any", "left", "right"];
+ ViolationTypes = [ViolationType.Timeout, ViolationType.ObjectRemoved];
+
+ AddRegionCommand = new DelegateCommand(() => { AddRegion(); Changed?.Invoke(); });
+ RemoveRegionCommand = new DelegateCommand(node => { RemoveRegion(node); Changed?.Invoke(); }, node => node is not null);
+
+ AddStepCommand = new DelegateCommand(() => { AddStep(); Changed?.Invoke(); });
+ RemoveStepCommand = new DelegateCommand(node => { RemoveStep(node); Changed?.Invoke(); }, node => node is not null);
+ MoveStepUpCommand = new DelegateCommand(node => { MoveStepUp(node); Changed?.Invoke(); }, node => node is not null && Steps.Any(s => s.Id < node.Id));
+ MoveStepDownCommand = new DelegateCommand(node => { MoveStepDown(node); Changed?.Invoke(); }, node => node is not null && Steps.Any(s => s.Id > node.Id));
+ }
+
+ /// 加区域
+ public DelegateCommand AddRegionCommand { get; }
+
+ /// 删区域
+ public DelegateCommand RemoveRegionCommand { get; }
+
+ /// 加步骤
+ public DelegateCommand AddStepCommand { get; }
+
+ /// 删步骤
+ public DelegateCommand RemoveStepCommand { get; }
+
+ /// 步骤上移
+ public DelegateCommand MoveStepUpCommand { get; }
+
+ /// 步骤下移
+ public DelegateCommand MoveStepDownCommand { get; }
+
+ /// 列表结构变了(ViewModel 借此重跑校验)
+ public event Action? Changed;
+
+ /// 文件名(不含扩展名;新建时可填,之后按它落盘)
+ public string FileName
+ {
+ get { return _fileName; }
+ set { SetProperty(ref _fileName, value); }
+ }
+
+ /// 新建(尚未落盘)
+ public bool IsNew
+ {
+ get { return _isNew; }
+ private set
+ {
+ if (!SetProperty(ref _isNew, value)) return;
+ RaisePropertyChanged(nameof(CanEditFileName));
+ }
+ }
+
+ /// 文件名是否可编辑(只有新建能改——SOP 页按文件名选配方,已存在的改名等于换个配方)
+ public bool CanEditFileName
+ {
+ get { return IsNew; }
+ }
+
+ internal void MarkSaved(string fileName)
+ {
+ FileName = fileName;
+ IsNew = false;
+ }
+
+ /// 配方名(sop.name)
+ public string Name
+ {
+ get { return _name; }
+ set { SetProperty(ref _name, value); }
+ }
+
+ /// 版本(sop.version)
+ public string Version
+ {
+ get { return _version; }
+ set { SetProperty(ref _version, value); }
+ }
+
+ /// 说明(sop.description)
+ public string Description
+ {
+ get { return _description; }
+ set { SetProperty(ref _description, value); }
+ }
+
+ /// 全局设置(sop.settings)
+ public RecipeSettingsNode Settings { get; } = new();
+
+ /// 区域(sop.regions,键 = 配方里引用的区域名)
+ public ObservableCollection Regions { get; } = [];
+
+ /// 步骤(sop.steps)
+ public ObservableCollection Steps { get; } = [];
+
+ /// 是否配置检测模型(不勾就不写 sop.model 节点)
+ public bool HasModel
+ {
+ get { return _hasModel; }
+ set
+ {
+ if (!SetProperty(ref _hasModel, value)) return;
+
+ // 勾上给一个可编辑的模型节点,取消勾选就丢弃
+ _model = value ? _model ?? new RecipeModelNode() : null;
+ RaisePropertyChanged(nameof(Model));
+ }
+ }
+
+ /// 模型定义(HasModel=false 时为 null)
+ public RecipeModelNode? Model
+ {
+ get { return _model; }
+ private set { SetProperty(ref _model, value); }
+ }
+
+ /// 当前编辑的区域
+ public RegionNode? SelectedRegion
+ {
+ get { return _selectedRegion; }
+ set { SetProperty(ref _selectedRegion, value); }
+ }
+
+ /// 当前编辑的步骤
+ public StepNode? SelectedStep
+ {
+ get { return _selectedStep; }
+ set { SetProperty(ref _selectedStep, value); }
+ }
+
+ /// method 下拉候选(空串 = 本步不写判定条件)
+ public IReadOnlyList Methods { get; }
+
+ /// hand 下拉候选
+ public IReadOnlyList Hands { get; }
+
+ /// 违规类型下拉候选
+ public IReadOnlyList ViolationTypes { get; }
+
+ /// 区域名下拉候选(含空项,表示该字段不引用区域)
+ public IReadOnlyList RegionNames
+ {
+ get
+ {
+ var names = Regions.Select(r => r.Key).Where(k => !string.IsNullOrWhiteSpace(k)).ToList();
+ names.Insert(0, "");
+ return names;
+ }
+ }
+
+ /// 加区域
+ public RegionNode AddRegion()
+ {
+ var node = new RegionNode
+ {
+ Key = $"region{Regions.Count + 1}",
+ Name = "新区域",
+ X1 = 100,
+ Y1 = 100,
+ X2 = 400,
+ Y2 = 400,
+ };
+
+ node.Renamed += OnRegionRenamed;
+ Regions.Add(node);
+ SelectedRegion = node;
+
+ return node;
+ }
+
+ /// 删区域(条件里引用了它的步骤会清掉引用,避免留下悬空引用)
+ public void RemoveRegion(RegionNode? node)
+ {
+ if (node is null) return;
+
+ Regions.Remove(node);
+ node.Renamed -= OnRegionRenamed;
+
+ foreach (var step in Steps.Where(s => s.Detection is not null && References(s.Detection, node.Key)))
+ ClearRegionReferences(step.Detection!, node.Key);
+
+ SelectedRegion = Regions.FirstOrDefault();
+ }
+
+ /// 加步骤(Id 取当前最大 +1,执行顺序按 Id 升序)
+ public StepNode AddStep()
+ {
+ var node = new StepNode
+ {
+ Id = Steps.Count == 0 ? 1 : Steps.Max(s => s.Id) + 1,
+ Name = "新步骤",
+ Detection = new ConditionNode(),
+ };
+
+ Steps.Add(node);
+ SelectedStep = node;
+
+ return node;
+ }
+
+ /// 删步骤
+ public void RemoveStep(StepNode? node)
+ {
+ if (node is null) return;
+
+ Steps.Remove(node);
+ SelectedStep = Steps.FirstOrDefault();
+ }
+
+ /// 上移(与上一个交换 Id——执行顺序就是 Id 升序)
+ public void MoveStepUp(StepNode? node)
+ {
+ if (node is null) return;
+
+ var prev = Steps.Where(s => s.Id < node.Id).OrderByDescending(s => s.Id).FirstOrDefault();
+ if (prev is null) return;
+
+ (node.Id, prev.Id) = (prev.Id, node.Id);
+ ResortSteps();
+ }
+
+ /// 下移
+ public void MoveStepDown(StepNode? node)
+ {
+ if (node is null) return;
+
+ var next = Steps.Where(s => s.Id > node.Id).OrderBy(s => s.Id).FirstOrDefault();
+ if (next is null) return;
+
+ (node.Id, next.Id) = (next.Id, node.Id);
+ ResortSteps();
+ }
+
+ ///
+ /// 区域键名变了 → 同步条件里的引用。不做这一步,改个区域名就得把每个引用它的步骤手改一遍。
+ ///
+ private void OnRegionRenamed(string from, string to)
+ {
+ if (string.Equals(from, to, StringComparison.OrdinalIgnoreCase)) return;
+
+ foreach (var step in Steps)
+ {
+ var condition = step.Detection;
+ if (condition is null) continue;
+
+ if (string.Equals(condition.Region, from, StringComparison.OrdinalIgnoreCase)) condition.Region = to;
+ if (string.Equals(condition.FromRegion, from, StringComparison.OrdinalIgnoreCase)) condition.FromRegion = to;
+ if (string.Equals(condition.ToRegion, from, StringComparison.OrdinalIgnoreCase)) condition.ToRegion = to;
+ }
+
+ RaisePropertyChanged(nameof(RegionNames));
+ }
+
+ /// 按 Id 重排(保持选中项)
+ private void ResortSteps()
+ {
+ var selected = SelectedStep;
+
+ var ordered = Steps.OrderBy(s => s.Id).ToList();
+ Steps.Clear();
+ foreach (var step in ordered) Steps.Add(step);
+
+ SelectedStep = selected;
+ }
+
+ private static bool References(ConditionNode condition, string key)
+ => new[] { condition.Region, condition.FromRegion, condition.ToRegion }
+ .Any(n => string.Equals(n, key, StringComparison.OrdinalIgnoreCase));
+
+ private static void ClearRegionReferences(ConditionNode condition, string key)
+ {
+ if (string.Equals(condition.Region, key, StringComparison.OrdinalIgnoreCase)) condition.Region = "";
+ if (string.Equals(condition.FromRegion, key, StringComparison.OrdinalIgnoreCase)) condition.FromRegion = "";
+ if (string.Equals(condition.ToRegion, key, StringComparison.OrdinalIgnoreCase)) condition.ToRegion = "";
+ }
+
+ ///
+ /// 配方 → 编辑器节点
+ ///
+ public static RecipeNode From(SopConfig config, string fileName, bool isNew)
+ {
+ var node = new RecipeNode
+ {
+ FileName = System.IO.Path.GetFileNameWithoutExtension(fileName),
+ IsNew = isNew,
+ Name = config.Sop.Name,
+ Version = config.Sop.Version,
+ Description = config.Sop.Description,
+ };
+
+ node.Settings.CopyFrom(config.Sop.Settings);
+
+ foreach (var (key, def) in config.Sop.Regions)
+ {
+ var region = new RegionNode { Key = key };
+ region.CopyFrom(def);
+ region.Renamed += node.OnRegionRenamed;
+ node.Regions.Add(region);
+ }
+
+ foreach (var step in config.Sop.Steps.OrderBy(s => s.Id))
+ {
+ var stepNode = new StepNode
+ {
+ Id = step.Id,
+ Name = step.Name,
+ Description = step.Description,
+ Timeout = step.Timeout,
+ StandardDurationMs = step.StandardDurationMs,
+ };
+
+ foreach (var item in step.MustKeep) stepNode.MustKeep.Items.Add(new TextItem { Text = item, RemoveCommand = stepNode.MustKeep.RemoveCommand });
+ foreach (var item in step.RequiredObjects) stepNode.RequiredObjects.Items.Add(new TextItem { Text = item, RemoveCommand = stepNode.RequiredObjects.RemoveCommand });
+
+ if (step.Detection is not null) stepNode.Detection = ConditionNode.From(step.Detection);
+
+ foreach (var rule in step.ViolationRules)
+ stepNode.ViolationRules.Items.Add(ViolationRuleNode.From(rule, stepNode.ViolationRules.RemoveCommand));
+
+ node.Steps.Add(stepNode);
+ }
+
+ if (config.Sop.Model is not null)
+ {
+ node.HasModel = true;
+ node.Model?.CopyFrom(config.Sop.Model);
+ }
+
+ node.SelectedStep = node.Steps.FirstOrDefault();
+ node.SelectedRegion = node.Regions.FirstOrDefault();
+
+ return node;
+ }
+
+ ///
+ /// 编辑器节点 → 配方(全新构造一份,不动原对象)
+ ///
+ public SopConfig ToConfig()
+ {
+ var config = new SopConfig();
+
+ config.Sop.Name = Name;
+ config.Sop.Version = Version;
+ config.Sop.Description = Description;
+
+ Settings.CopyTo(config.Sop.Settings);
+
+ foreach (var region in Regions.Where(r => !string.IsNullOrWhiteSpace(r.Key)))
+ {
+ var def = new RegionDef { Name = region.Name, Description = region.Description, Color = region.Color };
+ region.CopyTo(def);
+ config.Sop.Regions[region.Key.Trim()] = def;
+ }
+
+ foreach (var step in Steps.OrderBy(s => s.Id))
+ {
+ var def = new StepDef
+ {
+ Id = step.Id,
+ Name = step.Name,
+ Description = step.Description,
+ Timeout = step.Timeout,
+ StandardDurationMs = step.StandardDurationMs,
+ };
+
+ def.MustKeep.AddRange(step.MustKeep.Items.Select(i => i.Text).Where(s => !string.IsNullOrWhiteSpace(s)));
+ def.RequiredObjects.AddRange(step.RequiredObjects.Items.Select(i => i.Text).Where(s => !string.IsNullOrWhiteSpace(s)));
+
+ if (step.Detection is not null && !string.IsNullOrWhiteSpace(step.Detection.Method))
+ def.Detection = step.Detection.ToCondition();
+
+ foreach (var rule in step.ViolationRules.Items.Where(r => !string.IsNullOrWhiteSpace(r.Type)))
+ def.ViolationRules.Add(rule.ToRule());
+
+ config.Sop.Steps.Add(def);
+ }
+
+ // 只有勾了模型才写 sop.model:留一个 path 为空的节点会让校验里"需要模型"那几条提醒失灵
+ if (HasModel && Model is not null)
+ {
+ var def = new ModelDef { Path = Model.Path, InputSize = Model.InputSize };
+ def.Classes.AddRange(Model.Classes.Items.Select(c => c.Text).Where(c => !string.IsNullOrWhiteSpace(c)));
+ config.Sop.Model = def;
+ }
+
+ return config;
+ }
+}
+
+///
+/// sop.settings
+///
+public class RecipeSettingsNode : EditorNode
+{
+ private float _confidenceThreshold = 0.6f;
+ private int _stableFrames = 5;
+ private float _positionTolerance = 20f;
+ private bool _enableTimeoutDetection = true;
+ private bool _autoResetOnComplete = true;
+ private int _resetDelaySec = 1;
+ private int _frameStride = 1;
+ private double? _exposureTimeUs;
+
+ public double? ExposureTimeUs
+ {
+ get => _exposureTimeUs;
+ set => SetProperty(ref _exposureTimeUs, value);
+ }
+
+
+ /// 全局置信度阈值
+ public float ConfidenceThreshold
+ {
+ get { return _confidenceThreshold; }
+ set { SetProperty(ref _confidenceThreshold, value); }
+ }
+
+ /// 默认稳定帧数(条件未写 stable_frames 时用它)
+ public int StableFrames
+ {
+ get { return _stableFrames; }
+ set { SetProperty(ref _stableFrames, value); }
+ }
+
+ /// 区域命中容差(像素)
+ public float PositionTolerance
+ {
+ get { return _positionTolerance; }
+ set { SetProperty(ref _positionTolerance, value); }
+ }
+
+ /// 启用超时违规
+ public bool EnableTimeoutDetection
+ {
+ get { return _enableTimeoutDetection; }
+ set { SetProperty(ref _enableTimeoutDetection, value); }
+ }
+
+ /// 整轮完成后自动复位
+ public bool AutoResetOnComplete
+ {
+ get { return _autoResetOnComplete; }
+ set { SetProperty(ref _autoResetOnComplete, value); }
+ }
+
+ /// 复位前停留秒数
+ public int ResetDelaySec
+ {
+ get { return _resetDelaySec; }
+ set { SetProperty(ref _resetDelaySec, value); }
+ }
+
+ /// 抽帧间隔(1=每帧都判)
+ public int FrameStride
+ {
+ get { return _frameStride; }
+ set { SetProperty(ref _frameStride, value); }
+ }
+
+ /// 读入
+ public void CopyFrom(SopSettings from)
+ {
+ ExposureTimeUs = from.ExposureTimeUs;
+ ConfidenceThreshold = from.ConfidenceThreshold;
+ StableFrames = from.StableFrames;
+ PositionTolerance = from.PositionTolerance;
+ EnableTimeoutDetection = from.EnableTimeoutDetection;
+ AutoResetOnComplete = from.AutoResetOnComplete;
+ ResetDelaySec = from.ResetDelaySec;
+ FrameStride = from.FrameStride;
+ }
+
+ /// 写出
+ public void CopyTo(SopSettings to)
+ {
+ to.ExposureTimeUs = ExposureTimeUs;
+ to.ConfidenceThreshold = ConfidenceThreshold;
+ to.StableFrames = StableFrames;
+ to.PositionTolerance = PositionTolerance;
+ to.EnableTimeoutDetection = EnableTimeoutDetection;
+ to.AutoResetOnComplete = AutoResetOnComplete;
+ to.ResetDelaySec = ResetDelaySec;
+ to.FrameStride = FrameStride;
+ }
+}
+
+///
+/// sop.model
+///
+public class RecipeModelNode : EditorNode
+{
+ private string _path = "";
+ private int _inputSize = 640;
+
+ /// onnx 路径(相对程序目录)
+ public string Path
+ {
+ get { return _path; }
+ set { SetProperty(ref _path, value); }
+ }
+
+ /// 类别名(顺序必须与训练时一致)
+ public EditableList Classes { get; } = new() { Title = "类别名(顺序须与训练一致)" };
+
+ /// 输入尺寸
+ public int InputSize
+ {
+ get { return _inputSize; }
+ set { SetProperty(ref _inputSize, value); }
+ }
+
+ /// 读入
+ public void CopyFrom(ModelDef from)
+ {
+ Path = from.Path;
+ InputSize = from.InputSize;
+
+ Classes.Items.Clear();
+ foreach (var name in from.Classes) Classes.Items.Add(new TextItem { Text = name, RemoveCommand = Classes.RemoveCommand });
+ }
+}
+
+///
+/// regions 里的一项(Key = 配方里引用的区域名,即 YAML 的字典键)
+///
+public class RegionNode : EditorNode
+{
+ /// 整组更新,属性通知发出时四个坐标已一致。
+ public void SetBounds(Avalonia.PixelRect 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;
+ private int _x2;
+ private int _y2;
+ private string _name = "";
+ private string _description = "";
+ private string _color = "#4CAF50";
+
+ /// 区域键名(YAML 的键,条件里引用的就是它)
+ public string Key
+ {
+ get { return _key; }
+ set
+ {
+ var old = _key;
+ if (!SetProperty(ref _key, value)) return;
+ if (!string.IsNullOrWhiteSpace(old)) Renamed?.Invoke(old, value);
+ }
+ }
+
+ /// 左上 X
+ public int X1
+ {
+ get { return _x1; }
+ set { SetProperty(ref _x1, value); }
+ }
+
+ /// 左上 Y
+ public int Y1
+ {
+ get { return _y1; }
+ set { SetProperty(ref _y1, value); }
+ }
+
+ /// 右下 X
+ public int X2
+ {
+ get { return _x2; }
+ set { SetProperty(ref _x2, value); }
+ }
+
+ /// 右下 Y
+ public int Y2
+ {
+ get { return _y2; }
+ set { SetProperty(ref _y2, value); }
+ }
+
+ /// 显示名
+ public string Name
+ {
+ get { return _name; }
+ set { SetProperty(ref _name, value); }
+ }
+
+ /// 说明
+ public string Description
+ {
+ get { return _description; }
+ set { SetProperty(ref _description, value); }
+ }
+
+ /// 显示颜色(#RRGGBB)
+ public string Color
+ {
+ get { return _color; }
+ set
+ {
+ if (!SetProperty(ref _color, value)) return;
+ RaisePropertyChanged(nameof(Brush));
+ }
+ }
+
+ /// 色块预览(解析失败退回默认绿,别炸界面)
+ public SolidColorBrush Brush
+ {
+ get
+ {
+ try
+ {
+ return new SolidColorBrush(Avalonia.Media.Color.Parse(Color));
+ }
+ catch
+ {
+ return new SolidColorBrush(Avalonia.Media.Color.FromRgb(0x4C, 0xAF, 0x50));
+ }
+ }
+ }
+
+ /// 区域键名变了(配方里的引用要跟着改)
+ public event Action? Renamed;
+
+ /// 读入
+ public void CopyFrom(RegionDef from)
+ {
+ X1 = from.X1;
+ Y1 = from.Y1;
+ X2 = from.X2;
+ Y2 = from.Y2;
+ Name = from.Name;
+ Description = from.Description;
+ Color = from.Color;
+ }
+
+ /// 写出
+ public void CopyTo(RegionDef to)
+ {
+ to.X1 = X1;
+ to.Y1 = Y1;
+ to.X2 = X2;
+ to.Y2 = Y2;
+ to.Name = Name;
+ to.Description = Description;
+ to.Color = Color;
+ }
+}
+
+///
+/// steps 里的一项
+///
+public class StepNode : EditorNode
+{
+ private int _id;
+ private string _name = "";
+ private string _description = "";
+ private int _timeout;
+ private int _standardDurationMs;
+ // 即使 YAML 没有 detection,也保留可编辑对象,供界面写入新选择的方法。
+ private ConditionNode? _detection = new();
+
+ /// 步骤号(执行顺序按它升序)
+ public int Id
+ {
+ get { return _id; }
+ set { SetProperty(ref _id, value); }
+ }
+
+ /// 步骤名
+ public string Name
+ {
+ get { return _name; }
+ set { SetProperty(ref _name, value); }
+ }
+
+ /// 说明
+ public string Description
+ {
+ get { return _description; }
+ set { SetProperty(ref _description, value); }
+ }
+
+ /// 本步超时秒数(0=不限制)
+ public int Timeout
+ {
+ get { return _timeout; }
+ set { SetProperty(ref _timeout, value); }
+ }
+
+ /// 标准节拍毫秒(报表用,不参与判定)
+ public int StandardDurationMs
+ {
+ get { return _standardDurationMs; }
+ set { SetProperty(ref _standardDurationMs, value); }
+ }
+
+ /// 判定条件(method 留空 = 本步不写 detection 节点)
+ public ConditionNode? Detection
+ {
+ get { return _detection; }
+ set { SetProperty(ref _detection, value); }
+ }
+
+ /// 本步期间必须常在的物体
+ public EditableList MustKeep { get; } = new() { Title = "本步期间必须在的物体(被拿走即违规)" };
+
+ /// 本步完成时必须存在的物体
+ public EditableList RequiredObjects { get; } = new() { Title = "本步完成时必须存在的物体(漏放/缺料)" };
+
+ /// 违规规则
+ public EditableList ViolationRules { get; } = new() { Title = "违规规则" };
+
+ /// 本步是否有判定条件(取消勾选就清掉条件)
+ public bool HasCondition
+ {
+ get { return Detection is not null; }
+ set
+ {
+ if (value) Detection ??= new ConditionNode();
+ else Detection = null;
+
+ RaisePropertyChanged();
+ }
+ }
+}
+
+///
+/// 步骤的判定条件
+///
+public class ConditionNode : EditorNode
+{
+ private string _method = "";
+ private string _targetObject = "";
+ private string _region = "";
+ private string _fromRegion = "";
+ private string _toRegion = "";
+ private string _hand = "any";
+ private float _tolerance = 60f;
+ private float _minConfidence = 0.7f;
+ private int _stableFrames = 5;
+ private int _durationMs;
+
+ /// 判定方法
+ public string Method
+ {
+ get { return _method; }
+ set { SetProperty(ref _method, value); }
+ }
+
+ /// 目标物体类别
+ public string TargetObject
+ {
+ get { return _targetObject; }
+ set { SetProperty(ref _targetObject, value); }
+ }
+
+ /// 主区域名
+ public string Region
+ {
+ get { return _region; }
+ set { SetProperty(ref _region, value); }
+ }
+
+ /// 起点区域名(hand_move 的 from)
+ public string FromRegion
+ {
+ get { return _fromRegion; }
+ set { SetProperty(ref _fromRegion, value); }
+ }
+
+ /// 终点区域名(hand_move 的 to)
+ public string ToRegion
+ {
+ get { return _toRegion; }
+ set { SetProperty(ref _toRegion, value); }
+ }
+
+ /// 手:any/left/right
+ public string Hand
+ {
+ get { return _hand; }
+ set { SetProperty(ref _hand, value); }
+ }
+
+ /// 手-物相邻容差(像素)
+ public float Tolerance
+ {
+ get { return _tolerance; }
+ set { SetProperty(ref _tolerance, value); }
+ }
+
+ /// 本条件置信度阈值
+ public float MinConfidence
+ {
+ get { return _minConfidence; }
+ set { SetProperty(ref _minConfidence, value); }
+ }
+
+ /// 稳定帧数
+ public int StableFrames
+ {
+ get { return _stableFrames; }
+ set { SetProperty(ref _stableFrames, value); }
+ }
+
+ /// 计时毫秒(time_elapsed 用)
+ public int DurationMs
+ {
+ get { return _durationMs; }
+ set { SetProperty(ref _durationMs, value); }
+ }
+
+ /// 读入
+ public static ConditionNode From(StepCondition from) => new()
+ {
+ Method = from.Method,
+ TargetObject = from.TargetObject,
+ Region = from.Region,
+ FromRegion = from.FromRegion,
+ ToRegion = from.ToRegion,
+ Hand = from.Hand,
+ Tolerance = from.Tolerance,
+ MinConfidence = from.MinConfidence,
+ StableFrames = from.StableFrames,
+ DurationMs = from.DurationMs,
+ };
+
+ /// 写出
+ public StepCondition ToCondition() => new()
+ {
+ Method = Method,
+ TargetObject = TargetObject,
+ Region = Region,
+ FromRegion = FromRegion,
+ ToRegion = ToRegion,
+ Hand = Hand,
+ Tolerance = Tolerance,
+ MinConfidence = MinConfidence,
+ StableFrames = StableFrames,
+ DurationMs = DurationMs,
+ };
+}
+
+///
+/// 违规规则
+///
+public class ViolationRuleNode : EditorNode, IRemovable
+{
+ private string _type = ViolationType.Timeout;
+ private string _description = "";
+ private int _severity = 1;
+
+ /// 违规类型
+ public string Type
+ {
+ get { return _type; }
+ set { SetProperty(ref _type, value); }
+ }
+
+ /// 描述(告警横幅文案)
+ public string Description
+ {
+ get { return _description; }
+ set { SetProperty(ref _description, value); }
+ }
+
+ /// 严重度
+ public int Severity
+ {
+ get { return _severity; }
+ set { SetProperty(ref _severity, value); }
+ }
+
+ ///
+ public ICommand? RemoveCommand { get; set; }
+
+ /// 读入
+ public static ViolationRuleNode From(ViolationRule from, ICommand? removeCommand = null) => new()
+ {
+ Type = from.Type,
+ Description = from.Description,
+ Severity = from.Severity,
+ RemoveCommand = removeCommand,
+ };
+
+ /// 写出
+ public ViolationRule ToRule() => new()
+ {
+ Type = Type,
+ Description = Description,
+ Severity = Severity,
+ };
+}
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeDialogWindow.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeDialogWindow.cs
new file mode 100644
index 0000000..c16fdea
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeDialogWindow.cs
@@ -0,0 +1,15 @@
+using Avalonia.Controls;
+using Prism.Dialogs;
+
+namespace SopHelper.VVMs.RecipeEditor;
+public sealed class RecipeDialogWindow : Window,IDialogWindow
+{
+ public IDialogResult Result {get;set;}=new DialogResult();
+ public RecipeDialogWindow()
+ {
+ Width=1040;Height=760;MinWidth=1040;MinHeight=760;
+ WindowStartupLocation=WindowStartupLocation.CenterOwner;
+ HorizontalContentAlignment=Avalonia.Layout.HorizontalAlignment.Stretch;
+ VerticalContentAlignment=Avalonia.Layout.VerticalAlignment.Stretch;
+ }
+}
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
new file mode 100644
index 0000000..b0776dd
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml
@@ -0,0 +1,440 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml.cs
new file mode 100644
index 0000000..ae4f4b1
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml.cs
@@ -0,0 +1,4 @@
+using Avalonia.Controls;
+namespace SopHelper.VVMs.RecipeEditor;
+public partial class RecipeEditor : UserControl
+{ public RecipeEditor() { InitializeComponent(); } }
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
new file mode 100644
index 0000000..33063be
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs
@@ -0,0 +1,318 @@
+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;
+
+namespace SopHelper.VVMs.RecipeEditor;
+
+///
+/// 配方编辑器(SOP 页「编辑」按钮弹出)。表单在 EditorNodes 那一侧,
+/// 保存时整体映射回 SopConfig 交给 SopConfigLoader 写 YAML。
+/// 类名必须是"视图全名 + ViewModel",Prism 的 ViewModelLocator 按这个约定绑定(见 App)。
+///
+public class RecipeEditorViewModel : BindableBase, IDialogAware
+{
+ private RecipeNode _recipe = new();
+ private string _path = "";
+ private bool _isNew;
+ private Action? _onSaved;
+ private readonly HashSet _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; }
+
+ /// 当前编辑的配方目录(configs/sop)
+ private string _directory = "";
+
+ ///
+ public string Title => _isNew ? "新建配方" : $"编辑配方 - {FileNameText}";
+
+ ///
+ public DialogCloseListener RequestClose { get; } = new();
+
+ /// 标题栏显示的文件名
+ public string FileNameText => string.IsNullOrEmpty(_path) ? $"{_recipe.FileName}.yaml(新建)" : Path.GetFileName(_path);
+
+ /// 编辑中的配方
+ public RecipeNode Recipe
+ {
+ get { return _recipe; }
+ private set
+ {
+ if (!SetProperty(ref _recipe, value)) return;
+ RaisePropertyChanged(nameof(FileNameText));
+ RaisePropertyChanged(nameof(Title));
+ }
+ }
+
+ /// 保存前的校验提醒(不阻止保存——现场常见"先存草稿再补区域")
+ public ObservableCollection Warnings { get; } = [];
+
+ /// 保存
+ public DelegateCommand SaveCommand { get; private set; } = null!;
+
+ /// 关闭编辑器,未保存的修改不写入文件
+ public DelegateCommand CloseCommand { get; private set; } = null!;
+
+ ///
+ /// 配方编辑器
+ ///
+ 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);
+ }
+
+ ///
+ public void OnDialogOpened(IDialogParameters parameters)
+ {
+ _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();
+
+ // 新建时文件名还没定,用配方名兜底;已存在的文件名不可改(SOP 页按文件名选配方)
+ var fileName = string.IsNullOrEmpty(_path) ? config.Sop.Name : Path.GetFileNameWithoutExtension(_path);
+
+ Recipe = RecipeNode.From(config, fileName, _isNew);
+ Recipe.Changed += RefreshWarnings;
+
+ RefreshWarnings();
+ }
+
+ ///
+ public bool CanCloseDialog() => !IsCapturing;
+
+ ///
+ 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, AppContext.BaseDirectory);
+ 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(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 + ".yaml") : _path;
+
+ try
+ {
+ // Save 内部落盘后会回读校验,返回值就是磁盘上那份
+ 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);
+
+ SaveStatus = $"已保存 {Path.GetFileName(_path)}";
+ _onSaved?.Invoke(Path.GetFileName(_path));
+ }
+ catch (Exception ex)
+ {
+ // 写盘失败(文件被占用/只读)留给用户看,别让整个编辑器跟着炸
+ Warnings.Clear();
+ Warnings.Add("保存失败:" + ex.Message);
+ }
+ }
+
+ ///
+ /// 用当前编辑结果跑一遍加载器校验(就是"这一步永远不推进"那类问题)
+ ///
+ private void RefreshWarnings()
+ {
+ SaveStatus = "";
+ // 步骤和条件字段变化时同步校验,避免方法已选择却仍显示旧的缺失提示。
+ var current = new HashSet(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();
+}
diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RegionCanvas.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RegionCanvas.cs
new file mode 100644
index 0000000..e082bec
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RegionCanvas.cs
@@ -0,0 +1,96 @@
+using System.Collections.ObjectModel;
+using System.Collections.Specialized;
+using System.ComponentModel;
+using System.Globalization;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+using SopHelper.Presentation.Imaging;
+
+namespace SopHelper.VVMs.RecipeEditor;
+public sealed class RegionCanvas : Control
+{
+ public static readonly StyledProperty ImageProperty=AvaloniaProperty.Register(nameof(Image));
+ public static readonly StyledProperty?> RegionsProperty=AvaloniaProperty.Register?>(nameof(Regions));
+ public static readonly StyledProperty SelectedRegionProperty=AvaloniaProperty.Register(nameof(SelectedRegion));
+ public BitmapSource? Image {get=>GetValue(ImageProperty);set=>SetValue(ImageProperty,value);}
+ public ObservableCollection? Regions {get=>GetValue(RegionsProperty);set=>SetValue(RegionsProperty,value);}
+ public RegionNode? SelectedRegion {get=>GetValue(SelectedRegionProperty);set=>SetValue(SelectedRegionProperty,value);}
+ private readonly HashSet _observed=[];
+ private Point? _start;private Point _end;private RegionNode? _drawingRegion;private IPointer? _pointer;
+ static RegionCanvas(){AffectsRender(ImageProperty,RegionsProperty,SelectedRegionProperty);}
+ public RegionCanvas(){Focusable=true;Cursor=new Cursor(StandardCursorType.Cross);DetachedFromVisualTree+=(_,_)=>CancelDrag();}
+ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
+ {
+ base.OnPropertyChanged(change);
+ if(change.Property==ImageProperty||change.Property==SelectedRegionProperty)CancelDrag();
+ if(change.Property==RegionsProperty)
+ {
+ if(change.OldValue is ObservableCollection old)old.CollectionChanged-=CollectionChanged;
+ if(change.NewValue is ObservableCollection current)current.CollectionChanged+=CollectionChanged;
+ ObserveRegions();
+ }
+ }
+ public static Rect FitImage(Size viewport,Size image)
+ {
+ if(viewport.Width<=0||viewport.Height<=0||image.Width<=0||image.Height<=0)return default;
+ 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 PixelRect 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 PixelRect(x1,y1,x2-x1,y2-y1);
+ }
+ public override void Render(DrawingContext dc)
+ {
+ dc.DrawRectangle(new SolidColorBrush(Color.FromRgb(10,16,22)),null,new Rect(Bounds.Size));
+ if(Image is null)
+ {
+ var text=new FormattedText("从相机取图,或打开一张图片后画框",CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Microsoft YaHei, Noto Sans CJK SC"),13,Brushes.LightGray);
+ dc.DrawText(text,new Point(Math.Max(8,(Bounds.Width-text.Width)/2),Math.Max(8,Bounds.Height/2-text.Height/2)));return;
+ }
+ var size=new Size(Image.PixelWidth,Image.PixelHeight);var display=FitImage(Bounds.Size,size);if(display.Width<=0)return;
+ dc.DrawImage(Image,display);var scale=display.Width/size.Width;
+ using var clip=dc.PushClip(display);using var transform=dc.PushTransform(new Matrix(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);
+ if(selected)dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(35,0,184,212)),null,rect);
+ dc.DrawRectangle(null,new Pen(region.Brush,(selected?3:1.5)/scale),rect);
+ var label=new FormattedText(string.IsNullOrWhiteSpace(region.Name)?region.Key:region.Name,CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Microsoft YaHei, Noto Sans CJK SC"),12/scale,region.Brush);
+ 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)dc.DrawRectangle(null,new Pen(Brushes.Yellow,2/scale,new DashStyle([2,2],0)),
+ new Rect(Math.Min(start.X,_end.X),Math.Min(start.Y,_end.Y),Math.Abs(start.X-_end.X),Math.Abs(start.Y-_end.Y)));
+ }
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);if(!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed||Image is null||SelectedRegion is null)return;
+ var display=FitImage(Bounds.Size,new Size(Image.PixelWidth,Image.PixelHeight));var point=e.GetPosition(this);if(display.Width<=0||!display.Contains(point))return;
+ Focus();_pointer=e.Pointer;_pointer.Capture(this);_drawingRegion=SelectedRegion;_start=_end=ToImage(point,display,new Size(Image.PixelWidth,Image.PixelHeight));InvalidateVisual();e.Handled=true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);if(_start is null||Image is null)return;
+ _end=ToImage(e.GetPosition(this),FitImage(Bounds.Size,new Size(Image.PixelWidth,Image.PixelHeight)),new Size(Image.PixelWidth,Image.PixelHeight));InvalidateVisual();e.Handled=true;
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);if(_start is not Point start||Image is null)return;
+ var size=new Size(Image.PixelWidth,Image.PixelHeight);var display=FitImage(Bounds.Size,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 OnPointerCaptureLost(PointerCaptureLostEventArgs e){base.OnPointerCaptureLost(e);CancelDrag();}
+ private void CancelDrag(){_start=null;_drawingRegion=null;var pointer=_pointer;_pointer=null;if(pointer?.Captured==this)pointer.Capture(null);InvalidateVisual();}
+ private void CollectionChanged(object? sender,NotifyCollectionChangedEventArgs e){CancelDrag();ObserveRegions();}
+ private void ObserveRegions(){foreach(var n in _observed)n.PropertyChanged-=NodeChanged;_observed.Clear();foreach(var n in Regions??[]){_observed.Add(n);n.PropertyChanged+=NodeChanged;}InvalidateVisual();}
+ private void NodeChanged(object? sender,PropertyChangedEventArgs e)=>InvalidateVisual();
+}
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/DetectionOverlay.cs b/src/SopHelper.Avalonia/VVMs/SopPage/DetectionOverlay.cs
new file mode 100644
index 0000000..7e4c30a
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/DetectionOverlay.cs
@@ -0,0 +1,35 @@
+using System.Globalization;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Media;
+using SopHelper.Engine.Common;
+
+namespace SopHelper.VVMs.SopPage;
+public sealed class DetectionOverlay : Control
+{
+ public static readonly StyledProperty ResultProperty=AvaloniaProperty.Register(nameof(Result));
+ public FrameResult? Result {get=>GetValue(ResultProperty);set=>SetValue(ResultProperty,value);}
+ static DetectionOverlay(){AffectsRender(ResultProperty);}
+ public override void Render(DrawingContext dc)
+ {
+ base.Render(dc);var result=Result;if(result is null || result.Size.W<=0 || result.Size.H<=0 || Bounds.Width<=0 || Bounds.Height<=0)return;
+ using var clip=dc.PushClip(new Rect(Bounds.Size));
+ using var transform=dc.PushTransform(Matrix.CreateScale(Bounds.Width/result.Size.W,Bounds.Height/result.Size.H));
+ var unit=Math.Max(result.Size.W,result.Size.H)/700.0;
+ var imageBounds=new Rect(0,0,result.Size.W,result.Size.H);
+ var background=new SolidColorBrush(Color.FromArgb(220,12,18,24));
+ var padding=3*unit;
+ foreach(var d in result.Detections)
+ {
+ var r=d.Rect;if(r.W<=0||r.H<=0||!float.IsFinite(r.X)||!float.IsFinite(r.Y)||!float.IsFinite(r.Right)||!float.IsFinite(r.Bottom)||!float.IsFinite(d.Confidence))continue;
+ var rect=imageBounds.Intersect(new Rect(r.X,r.Y,r.W,r.H));if(rect.Width<=0||rect.Height<=0)continue;
+ dc.DrawRectangle(null,new Pen(Brushes.Orange,2*unit),rect);
+ var text=new FormattedText($"{d.Label} {d.Confidence:P0}",CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Microsoft YaHei, Noto Sans CJK SC"),12*unit,Brushes.White)
+ {MaxTextWidth=Math.Max(1,imageBounds.Width-2*padding),MaxLineCount=1,Trimming=TextTrimming.CharacterEllipsis};
+ var size=new Size(text.Width+2*padding,text.Height+2*padding);
+ var left=Math.Clamp(rect.Left,0,Math.Max(0,imageBounds.Width-size.Width));
+ var top=Math.Clamp(rect.Top>=size.Height?rect.Top-size.Height:rect.Top,0,Math.Max(0,imageBounds.Height-size.Height));
+ dc.DrawRectangle(background,null,new Rect(new Point(left,top),size));dc.DrawText(text,new Point(left+padding,top+padding));
+ }
+ }
+}
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/HandOverlay.cs b/src/SopHelper.Avalonia/VVMs/SopPage/HandOverlay.cs
new file mode 100644
index 0000000..31f7ecd
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/HandOverlay.cs
@@ -0,0 +1,30 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Media;
+using SopHelper.Engine.Common;
+
+namespace SopHelper.VVMs.SopPage;
+public sealed class HandOverlay : Control
+{
+ public static readonly StyledProperty ResultProperty=AvaloniaProperty.Register(nameof(Result));
+ public FrameResult? Result { get=>GetValue(ResultProperty);set=>SetValue(ResultProperty,value); }
+ private static readonly (int From,int To)[] Bones=[(0,1),(1,2),(2,3),(3,4),(0,5),(5,6),(6,7),(7,8),(5,9),(9,10),(10,11),(11,12),(9,13),(13,14),(14,15),(15,16),(13,17),(0,17),(17,18),(18,19),(19,20)];
+ static HandOverlay(){AffectsRender(ResultProperty);}
+ public override void Render(DrawingContext drawing)
+ {
+ base.Render(drawing);var result=Result;
+ if(result is null || result.Size.W<=0 || result.Size.H<=0 || Bounds.Width<=0 || Bounds.Height<=0)return;
+ using var clip=drawing.PushClip(new Rect(Bounds.Size));
+ using var scale=drawing.PushTransform(Matrix.CreateScale(Bounds.Width/result.Size.W,Bounds.Height/result.Size.H));
+ var unit=Math.Max(result.Size.W,result.Size.H)/700.0;
+ foreach(var hand in result.Hands)
+ {
+ var brush=hand.HandType switch {HandType.Left=>Brushes.LimeGreen,HandType.Right=>Brushes.DeepSkyBlue,_=>Brushes.Gray};
+ var pen=new Pen(brush,unit*2);
+ var points=hand.Keypoints.Where(p=>p.Index is >=0 and <=20 && p.Confidence>0 && float.IsFinite(p.X) && float.IsFinite(p.Y)).GroupBy(p=>p.Index).ToDictionary(g=>g.Key,g=>g.First());
+ foreach(var (from,to) in Bones)
+ if(points.TryGetValue(from,out var a)&&points.TryGetValue(to,out var b))drawing.DrawLine(pen,new Point(a.X,a.Y),new Point(b.X,b.Y));
+ foreach(var p in points.Values)drawing.DrawEllipse(Brushes.Yellow,null,new Point(p.X,p.Y),unit*3,unit*3);
+ }
+ }
+}
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
new file mode 100644
index 0000000..a411ffb
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml
@@ -0,0 +1,203 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml.cs
new file mode 100644
index 0000000..4e568e6
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPage.axaml.cs
@@ -0,0 +1,5 @@
+using Avalonia.Controls;
+namespace SopHelper.VVMs.SopPage;
+[SopHelper.Core.Prism.NavigationPage(ViewName="SopPage", DisplayName="SOP 辅助", Index=0)]
+public partial class SopPage : UserControl
+{ public SopPage() { InitializeComponent(); } }
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
new file mode 100644
index 0000000..8e5cb42
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -0,0 +1,846 @@
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Text.Json;
+using Avalonia.Media;
+using ImageSource = Avalonia.Media.IImage;
+using SopHelper.Presentation.Imaging;
+using SopHelper.Presentation.Threading;
+using OpenCvSharp;
+using Prism.Commands;
+using Prism.Dialogs;
+using SopHelper.Core.Prism;
+using SopHelper.Engine.Camera;
+using SopHelper.Engine.Common;
+using SopHelper.Engine.Pipeline;
+using SopHelper.Engine.Sop;
+
+namespace SopHelper.VVMs.SopPage;
+
+///
+/// SOP 主页视图模型:相机 → 推理管线 → SOP 引擎,界面只订阅事件。
+///
+public class SopPageViewModel : ViewModelBase
+{
+ private const int MaxLogLines = 300;
+ private const int MaxTopViolations = 3;
+
+ /// 配方目录(相对程序目录)
+ private static string RecipeDirectory => Path.Combine(AppContext.BaseDirectory, "configs", "sop");
+
+ private static string LastCameraPath => Path.Combine(
+ Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SopHelper", "last-camera.json");
+
+ /// 配方编辑器弹窗的注册名(见 App.RegisterTypes)
+ private const string EditorDialogName = "RecipeEditorDialog";
+
+ private readonly ICameraService _camera;
+ private readonly DetectionPipeline _pipeline;
+ private readonly SopEngine _engine;
+ private readonly IDialogService _dialogs;
+ private readonly Dispatcher _dispatcher;
+
+ private readonly DispatcherTimer _renderTimer;
+
+ /// 采集线程写、UI 线程取最新帧
+ private readonly object _frameLock = new();
+
+ private Mat? _pending;
+ private bool _destroyed;
+
+ /// 最近一次处理过的帧(快照按钮存盘用,由推理线程写入)
+ private FrameResult? _lastFrame;
+ private FrameResult? _handResult;
+ private WriteableBitmap? _bitmap;
+ private long _frameCount;
+ private long _lastTickCount;
+
+ private CameraInfo? _selectedCamera;
+ private CameraInfo? _lastUsedCamera;
+ private string? _selectedRecipe;
+ private ImageSource? _frame;
+ private string _statusText = "就绪";
+ private string _fpsText = "—";
+ private string _inferenceText = "—";
+ private bool _isRunning;
+ private bool _isConnected;
+ private bool _isCameraBusy;
+ private double _frameWidth;
+ private double _frameHeight;
+ private double _confidence = 0.6;
+ private int _frameStride = 2;
+
+ ///
+ /// SOP 主页视图模型
+ ///
+ public SopPageViewModel(ICameraService camera, DetectionPipeline pipeline, SopEngine engine, IDialogService dialogs)
+ {
+ _camera = camera;
+ _pipeline = pipeline;
+ _engine = engine;
+ _dialogs = dialogs;
+ _dispatcher = Dispatcher.CurrentDispatcher;
+
+ _camera.ConnectionChanged += on => _dispatcher.BeginInvoke(() =>
+ {
+ IsConnected = on;
+ if (!on && IsRunning)
+ {
+ IsRunning = false;
+ StatusText = "相机已断开";
+ RaiseCommands();
+ }
+ });
+ _camera.Error += message => _dispatcher.BeginInvoke(() => Log("warn", message));
+
+ _pipeline.ResultArrived += result => _dispatcher.BeginInvoke(() => OnResult(result));
+
+ // 帧 Mat 只在采集线程的事件存活期内有效(事件返回即被释放),必须当场克隆
+ _camera.FrameArrived += OnCameraFrame;
+ _engine.LogArrived += entry => _dispatcher.BeginInvoke(() => AppendLog(entry));
+ _engine.ViolationRaised += violation => _dispatcher.BeginInvoke(() => AppendViolation(violation));
+ _engine.StepSnapshotChanged += snapshot => _dispatcher.BeginInvoke(() => UpdateCard(snapshot));
+ _engine.Completed += () => _dispatcher.BeginInvoke(() => StatusText = "本轮完成");
+
+ // 渲染定时器:从采集线程留下的最新帧取一份画出来(天然限帧,不在采集线程做 UI 活)
+ _renderTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(40) };
+ _renderTimer.Tick += (_, _) => RenderFrame();
+ _renderTimer.Start();
+
+ LoadRecipes();
+
+ // 命令接线(DelegateCommand 的可用条件都挂在这里)
+ RefreshCamerasCommand = new DelegateCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
+ StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
+ TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
+ ResetCommand = new DelegateCommand(_engine.Reset, () => 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 && !_isCameraBusy);
+
+ StatusText = "选择相机和配方,点开始";
+ LoadLastCamera();
+ _ = RefreshCamerasAsync();
+ }
+
+ /// 可用相机
+ public ObservableCollection Cameras { get; } = [];
+
+ /// 可用配方文件
+ public ObservableCollection Recipes { get; } = [];
+
+ /// 步骤卡
+ public ObservableCollection StepCards { get; } = [];
+
+ /// Top3 违规
+ public ObservableCollection Violations { get; } = [];
+
+ /// 日志
+ public ObservableCollection Logs { get; } = [];
+
+ /// 画面 ROI
+ public ObservableCollection Rois { get; } = [];
+
+ /// 选中相机
+ public CameraInfo? SelectedCamera
+ {
+ get { return _selectedCamera; }
+ set
+ {
+ if (!SetProperty(ref _selectedCamera, value)) return;
+ RaiseCommands(); // 实测:不刷新会导致"开始/停止"一直灰着,选了相机也点不动
+ }
+ }
+
+ /// 选中配方
+ public string? SelectedRecipe
+ {
+ get { return _selectedRecipe; }
+ set
+ {
+ if (!SetProperty(ref _selectedRecipe, value)) return;
+ RaiseCommands();
+ }
+ }
+
+ /// 画面
+ public ImageSource? Frame
+ {
+ get { return _frame; }
+ set { SetProperty(ref _frame, value); }
+ }
+
+ /// 最近一次推理结果,供图像上的手部与目标检测绘制层使用。
+ public FrameResult? HandResult
+ {
+ get => _handResult;
+ private set => SetProperty(ref _handResult, value);
+ }
+
+ /// 状态
+ public string StatusText
+ {
+ get { return _statusText; }
+ set { SetProperty(ref _statusText, value); }
+ }
+
+ /// 结果帧率
+ public string FpsText
+ {
+ get { return _fpsText; }
+ set { SetProperty(ref _fpsText, value); }
+ }
+
+ /// 推理耗时
+ public string InferenceText
+ {
+ get { return _inferenceText; }
+ set { SetProperty(ref _inferenceText, value); }
+ }
+
+ /// 是否运行中
+ public bool IsRunning
+ {
+ get { return _isRunning; }
+ set
+ {
+ if (!SetProperty(ref _isRunning, value)) return;
+ if (!value) HandResult = null;
+ RaisePropertyChanged(nameof(CanSelectCamera));
+ RaiseCommands();
+ }
+ }
+
+ /// 连接、枚举、采集期间不切换设备。
+ public bool CanSelectCamera => !IsRunning && !_isCameraBusy;
+
+ /// 相机是否已连接
+ public bool IsConnected
+ {
+ get { return _isConnected; }
+ set
+ {
+ if (!SetProperty(ref _isConnected, value)) return;
+ RaisePropertyChanged(nameof(ConnectionText));
+ }
+ }
+
+ /// 右下角连接文字(实测静态文字不反映状态,改成绑定)
+ public string ConnectionText => IsConnected ? "相机已连接" : "相机未连接";
+
+ /// 画面像素宽(ROI 覆盖层按它缩放)
+ public double FrameWidth
+ {
+ get { return _frameWidth; }
+ set { SetProperty(ref _frameWidth, value); }
+ }
+
+ /// 画面像素高
+ public double FrameHeight
+ {
+ get { return _frameHeight; }
+ set { SetProperty(ref _frameHeight, value); }
+ }
+
+ /// 置信度阈值(透传给 YOLO)
+ public double Confidence
+ {
+ get { return _confidence; }
+ set { SetProperty(ref _confidence, value); }
+ }
+
+ /// 抽帧间隔
+ public int FrameStride
+ {
+ get { return _frameStride; }
+ set { SetProperty(ref _frameStride, value); }
+ }
+
+ /// 刷新相机列表
+ public DelegateCommand RefreshCamerasCommand { get; private set; } = null!;
+
+ /// 开始 / 停止
+ public DelegateCommand StartStopCommand { get; private set; } = null!;
+
+ /// 暂停 / 继续
+ public DelegateCommand TogglePauseCommand { get; private set; } = null!;
+
+ /// 复位
+ public DelegateCommand ResetCommand { get; private set; } = null!;
+
+ /// 应用配方
+ public DelegateCommand ApplyRecipeCommand { get; private set; } = null!;
+
+ /// 快照
+ public DelegateCommand SnapshotCommand { get; private set; } = null!;
+
+ /// 编辑当前选中的配方(弹窗)
+ public DelegateCommand EditRecipeCommand { get; private set; } = null!;
+
+ /// 新建配方(弹窗)
+ public DelegateCommand NewRecipeCommand { get; private set; } = null!;
+
+ private bool CanStart() => !_isCameraBusy && (SelectedCamera is not null || IsRunning);
+
+ private void SetCameraBusy(bool busy)
+ {
+ _isCameraBusy = busy;
+ RaisePropertyChanged(nameof(CanSelectCamera));
+ RaiseCommands();
+ }
+
+ /// 运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用
+ private bool CanEditRecipe() => !IsRunning && !_isCameraBusy && !string.IsNullOrWhiteSpace(SelectedRecipe);
+
+ ///
+ /// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
+ /// 绑定上去的按钮不会因属性变化自动亮起来(实测:选了相机"开始/停止"仍灰着)。
+ ///
+ private void RaiseCommands()
+ {
+ // 构造函数里 LoadRecipes() 会先设 SelectedRecipe,那时命令还没创建,必须空安全
+ RefreshCamerasCommand?.RaiseCanExecuteChanged();
+ StartStopCommand?.RaiseCanExecuteChanged();
+ TogglePauseCommand?.RaiseCanExecuteChanged();
+ ResetCommand?.RaiseCanExecuteChanged();
+ ApplyRecipeCommand?.RaiseCanExecuteChanged();
+ SnapshotCommand?.RaiseCanExecuteChanged();
+ EditRecipeCommand?.RaiseCanExecuteChanged();
+ NewRecipeCommand?.RaiseCanExecuteChanged();
+ }
+
+ ///
+ /// 采集线程:克隆一份交给渲染定时器,避免与相机的释放抢生命周期
+ ///
+ private void OnCameraFrame(CameraFrame frame)
+ {
+ lock (_frameLock)
+ {
+ if (_destroyed) return;
+ var clone = frame.Bgr.Clone();
+ var old = _pending;
+ _pending = clone;
+ old?.Dispose();
+ }
+ }
+
+ ///
+ /// 快照:把最近处理过的帧连同 ROI 存到 snaps/
+ ///
+ private void Snapshot()
+ {
+ var frame = _lastFrame;
+ if (frame is null) return;
+
+ lock (_frameLock)
+ {
+ if (_pending is null) return;
+
+ var dir = Path.Combine(AppContext.BaseDirectory, "snaps");
+ Directory.CreateDirectory(dir);
+
+ var path = Path.Combine(dir, $"{frame.FrameId}_{frame.Timestamp:HHmmss_fff}.png");
+ Cv2.ImWrite(path, _pending);
+
+ Log("info", $"快照已存:{path}");
+ }
+ }
+
+ ///
+ public override void Destroy()
+ {
+ _renderTimer.Stop();
+ _camera.FrameArrived -= OnCameraFrame;
+
+ lock (_frameLock)
+ {
+ _destroyed = true;
+ _pending?.Dispose();
+ _pending = null;
+ }
+
+ // 相机与推理管线是应用级单例,由 App.OnExit 按顺序统一释放。
+
+ base.Destroy();
+ }
+
+ ///
+ /// 扫描 configs/sop/*.yaml
+ ///
+ private void LoadRecipes()
+ {
+ if (!Directory.Exists(RecipeDirectory)) return;
+
+ foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
+ Recipes.Add(Path.GetFileName(file));
+
+ if (Recipes.Count > 0) SelectedRecipe = Recipes[0];
+ }
+
+ ///
+ /// 编辑器保存后:重扫目录(新建的文件要能选到),选中刚存的那个,再重新应用一次
+ ///
+ private void RefreshRecipes(string fileName)
+ {
+ Recipes.Clear();
+
+ if (Directory.Exists(RecipeDirectory))
+ foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
+ Recipes.Add(Path.GetFileName(file));
+
+ var pick = Recipes.Contains(fileName) ? fileName : Recipes.FirstOrDefault();
+ if (pick is not null) SelectedRecipe = pick;
+
+ ApplyRecipe();
+ }
+
+ ///
+ /// 编辑当前选中的配方
+ ///
+ private void EditRecipe()
+ {
+ var path = Path.Combine(RecipeDirectory, SelectedRecipe!);
+ if (!File.Exists(path))
+ {
+ Log("warn", $"配方不存在:{path}");
+ return;
+ }
+
+ // 编辑器读的是这个已解析的 config(含校验提醒),保存时再整体映射回去
+ OpenEditor(path, false, SopConfigLoader.Load(path));
+ }
+
+ ///
+ /// 新建配方(空白配方,文件名在编辑器里填)
+ ///
+ private void NewRecipe()
+ {
+ OpenEditor("", true, new SopConfig());
+ }
+
+ ///
+ /// 弹出配方编辑器。每次保存成功后刷新配方列表,编辑窗口保持打开。
+ ///
+ private void OpenEditor(string path, bool isNew, SopConfig config)
+ {
+ var parameters = new DialogParameters();
+ parameters.Add("directory", RecipeDirectory);
+ parameters.Add("path", path);
+ parameters.Add("new", isNew);
+ parameters.Add("config", config);
+ 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)
+ {
+ var preview = image.Clone();
+ preview.Freeze();
+ parameters.Add("preview", preview);
+ }
+
+ _dialogs.ShowDialog(EditorDialogName, parameters, _ => { });
+ }
+
+ private void LoadLastCamera()
+ {
+ try
+ {
+ if (File.Exists(LastCameraPath))
+ _lastUsedCamera = JsonSerializer.Deserialize(File.ReadAllText(LastCameraPath));
+ }
+ catch (Exception ex)
+ {
+ Log("warn", $"读取上次使用的相机失败:{ex.Message}");
+ }
+ }
+
+ private void RememberCamera(CameraInfo camera)
+ {
+ _lastUsedCamera = camera;
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(LastCameraPath)!);
+ File.WriteAllText(LastCameraPath, JsonSerializer.Serialize(camera));
+ }
+ catch (Exception ex)
+ {
+ Log("warn", $"保存上次使用的相机失败:{ex.Message}");
+ }
+ }
+
+ private async Task RefreshCamerasAsync()
+ {
+ if (_destroyed || !CanSelectCamera) return;
+ SetCameraBusy(true);
+ try
+ {
+ var previous = SelectedCamera ?? _lastUsedCamera;
+ SelectedCamera = null;
+ Cameras.Clear();
+
+ var cameras = await _camera.EnumerateAsync();
+ if (_destroyed) return;
+ foreach (var info in cameras)
+ Cameras.Add(info);
+
+ if (Cameras.Count == 0)
+ {
+ Log("warn", "没有枚举到相机(支持 UVC、海康 GigE/USB 工业相机)");
+ return;
+ }
+
+ SelectedCamera = Cameras.FirstOrDefault(c => c.Kind == previous?.Kind &&
+ (c.Kind == CameraKind.Hikvision ? c.SerialNumber == previous.SerialNumber : c.Index == previous.Index))
+ ?? Cameras[0];
+ Log("info", $"枚举到 {Cameras.Count} 个相机");
+ }
+ catch (Exception ex)
+ {
+ Log("warn", $"刷新相机失败:{ex.Message}");
+ }
+ finally { SetCameraBusy(false); }
+ }
+
+ private async Task StartStopAsync()
+ {
+ if (_isCameraBusy) return;
+ SetCameraBusy(true);
+ try { await StartStopCoreAsync(); }
+ catch (Exception ex)
+ {
+ await Task.Run(_camera.Disconnect);
+ IsRunning = false;
+ StatusText = "启动失败";
+ Log("warn", $"相机操作失败:{ex.Message}");
+ }
+ finally { SetCameraBusy(false); }
+ }
+
+ private async Task StartStopCoreAsync()
+ {
+ if (IsRunning)
+ {
+ await Task.Run(() =>
+ {
+ _pipeline.Stop();
+ // Recording opens its own capture session; stopping SOP must release the device.
+ _camera.Disconnect();
+ });
+ IsRunning = false;
+ StatusText = "已停止";
+ return;
+ }
+
+ if (SelectedCamera is null)
+ {
+ Log("warn", "先选相机");
+ return;
+ }
+
+ if (string.IsNullOrWhiteSpace(SelectedRecipe))
+ {
+ Log("warn", "先选配方");
+ return;
+ }
+
+ if (!await _camera.ConnectAsync(SelectedCamera)) return;
+
+ ApplyRecipe();
+
+ if (_engine.Config.Sop.Settings.ExposureTimeUs is { } exposure)
+ {
+ try
+ {
+ if (!double.IsFinite(exposure) || exposure <= 0)
+ throw new InvalidOperationException("相机曝光必须大于 0(微秒),或留空保留相机设置");
+ await _camera.SetExposureTimeAsync(exposure);
+ }
+ catch (Exception ex)
+ {
+ Log("error", "设置相机曝光失败:" + ex.Message);
+ await Task.Run(_camera.Disconnect);
+ StatusText = "设置相机曝光失败";
+ return;
+ }
+ }
+
+ // 阈值 / 抽帧从界面参数覆盖配方默认值
+ _pipeline.SetThresholds((float)Confidence, 0.45f);
+ _engine.Config.Sop.Settings.FrameStride = Math.Max(1, FrameStride);
+
+ if (!await _pipeline.StartAsync())
+ {
+ await Task.Run(_camera.Disconnect);
+ Log("warn", "采集启动失败");
+ return;
+ }
+
+ _engine.Start();
+ IsRunning = true;
+ RememberCamera(SelectedCamera);
+ StatusText = "运行中";
+ }
+
+ private void ApplyRecipe()
+ {
+ HandResult = null;
+ if (string.IsNullOrWhiteSpace(SelectedRecipe)) return;
+
+ var path = Path.Combine(RecipeDirectory, SelectedRecipe);
+ if (!File.Exists(path))
+ {
+ Log("warn", $"配方不存在:{path}");
+ return;
+ }
+
+ var config = SopConfigLoader.Load(path);
+
+ _engine.Load(config);
+
+ // 模型:配方写了就用配方的,没写就跳过(只有手部/计时类条件能工作)
+ var options = new PipelineOptions
+ {
+ YoloModelPath = ResolveModel(config.Sop.Model?.Path),
+ YoloClasses = config.Sop.Model?.Classes ?? [],
+ YoloInputSize = config.Sop.Model?.InputSize ?? 640,
+ // 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑
+ PalmModelPath = ResolveModel("models/palm_detection_full_Nx3x192x192_post.onnx"),
+ LandmarkModelPath = ResolveModel("models/hand_landmark_sparse_Nx3x224x224.onnx"),
+ FrameStride = Math.Max(1, config.Sop.Settings.FrameStride),
+ };
+
+ _pipeline.LoadModels(options);
+ Log("info", $"推理设备:手部={_pipeline.HandBackend},YOLO={_pipeline.YoloBackend}");
+
+ StepCards.Clear();
+ Rois.Clear();
+
+ foreach (var step in config.Sop.Steps.OrderBy(s => s.Id))
+ StepCards.Add(new StepCard { StepId = step.Id, Name = step.Name, Message = "—" });
+
+ foreach (var (name, def) in config.Sop.Regions)
+ Rois.Add(new RoiItem { Name = name, X = def.X1, Y = def.Y1, W = def.X2 - def.X1, H = def.Y2 - def.Y1, ColorHex = def.Color });
+
+ foreach (var warning in config.Warnings)
+ Log("warn", warning);
+
+ Log("info", $"配方已加载:{config.Sop.Name}({StepCards.Count} 步 / {Rois.Count} 区域)");
+
+ foreach (var warning in _pipeline.Warnings)
+ Log("warn", warning);
+
+ if (options.PalmModelPath is null || options.LandmarkModelPath is null)
+ Log("warn", "手部模型缺失,手部检测及画面标记不可用,请检查 models 目录中的 palm / landmark ONNX 文件");
+ }
+
+ ///
+ /// 模型路径解析:相对程序目录。不存在返回 null(管线会跳过并记警告)。
+ ///
+ private static string? ResolveModel(string? relative)
+ {
+ if (string.IsNullOrWhiteSpace(relative)) return null;
+
+ var path = Path.IsPathRooted(relative) ? relative : Path.Combine(AppContext.BaseDirectory, relative);
+
+ return File.Exists(path) ? path : null;
+ }
+
+ private void OnResult(FrameResult result)
+ {
+ if (_destroyed || !IsRunning) return;
+ lock (_frameLock)
+ {
+ _lastFrame = result;
+ }
+
+ _engine.ProcessFrame(result);
+
+ // 每帧均更新,无检测结果时清除上一帧的手部标记和目标框。
+ HandResult = result;
+
+ InferenceText = $"{result.InferenceMs:F1} ms";
+ }
+
+ ///
+ /// 渲染定时器:取采集线程留下的最新帧
+ ///
+ private void RenderFrame()
+ {
+ Mat? src;
+
+ lock (_frameLock)
+ {
+ src = _pending;
+ _pending = null;
+ }
+
+ if (src is null) return;
+
+ _frameCount++;
+
+ using (src)
+ {
+ if (_bitmap is null || _bitmap.PixelWidth != src.Width || _bitmap.PixelHeight != src.Height)
+ {
+ _bitmap = new WriteableBitmap(src.Cols, src.Rows, 96, 96, PixelFormats.Bgr24, null);
+
+ // ROI 覆盖层的坐标系就是帧像素坐标系,所以内层 Grid 尺寸必须跟着帧走
+ FrameWidth = src.Cols;
+ FrameHeight = src.Rows;
+ if (HandResult?.Size != (src.Cols, src.Rows)) HandResult = null;
+ }
+
+ var bytes = new byte[src.Rows * src.Cols * src.Channels()];
+ Marshal.Copy(src.Data, bytes, 0, bytes.Length);
+
+ // Mat.Step 是方法不是属性;这里按行字节数显式算,别依赖 Mat 的内部 stride
+ var stride = src.Cols * src.ElemSize();
+
+ // 注意:rect 是 (宽, 高),OpenCvSharp 的 Rows/Cols 是 (高, 宽),别写反
+ _bitmap.WritePixels(new Avalonia.PixelRect(0, 0, src.Cols, src.Rows), bytes, stride, 0);
+ }
+
+ Frame = _bitmap;
+
+ // 帧率:这 40ms 里处理了几帧
+ var delta = _frameCount - _lastTickCount;
+ _lastTickCount = _frameCount;
+ FpsText = $"{delta * 25.0:F1} fps(渲染)";
+ }
+
+ private void UpdateCard(StepSnapshot snapshot)
+ {
+ var card = StepCards.FirstOrDefault(c => c.StepId == snapshot.StepId);
+ if (card is null) return;
+
+ card.IsCurrent = snapshot.IsCurrent;
+ card.IsMet = snapshot.IsMet;
+ card.Message = snapshot.Message;
+ }
+
+ private void AppendViolation(ViolationEvent violation)
+ {
+ Violations.Insert(0, new ViolationItem
+ {
+ Time = violation.At,
+ StepId = violation.StepId,
+ Type = violation.Type,
+ Message = violation.Message,
+ });
+
+ while (Violations.Count > MaxTopViolations)
+ Violations.RemoveAt(Violations.Count - 1);
+ }
+
+ private void AppendLog(LogEntry entry)
+ {
+ Logs.Add(new LogItem { Time = entry.At, Level = entry.Level, Message = entry.Message });
+
+ while (Logs.Count > MaxLogLines)
+ Logs.RemoveAt(0);
+ }
+
+ private void Log(string level, string message)
+ {
+ AppendLog(new LogEntry { Level = level, Message = message });
+ }
+}
+
+///
+/// 步骤卡数据
+///
+public class StepCard : ViewModelBase
+{
+ private bool _isCurrent;
+ private bool _isMet;
+ private string _message = "";
+
+ /// 步骤 Id
+ public int StepId { get; set; }
+
+ /// 步骤名
+ public string Name { get; set; } = "";
+
+ /// 当前步骤
+ public bool IsCurrent
+ {
+ get { return _isCurrent; }
+ set { SetProperty(ref _isCurrent, value); }
+ }
+
+ /// 已完成
+ public bool IsMet
+ {
+ get { return _isMet; }
+ set { SetProperty(ref _isMet, value); }
+ }
+
+ /// 判定说明
+ public string Message
+ {
+ get { return _message; }
+ set { SetProperty(ref _message, value); }
+ }
+}
+
+///
+/// Top3 违规条目
+///
+public class ViolationItem
+{
+ /// 时刻
+ public DateTime Time { get; set; }
+
+ /// 步骤 Id
+ public int StepId { get; set; }
+
+ /// 类型
+ public string Type { get; set; } = "";
+
+ /// 文案
+ public string Message { get; set; } = "";
+}
+
+///
+/// 日志条目
+///
+public class LogItem
+{
+ /// 时刻
+ public DateTime Time { get; set; }
+
+ /// 级别 info/warn/viol
+ public string Level { get; set; } = "info";
+
+ /// 文案
+ public string Message { get; set; } = "";
+}
+
+///
+/// ROI 覆盖层条目(坐标 = 配方像素坐标,外层 Viewbox 负责缩放)
+///
+public class RoiItem
+{
+ /// 区域名
+ public string Name { get; set; } = "";
+
+ /// X
+ public double X { get; set; }
+
+ /// Y
+ public double Y { get; set; }
+
+ /// W
+ public double W { get; set; }
+
+ /// H
+ public double H { get; set; }
+
+ /// 颜色(#RRGGBB)。不叫 Color——会和 Avalonia.Media.Color 撞名
+ public string ColorHex { get; set; } = "#4CAF50";
+
+ /// 画刷
+ public SolidColorBrush Brush => new((Avalonia.Media.Color)Color.Parse(ColorHex));
+}
diff --git a/src/SopHelper.CrossPlatform.Engine/MvsNativeBindings.cs b/src/SopHelper.CrossPlatform.Engine/MvsNativeBindings.cs
new file mode 100644
index 0000000..35aba32
--- /dev/null
+++ b/src/SopHelper.CrossPlatform.Engine/MvsNativeBindings.cs
@@ -0,0 +1,28 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using MvCameraControl;
+
+namespace SopHelper.Engine.Camera;
+
+internal static class MvsNativeBindings
+{
+ // The managed SDK's acquisition APIs import MvCameraControl.dll by name. On
+ // Linux bind those same calls to the MVS C runtime; no application/UI fork.
+ [ModuleInitializer]
+ [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage","CA2255",Justification="This application-owned adapter must install the SDK resolver before its first P/Invoke.")]
+ internal static void Initialize()
+ {
+ if(!OperatingSystem.IsWindows())NativeLibrary.SetDllImportResolver(typeof(SDKSystem).Assembly,Resolve);
+ }
+ private static IntPtr Resolve(string name,Assembly assembly,DllImportSearchPath? searchPath)
+ {
+ if(name!="MvCameraControl.dll")return IntPtr.Zero;
+ var configured=Environment.GetEnvironmentVariable("MVS_LIB_DIR");
+ var candidates=new List();
+ if(!string.IsNullOrWhiteSpace(configured))candidates.Add(Path.Combine(configured,"libMvCameraControl.so"));
+ candidates.AddRange(["/opt/MVS/lib/64/libMvCameraControl.so","/opt/MVS/lib/aarch64/libMvCameraControl.so","libMvCameraControl.so"]);
+ foreach(var candidate in candidates)if(NativeLibrary.TryLoad(candidate,out var handle))return handle;
+ throw new DllNotFoundException("未找到 Linux MVS 原生运行库。请安装与托管 SDK 匹配的 MVS,并设置 MVS_LIB_DIR 及 LD_LIBRARY_PATH。");
+ }
+}
diff --git a/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj b/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj
index aff7a18..77575b4 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj
+++ b/src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj
@@ -21,4 +21,8 @@
+
+
+
+
diff --git a/tests/Avalonia.Smoke/Avalonia.Smoke.csproj b/tests/Avalonia.Smoke/Avalonia.Smoke.csproj
new file mode 100644
index 0000000..06bb778
--- /dev/null
+++ b/tests/Avalonia.Smoke/Avalonia.Smoke.csproj
@@ -0,0 +1,7 @@
+
+ Exenet8.0enableenable
+
+
+
+
+
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
new file mode 100644
index 0000000..5aae521
--- /dev/null
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -0,0 +1,166 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.ApplicationLifetimes;
+using Avalonia.Headless;
+using Avalonia.Media.Imaging;
+using Avalonia.Threading;
+using Prism.Ioc;
+using Prism.Dialogs;
+using SopHelper;
+using SopHelper.Engine.Camera;
+using SopHelper.Engine.Training;
+using SopHelper.Models;
+using SopHelper.Training;
+using SopHelper.VVMs.SopPage;
+using SopHelper.VVMs.RecipeEditor;
+using System.Text.Json;
+using Avalonia.VisualTree;
+using OpenCvSharp;
+using Window = Avalonia.Controls.Window;
+using Point = Avalonia.Point;
+using Size = Avalonia.Size;
+using Avalonia.Input;
+
+internal static class Smoke
+{
+ private static int _exit=1;
+ private static readonly FakeCamera Camera=new();
+ [STAThread]
+ public static int Main()
+ {
+ var settingsPath=Path.GetFullPath("workspace/settings.json");
+ var settingsBefore=File.Exists(settingsPath)?File.ReadAllBytes(settingsPath):null;
+ System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
+ Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS","4");
+ try
+ {
+ AppBuilder.Configure(()=>new App(Camera)).UseSkia()
+ .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing=false })
+ .LogToTrace(Avalonia.Logging.LogEventLevel.Warning)
+ .AfterSetup(_=>
+ {
+ var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!;
+ lifetime.Startup+=(_,_)=>Dispatcher.UIThread.Post(async()=>await Run(lifetime));
+ }).StartWithClassicDesktopLifetime([],ShutdownMode.OnExplicitShutdown);
+ }
+ finally
+ {
+ if(settingsBefore is not null)File.WriteAllBytes(settingsPath,settingsBefore);
+ else if(File.Exists(settingsPath))File.Delete(settingsPath);
+ }
+ return _exit;
+ }
+ private static async Task Run(IClassicDesktopStyleApplicationLifetime lifetime)
+ {
+ try
+ {
+ await Task.Delay(150);
+ var app=(App)Application.Current!;var window=lifetime.MainWindow!;
+ var navigation=app.Container.Resolve();
+ Check(navigation.Pages.Count==2,"Both original navigation pages registered");
+ Check(navigation.Pages[0].DisplayName=="SOP 辅助"&&navigation.Pages[1].DisplayName=="零件标注与训练","Original navigation labels retained");
+ window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;
+ await Task.Delay(150);
+ var sop=app.Container.Resolve();
+ sop.ApplyRecipeCommand.Execute();
+ Check(sop.StepCards.Count==4&&sop.Rois.Count==3,"Original SOP recipe creates four steps and three ROIs");
+ sop.StartStopCommand.Execute();
+ for(var i=0;i<100&&!sop.IsRunning;i++)await Task.Delay(20);
+ Check(sop.IsRunning,"Original start command connects the shared camera/pipeline");
+ await Task.Run(()=>{Camera.Emit();Camera.Emit();});
+ await Task.Delay(150);
+ Check(sop.Frame is not null&&sop.FrameWidth==640&&sop.FrameHeight==480,"Camera buffer renders through the shared Avalonia bitmap adapter");
+ Save(window,"sop");
+ sop.StartStopCommand.Execute();for(var i=0;i<100&&sop.IsRunning;i++)await Task.Delay(20);
+ Check(!sop.IsRunning&&!Camera.IsConnected,"Stop command releases acquisition");
+ Check(window.GetVisualDescendants().OfType().Any(),"SOP page navigates");
+ sop.EditRecipeCommand.Execute();await Task.Delay(150);
+ var modal=lifetime.Windows.OfType().Single();
+ Check(modal.Width==1040&&modal.Height==760&&modal.DataContext is RecipeEditorViewModel,"Original edit command opens the sized Prism recipe dialog");
+ ((RecipeEditorViewModel)modal.DataContext!).CloseCommand.Execute();await Task.Delay(80);
+ Check(!lifetime.Windows.Contains(modal),"Recipe close command respects the Prism dialog lifecycle");
+ navigation.SelectedIndex=1;await Task.Delay(150);Save(window,"training");
+ Check(window.GetVisualDescendants().OfType().Any(),"Training page navigates");
+ var trainer=app.Container.Resolve();
+ var temporary=Path.Combine(Path.GetTempPath(),"sophelper-avalonia-project-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(temporary);
+ using(var trainingFrame=new Mat(480,640,MatType.CV_8UC3,new Scalar(30,60,90)))Cv2.ImWrite(Path.Combine(temporary,"frame.png"),trainingFrame);
+ var project=new TrainingProject { FilePath=Path.Combine(temporary,"project.json"),Name="测试零件",Width=640,Height=480,
+ Frames=[new FrameAnnotation {Index=0,Image="frame.png",Status="unlabeled"}] };
+ project.Save();trainer.Load(project.FilePath);trainer.DrawBox([10,20,100,200]);trainer.ApproveCommand.Execute();
+ Check(TrainingProject.Load(project.FilePath).Frames[0].Status=="reviewed","Training annotation and review still save the original project format");
+ navigation.SelectedIndex=0;navigation.SelectedIndex=1;await Task.Delay(80);
+ Check(ReferenceEquals(trainer,app.Container.Resolve())&&trainer.SelectedFrame?.Box is { Length:4 },"Navigation preserves the training project and annotation state");
+ Save(window,"training-project");
+ trainer.DoctorCommand.Execute();
+ for(var i=0;i<300&&trainer.IsBusy;i++)await Task.Delay(100);
+ Check(!trainer.IsBusy&&trainer.Progress==100&&trainer.Logs.Contains("Python ")&&trainer.Logs.Contains("PyTorch"),"Training worker command completes using the repository Python runtime");
+ var editorVm=new RecipeEditorViewModel();
+ editorVm.OnDialogOpened(new DialogParameters { {"directory",Path.Combine(AppContext.BaseDirectory,"configs","sop")},
+ {"config",SopHelper.Engine.Sop.SopConfigLoader.Load(Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml"))},
+ {"path",Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml")}, {"new",false} });
+ var editor=new RecipeEditor { DataContext=editorVm };
+ var recipeBefore=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig());
+ var dialog=new Window { Width=1180,Height=820,Content=editor };dialog.Show();await Task.Delay(100);
+ var tabs=editor.GetVisualDescendants().OfType().First();
+ Check(tabs.ItemCount==4,"All four original recipe tabs retained");
+ for(var i=0;i0,"Original recipe ViewModel loads steps");
+ Check(editorVm.Recipe.Steps[0].Detection?.Method=="hand_in_region","Recipe bindings preserve selected condition method");
+ Check(SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig())==recipeBefore,"Opening all recipe tabs does not alter any recipe fields");
+ dialog.Close();editorVm.OnDialogClosed();
+ var recorder=new CameraWindow(new CameraViewModel(new FakeCamera(),Path.Combine(Path.GetTempPath(),"sophelper-avalonia-smoke")));
+ recorder.Show();await Task.Delay(100);Save(recorder,"camera");recorder.Close();
+ var fitted=RegionCanvas.FitImage(new Size(1000,800),new Size(1920,1080));
+ var pixel=RegionCanvas.ToImage(fitted.Center,fitted,new Size(1920,1080));
+ Check(Math.Abs(pixel.X-960)<.001&&Math.Abs(pixel.Y-540)<.001,"ROI maps letterbox center back to original pixels");
+ Check(RegionCanvas.PixelBounds(new Point(100,120),new Point(10,20),new Size(1920,1080))==new PixelRect(10,20,90,100),"Reverse ROI drag preserves bounds");
+ var pixels=new byte[]{3,17,240,29,100,31};
+ using(var bitmap=SopHelper.Presentation.Imaging.BitmapSource.Create(2,1,96,96,SopHelper.Presentation.Imaging.PixelFormats.Bgr24,null,pixels,6))
+ {
+ pixels[0]=255;bitmap.Save(Path.Combine(Output,"pixels.png"));
+ using var decoded=Cv2.ImRead(Path.Combine(Output,"pixels.png"));
+ Check(decoded.At(0,0)==new Vec3b(3,17,240)&&decoded.At(0,1)==new Vec3b(29,100,31),"Bitmap adapter owns its buffer and preserves BGR colors");
+ }
+ using(var image=SopHelper.Presentation.Imaging.BitmapSource.Create(200,100,96,96,SopHelper.Presentation.Imaging.PixelFormats.Bgr24,null,new byte[200*100*3],600))
+ {
+ var region=new RegionNode {Key="roi",X1=0,Y1=0,X2=10,Y2=10};
+ var canvas=new RegionCanvas {Image=image,Regions=[region],SelectedRegion=region};
+ var drawing=new Window {Width=400,Height=400,Content=canvas};drawing.Show();await Task.Delay(60);
+ drawing.MouseDown(new Point(300,250),MouseButton.Left);drawing.MouseMove(new Point(100,150));drawing.MouseUp(new Point(100,150),MouseButton.Left);
+ Check(region.X1==50&®ion.Y1==25&®ion.X2==150&®ion.Y2==75,"Actual ROI pointer drag excludes image letterboxing and supports reverse drawing");
+ double[]? drawn=null;var annotation=new AnnotationCanvas {Source=image};annotation.BoxDrawn+=box=>drawn=box;drawing.Content=annotation;await Task.Delay(60);
+ drawing.MouseDown(new Point(300,250),MouseButton.Left);drawing.MouseMove(new Point(100,150));drawing.MouseUp(new Point(100,150),MouseButton.Left);
+ Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Actual annotation drag preserves original-image box coordinates");
+ drawing.Close();
+ }
+ File.WriteAllText(Path.Combine(Output,"result.json"),JsonSerializer.Serialize(new {passed=true,pages=navigation.Pages.Select(p=>p.DisplayName),recipeTabs=tabs.ItemCount}));
+ _exit=0;
+ }
+ catch(Exception ex){Console.Error.WriteLine(ex);}
+ finally{lifetime.Shutdown(_exit);}
+ }
+ private static string Output {get{var p=Path.GetFullPath("artifacts/avalonia-smoke");Directory.CreateDirectory(p);return p;}}
+ private static void Save(Window window,string name)
+ {
+ window.UpdateLayout();
+ using var image=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height));image.Render(window);image.Save(Path.Combine(Output,name+".png"));
+ }
+ private static void Check(bool condition,string message){if(!condition)throw new Exception(message);Console.WriteLine("PASS: "+message);}
+}
+internal sealed class FakeCamera : ICameraService
+{
+ public bool IsConnected{get;private set;}public bool IsGrabbing{get;private set;}
+ public event Action? FrameArrived;
+ public event Action? ConnectionChanged;
+ public event Action? Error {add{}remove{}}
+ public Task> EnumerateAsync()=>Task.FromResult(new List{new(){Index=0,Name="测试相机"}});
+ public Task ConnectAsync(CameraInfo camera){IsConnected=true;ConnectionChanged?.Invoke(true);return Task.FromResult(true);}
+ public Task StartAsync(){IsGrabbing=true;return Task.FromResult(true);}
+ public void Stop(){IsGrabbing=false;}public void Disconnect(){Stop();IsConnected=false;ConnectionChanged?.Invoke(false);}public void Dispose()=>Disconnect();
+ private long _id;
+ public void Emit()
+ {
+ using var frame=new CameraFrame {FrameId=++_id,Timestamp=DateTime.Now,Bgr=new Mat(480,640,MatType.CV_8UC3,new Scalar(35,60,90))};
+ FrameArrived?.Invoke(frame);
+ }
+}