From 78b83264b0e2f263eb6f3a76573da2b1dc2e05cd Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Tue, 10 Nov 2026 14:21:52 +0800
Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E9=85=8D=E6=96=B9=E5=88=A0?=
=?UTF-8?q?=E9=99=A4=E6=8C=89=E9=92=AE=E5=8F=8A=E7=A1=AE=E8=AE=A4=E5=BC=B9?=
=?UTF-8?q?=E7=AA=97=E5=B9=B6=E4=BF=9D=E7=95=99=E5=8F=AF=E6=81=A2=E5=A4=8D?=
=?UTF-8?q?=E5=A4=87=E4=BB=BD?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README.md | 1 +
.../RuntimeSettings/DeleteRecipeDialog.cs | 28 ++++++++
.../RuntimeSettings/RuntimeSettings.axaml | 3 +
.../RuntimeSettings/RuntimeSettings.axaml.cs | 5 ++
.../VVMs/SopPage/SopPageViewModel.cs | 66 +++++++++++++++++--
.../Training/RecipeWorkspace.cs | 33 +++++++++-
tests/Avalonia.Smoke/Program.cs | 40 +++++++++++
tests/Training.Smoke/Program.cs | 12 ++++
8 files changed, 182 insertions(+), 6 deletions(-)
create mode 100644 src/SopHelper.Avalonia/VVMs/RuntimeSettings/DeleteRecipeDialog.cs
diff --git a/README.md b/README.md
index 141d312..2546026 100644
--- a/README.md
+++ b/README.md
@@ -45,6 +45,7 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
1. 接好 UVC 或海康相机,选择设备和配方,应用后开始检测。
- 选择配方后立即记住,下次启动恢复该选择;记忆保存在当前工作区的 `workspace/last-recipe.json`。原配方不存在时选择可用配方,恢复选择不会自动开始采集。
+ - 在运行设置中选中配方,点击“删除”并确认即可移除。采集运行或相机仍连接时不可删除;整份配方数据会移至 `workspace/deleted-recipes/配方名/版本/` 备份,不会在下次启动自动导入回来。需要恢复时,退出程序后将该版本文件夹中的全部内容恢复到 `recipes/配方名/`。
2. 配方编辑器包含步骤、区域、全局设置、零件列表、检测模型、SOP流程视频、零件标注与训练七个标签页;区域坐标使用原图像素。
- 零件名称只在“零件列表”维护,随配方保存到 `sop.parts`。标注类别、步骤目标类别、必留物品和完成必需物品均从该列表选择。
- 旧配方首次编辑时汇总已有训练类别、模型配置、步骤和标注项目名称;保存后列表成为唯一来源。重名、空名以及删除仍被步骤或标注项目引用的名称会阻止保存。
diff --git a/src/SopHelper.Avalonia/VVMs/RuntimeSettings/DeleteRecipeDialog.cs b/src/SopHelper.Avalonia/VVMs/RuntimeSettings/DeleteRecipeDialog.cs
new file mode 100644
index 0000000..9315705
--- /dev/null
+++ b/src/SopHelper.Avalonia/VVMs/RuntimeSettings/DeleteRecipeDialog.cs
@@ -0,0 +1,28 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Layout;
+using Avalonia.Media;
+
+namespace SopHelper.VVMs.RuntimeSettings;
+
+public sealed class DeleteRecipeDialog : Window
+{
+ public DeleteRecipeDialog(string name)
+ {
+ Title = "删除配方"; Width = 480; SizeToContent = SizeToContent.Height;
+ CanResize = false; WindowStartupLocation = WindowStartupLocation.CenterOwner;
+ var cancel = new Button { Content = "取消", IsCancel = true, IsDefault = true };
+ var delete = new Button { Content = "确认删除", Foreground = new SolidColorBrush(Color.FromRgb(240, 83, 60)) };
+ cancel.Click += (_, _) => Close(false); delete.Click += (_, _) => Close(true);
+ Content = new StackPanel
+ {
+ Margin = new Thickness(20), Spacing = 18,
+ Children =
+ {
+ new TextBlock { Text = $"确定删除配方“{name}”?", FontSize = 16, FontWeight = FontWeight.Bold, TextWrapping = TextWrapping.Wrap },
+ new TextBlock { Text = "此配方的配置、录像、标注数据和训练模型会一并从配方列表移除,移入本地“已删除配方”目录,必要时可以找回。", TextWrapping = TextWrapping.Wrap },
+ new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Spacing = 8, Children = { cancel, delete } }
+ }
+ };
+ }
+}
diff --git a/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml b/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml
index 78900c9..361de90 100644
--- a/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml
+++ b/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml
@@ -29,12 +29,14 @@
+
+
@@ -66,6 +68,7 @@
+
diff --git a/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml.cs b/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml.cs
index 388326a..d92b165 100644
--- a/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml.cs
+++ b/src/SopHelper.Avalonia/VVMs/RuntimeSettings/RuntimeSettings.axaml.cs
@@ -11,5 +11,10 @@ public partial class RuntimeSettings : UserControl
{
InitializeComponent();
DataContext = model;
+ model.ConfirmDeleteRecipeAsync = async name =>
+ {
+ if (TopLevel.GetTopLevel(this) is not Window owner) return false;
+ return await new DeleteRecipeDialog(name).ShowDialog(owner);
+ };
}
}
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index f8eda8e..43934db 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -66,6 +66,8 @@ public class SopPageViewModel : ViewModelBase
private CameraInfo? _lastUsedCamera;
private string? _selectedRecipe;
private bool _refreshingRecipes;
+ private bool _deletingRecipe;
+ public Func>? ConfirmDeleteRecipeAsync { get; set; }
private string _activeRecipe = "未应用配方";
private ImageSource? _frame;
private string _statusText = "就绪";
@@ -119,10 +121,11 @@ public class SopPageViewModel : ViewModelBase
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
ResetCommand = new DelegateCommand(_engine.Reset, () => IsRunning);
- ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => !IsRunning && !_isCameraBusy);
+ ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
- NewRecipeCommand = new DelegateCommand(NewRecipe, () => !IsRunning && !_isCameraBusy);
+ NewRecipeCommand = new DelegateCommand(NewRecipe, () => CanSelectCamera);
+ DeleteRecipeCommand = new DelegateCommand(async () => await DeleteRecipeAsync(), CanDeleteRecipe);
OpenRecipeFolderCommand = new DelegateCommand(() =>
{
try { DesktopPlatform.Reveal(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(SelectedRecipe!))); }
@@ -236,7 +239,7 @@ public class SopPageViewModel : ViewModelBase
}
/// 连接、枚举、采集期间不切换设备。
- public bool CanSelectCamera => !IsRunning && !_isCameraBusy;
+ public bool CanSelectCamera => !IsRunning && !_isCameraBusy && !_deletingRecipe;
/// 相机是否已连接
public bool IsConnected
@@ -246,6 +249,7 @@ public class SopPageViewModel : ViewModelBase
{
if (!SetProperty(ref _isConnected, value)) return;
RaisePropertyChanged(nameof(ConnectionText));
+ RaiseCommands();
}
}
@@ -291,6 +295,7 @@ public class SopPageViewModel : ViewModelBase
/// 复位
public DelegateCommand ResetCommand { get; private set; } = null!;
+ public DelegateCommand DeleteRecipeCommand { get; private set; } = null!;
/// 应用配方
public DelegateCommand ApplyRecipeCommand { get; private set; } = null!;
@@ -305,7 +310,8 @@ public class SopPageViewModel : ViewModelBase
public DelegateCommand NewRecipeCommand { get; private set; } = null!;
public DelegateCommand OpenRecipeFolderCommand { get; private set; } = null!;
- private bool CanStart() => !_isCameraBusy && (SelectedCamera is not null || IsRunning);
+ private bool CanStart() => !_isCameraBusy && !_deletingRecipe &&
+ (IsRunning || (SelectedCamera is not null && SelectedRecipe is not null && Recipes.Contains(SelectedRecipe)));
private void SetCameraBusy(bool busy)
{
@@ -315,7 +321,8 @@ public class SopPageViewModel : ViewModelBase
}
/// 运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用
- private bool CanEditRecipe() => !IsRunning && !_isCameraBusy && !string.IsNullOrWhiteSpace(SelectedRecipe);
+ private bool CanEditRecipe() => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe);
+ private bool CanDeleteRecipe() => CanSelectCamera && !IsConnected && SelectedRecipe is not null && Recipes.Contains(SelectedRecipe);
///
/// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
@@ -332,6 +339,7 @@ public class SopPageViewModel : ViewModelBase
SnapshotCommand?.RaiseCanExecuteChanged();
EditRecipeCommand?.RaiseCanExecuteChanged();
NewRecipeCommand?.RaiseCanExecuteChanged();
+ DeleteRecipeCommand?.RaiseCanExecuteChanged();
OpenRecipeFolderCommand?.RaiseCanExecuteChanged();
}
@@ -452,6 +460,54 @@ public class SopPageViewModel : ViewModelBase
ApplyRecipe();
}
+ private async Task DeleteRecipeAsync()
+ {
+ if (!CanDeleteRecipe() || SelectedRecipe is not { } fileName) return;
+ if (ConfirmDeleteRecipeAsync is null) { StatusText = "请在运行设置中确认删除配方"; return; }
+ _deletingRecipe = true; RaisePropertyChanged(nameof(CanSelectCamera)); RaiseCommands();
+ var wasActive = false;
+ try
+ {
+ var name = Path.GetFileNameWithoutExtension(fileName);
+ if (!await ConfirmDeleteRecipeAsync(name)) { StatusText = "已取消删除配方"; return; }
+ if (_destroyed || IsRunning || _isCameraBusy || IsConnected) return;
+ wasActive = ActiveRecipe == fileName;
+ if (wasActive) ClearActiveRecipe();
+ var archive = DesktopPlatform.Recipes.Delete(name);
+ var next = SelectedRecipe == fileName ? null : SelectedRecipe;
+ LoadRecipes(next);
+ if (Recipes.Count == 0)
+ {
+ if (!wasActive) ClearActiveRecipe();
+ try { if (File.Exists(LastRecipePath)) File.Delete(LastRecipePath); }
+ catch (Exception error) when (error is IOException or UnauthorizedAccessException)
+ { Log("warn", "清除配方选择记录失败:" + error.Message); }
+ }
+ StatusText = $"已删除配方“{name}”,数据已移至本地已删除配方目录";
+ Log("info", $"{StatusText}:{archive}");
+ }
+ catch (Exception error)
+ {
+ if (wasActive && File.Exists(RecipePath(fileName)))
+ {
+ try { ApplyRecipe(); } catch (Exception restoreError) { Log("warn", "恢复配方失败:" + restoreError.Message); }
+ }
+ LoadRecipes(SelectedRecipe);
+ StatusText = "删除配方失败:" + error.Message; Log("warn", StatusText);
+ }
+ finally { _deletingRecipe = false; RaisePropertyChanged(nameof(CanSelectCamera)); RaiseCommands(); }
+ }
+
+ private void ClearActiveRecipe()
+ {
+ _pipeline.LoadModels(new PipelineOptions());
+ _engine.Load(new SopConfig());
+ StepCards.Clear(); Rois.Clear(); HandResult = null; _lastFrame = null;
+ ActiveRecipe = "未应用配方";
+ RaisePropertyChanged(nameof(InferenceBackendText));
+ RaiseCommands();
+ }
+
///
/// 编辑当前选中的配方
///
diff --git a/src/SopHelper.CrossPlatform.Engine/Training/RecipeWorkspace.cs b/src/SopHelper.CrossPlatform.Engine/Training/RecipeWorkspace.cs
index 1e323bf..64cdda2 100644
--- a/src/SopHelper.CrossPlatform.Engine/Training/RecipeWorkspace.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Training/RecipeWorkspace.cs
@@ -10,6 +10,36 @@ public sealed class RecipeWorkspace(string root)
{
public string Root { get; } = Path.GetFullPath(root);
public string RecipesDirectory => Path.Combine(Root, "recipes");
+ public string DeletedRecipesDirectory => Path.Combine(Root, "workspace", "deleted-recipes");
+ private bool WasDeleted(string name) => Directory.Exists(Path.Combine(DeletedRecipesDirectory, name));
+
+ /// 移出活动配方并保留整目录备份;归档目录也阻止下次启动重新导入旧配方。
+ public string Delete(string name)
+ {
+ var source = Path.GetFullPath(DirectoryFor(name));
+ var container = Path.GetFullPath(Path.Combine(DeletedRecipesDirectory, name));
+ var destination = Path.Combine(container, DateTime.UtcNow.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N"));
+ if (!IsWithin(source, RecipesDirectory) || !IsWithin(destination, DeletedRecipesDirectory))
+ throw new IOException("配方删除路径超出工作区");
+ if (!File.Exists(ConfigPath(name))) throw new FileNotFoundException("配方不存在,无法删除", ConfigPath(name));
+ CheckDirectoryLinks(source); CheckDirectoryLinks(container);
+ var existed = Directory.Exists(container);
+ Directory.CreateDirectory(container);
+ try { Directory.Move(source, destination); }
+ catch
+ {
+ if (!existed && !Directory.EnumerateFileSystemEntries(container).Any()) Directory.Delete(container);
+ throw;
+ }
+ return destination;
+ }
+
+ private void CheckDirectoryLinks(string path)
+ {
+ for (var directory = new DirectoryInfo(path); directory is not null && IsWithin(directory.FullName, Root); directory = directory.Parent)
+ if (directory.Exists && (directory.Attributes & FileAttributes.ReparsePoint) != 0)
+ throw new IOException("配方目录或备份目录包含链接,无法直接删除");
+ }
public string DirectoryFor(string name)
{
if (GetNameError(name) is { } error) throw new ArgumentException(error, nameof(name));
@@ -100,7 +130,7 @@ public sealed class RecipeWorkspace(string root)
{
var source = previous.DirectoryFor(name);
var destination = DirectoryFor(name);
- if (File.Exists(ConfigPath(name))) continue;
+ if (File.Exists(ConfigPath(name)) || WasDeleted(name)) continue;
var staging = destination + ".migrating";
CopyTree(source, staging);
var mappings = new Dictionary(StringComparer.OrdinalIgnoreCase) { [source] = destination };
@@ -147,6 +177,7 @@ public sealed class RecipeWorkspace(string root)
NormalizeName(configPath, name);
continue;
}
+ if (WasDeleted(name)) continue;
Directory.CreateDirectory(destination);
var source = group.OrderByDescending(File.GetLastWriteTimeUtc).First();
var oldTraining = Path.Combine(Root, "workspace", "training", name);
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index f3a3e6f..5ac62c6 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -103,6 +103,7 @@ internal static class Smoke
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);
@@ -113,6 +114,7 @@ internal static class Smoke
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().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);
@@ -407,6 +409,44 @@ internal static class Smoke
}
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