diff --git a/README.md b/README.md
index 9f7d9f3..141d312 100644
--- a/README.md
+++ b/README.md
@@ -44,6 +44,7 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
## 操作流程
1. 接好 UVC 或海康相机,选择设备和配方,应用后开始检测。
+ - 选择配方后立即记住,下次启动恢复该选择;记忆保存在当前工作区的 `workspace/last-recipe.json`。原配方不存在时选择可用配方,恢复选择不会自动开始采集。
2. 配方编辑器包含步骤、区域、全局设置、零件列表、检测模型、SOP流程视频、零件标注与训练七个标签页;区域坐标使用原图像素。
- 零件名称只在“零件列表”维护,随配方保存到 `sop.parts`。标注类别、步骤目标类别、必留物品和完成必需物品均从该列表选择。
- 旧配方首次编辑时汇总已有训练类别、模型配置、步骤和标注项目名称;保存后列表成为唯一来源。重名、空名以及删除仍被步骤或标注项目引用的名称会阻止保存。
diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
index 1aa19cb..f8eda8e 100644
--- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
+++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs
@@ -29,6 +29,7 @@ public class SopPageViewModel : ViewModelBase
/// 配方目录(相对程序目录)
private static string RecipeDirectory => DesktopPlatform.Recipes.RecipesDirectory;
private static string RecipePath(string fileName) => DesktopPlatform.Recipes.ConfigPath(Path.GetFileNameWithoutExtension(fileName));
+ private static string LastRecipePath => Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "last-recipe.json");
// 独立工作区(包括自动化测试)不能覆盖正式程序的用户偏好。
private static string LastCameraPath =>
@@ -64,6 +65,7 @@ public class SopPageViewModel : ViewModelBase
private CameraInfo? _selectedCamera;
private CameraInfo? _lastUsedCamera;
private string? _selectedRecipe;
+ private bool _refreshingRecipes;
private string _activeRecipe = "未应用配方";
private ImageSource? _frame;
private string _statusText = "就绪";
@@ -170,6 +172,7 @@ public class SopPageViewModel : ViewModelBase
set
{
if (!SetProperty(ref _selectedRecipe, value)) return;
+ if (!_refreshingRecipes) RememberRecipe(value);
RaiseCommands();
}
}
@@ -402,13 +405,42 @@ public class SopPageViewModel : ViewModelBase
///
/// 扫描 configs/sop/*.yaml
///
- private void LoadRecipes()
+ private void LoadRecipes(string? preferred = null)
{
- if (!Directory.Exists(RecipeDirectory)) return;
+ if (preferred is null)
+ {
+ try
+ {
+ if (File.Exists(LastRecipePath)) preferred = JsonSerializer.Deserialize(File.ReadAllText(LastRecipePath));
+ }
+ catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException)
+ { Log("warn", "读取上次配方选择失败:" + error.Message); }
+ }
+ _refreshingRecipes = true;
+ try
+ {
+ Recipes.Clear();
+ foreach (var name in DesktopPlatform.Recipes.Names()) Recipes.Add(name + ".yaml");
+ SelectedRecipe = preferred is not null && Recipes.Contains(preferred) ? preferred : Recipes.FirstOrDefault();
+ RaisePropertyChanged(nameof(SelectedRecipe));
+ }
+ finally { _refreshingRecipes = false; }
+ RememberRecipe(SelectedRecipe);
+ }
- foreach (var name in DesktopPlatform.Recipes.Names()) Recipes.Add(name + ".yaml");
-
- if (Recipes.Count > 0) SelectedRecipe = Recipes[0];
+ private void RememberRecipe(string? name)
+ {
+ // Ignore transient nulls while the selection control refreshes, and invalid selections.
+ if (string.IsNullOrWhiteSpace(name) || !Recipes.Contains(name)) return;
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(LastRecipePath)!);
+ var temporary = LastRecipePath + ".tmp";
+ File.WriteAllText(temporary, JsonSerializer.Serialize(name));
+ File.Move(temporary, LastRecipePath, overwrite: true);
+ }
+ catch (Exception error) when (error is IOException or UnauthorizedAccessException)
+ { Log("warn", "保存配方选择失败:" + error.Message); }
}
///
@@ -416,14 +448,7 @@ public class SopPageViewModel : ViewModelBase
///
private void RefreshRecipes(string fileName)
{
- Recipes.Clear();
-
- if (Directory.Exists(RecipeDirectory))
- foreach (var name in DesktopPlatform.Recipes.Names()) Recipes.Add(name + ".yaml");
-
- var pick = Recipes.Contains(fileName) ? fileName : Recipes.FirstOrDefault();
- if (pick is not null) SelectedRecipe = pick;
-
+ LoadRecipes(fileName);
ApplyRecipe();
}
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index 34a8466..f3a3e6f 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -66,6 +66,7 @@ internal static class Smoke
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");
@@ -406,6 +407,46 @@ internal static class Smoke
}
finally {window.Width=width;trainer.Logs=logs;trainer.Status=status;tabs.SelectedIndex=selectedTab;}
}
+ private static void CheckRecipePreferences(App app)
+ {
+ var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
+ var path=Path.Combine(store.Root,"workspace","last-recipe.json");
+ var before=File.Exists(path)?File.ReadAllBytes(path):null;
+ var name="preferred-recipe-"+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;
+ SopHelper.Engine.Sop.SopConfigLoader.Save(config,store.ConfigPath(name));
+ void WithVm(Action check)
+ {
+ using var camera=new FakeCamera{Devices=[]};
+ using var pipeline=new SopHelper.Engine.Pipeline.DetectionPipeline(camera);
+ var vm=new SopPageViewModel(camera,pipeline,new SopHelper.Engine.Sop.SopEngine(),app.Container.Resolve());
+ try{check(vm);}finally{vm.Destroy();}
+ }
+ try
+ {
+ WithVm(vm=>
+ {
+ Check(vm.Recipes[0]!=file,"Preference test chooses a recipe other than the first list entry");
+ vm.SelectedRecipe=file;
+ Check(JsonSerializer.Deserialize(File.ReadAllText(path))==file&&!vm.IsRunning,"Selecting a recipe persists immediately without applying or starting");
+ vm.SelectedRecipe=null;vm.SelectedRecipe="not-a-recipe.yaml";
+ Check(JsonSerializer.Deserialize(File.ReadAllText(path))==file,"Transient empty and invalid selections do not overwrite the saved recipe");
+ });
+ WithVm(vm=>Check(vm.SelectedRecipe==file&&vm.ActiveRecipe=="未应用配方"&&!vm.IsRunning,"Restart restores the last selected recipe without applying it or starting acquisition"));
+ File.Delete(store.ConfigPath(name));
+ WithVm(vm=>Check(vm.SelectedRecipe is not null&&vm.Recipes.Contains(vm.SelectedRecipe)&&vm.SelectedRecipe!=file,"A deleted preferred recipe falls back to an available recipe"));
+ File.WriteAllText(path,"{invalid-json");
+ WithVm(vm=>Check(vm.SelectedRecipe is not null&&vm.Recipes.Contains(vm.SelectedRecipe),"Corrupt recipe preference does not prevent startup"));
+ }
+ finally
+ {
+ if(before is not null)File.WriteAllBytes(path,before);else if(File.Exists(path))File.Delete(path);
+ File.Delete(store.ConfigPath(name));Directory.Delete(directory);
+ }
+ }
+
private static void CheckCameraPreferences(App app)
{
var path=Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!,"workspace","last-camera.json");