488 lines
39 KiB
C#
488 lines
39 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 previousRoot=Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
|
|
var dataRoot=Path.Combine(Path.GetTempPath(),"sophelper-layout-smoke-"+Guid.NewGuid().ToString("N"));
|
|
Directory.CreateDirectory(dataRoot);
|
|
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT",dataRoot);
|
|
var settingsPath=Path.Combine(dataRoot,"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);
|
|
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT",previousRoot);
|
|
if(!Path.GetFullPath(dataRoot).StartsWith(Path.GetFullPath(Path.GetTempPath())))throw new Exception("Unexpected test data root");
|
|
Directory.Delete(dataRoot,true);
|
|
}
|
|
return _exit;
|
|
}
|
|
private static async Task Run(IClassicDesktopStyleApplicationLifetime lifetime)
|
|
{
|
|
try
|
|
{
|
|
var userCameraPath=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"SopHelper","last-camera.json");
|
|
var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null;
|
|
await Task.Delay(150);
|
|
var app=(App)Application.Current!;var window=lifetime.MainWindow!;
|
|
CheckCameraPreferences(app);
|
|
var navigation=app.Container.Resolve<NavigationModel>();
|
|
Check(navigation.Pages.Count==2&&navigation.Pages[1].DisplayName=="运行设置","Sidebar contains operator and runtime settings pages only");
|
|
Check(navigation.Pages[0].DisplayName=="SOP 辅助"&&!navigation.Pages.Any(p=>p.DisplayName=="零件标注与训练"),"Training no longer has a standalone sidebar entry");
|
|
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=1;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<TextBlock>().Any(t=>t.Name=="InferenceBackend"&&t.Text==sop.InferenceBackendText)
|
|
&&sop.InferenceBackendText.Contains("手部:")&&sop.InferenceBackendText.Contains("目标:"),
|
|
"Operator page displays the actual inference backends, including CPU fallback");
|
|
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=1;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=1;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=1;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==1180&&modal.Height==880&&modal.DataContext is RecipeEditorViewModel,"Edit command opens a recipe dialog sized for embedded annotation and training");
|
|
Check(ReferenceEquals(((RecipeEditorViewModel)modal.DataContext!).SopRecording!.SelectedCamera,sop.SelectedCamera),"SOP recording inherits the runtime settings camera");
|
|
((RecipeEditorViewModel)modal.DataContext!).CloseCommand.Execute();
|
|
for(var i=0;i<100&&lifetime.Windows.Contains(modal);i++)await Task.Delay(20);
|
|
Check(!lifetime.Windows.Contains(modal),"Recipe close command respects the Prism dialog lifecycle");
|
|
sop.EditRecipeCommand.Execute();await Task.Delay(150);
|
|
var titlebarModal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();titlebarModal.Close();
|
|
for(var i=0;i<100&&lifetime.Windows.Contains(titlebarModal);i++)await Task.Delay(20);
|
|
Check(!lifetime.Windows.Contains(titlebarModal),"Titlebar close awaits SOP camera shutdown and closes the Prism dialog");
|
|
sop.EditRecipeCommand.Execute();await Task.Delay(150);
|
|
var trainingDialog=lifetime.Windows.OfType<RecipeDialogWindow>().Single();
|
|
var trainingEditorVm=(RecipeEditorViewModel)trainingDialog.DataContext!;
|
|
var outerTabs=trainingDialog.GetVisualDescendants().OfType<TabControl>().First();outerTabs.SelectedIndex=6;await Task.Delay(100);
|
|
var trainingView=trainingDialog.GetVisualDescendants().OfType<TrainingPage>().Single();
|
|
var trainer=trainingView.Model;
|
|
Save(trainingDialog,"training");
|
|
Check(ReferenceEquals(trainingView,trainingEditorVm.TrainingView)&&trainer.RecipeName==Path.GetFileNameWithoutExtension(sop.SelectedRecipe),"Training is embedded in the current recipe editor");
|
|
Check(!trainingView.GetVisualDescendants().OfType<ComboBox>().Any(c=>ReferenceEquals(c.ItemsSource,trainer.Recipes)),"Embedded training has no recipe selector");
|
|
var saveParameters=trainingView.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="保存参数");
|
|
Check(ReferenceEquals(saveParameters.Command,trainer.SaveParametersCommand)&&trainer.Project is null&&saveParameters.Command!.CanExecute(null),"Save parameters is available without an annotation project");
|
|
trainer.ExtractStride=3;trainer.MaxFrames=420;trainer.ExportEvery=2;trainer.ImageSize=960;trainer.Epochs=12;trainer.Batch=2;
|
|
saveParameters.Command!.Execute(null);
|
|
var restoredTrainer=new SopHelper.Training.MainViewModel(new WorkerClient());
|
|
restoredTrainer.RecipeName=trainer.RecipeName;
|
|
Check(restoredTrainer.ExtractStride==3&&restoredTrainer.MaxFrames==420&&restoredTrainer.ExportEvery==2&&restoredTrainer.ImageSize==960&&restoredTrainer.Epochs==12&&restoredTrainer.Batch==2,"Explicit save restores annotation and training parameters in a new view model");
|
|
Check(trainer.Status=="参数已保存,下次打开时自动恢复"&&!trainer.IsBusy,"Saving confirms success without starting a worker task");
|
|
await CheckTrainingImport(lifetime,trainingDialog,trainingView,trainer);
|
|
var savedRecipe=trainer.RecipeName;
|
|
restoredTrainer.RecipeName=savedRecipe;
|
|
Check(restoredTrainer.ImageSize==960,"Reopening the same recipe restores its saved training parameters");
|
|
restoredTrainer.RecipeName="另一配方";
|
|
Check(restoredTrainer.ImageSize==640&&restoredTrainer.ExtractStride==1,"New recipes have independent default parameters");
|
|
restoredTrainer.ImageSize=320;restoredTrainer.SaveParametersCommand.Execute();restoredTrainer.RecipeName=savedRecipe;
|
|
Check(restoredTrainer.ImageSize==960&&restoredTrainer.ExtractStride==3,"Switching recipes restores each recipe's own parameters");
|
|
var recipeId="onnx-smoke-"+Guid.NewGuid().ToString("N");
|
|
var storage=new RecipeWorkspace(trainer.Root);
|
|
var createEditor=new RecipeEditorViewModel();
|
|
createEditor.OnDialogOpened(new DialogParameters{{"directory",storage.RecipesDirectory},{"new",true},{"config",new SopHelper.Engine.Sop.SopConfig()}});
|
|
foreach(var invalid in new[]{"非法/配方","非法:配方","CON","配方.","配方 ",""})
|
|
{
|
|
createEditor.Recipe.Name=invalid;
|
|
Check(createEditor.NameValidationMessage.Length>0&&!createEditor.SaveCommand.CanExecute(),"Invalid recipe name disables save and displays the reason: "+invalid);
|
|
createEditor.SaveCommand.Execute();
|
|
}
|
|
createEditor.Recipe.Name="新建配方.v1";
|
|
Check(createEditor.SaveCommand.CanExecute()&&createEditor.NameValidationMessage.Length==0,"A valid name immediately re-enables save");
|
|
createEditor.SaveCommand.Execute();
|
|
Check(File.Exists(storage.ConfigPath("新建配方.v1"))&&SopHelper.Engine.Sop.SopConfigLoader.Load(storage.ConfigPath("新建配方.v1")).Sop.Name=="新建配方.v1","Recipe name, directory and filename match exactly, including dots");
|
|
createEditor.OnDialogClosed();
|
|
var recipeCamera=new CameraViewModel(new FakeCamera(),trainer.Root,savedRecipe);
|
|
recipeCamera.SaveDirectory=Path.GetTempPath();
|
|
Check(recipeCamera.SaveDirectory==Path.Combine(storage.DirectoryFor(savedRecipe),"recordings")&&!recipeCamera.BrowseCommand.CanExecute(),"Recipe recordings stay in the selected recipe directory");
|
|
await recipeCamera.ShutdownAsync();
|
|
var recipeFile=storage.ConfigPath(recipeId);
|
|
var recipeWorkspace=storage.DirectoryFor(recipeId);
|
|
Directory.CreateDirectory(recipeWorkspace);
|
|
var modelFile=Path.Combine(recipeWorkspace,recipeId+".onnx");
|
|
var manifestFile=Path.Combine(recipeWorkspace,"latest-model.json");
|
|
try
|
|
{
|
|
File.Copy(Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml"),recipeFile);
|
|
// The model loader may reject this stub; this checks recipe routing and metadata independently.
|
|
File.WriteAllBytes(modelFile,[]);
|
|
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
|
|
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
|
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
|
|
Check(engine.Config.Sop.Model is {InputSize:960} trained&&trained.Path==modelFile&&trained.Classes.SequenceEqual(new[]{"测试零件"}),"Applying a recipe selects its trained ONNX, class order and input size");
|
|
sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
|
|
Check(engine.Config.Sop.Model?.Path!=modelFile,"Switching recipes does not reuse the previous recipe's ONNX");
|
|
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName=recipeId,weights=Path.ChangeExtension(modelFile,".pt"),classes=new[]{"测试零件"},imageSize=960}));
|
|
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
|
Check(engine.Config.Sop.Model?.Path==modelFile,"Older training records discover an existing ONNX beside their checkpoint");
|
|
File.WriteAllText(manifestFile,JsonSerializer.Serialize(new {recipeName="another-recipe",onnx=modelFile,classes=new[]{"测试零件"},imageSize=960}));
|
|
sop.SelectedRecipe=recipeId+".yaml";sop.ApplyRecipeCommand.Execute();
|
|
Check(engine.Config.Sop.Model is null,"Mismatched recipe metadata cannot replace the configured model");
|
|
}
|
|
finally
|
|
{
|
|
sop.SelectedRecipe=selected;sop.ApplyRecipeCommand.Execute();
|
|
File.Delete(recipeFile);File.Delete(modelFile);File.Delete(manifestFile);Directory.Delete(recipeWorkspace);
|
|
}
|
|
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(trainingDialog,"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(trainer.Project!.FilePath).Frames[0].Status=="reviewed"&&RecipeWorkspace.IsWithin(trainer.Project.FilePath,storage.DirectoryFor(savedRecipe)),"Opened annotation projects are copied into their recipe and review saves there");
|
|
outerTabs.SelectedIndex=0;outerTabs.SelectedIndex=6;await Task.Delay(80);
|
|
Check(ReferenceEquals(trainer,trainingEditorVm.TrainingView!.Model)&&trainer.SelectedFrame?.Box is { Length:4 },"Switching editor tabs preserves annotation state");
|
|
try{trainer.RecipeName="另一配方";throw new Exception("Locked recipe accepted a switch");}catch(InvalidOperationException){}
|
|
Check(trainer.RecipeName==savedRecipe&&trainer.Project is not null,"Embedded training cannot switch away from the edited recipe");
|
|
var foreign=new TrainingProject{FilePath=Path.Combine(temporary,"foreign.json"),Name="其他零件",RecipeName="另一配方",Width=100,Height=100,Frames=[new FrameAnnotation{Index=0,Image="frame.png"}]};foreign.Save();
|
|
try{trainer.Load(foreign.FilePath);throw new Exception("Foreign recipe project was accepted");}catch(InvalidOperationException){}
|
|
Check(trainer.SelectedFrame?.Box is {Length:4},"Opening another recipe's project is rejected without altering current annotations");
|
|
await CheckTrainingLayout(trainingDialog,trainingView,trainer);
|
|
Save(trainingDialog,"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");
|
|
trainer.DoctorCommand.Execute();Check(trainer.IsBusy,"A training worker operation is running before editor close");
|
|
trainingEditorVm.CloseCommand.Execute();
|
|
for(var i=0;i<200&&lifetime.Windows.Contains(trainingDialog);i++)await Task.Delay(20);
|
|
Check(!lifetime.Windows.Contains(trainingDialog)&&!trainer.IsBusy&&File.Exists(trainer.Project!.FilePath),"Closing the editor cancels its worker and preserves saved annotations");
|
|
var editorVm=new RecipeEditorViewModel();
|
|
editorVm.OnDialogOpened(new DialogParameters { {"directory",storage.RecipesDirectory},
|
|
{"config",SopHelper.Engine.Sop.SopConfigLoader.Load(storage.ConfigPath("demo"))},
|
|
{"path",storage.ConfigPath("demo")}, {"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==7,"Recipe tabs include parts, SOP recording and annotation/training");
|
|
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");
|
|
var closingTrainer=editorVm.TrainingView!.Model;
|
|
closingTrainer.ImportCommand.Execute();await Task.Delay(40);
|
|
Check(closingTrainer.IsImporting&&lifetime.Windows.OfType<ImportPartDialog>().Any(),"Import part picker is open before closing the editor");
|
|
dialog.Close();
|
|
for(var i=0;i<100&&dialog.IsVisible;i++)await Task.Delay(20);
|
|
Check(!dialog.IsVisible&&!closingTrainer.IsImporting&&!lifetime.Windows.OfType<ImportPartDialog>().Any(),"Closing the editor cancels the part picker without starting import");
|
|
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");
|
|
drawn=null;
|
|
drawing.MouseWheel(new Point(150,175),new Vector(0,1));
|
|
drawing.MouseDown(new Point(150,175),MouseButton.Right);drawing.MouseMove(new Point(170,185));drawing.MouseUp(new Point(170,185),MouseButton.Right);
|
|
Check(drawn is null,"Right-button panning never creates an annotation");
|
|
drawing.MouseDown(new Point(350,275),MouseButton.Left);drawing.MouseMove(new Point(110,155));drawing.MouseUp(new Point(110,155),MouseButton.Left);
|
|
Check(drawn is {Length:4}&&drawn.Zip(new double[]{50,25,150,75}).All(p=>Math.Abs(p.First-p.Second)<.001),"Cursor-centered wheel zoom and right-button pan preserve original-image box coordinates");
|
|
using(var nextImage=SopHelper.Presentation.Imaging.BitmapSource.Create(200,100,96,96,SopHelper.Presentation.Imaging.PixelFormats.Bgr24,null,new byte[200*100*3],600))
|
|
{
|
|
annotation.Source=nextImage;drawn=null;
|
|
drawing.MouseDown(new Point(110,155),MouseButton.Left);drawing.MouseUp(new Point(350,275),MouseButton.Left);
|
|
Check(drawn is {Length:4}&&drawn.Zip(new double[]{50,25,150,75}).All(p=>Math.Abs(p.First-p.Second)<.001),"Switching same-size frames retains zoom and pan");
|
|
annotation.ResetView();drawn=null;
|
|
drawing.MouseDown(new Point(100,150),MouseButton.Left);drawing.MouseUp(new Point(300,250),MouseButton.Left);
|
|
Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Fit-to-window resets both zoom and pan");
|
|
drawing.MouseDown(new Point(200,200),MouseButton.Right);drawing.MouseMove(new Point(220,210));
|
|
annotation.Source=null;drawing.MouseUp(new Point(220,210),MouseButton.Right);annotation.Source=image;drawn=null;
|
|
drawing.MouseDown(new Point(100,150),MouseButton.Left);drawing.MouseUp(new Point(300,250),MouseButton.Left);
|
|
Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Clearing the image cancels panning and restores the fitted view");
|
|
}
|
|
drawing.Close();
|
|
}
|
|
Check(userCameraBefore is null ? !File.Exists(userCameraPath) : File.Exists(userCameraPath)&&userCameraBefore.SequenceEqual(File.ReadAllBytes(userCameraPath)),"Smoke tests leave the real user's camera preference unchanged");
|
|
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 async Task CheckTrainingImport(IClassicDesktopStyleApplicationLifetime lifetime,Window owner,TrainingPage view,SopHelper.Training.MainViewModel trainer)
|
|
{
|
|
var store=new RecipeWorkspace(trainer.Root);var configPath=store.ConfigPath(trainer.RecipeName);
|
|
var config=SopHelper.Engine.Sop.SopConfigLoader.Load(configPath);config.Sop.Parts=["支架","螺丝","测试零件"];
|
|
SopHelper.Engine.Sop.SopConfigLoader.Save(config,configPath);trainer.RefreshPartNames();
|
|
var selectVideo=trainer.SelectImportVideoAsync;var selectPart=trainer.SelectImportPartAsync;
|
|
var videoCalls=0;
|
|
async Task WaitImport()
|
|
{
|
|
for(var i=0;i<400&&(trainer.IsImporting||trainer.IsBusy);i++)await Task.Delay(25);
|
|
Check(!trainer.IsImporting&&!trainer.IsBusy,"Video import operation finishes");
|
|
}
|
|
async Task<ImportPartDialog> Picker()
|
|
{
|
|
trainer.ImportCommand.Execute();await Task.Delay(40);
|
|
return lifetime.Windows.OfType<ImportPartDialog>().Single();
|
|
}
|
|
void Confirm(ImportPartDialog dialog,string name)
|
|
{
|
|
dialog.GetVisualDescendants().OfType<ComboBox>().Single().SelectedItem=name;
|
|
var button=dialog.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="下一步:选择视频");
|
|
Check(button.IsEnabled,"Choosing an existing part enables video selection");
|
|
button.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
|
}
|
|
try
|
|
{
|
|
trainer.SelectImportVideoAsync=()=>{videoCalls++;return Task.FromResult<string?>(null);};
|
|
var picker=await Picker();
|
|
var partPicker=picker.GetVisualDescendants().OfType<ComboBox>().Single();
|
|
Check(partPicker.SelectedItem is null&&partPicker.Items.Cast<string>().SequenceEqual(config.Sop.Parts),"Import first requires explicit selection from the recipe part catalog");
|
|
Check(!picker.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="下一步:选择视频").IsEnabled,"Import cannot advance without a target part");
|
|
Save(picker,"import-target-part");picker.Close(null);await WaitImport();
|
|
Check(videoCalls==0&&trainer.Project is null&&trainer.Label=="","Cancelling part selection never opens the video picker or changes the current project");
|
|
picker=await Picker();Confirm(picker,"螺丝");await WaitImport();
|
|
Check(videoCalls==1&&trainer.Project is null&&trainer.Label=="","Cancelling video selection does not assign a target");
|
|
var videoPath=Path.Combine(trainer.Root,"import-target-test.avi");
|
|
using(var writer=new VideoWriter(videoPath,FourCC.MJPG,10,new OpenCvSharp.Size(64,48)))
|
|
{
|
|
Check(writer.IsOpened(),"Import fixture video opens for writing");
|
|
using var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90));for(var i=0;i<20;i++)writer.Write(frame);
|
|
}
|
|
trainer.SelectImportVideoAsync=()=>{videoCalls++;return Task.FromResult<string?>(videoPath);};
|
|
picker=await Picker();Confirm(picker,"支架");await WaitImport();
|
|
Check(trainer.Project is {Name:"支架"}&&trainer.Label=="支架"&&trainer.Frames.Count>0,"Real video extraction stores and locks the selected part");
|
|
var first=trainer.Project!.FilePath;var before=File.ReadAllBytes(first);
|
|
Check(view.FindControl<TextBlock>("TrainingTargetPart")!.Text=="支架"&&!view.GetVisualDescendants().OfType<ComboBox>().Any(c=>ReferenceEquals(c.ItemsSource,trainer.PartNames)),"Annotation page displays the locked target without a category selector");
|
|
var calls=videoCalls;picker=await Picker();picker.Close(null);await WaitImport();
|
|
Check(videoCalls==calls&&trainer.Project.FilePath==first&&File.ReadAllBytes(first).SequenceEqual(before),"Cancelling a later import preserves the current project and target");
|
|
trainer.SelectImportVideoAsync=()=>{videoCalls++;return Task.FromResult<string?>(null);};
|
|
picker=await Picker();Confirm(picker,"螺丝");await WaitImport();
|
|
Check(trainer.Label=="支架"&&File.ReadAllBytes(first).SequenceEqual(before),"Cancelling a different target's video picker does not relabel current annotations");
|
|
trainer.Project.Name="螺丝";trainer.ExportCommand.Execute();
|
|
Check(trainer.Status.Contains("不能")&&SopHelper.Engine.Training.TrainingProject.Load(first).Name=="支架"&&!trainer.IsBusy,"Training/export reject target changes instead of rewriting project metadata");
|
|
trainer.Load(first);Check(trainer.Label=="支架","Reopening a project restores its original locked target");
|
|
trainer.SelectImportPartAsync=_=>Task.FromResult<string?>("未知零件");calls=videoCalls;
|
|
trainer.ImportCommand.Execute();await WaitImport();
|
|
Check(videoCalls==calls&&trainer.Status.Contains("零件列表")&&trainer.Label=="支架","Unknown import targets are rejected before opening the video picker");
|
|
trainer.SelectImportPartAsync=selectPart;
|
|
trainer.SelectImportVideoAsync=()=>Task.FromResult<string?>(videoPath);
|
|
picker=await Picker();Confirm(picker,"螺丝");await WaitImport();
|
|
Check(trainer.Project is {Name:"螺丝"}&&trainer.Label=="螺丝"&&trainer.Project.FilePath!=first&&TrainingProject.Load(first).Name=="支架","Each newly imported video gets its own fixed target without altering older projects");
|
|
}
|
|
finally {trainer.SelectImportVideoAsync=selectVideo;trainer.SelectImportPartAsync=selectPart;}
|
|
}
|
|
|
|
private static async Task CheckTrainingLayout(Window window,TrainingPage view,SopHelper.Training.MainViewModel trainer)
|
|
{
|
|
var width=window.Width;var logs=trainer.Logs;var status=trainer.Status;
|
|
var scroll=(ScrollViewer)view.Content!;var layout=(Grid)scroll.Content!;
|
|
var canvas=view.GetVisualDescendants().OfType<AnnotationCanvas>().Single();
|
|
var tabs=view.GetVisualDescendants().OfType<TabControl>().Single();var selectedTab=tabs.SelectedIndex;
|
|
try
|
|
{
|
|
trainer.Logs="训练日志:"+new string('W',3000);trainer.Status="训练状态:"+new string('W',1000);
|
|
foreach(var size in new[]{1180d,1600d,1000d,1180d})
|
|
{
|
|
window.Width=size;
|
|
for(var tab=0;tab<tabs.ItemCount;tab++)
|
|
{
|
|
tabs.SelectedIndex=tab;await Task.Delay(60);window.UpdateLayout();
|
|
var expected=Math.Max(960,scroll.Viewport.Width);
|
|
Check(Math.Abs(layout.Bounds.Width-expected)<1,
|
|
$"Training layout stays within viewport/minimum width with long logs and status ({size}, tab {tab}); actual={layout.Bounds.Width}, expected={expected}");
|
|
Check(canvas.Bounds.Width>100&&canvas.Bounds.Width<=expected-504,
|
|
"Annotation canvas stays within the center column after resizing and tab changes");
|
|
}
|
|
}
|
|
}
|
|
finally {window.Width=width;trainer.Logs=logs;trainer.Status=status;tabs.SelectedIndex=selectedTab;}
|
|
}
|
|
private static void CheckCameraPreferences(App app)
|
|
{
|
|
var path=Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!,"workspace","last-camera.json");
|
|
var before=File.Exists(path)?File.ReadAllBytes(path):null;
|
|
var first=new CameraInfo {Index=0,Name="测试相机"};
|
|
var preferred=new CameraInfo {Kind=CameraKind.Hikvision,SerialNumber="camera-preferred",Index=1,Name="首选相机"};
|
|
void WithCameras(List<CameraInfo> devices,Action<SopPageViewModel,FakeCamera> check)
|
|
{
|
|
using var camera=new FakeCamera {Devices=devices};
|
|
using var pipeline=new SopHelper.Engine.Pipeline.DetectionPipeline(camera);
|
|
var vm=new SopPageViewModel(camera,pipeline,new SopHelper.Engine.Sop.SopEngine(),app.Container.Resolve<IDialogService>());
|
|
try {check(vm,camera);} finally {vm.Destroy();}
|
|
}
|
|
try
|
|
{
|
|
if(File.Exists(path))File.Delete(path);
|
|
WithCameras([first,preferred],(vm,_)=>
|
|
{
|
|
vm.SelectedCamera=preferred;
|
|
Check(!vm.IsRunning&&JsonSerializer.Deserialize<CameraInfo>(File.ReadAllText(path))!.SerialNumber==preferred.SerialNumber,"Changing camera saves immediately without starting acquisition");
|
|
});
|
|
var reindexed=new CameraInfo {Kind=preferred.Kind,SerialNumber=preferred.SerialNumber,Index=7,Name=preferred.Name};
|
|
WithCameras([reindexed,first],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,reindexed),"Restart restores the selected camera by serial number despite enumeration order/index changes"));
|
|
var saved=File.ReadAllText(path);
|
|
WithCameras([first],(vm,camera)=>
|
|
{
|
|
Check(vm.SelectedCamera is null&&File.ReadAllText(path)==saved,"Missing preferred camera is not silently replaced or overwritten");
|
|
camera.Devices=[];vm.RefreshCamerasCommand.Execute();
|
|
Check(vm.SelectedCamera is null&&File.ReadAllText(path)==saved,"An empty enumeration preserves camera preference");
|
|
camera.Devices=[first,reindexed];vm.RefreshCamerasCommand.Execute();
|
|
Check(ReferenceEquals(vm.SelectedCamera,reindexed),"Refreshing after reconnection restores the preferred camera");
|
|
vm.SelectedCamera=first;
|
|
});
|
|
WithCameras([reindexed,first],(vm,_)=>Check(ReferenceEquals(vm.SelectedCamera,first),"Switching camera without starting is restored on the next launch"));
|
|
}
|
|
finally
|
|
{
|
|
if(before is not null)File.WriteAllBytes(path,before);
|
|
else if(File.Exists(path))File.Delete(path);
|
|
}
|
|
}
|
|
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 List<CameraInfo> Devices {get;set;}=[new(){Index=0,Name="测试相机"}];
|
|
public Task<List<CameraInfo>> EnumerateAsync()=>Task.FromResult(Devices.ToList());
|
|
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);
|
|
}
|
|
}
|