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 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +