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 SopHelper.Engine.SopAgent; 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 bool _visionOnly; private static bool _processImagesOnly; private static bool _recipeSelectionOnly; private static string? _agentSettingsFile; private static readonly FakeCamera Camera=new(); [STAThread] public static int Main(string[] args) { _visionOnly=args.Contains("--vision-only"); _processImagesOnly=args.Contains("--process-images-only"); _recipeSelectionOnly=args.Contains("--recipe-selection-only"); var agentSettingsIndex=Array.IndexOf(args,"--agent-settings-file"); if(agentSettingsIndex>=0) { if(agentSettingsIndex+1>=args.Length)throw new ArgumentException("--agent-settings-file 后需提供设置文件路径"); _agentSettingsFile=Path.GetFullPath(args[agentSettingsIndex+1]); } var previousRoot=Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT"); var dataRoot=Path.Combine(Path.GetTempPath(),"sophelper-layout-smoke-"+Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dataRoot); if(_agentSettingsFile is not null) { Directory.CreateDirectory(Path.Combine(dataRoot,"workspace")); File.Copy(_agentSettingsFile,Path.Combine(dataRoot,"workspace","sop-agent.json")); } 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); if(args.Contains("--camera-lifecycle-only")&&_exit==0) Check(!Camera.IsConnected&&Camera.DisposeCount>0,"Application exit releases the retained camera connection"); } 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!; if(Environment.GetCommandLineArgs().Contains("--sidebar-layout-only")) { var model=app.Container.Resolve(); var sidebarNavigation=app.Container.Resolve(); window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820; model.ApplyRecipeCommand.Execute();await Task.Delay(100); var log=window.FindControl("LogPanel")!; var list=log.GetVisualDescendants().OfType().Single(); Check(ReferenceEquals(log.DataContext,model)&&ReferenceEquals(list.ItemsSource,model.Logs),"Sidebar log shares the runtime log collection"); var view=window.GetVisualDescendants().OfType().Single(); var steps=view.GetVisualDescendants().OfType().Single(b=>b.Child is ScrollViewer); foreach(var height in new[]{720,1080}) { window.Height=height;await Task.Delay(80);window.UpdateLayout(); var logPosition=log.TranslatePoint(default,window)!.Value; var stepsPosition=steps.TranslatePoint(default,window)!.Value; Check(logPosition.X<180&&logPosition.Y>150&&log.Bounds.Height>200,"Log occupies the sidebar below sidebarNavigation at height "+height); Check(steps.Bounds.Height>height-500&&stepsPosition.X>logPosition.X+log.Bounds.Width,"Steps fill the released right column at height "+height); } var screenshots=Path.GetFullPath(Path.Combine("..","scratch","screenshots"));Directory.CreateDirectory(screenshots); using(var rendered=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height))) {rendered.Render(window);rendered.Save(Path.Combine(screenshots,"sidebar-log-layout.png"));} sidebarNavigation.SelectedIndex=1;await Task.Delay(80); Check(log.IsEffectivelyVisible&&ReferenceEquals(list.ItemsSource,model.Logs),"Sidebar log remains visible when navigating to settings"); _exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--recipe-close-only")) { await CheckRecipeClose(app,lifetime);_exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--runtime-settings-only")) { var model=app.Container.Resolve(); var view=new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(model); var dialog=new Window{Content=view,Width=900,Height=720};dialog.Show();await Task.Delay(100); try { view.GetVisualDescendants().OfType().Single().Value=3; view.FindControl("AutoResetCheckBox")!.IsChecked=false; view.FindControl("ResetDelayInput")!.Value=4; await Task.Delay(50); var saved=RuntimeSettingsStore.Current.Read()!; Check(model.FrameStride==3&&!model.AutoResetOnComplete&&model.ResetDelaySec==4 &&saved.FrameStride==3&&!saved.AutoResetOnComplete&&saved.ResetDelaySec==4,"运行设置控件绑定并自动保存三个运行参数"); model.ApplyRecipeCommand.Execute(); var engine=app.Container.Resolve(); Check(engine.Config.Sop.Settings.FrameStride==3&&!engine.Config.Sop.Settings.AutoResetOnComplete&&engine.Config.Sop.Settings.ResetDelaySec==4, "应用配方不会覆盖运行设置,并传给引擎"); model.IsRunning=true;await Task.Delay(30); Check(!view.FindControl("AutoResetCheckBox")!.IsEnabled&&!view.FindControl("ResetDelayInput")!.IsEnabled,"运行中禁止修改自动复位和延时"); model.AutoResetOnComplete=true;model.FrameStride=8;model.ResetDelaySec=20; Check(model.FrameStride==3&&!model.AutoResetOnComplete&&model.ResetDelaySec==4,"运行中参数赋值也不会覆盖已保存设置"); model.IsRunning=false; using var rendered=new RenderTargetBitmap(new PixelSize(900,720));rendered.Render(dialog); var screenshots=Path.Combine(Directory.GetCurrentDirectory(),"..","scratch","screenshots");Directory.CreateDirectory(screenshots); rendered.Save(Path.Combine(screenshots,"runtime-settings.png")); } finally{model.IsRunning=false;dialog.Close();} _exit=0;return; } if(_agentSettingsFile is not null) { var model=new RecipeEditorViewModel(); var view=new RecipeEditor{DataContext=model}; var dialog=new Window{Width=1040,Height=900,Content=view};dialog.Show(); model.OnDialogOpened(new DialogParameters{{"new",true}}); view.GetVisualDescendants().OfType().First().SelectedIndex=4; view.FindControl("AgentSettingsExpander")!.IsExpanded=true; model.FetchAgentModelsCommand.Execute(); for(var i=0;i<180&&model.AgentModels.Count==0;i++)await Task.Delay(100); Check(model.AgentModels.Count>0,"Live editor model discovery: "+model.AgentStatus); Console.WriteLine("Models: "+string.Join(", ",model.AgentModels)); await model.ShutdownAsync();dialog.Close();_exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--diagnostics-only")) { var model=app.Container.Resolve(); model.ApplyRecipeCommand.Execute();await Task.Delay(80); Check(!window.GetVisualDescendants().OfType().Any(t=>t.Name=="InferenceBackend"),"Operator page hides inference backend diagnostic details"); Check(model.Logs.Any(l=>l.Message.Contains("推理设备:")&&l.Message.Contains("步骤确认=")),"Inference backend diagnostics remain available in the runtime log"); _exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--camera-lifecycle-only")) { await CheckCameraLifecycle(app,window); _exit=0; return; } if(Environment.GetCommandLineArgs().Contains("--usb-capture-only")) { await CheckUsbCapture(app); _exit=0; return; } CheckCameraPreferences(app); CheckRecipePreferences(app); var navigation=app.Container.Resolve(); 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(); if(_visionOnly){await CheckVisionConfirmation(app,sop);_exit=0;return;} var sopView=window.GetVisualDescendants().OfType().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().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().Single(); Check(ReferenceEquals(settings.DataContext,sop),"Settings and operator page share runtime state"); Check(settings.GetVisualDescendants().OfType().Count()==2&&settings.GetVisualDescendants().OfType().Count()==1,"Camera, recipe and stride editors are on settings page"); await CheckRecipeSelection(window,navigation,sop); if(_recipeSelectionOnly){_exit=0;return;} // 后续断言针对 demo 的四步三域,不能依赖新增模板后的文件排序。 sop.SelectedRecipe="demo.yaml"; 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().Any(t=>t.Name=="InferenceBackend") &&sop.Logs.Any(l=>l.Message.Contains("推理设备:")&&l.Message.Contains("步骤确认=")), "Inference backend diagnostics appear in logs instead of the operator page"); Check(window.GetVisualDescendants().OfType().Single().GetVisualDescendants().OfType().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().Single().GetVisualDescendants().OfType().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().Single().GetVisualDescendants().OfType().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().All(c=>!c.IsEnabled),"Runtime settings cannot be edited during acquisition"); Check(!sop.DeleteRecipeCommand.CanExecute(),"Recipe deletion is disabled 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&&!Camera.IsGrabbing,"Stop command retains the idle camera connection"); await CheckProcessImages(app,sop,window); await CheckRuntimeStatistics(app,sop,window); await CheckCompletionImageSaving(app,sop); if(_processImagesOnly){_exit=0;return;} navigation.SelectedIndex=1;await Task.Delay(80); Check(settings.GetVisualDescendants().Where(c=>c is ComboBox or Slider).Cast().All(c=>c.IsEnabled),"Runtime settings become editable after stopping"); await CheckRecipeDeletion(lifetime,settings,sop); navigation.SelectedIndex=0;await Task.Delay(80); Check(window.GetVisualDescendants().OfType().Any(),"SOP page navigates"); sop.EditRecipeCommand.Execute();await Task.Delay(150); var modal=lifetime.Windows.OfType().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(); await ChooseRecipeClose(modal,"SaveRecipeAndCloseButton"); 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().Single();titlebarModal.Close(); await ChooseRecipeClose(titlebarModal,"DiscardRecipeAndCloseButton"); 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"); 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,TargetName="目标零件 · 支架"};annotation.BoxDrawn+=box=>drawn=box;drawing.Content=annotation;await Task.Delay(60); drawing.MouseDown(new Point(100,150),MouseButton.Left);drawing.MouseMove(new Point(300,250));Save(drawing,"annotation-target-drag");drawing.MouseUp(new Point(300,250),MouseButton.Left); annotation.Box=drawn;Save(drawing,"annotation-target-saved"); annotation.Box=[0,0,100,60];Save(drawing,"annotation-target-edge");annotation.Box=null; 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)})); _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; async Task Import() { trainer.ImportCommand.Execute(); for(var i=0;i<400&&(trainer.IsBusy||trainer.IsImporting);i++)await Task.Delay(20); Check(!trainer.IsBusy&&!trainer.IsImporting,"Video import finishes without a part picker"); } try { trainer.SelectImportVideoAsync=()=>Task.FromResult(null);await Import(); Check(trainer.Project is null,"Cancelling the video picker leaves the current project unchanged"); var videoPath=Path.Combine(trainer.Root,"multi-part-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<30;i++)writer.Write(frame); } trainer.SelectImportVideoAsync=()=>Task.FromResult(videoPath);await Import(); Check(trainer.Project is {AnnotationVersion:2}&&trainer.Frames.Count>0,"Video import creates an unassigned multi-part project"); var selector=view.FindControl("TrainingTargetPart")!; selector.SelectedItem="支架";trainer.DrawBox([1,1,60,44]); selector.SelectedItem="螺丝";trainer.DrawBox([10,10,25,25]); Check(trainer.SelectedFrame!.Objects.Count==2&&trainer.CurrentAnnotations.Count==2&&trainer.SelectedFrame.Status=="auto","A nested second part preserves the first box and requires whole-frame review"); Check(view.GetVisualDescendants().OfType().Single().Annotations!.Count==2,"Annotation canvas receives both part boxes at once"); trainer.ApproveCommand.Execute();var first=trainer.Project!.FilePath; var saved=TrainingProject.Load(first); Check(saved.Frames[0].Status=="reviewed"&&saved.Frames[0].Objects.All(o=>o.Status=="reviewed"),"Whole-frame review saves both part labels"); Save(owner,"multi-part-annotation"); trainer.AbsentCommand.Execute(); Check(trainer.SelectedFrame.Objects.Single(o=>o.Label=="支架").Box!=null&&trainer.CurrentBox==null,"Marking the selected part absent preserves other part boxes"); trainer.Label="支架";trainer.DrawBox([2,2,58,43]); Check(trainer.SelectedFrame.Objects.Count==2&&trainer.SelectedFrame.Objects.Single(o=>o.Label=="螺丝").Status=="absent","Redrawing updates only the selected part"); trainer.SelectedFrame=trainer.Frames[1];trainer.Label="螺丝";trainer.DrawBox([10,10,25,25]);trainer.Label="支架"; trainer.Load(first,1);Check(trainer.SelectedFrame!.Objects.Single().Label=="螺丝","Reopening preserves per-frame part identities without relabeling"); var before=File.ReadAllBytes(first);trainer.SelectImportVideoAsync=()=>Task.FromResult(null);await Import(); Check(trainer.Project.FilePath==first&&File.ReadAllBytes(first).SequenceEqual(before),"Cancelling a later import preserves every existing annotation"); } finally{trainer.SelectImportVideoAsync=selectVideo;} } 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().Single(); var tabs=view.GetVisualDescendants().OfType().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;tab100&&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 async Task CheckRecipeDeletion(IClassicDesktopStyleApplicationLifetime lifetime,Control settings,SopPageViewModel sop) { var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!); var name="delete-test-"+Guid.NewGuid().ToString("N");var file=name+".yaml"; var directory=store.DirectoryFor(name);Directory.CreateDirectory(directory); var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name; config.Sop.Steps=[new SopHelper.Engine.Sop.StepDef{Id=1,Name="删除检查",Detection=new SopHelper.Engine.Sop.StepCondition{Method=SopHelper.Engine.Sop.ConditionMethod.TimeElapsed}}]; SopHelper.Engine.Sop.SopConfigLoader.Save(config,store.ConfigPath(name)); foreach(var folder in new[]{"recordings","parts","models","sop_stand"}) {Directory.CreateDirectory(Path.Combine(directory,folder));File.WriteAllText(Path.Combine(directory,folder,"keep.bin"),folder);} var selected=sop.SelectedRecipe;sop.Recipes.Add(file);sop.SelectedRecipe=file; var button=settings.GetVisualDescendants().OfType