新增配方删除按钮及确认弹窗并保留可恢复备份

This commit is contained in:
tfarcraw 2026-11-10 14:21:52 +08:00
parent a37fe65914
commit 78b83264b0
8 changed files with 182 additions and 6 deletions

View File

@ -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`。标注类别、步骤目标类别、必留物品和完成必需物品均从该列表选择。
- 旧配方首次编辑时汇总已有训练类别、模型配置、步骤和标注项目名称;保存后列表成为唯一来源。重名、空名以及删除仍被步骤或标注项目引用的名称会阻止保存。

View File

@ -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 } }
}
};
}
}

View File

@ -29,12 +29,14 @@
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="配方" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" IsEnabled="{Binding CanSelectCamera}" ItemsSource="{Binding Recipes}" SelectedItem="{Binding SelectedRecipe, Converter={StaticResource SelectionConverter}}" />
<Button Grid.Column="2" Content="编辑" Margin="6,0,0,0" Padding="10,4" Command="{Binding EditRecipeCommand}" />
<Button Grid.Column="3" Content="新建" Margin="6,0,0,0" Padding="10,4" Command="{Binding NewRecipeCommand}" />
<Button Grid.Column="4" Content="应用" Margin="6,0,0,0" Padding="10,4" Command="{Binding ApplyRecipeCommand}" />
<Button Grid.Column="5" Content="删除" Margin="6,0,0,0" Padding="10,4" Command="{Binding DeleteRecipeCommand}" Foreground="{StaticResource Ng}" />
</Grid>
<Button Content="打开配方文件夹" Command="{Binding OpenRecipeFolderCommand}" Margin="0,8,0,0" HorizontalAlignment="Left" />
<Grid Margin="0,8,0,0">
@ -66,6 +68,7 @@
<TextBlock Text="选择配方后点击“应用”;阈值和抽帧参数在下次开始运行时生效。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
</StackPanel>
</Border>
<TextBlock Text="{Binding StatusText}" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
</StackPanel>
</ScrollViewer>
</UserControl>

View File

@ -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<bool>(owner);
};
}
}

View File

@ -66,6 +66,8 @@ public class SopPageViewModel : ViewModelBase
private CameraInfo? _lastUsedCamera;
private string? _selectedRecipe;
private bool _refreshingRecipes;
private bool _deletingRecipe;
public Func<string, Task<bool>>? 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
}
/// <summary>连接、枚举、采集期间不切换设备。</summary>
public bool CanSelectCamera => !IsRunning && !_isCameraBusy;
public bool CanSelectCamera => !IsRunning && !_isCameraBusy && !_deletingRecipe;
/// <summary>相机是否已连接</summary>
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
/// <summary>复位</summary>
public DelegateCommand ResetCommand { get; private set; } = null!;
public DelegateCommand DeleteRecipeCommand { get; private set; } = null!;
/// <summary>应用配方</summary>
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
}
/// <summary>运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用</summary>
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);
/// <summary>
/// 刷新所有命令的可用状态。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();
}
/// <summary>
/// 编辑当前选中的配方
/// </summary>

View File

@ -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));
/// <summary>移出活动配方并保留整目录备份;归档目录也阻止下次启动重新导入旧配方。</summary>
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<string, string>(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);

View File

@ -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<Control>().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<Control>().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<SopPage>().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<Button>().Single(b=>b.Content?.ToString()=="删除");
Check(ReferenceEquals(button.Command,sop.DeleteRecipeCommand)&&button.Command!.CanExecute(null),"Runtime settings exposes a working delete recipe button");
var confirm=sop.ConfirmDeleteRecipeAsync;sop.ConfirmDeleteRecipeAsync=null;sop.DeleteRecipeCommand.Execute();
Check(File.Exists(store.ConfigPath(name)),"Deleting without a confirmation handler cannot remove a recipe");sop.ConfirmDeleteRecipeAsync=confirm;
sop.DeleteRecipeCommand.Execute();await Task.Delay(50);
var popup=lifetime.Windows.OfType<SopHelper.VVMs.RuntimeSettings.DeleteRecipeDialog>().Single();
Check(File.Exists(store.ConfigPath(name))&&popup.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text?.Contains(name)==true),"Deletion confirmation identifies the recipe before any files move");
Save(popup,"delete-recipe-confirm");popup.Close(false);await Task.Delay(40);
Check(File.Exists(store.ConfigPath(name))&&sop.SelectedRecipe==file,"Cancelling deletion leaves the selected recipe and its data intact");
sop.DeleteRecipeCommand.Execute();await Task.Delay(50);
popup=lifetime.Windows.OfType<SopHelper.VVMs.RuntimeSettings.DeleteRecipeDialog>().Single();
// A queued editor-save callback may apply a recipe while its deletion is being confirmed.
sop.ApplyRecipeCommand.Execute();Check(sop.ActiveRecipe==file&&sop.StepCards.Count==1,"Recipe becomes active while deletion confirmation is open");
popup.GetVisualDescendants().OfType<Button>().Single(b=>b.Content?.ToString()=="确认删除").RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
await Task.Delay(100);
Check(!Directory.Exists(directory)&&!sop.Recipes.Contains(file)&&sop.SelectedRecipe!=file,"Confirmed deletion removes the recipe and refreshes the selection");
Check(sop.ActiveRecipe=="未应用配方"&&sop.StepCards.Count==0&&sop.Rois.Count==0,"Deleting the active recipe clears its runtime state");
Check(settings.GetVisualDescendants().OfType<TextBlock>().Any(t=>t.Text==sop.StatusText),"Deletion feedback is visible in runtime settings");
var archive=Directory.GetDirectories(Path.Combine(store.DeletedRecipesDirectory,name)).Single();
Check(File.Exists(Path.Combine(archive,file))&&new[]{"recordings","parts","models","sop_stand"}.All(folder=>File.ReadAllText(Path.Combine(archive,folder,"keep.bin"))==folder),"Deletion preserves all recipe data in a local archive");
var preference=Path.Combine(store.Root,"workspace","last-recipe.json");
Check(JsonSerializer.Deserialize<string>(File.ReadAllText(preference))==sop.SelectedRecipe,"Deletion updates the remembered recipe selection");
sop.SelectedRecipe=null;Check(!sop.DeleteRecipeCommand.CanExecute(),"An empty selection cannot be deleted");
Check(!sop.StartStopCommand.CanExecute(),"Acquisition cannot start with an empty recipe selection");
sop.SelectedRecipe=selected;
}
private static void CheckRecipePreferences(App app)
{
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);

View File

@ -85,6 +85,18 @@ try
var movedProject=TrainingProject.Load(relocatedRegistry["projects"]![0]!.GetValue<string>());
if(!RecipeWorkspace.IsWithin(movedProject.Video,relocated.RecipesDirectory)||!File.Exists(movedProject.Video))throw new Exception("Moving a complete runtime directory left stale source references");
Console.WriteLine("PASS: Moving the entire runtime directory automatically rebases recipe paths");
var archive=store.Delete("配方甲");
if(Directory.Exists(store.DirectoryFor("配方甲"))||!File.Exists(Path.Combine(archive,"配方甲.yaml"))||!Directory.Exists(Path.Combine(archive,"parts")))
throw new Exception("Recipe deletion failed to preserve its complete directory");
store.Initialize(legacyConfigs);store.ImportFrom(portable.Root);
if(File.Exists(store.ConfigPath("配方甲")))throw new Exception("Deleted recipe was automatically reimported");
if(!File.Exists(oldProject.FilePath)||!File.Exists(video))throw new Exception("Deletion modified legacy/source data");
Directory.CreateDirectory(store.DirectoryFor("配方甲"));SopConfigLoader.Save(new SopConfig{Sop=new SopBody{Name="配方甲"}},store.ConfigPath("配方甲"));
if(!store.Names().Contains("配方甲"))throw new Exception("Deleted name could not be reused for a new recipe");
store.Delete("配方甲");
if(Directory.GetDirectories(Path.Combine(store.DeletedRecipesDirectory,"配方甲")).Length!=2)throw new Exception("Second deletion overwrote the first archive");
try{store.Delete("../escape");throw new Exception("Delete accepted traversal");}catch(ArgumentException){}
Console.WriteLine("PASS: Recipe deletion archives all data, blocks automatic reimport, allows name reuse and rejects unsafe paths");
if (args.Length > 0)
{
var script = Path.Combine(root, "worker.py");