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 bool _visionOnly; private static bool _processImagesOnly; private static bool _recipeSelectionOnly; 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 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); 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()==2,"Camera, recipe, threshold and stride editors are on settings page"); await CheckRecipeSelection(window,navigation,sop); if(_recipeSelectionOnly){_exit=0;return;} 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"&&t.Text==sop.InferenceBackendText) &&sop.InferenceBackendText.Contains("手部:")&&sop.InferenceBackendText.Contains("目标:"), "Operator page displays the actual inference backends, including CPU fallback"); 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,"Stop command releases acquisition"); 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(); 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(); 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().Single(); var trainingEditorVm=(RecipeEditorViewModel)trainingDialog.DataContext!; var outerTabs=trainingDialog.GetVisualDescendants().OfType().First();outerTabs.SelectedIndex=6;await Task.Delay(100); var trainingView=trainingDialog.GetVisualDescendants().OfType().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().Any(c=>ReferenceEquals(c.ItemsSource,trainer.Recipes)),"Embedded training has no recipe selector"); var saveParameters=trainingView.GetVisualDescendants().OfType