234 lines
17 KiB
C#
234 lines
17 KiB
C#
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<NavigationModel>();
|
|
Check(navigation.Pages.Count==3&&navigation.Pages[2].DisplayName=="运行设置","Runtime settings navigation page 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<SopPageViewModel>();
|
|
var sopView=window.GetVisualDescendants().OfType<SopPage>().Single();
|
|
Check(!sopView.GetVisualDescendants().Any(c=>c is ComboBox or Slider),"Operator page contains no camera, recipe or parameter editors");
|
|
Check(sop.ActiveRecipe=="未应用配方","No recipe is reported active before applying");
|
|
Check(!string.IsNullOrWhiteSpace(sop.SelectedRecipe)&&sopView.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text==sop.SelectedRecipe),"Operator page displays the selected recipe before applying or starting");
|
|
navigation.SelectedIndex=2;await Task.Delay(100);
|
|
var settings=window.GetVisualDescendants().OfType<SopHelper.VVMs.RuntimeSettings.RuntimeSettings>().Single();
|
|
Check(ReferenceEquals(settings.DataContext,sop),"Settings and operator page share runtime state");
|
|
Check(settings.GetVisualDescendants().OfType<ComboBox>().Count()==2&&settings.GetVisualDescendants().OfType<Slider>().Count()==2,"Camera, recipe, threshold and stride editors are on settings page");
|
|
sop.ApplyRecipeCommand.Execute();
|
|
Check(sop.ActiveRecipe==sop.SelectedRecipe,"Applied recipe is shown as current");
|
|
var applied=sop.ActiveRecipe;var selected=sop.SelectedRecipe;
|
|
sop.SelectedRecipe="pending.yaml";
|
|
Check(sop.ActiveRecipe==applied,"Unapplied recipe selection does not change current recipe");
|
|
navigation.SelectedIndex=0;await Task.Delay(80);
|
|
Check(window.GetVisualDescendants().OfType<SopPage>().Single().GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text=="pending.yaml"),"Operator page updates to the selected recipe without applying or starting");
|
|
sop.SelectedRecipe=selected;await Task.Delay(80);
|
|
Check(window.GetVisualDescendants().OfType<SopPage>().Single().GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text==selected),"Recipe selection changes notify the operator page immediately");
|
|
navigation.SelectedIndex=2;await Task.Delay(80);
|
|
Save(window,"runtime-settings");
|
|
navigation.SelectedIndex=0;await Task.Delay(100);
|
|
Check(window.GetVisualDescendants().OfType<SopPage>().Single().GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text==applied),"Operator page displays the applied recipe");
|
|
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");
|
|
navigation.SelectedIndex=2;await Task.Delay(80);
|
|
Check(settings.GetVisualDescendants().Where(c=>c is ComboBox or Slider).Cast<Control>().All(c=>!c.IsEnabled),"Runtime settings cannot be edited during acquisition");
|
|
navigation.SelectedIndex=0;await Task.Delay(80);
|
|
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");
|
|
await CheckMovingPreview(sop,window);
|
|
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");
|
|
navigation.SelectedIndex=2;await Task.Delay(80);
|
|
Check(settings.GetVisualDescendants().Where(c=>c is ComboBox or Slider).Cast<Control>().All(c=>c.IsEnabled),"Runtime settings become editable after stopping");
|
|
navigation.SelectedIndex=0;await Task.Delay(80);
|
|
Check(window.GetVisualDescendants().OfType<SopPage>().Any(),"SOP page navigates");
|
|
sop.EditRecipeCommand.Execute();await Task.Delay(150);
|
|
var modal=lifetime.Windows.OfType<RecipeDialogWindow>().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<TrainingPage>().Any(),"Training page navigates");
|
|
var trainer=app.Container.Resolve<SopHelper.Training.MainViewModel>();
|
|
Check(trainer.Recipes.Contains(Path.GetFileNameWithoutExtension(sop.SelectedRecipe)!) && trainer.RecipeName==Path.GetFileNameWithoutExtension(sop.SelectedRecipe),"Training offers the current SOP recipe automatically");
|
|
var trainingView=window.GetVisualDescendants().OfType<TrainingPage>().Single();
|
|
var trainingTabs=trainingView.GetVisualDescendants().OfType<TabControl>().Single();
|
|
trainingTabs.SelectedIndex=1;await Task.Delay(80);
|
|
Check(trainingView.GetVisualDescendants().OfType<Button>().Any(b=>b.Content?.ToString()=="训练并更新配方模型"),"Recipe model update action is visible on the training tab");
|
|
Save(window,"training-recipe-model");
|
|
trainingTabs.SelectedIndex=0;
|
|
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<SopHelper.Training.MainViewModel>())&&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<TabControl>().First();
|
|
Check(tabs.ItemCount==4,"All four original recipe tabs retained");
|
|
for(var i=0;i<tabs.ItemCount;i++){tabs.SelectedIndex=i;await Task.Delay(80);Save(dialog,"recipe-"+i);}
|
|
Check(editorVm.Recipe.Steps.Count>0,"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<Vec3b>(0,0)==new Vec3b(3,17,240)&&decoded.At<Vec3b>(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 async Task CheckMovingPreview(SopPageViewModel sop,Window window)
|
|
{
|
|
var image=window.GetVisualDescendants().OfType<SopPage>().Single()
|
|
.GetVisualDescendants().OfType<Image>().Single();
|
|
var changes=0;
|
|
System.ComponentModel.PropertyChangedEventHandler onChanged=(_,e)=>{if(e.PropertyName==nameof(sop.Frame))changes++;};
|
|
sop.PropertyChanged+=onChanged;
|
|
try
|
|
{
|
|
foreach(var x in new[]{40,240,40})
|
|
{
|
|
var previous=sop.Frame;
|
|
await Task.Run(()=>Camera.Emit(x));
|
|
for(var i=0;i<50&&ReferenceEquals(previous,sop.Frame);i++)await Task.Delay(20);
|
|
Check(!ReferenceEquals(previous,sop.Frame)&&ReferenceEquals(image.Source,sop.Frame),
|
|
"Each moving frame updates the bound Image source even at the same resolution");
|
|
using var rendered=new RenderTargetBitmap(new PixelSize(640,480));
|
|
var preview=new Image {Source=sop.Frame,Width=640,Height=480};
|
|
preview.Measure(new Size(640,480));preview.Arrange(new Avalonia.Rect(0,0,640,480));
|
|
rendered.Render(preview);
|
|
var path=Path.Combine(Output,"motion-"+changes+".png");rendered.Save(path);
|
|
using var decoded=Cv2.ImRead(path);
|
|
var clearedX=x==40?260:60;
|
|
Check(decoded.At<Vec3b>(60,x+20)==new Vec3b(0,0,255)&&decoded.At<Vec3b>(60,clearedX)==new Vec3b(35,60,90),
|
|
"Moving object renders at its new position and clears its previous position");
|
|
}
|
|
Check(changes==3,"All three same-size frames notify the UI");
|
|
var last=sop.Frame;await Task.Delay(120);
|
|
Check(ReferenceEquals(last,sop.Frame),"No new camera frame leaves the displayed image intact");
|
|
}
|
|
finally{sop.PropertyChanged-=onChanged;}
|
|
}
|
|
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<CameraFrame>? FrameArrived;
|
|
public event Action<bool>? ConnectionChanged;
|
|
public event Action<string>? Error {add{}remove{}}
|
|
public Task<List<CameraInfo>> EnumerateAsync()=>Task.FromResult(new List<CameraInfo>{new(){Index=0,Name="测试相机"}});
|
|
public Task<bool> ConnectAsync(CameraInfo camera){IsConnected=true;ConnectionChanged?.Invoke(true);return Task.FromResult(true);}
|
|
public Task<bool> 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(int? objectX=null)
|
|
{
|
|
using var frame=new CameraFrame {FrameId=++_id,Timestamp=DateTime.Now,Bgr=new Mat(480,640,MatType.CV_8UC3,new Scalar(35,60,90))};
|
|
if(objectX is int x)Cv2.Rectangle(frame.Bgr,new OpenCvSharp.Rect(x,40,60,60),new Scalar(0,0,255),-1);
|
|
FrameArrived?.Invoke(frame);
|
|
}
|
|
}
|