From c2571961c4f69155c331983d327e361de101a533 Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Mon, 9 Nov 2026 14:38:15 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E9=85=8D=E6=96=B9=E5=90=8D?= =?UTF-8?q?=E4=B8=8E=E6=96=87=E4=BB=B6=E5=90=8D=E5=B9=B6=E9=99=90=E5=88=B6?= =?UTF-8?q?=E9=9D=9E=E6=B3=95=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 ++ .../VVMs/RecipeEditor/EditorNodes.cs | 15 ++++---- .../VVMs/RecipeEditor/RecipeEditor.axaml | 11 +++--- .../RecipeEditor/RecipeEditorViewModel.cs | 17 +++++---- .../Training/RecipeWorkspace.cs | 35 ++++++++++++++++--- tests/Avalonia.Smoke/Program.cs | 12 +++++-- tests/Training.Smoke/Program.cs | 7 +++- 7 files changed, 74 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 517aa51..beac402 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,8 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部 实际配方统一保存在 `recipes/<配方名>/<配方名>.yaml`。新建配方自动创建同名目录;编辑器选择的外部 ONNX 会复制到该配方的 `models`,运行快照保存在 `snaps`。 +配方名同时作为文件名和目录名,编辑器只提供一个名称输入框,保存后名称固定。禁止 `< > : " / \ | ? *`、控制字符、末尾空格或句点及 `CON`、`NUL`、`COM1` 等系统保留名称;不合法时显示原因并禁止保存。已有配方以当前文件名为统一名称。 + 首次启动会从旧 `configs/sop` 和 `workspace/training` 复制配方及关联数据,并修正标注项目、视频、模型和类别注册表的路径。已有的新目录不被旧数据覆盖;原文件保留作回退副本。无法确认归属的公共录像留在原位置。也可运行 `SopHelper.Avalonia --migrate-recipes` 单独完成迁移。 源码运行时 `recipes` 位于仓库根目录,发布程序默认位于程序目录。可通过 `SOPHELPER_WORKSPACE_ROOT` 指定统一数据根目录;升级或搬迁程序时应保留整个 `recipes` 目录。手部模型、SAM2 等共用运行资源仍在程序资源目录。 diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs index 7300aca..8666567 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs @@ -86,7 +86,6 @@ public class EditableList : EditorNode where T : EditorNode, IRemovable, new( /// public class RecipeNode : EditorNode { - private string _fileName = ""; private bool _isNew; private string _name = ""; private string _version = "1.0"; @@ -149,8 +148,8 @@ public class RecipeNode : EditorNode /// 文件名(不含扩展名;新建时可填,之后按它落盘) public string FileName { - get { return _fileName; } - set { SetProperty(ref _fileName, value); } + get { return Name; } + set { Name = value; } } /// 新建(尚未落盘) @@ -180,7 +179,12 @@ public class RecipeNode : EditorNode public string Name { get { return _name; } - set { SetProperty(ref _name, value); } + set + { + if (!SetProperty(ref _name, value)) return; + RaisePropertyChanged(nameof(FileName)); + Changed?.Invoke(); + } } /// 版本(sop.version) @@ -394,9 +398,8 @@ public class RecipeNode : EditorNode { var node = new RecipeNode { - FileName = System.IO.Path.GetFileNameWithoutExtension(fileName), IsNew = isNew, - Name = config.Sop.Name, + Name = isNew ? config.Sop.Name : fileName, Version = config.Sop.Version, Description = config.Sop.Description, }; diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index b0776dd..5961cef 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -93,14 +93,15 @@ - + + - - - + + + @@ -437,4 +438,4 @@ - \ No newline at end of file + diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs index aa8ce82..dab87f7 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditorViewModel.cs @@ -29,6 +29,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware private string _saveStatus = ""; public string SaveStatus { get => _saveStatus; private set => SetProperty(ref _saveStatus, value); } + public string NameValidationMessage => RecipeWorkspace.GetNameError(Recipe.Name) ?? ""; private BitmapSource? _previewImage; private string _previewStatus = "选中一个区域后,在图像上拖动画框;Esc 取消本次绘制"; private bool _isCapturing; @@ -92,7 +93,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware /// public RecipeEditorViewModel() { - SaveCommand = new DelegateCommand(Save, () => !IsCapturing); + SaveCommand = new DelegateCommand(Save, () => !IsCapturing && NameValidationMessage.Length == 0); CloseCommand = new DelegateCommand(() => RequestClose.Invoke(ButtonResult.Cancel), () => !IsCapturing); CaptureImageCommand = new DelegateCommand(async () => await CaptureImageAsync(), () => !IsCapturing && _camera is not null && _cameraInfo is not null); @@ -249,16 +250,15 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware Warnings.Add("相机曝光必须大于 0(微秒),或留空保留相机设置"); return; } - if (string.IsNullOrWhiteSpace(Recipe.Name)) + if (RecipeWorkspace.GetNameError(Recipe.Name) is { } nameError) { - Warnings.Add("配方名(sop.name)不能为空"); + SaveStatus = nameError; return; } - var fileName = string.IsNullOrWhiteSpace(Recipe.FileName) ? Recipe.Name : Recipe.FileName; - - // 只取文件名部分,别让人在这儿塞路径 - fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars())); + var fileName = Recipe.Name; + if (!_isNew && fileName != Path.GetFileNameWithoutExtension(_path)) + { SaveStatus = "已有配方名与文件名一致,不可在编辑器中改名"; return; } var path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName, fileName + ".yaml") : _path; @@ -307,6 +307,9 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware private void RefreshWarnings() { SaveStatus = ""; + RaisePropertyChanged(nameof(NameValidationMessage)); + RaisePropertyChanged(nameof(FileNameText)); + SaveCommand.RaiseCanExecuteChanged(); // 步骤和条件字段变化时同步校验,避免方法已选择却仍显示旧的缺失提示。 var current = new HashSet(Recipe.Steps); foreach (var step in Recipe.Steps) diff --git a/src/SopHelper.CrossPlatform.Engine/Training/RecipeWorkspace.cs b/src/SopHelper.CrossPlatform.Engine/Training/RecipeWorkspace.cs index 22de7e2..9eecd52 100644 --- a/src/SopHelper.CrossPlatform.Engine/Training/RecipeWorkspace.cs +++ b/src/SopHelper.CrossPlatform.Engine/Training/RecipeWorkspace.cs @@ -12,11 +12,23 @@ public sealed class RecipeWorkspace(string root) public string RecipesDirectory => Path.Combine(Root, "recipes"); public string DirectoryFor(string name) { - if (string.IsNullOrWhiteSpace(name) || name is "." or ".." || name.EndsWith('.') || - name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || name.Contains('/') || name.Contains('\\')) - throw new ArgumentException("请先选择有效的配方名"); + if (GetNameError(name) is { } error) throw new ArgumentException(error, nameof(name)); return Path.Combine(RecipesDirectory, name); } + public static string? GetNameError(string name) + { + if (string.IsNullOrWhiteSpace(name)) return "配方名不能为空"; + if (name.Any(c => c < 32 || "<>:\"/\\|?*".Contains(c))) + return "配方名不能包含 < > : \" / \\ | ? * 或控制字符"; + if (name.EndsWith('.') || name.EndsWith(' ')) return "配方名不能以空格或句点结尾"; + var stem = name.Split('.')[0].TrimEnd(' ').ToUpperInvariant(); + if (stem is "CON" or "PRN" or "AUX" or "NUL" || + (stem.Length == 4 && (stem.StartsWith("COM") || stem.StartsWith("LPT")) && "123456789¹²³".Contains(stem[3]))) + return "配方名不能使用系统保留名称(如 CON、NUL、COM1、LPT1)"; + if (System.Text.Encoding.UTF8.GetByteCount(name + ".yaml") > 255) + return "配方名过长,请缩短名称"; + return null; + } public string ConfigPath(string name) => Path.Combine(DirectoryFor(name), name + ".yaml"); public IEnumerable Names() => Directory.Exists(RecipesDirectory) ? Directory.GetDirectories(RecipesDirectory).Select(Path.GetFileName).OfType() @@ -92,7 +104,11 @@ public sealed class RecipeWorkspace(string root) var name = group.Key!; var destination = DirectoryFor(name); var configPath = ConfigPath(name); - if (File.Exists(configPath)) continue; + if (File.Exists(configPath)) + { + NormalizeName(configPath, name); + continue; + } Directory.CreateDirectory(destination); var source = group.OrderByDescending(File.GetLastWriteTimeUtc).First(); var oldTraining = Path.Combine(Root, "workspace", "training", name); @@ -127,6 +143,7 @@ public sealed class RecipeWorkspace(string root) } } var config = SopConfigLoader.Load(source); + config.Sop.Name = name; if (config.Sop.Model is { Path.Length: > 0 } model) { var original = model.Path; @@ -162,6 +179,16 @@ public sealed class RecipeWorkspace(string root) SopConfigLoader.Save(config, configPath + ".migrating"); File.Move(configPath + ".migrating", configPath); } + foreach (var name in Names()) NormalizeName(ConfigPath(name), name); + } + + private static void NormalizeName(string path, string name) + { + var config = SopConfigLoader.Load(path); + if (config.Sop.Name == name) return; + config.Sop.Name = name; + SopConfigLoader.Save(config, path + ".tmp"); + File.Move(path + ".tmp", path, true); } private static void CopyTree(string source, string destination) diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs index f98c693..e989ee8 100644 --- a/tests/Avalonia.Smoke/Program.cs +++ b/tests/Avalonia.Smoke/Program.cs @@ -137,8 +137,16 @@ internal static class Smoke var storage=new RecipeWorkspace(trainer.Root); var createEditor=new RecipeEditorViewModel(); createEditor.OnDialogOpened(new DialogParameters{{"directory",storage.RecipesDirectory},{"new",true},{"config",new SopHelper.Engine.Sop.SopConfig()}}); - createEditor.Recipe.FileName="新建配方";createEditor.Recipe.Name="新建配方";createEditor.SaveCommand.Execute(); - Check(File.Exists(storage.ConfigPath("新建配方")),"Creating a recipe writes its config inside its own named directory"); + foreach(var invalid in new[]{"非法/配方","非法:配方","CON","配方.","配方 ",""}) + { + createEditor.Recipe.Name=invalid; + Check(createEditor.NameValidationMessage.Length>0&&!createEditor.SaveCommand.CanExecute(),"Invalid recipe name disables save and displays the reason: "+invalid); + createEditor.SaveCommand.Execute(); + } + createEditor.Recipe.Name="新建配方.v1"; + Check(createEditor.SaveCommand.CanExecute()&&createEditor.NameValidationMessage.Length==0,"A valid name immediately re-enables save"); + createEditor.SaveCommand.Execute(); + Check(File.Exists(storage.ConfigPath("新建配方.v1"))&&SopHelper.Engine.Sop.SopConfigLoader.Load(storage.ConfigPath("新建配方.v1")).Sop.Name=="新建配方.v1","Recipe name, directory and filename match exactly, including dots"); createEditor.OnDialogClosed(); var recipeCamera=new CameraViewModel(new FakeCamera(),trainer.Root,savedRecipe); recipeCamera.SaveDirectory=Path.GetTempPath(); diff --git a/tests/Training.Smoke/Program.cs b/tests/Training.Smoke/Program.cs index 9d57b9a..a4ec45c 100644 --- a/tests/Training.Smoke/Program.cs +++ b/tests/Training.Smoke/Program.cs @@ -55,8 +55,13 @@ try File.WriteAllText(Path.Combine(legacyConfigs,"配方甲.yaml"),"obsolete");store.Initialize(legacyConfigs); if(SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Name!="配方甲")throw new Exception("Migration overwrote managed settings"); if(!File.Exists(oldProject.FilePath)||!File.Exists(video))throw new Exception("Migration modified original data"); - foreach(var bad in new[]{"..","../escape","a/b","a\\b"}) + foreach(var bad in new[]{"..","../escape","a/b","a\\b","配方:甲","配方*甲","配方?","配方\"","配方<","配方>","配方|","末尾 ","末尾.","CON","nul.txt","COM1","LPT9","COM¹","换\n行",new string('长',100)}) try{store.DirectoryFor(bad);throw new Exception("Unsafe recipe name accepted");}catch(ArgumentException){} + foreach(var good in new[]{"装配线A","配方.v1","配方 甲","COM10","普通配方(测试)"}) + if(RecipeWorkspace.GetNameError(good) is not null)throw new Exception("Valid recipe name rejected: "+good); + var renamedDisplay=SopConfigLoader.Load(store.ConfigPath("配方甲"));renamedDisplay.Sop.Name="另一个显示名称"; + SopConfigLoader.Save(renamedDisplay,store.ConfigPath("配方甲"));store.Initialize(legacyConfigs); + if(SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Name!="配方甲")throw new Exception("Existing recipe name differs from filename"); Console.WriteLine("PASS: Unified recipe migration, model/video copies, registry rebasing, independent config and safe names"); if (args.Length > 0) {