using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Headless; using Avalonia.Media.Imaging; using Avalonia.Media; using Avalonia.Threading; using Prism.Ioc; using Prism.Dialogs; using SopHelper; using SopHelper.Engine.Camera; using SopHelper.Engine.Recipes; using SopHelper.Models; using SopHelper.SopVideo; using SopHelper.VVMs.SopPage; using SopHelper.VVMs.RecipeEditor; using System.Text.Json; using Avalonia.VisualTree; using OpenCvSharp; using SopHelper.Engine.SopAgent; using SopHelper.Engine.Sop; 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(); private static readonly LicenseUiTests Licensing = new(); [STAThread] public static int Main(string[] args) { if (args.Contains("--add-step-only")) { CheckAddStep(); return 0; } _visionOnly=args.Contains("--vision-only"); if (args.Contains("--license-ui-only")) Licensing.Expire(); _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 { if (args.Contains("--auto-login-only")) PrepareAutoLogin(dataRoot); AppBuilder.Configure(()=>new App(Camera, Licensing.Service)).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("--license-ui-only")) { await Licensing.Run(app, lifetime); _exit = 0; return; } if (Environment.GetCommandLineArgs().Contains("--login-users-only")) { await CheckLoginUserSelection(window); _exit = 0; return; } if (Environment.GetCommandLineArgs().Contains("--auto-login-only")) { await CheckAutoLogin(app); _exit = 0; return; } if (Environment.GetCommandLineArgs().Contains("--permissions-only")) { await CheckPermissions(app, window); await CheckOwnPasswords(window); _exit = 0; return; } // 既有业务回归使用显式测试管理员;不改变生产环境默认未登录状态。 UserAccess.Current.Setup("smoke-admin", "SmokePassword123"); if (Environment.GetCommandLineArgs().Contains("--recipe-transfer-only")) { // 单独跑配方导入导出入口检查:视图需要真实窗口宿主,确认窗才能以模态方式打开。 var transferModel = app.Container.Resolve(); var transferView = new SopHelper.VVMs.RuntimeSettings.RuntimeSettings(transferModel); var transferWindow = new Window { Content = transferView, Width = 900, Height = 900 }; transferWindow.Show(); await Task.Delay(120); await CheckRecipeTransfer(lifetime, transferView, transferModel); transferWindow.Close(); _exit = 0; return; } if(Environment.GetCommandLineArgs().Contains("--djev-shutdown-only")) { // 注入尚未完成的启动任务,验证关闭必须先取消并等待,且重复点击不会提前销毁窗口。 var startup=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var fields=System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic; var options=new D3StartupOptions(new("http://127.0.0.1:8766/v1/systemone"), Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!,"unused","unused","unused", TimeSpan.FromSeconds(2),TimeSpan.FromMilliseconds(20)); // 用当前进程的错误启动时间模拟过期记录,不接触真实模型,也不能结束测试宿主。 File.WriteAllText(options.MarkerPath,JsonSerializer.Serialize(new D3ProcessMarker(Environment.ProcessId,DateTime.UnixEpoch))); typeof(App).GetField("_d3Options",fields)!.SetValue(app,options); typeof(App).GetField("_d3Startup",fields)!.SetValue(app,startup.Task); var cancellation=(CancellationTokenSource)typeof(App).GetField("_d3StartupCancellation",fields)!.GetValue(app)!; window.Close();window.Close(); Check(cancellation.IsCancellationRequested&&window.IsVisible&&Camera.DisposeCount==0,"退出先取消模型启动,等待期间重复关闭不提前释放资源"); startup.SetResult(); for(var retry=0;window.IsVisible&&retry<100;retry++)await Task.Delay(20); Check(!window.IsVisible&&!File.Exists(options.MarkerPath)&&Camera.DisposeCount>0,"启动任务完成后清理模型记录、关闭窗口并释放相机"); _exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--check-progress-only")) { await CheckRemainingWindowProgress(app,window);_exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--standard-sop-only")) { await CheckStandardSopPlayback(app,window);_exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--step-counts-only")) { await CheckStepCounts(app,window);_exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--startup-recipe-only")) { var model=app.Container.Resolve(); Check(model.SelectedRecipe is not null&&model.ActiveRecipe==model.SelectedRecipe&&model.StepCards.Count>0, "Startup applies the selected recipe and populates step cards"); Check(!model.IsRunning&&!Camera.IsConnected&&!Camera.IsGrabbing&&Camera.ConnectCount==0, "Startup application never connects or starts the camera"); CheckRecipePreferences(app); _exit=0;return; } if(Environment.GetCommandLineArgs().Contains("--time-display-only")) { foreach(var (duration,expected) in new[]{(TimeSpan.Zero,"00:00:00"),(TimeSpan.FromMilliseconds(999),"00:00:00"), (TimeSpan.FromMilliseconds(1999),"00:00:01"),(TimeSpan.FromMilliseconds(60001),"00:01:00"), (TimeSpan.FromHours(25)+TimeSpan.FromMilliseconds(1250),"25:00:01")}) Check(SopPageViewModel.FormatDuration(duration)==expected,"Elapsed time drops fractional seconds: "+duration); var model=app.Container.Resolve(); var engine=app.Container.Resolve(); var name=Path.GetFileNameWithoutExtension(model.SelectedRecipe)!; SopStandardVideoDuration.Remember(new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!).DirectoryFor(name),TimeSpan.FromSeconds(3.25)); var statistics=engine.GetStatistics(name);statistics.StartRound();await Task.Delay(1150);statistics.Pause();await Task.Delay(120); Check(model.FlowElapsedText=="00:00:01"&&model.StepElapsedText=="00:00:01" &&model.StandardDurationText=="00:00:03"&&model.AverageDurationText=="00:00:00","Main statistics render whole seconds"); Check(new StepCard().ElapsedText=="00:00:00","New step cards start with whole seconds"); model.StepCards.Clear();model.StepCards.Add(new(){StepId=1,Name="计时步骤",SaveCompletionImage=false}); typeof(SopPageViewModel).GetMethod("UpdateCard",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)! .Invoke(model,[new SopHelper.Engine.Sop.StepSnapshot{StepId=1,Elapsed=TimeSpan.FromMilliseconds(1999)}]); Check(model.StepCards[0].ElapsedText=="00:00:01","Step snapshots render whole seconds"); model.IsRunning=true; using(var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90))) typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)! .Invoke(model,[new SopHelper.Engine.Common.FrameResult{Size=(64,48),InferenceMs=1999},frame]); await Task.Delay(80); Check(model.InferenceText=="1 秒","Inference duration uses whole seconds"); model.IsRunning=false; _exit=0;return; } 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 navigationPanel=window.FindControl("NavigationPanel")!; 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 navigation at height "+height); Check(Math.Abs(navigationPanel.Bounds.Height-log.Bounds.Height)<1,"Navigation and log have equal heights at "+height); Check(steps.Bounds.Height>height-500&&stepsPosition.X>logPosition.X+log.Bounds.Width,"Steps fill the released right column at height "+height); } model.StepCards.Clear(); var completedCard=new StepCard{StepId=1,Name="已完成步骤",IsMet=true}; var skippedCard=new StepCard{StepId=2,Name="异常跳过步骤",IsSkipped=true}; model.StepCards.Add(completedCard);model.StepCards.Add(skippedCard); await Task.Delay(80); var cards=steps.GetVisualDescendants().OfType().Where(b=>b.Name=="card").ToArray(); Check(cards.Length==2&&cards[0].Background is ISolidColorBrush green&&green.Color==Color.Parse("#14532D") &&cards[1].Background is ISolidColorBrush red&&red.Color==Color.Parse("#7F1D1D"),"Completed steps render green and skipped steps render red"); var greenBackground=cards[0].Background; completedCard.IsMet=false;skippedCard.IsSkipped=false;await Task.Delay(30); Check(!Equals(cards[0].Background,greenBackground)&&Equals(cards[0].Background,cards[1].Background),"Reset removes completion and skip background colors"); completedCard.IsMet=true;skippedCard.IsSkipped=true;await Task.Delay(30); 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("--step-trigger-tabs-only")) { await CheckStepTriggerTabs(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 { // 旧工作区的判定超时继续生效,运行设置界面只调整其余运行参数。 RuntimeSettingsStore.Current.Save(new RuntimeOptions { DjevTimeoutMs = 375 }); model.ApplyRecipeCommand.Execute(); Check(!view.GetVisualDescendants().OfType().Any(text => text.Text?.Contains("djev", StringComparison.OrdinalIgnoreCase) == true) && view.FindControl("DjevTimeoutInput") is null && view.FindControl("DjevTierInput") is null, "运行设置已移除 djev 区块"); 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 &&saved.DjevTimeoutMs==375,"自动保存运行参数时保留既有判定超时"); Check(new RuntimeSettingsStore(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!).Read()!.DjevTimeoutMs==375, "新建设置存储实例仍能恢复全局djev超时"); 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&&engine.Config.Sop.Settings.DjevTimeoutMs==375, "应用配方不会覆盖运行设置,并传给引擎"); 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")) { CheckCameraPreferences(app); await CheckCameraLifecycle(app,window); _exit=0; return; } if(Environment.GetCommandLineArgs().Contains("--usb-capture-only")) { await CheckUsbCapture(app); _exit=0; return; } if(Environment.GetCommandLineArgs().Contains("--agent-only")) { await CheckVisionConfirmation(app,app.Container.Resolve());_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=="运行"&&!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(Environment.GetCommandLineArgs().Contains("--completion-images-only")){await CheckCompletionImageSaving(app,sop);_exit=0;return;} 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==sop.SelectedRecipe&&!sop.IsRunning,"Startup applies the selected recipe without starting acquisition"); 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"); // 相机、配方和 djev 启动档位各有下拉,抽帧是唯一的滑块。 Check(settings.GetVisualDescendants().OfType().Count()==3&&settings.GetVisualDescendants().OfType().Count()==1,"Camera, recipe, djev tier 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); await CheckRecipeTransfer(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 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"); 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 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