统一配方名与文件名并限制非法名称

This commit is contained in:
tfarcraw 2026-11-09 14:38:15 +08:00
parent dab92c08e0
commit c2571961c4
7 changed files with 74 additions and 25 deletions

View File

@ -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 等共用运行资源仍在程序资源目录。

View File

@ -86,7 +86,6 @@ public class EditableList<T> : EditorNode where T : EditorNode, IRemovable, new(
/// </summary>
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
/// <summary>文件名(不含扩展名;新建时可填,之后按它落盘)</summary>
public string FileName
{
get { return _fileName; }
set { SetProperty(ref _fileName, value); }
get { return Name; }
set { Name = value; }
}
/// <summary>新建(尚未落盘)</summary>
@ -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();
}
}
/// <summary>版本(sop.version)</summary>
@ -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,
};

View File

@ -93,14 +93,15 @@
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,10">
<StackPanel Grid.Row="0" Margin="0,0,0,10">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" Classes="Title" />
<TextBlock Text="文件名" Margin="24,0,8,0" Classes="Field" />
<TextBox Width="150" IsEnabled="{Binding Recipe.CanEditFileName}" Text="{Binding Recipe.FileName, Mode=TwoWay}" ToolTip.Tip="只有新建时能改——SOP 页是按文件名选配方的" />
<TextBlock Text="配方名" Margin="16,0,8,0" Classes="Field" />
<TextBox Width="170" Text="{Binding Recipe.Name, Mode=TwoWay}" />
<TextBox Width="220" IsEnabled="{Binding Recipe.CanEditFileName}" Text="{Binding Recipe.Name, Mode=TwoWay}" ToolTip.Tip="文件名和目录名自动使用配方名;已有配方名称固定" />
<TextBlock Text="版本" Margin="16,0,8,0" Classes="Field" />
<TextBox Width="60" Text="{Binding Recipe.Version, Mode=TwoWay}" />
</StackPanel>
<TextBlock Text="{Binding NameValidationMessage}" Foreground="#F0533C" TextWrapping="Wrap" Margin="0,6,0,0" />
</StackPanel>
<TabControl Grid.Row="1">
<TabItem Header="步骤">
@ -437,4 +438,4 @@
</StackPanel>
</Grid>
</Grid>
</UserControl>
</UserControl>

View File

@ -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
/// </summary>
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<EditorNode>(Recipe.Steps);
foreach (var step in Recipe.Steps)

View File

@ -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<string> Names() => Directory.Exists(RecipesDirectory)
? Directory.GetDirectories(RecipesDirectory).Select(Path.GetFileName).OfType<string>()
@ -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)

View File

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

View File

@ -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)
{