Support every named project object through one reviewed rename tool

This commit is contained in:
wanglei 2026-12-05 22:46:29 +08:00
parent 34f329c532
commit fadcf27b75
13 changed files with 265 additions and 45 deletions

View File

@ -28,7 +28,7 @@ internal sealed class ProjectGateway(string root, bool allowWrite)
return ProjectPipe.Call(root, new() { ["operation"] = operation, ["arguments"] = arguments }, () =>
{
using var project = ProjectDirectory.Open(root);
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status")
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status")
return changes.Execute(project, operation, arguments, allowWrite, change => (change.Review == null && change.Rename == null) || approved);
return ProjectInspection.Query(project, operation, arguments);
}).ToJsonString();

View File

@ -15,6 +15,10 @@ internal sealed class ProjectTools(ProjectGateway gateway)
public string PreviewVisionAssetRename(string kind, string id, string newName) =>
gateway.Call("previewVisionAssetRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName });
[McpServerTool(Name = "preview_object_rename"), Description("Preview a rename of any named project object. Use the kind and ID from list_objects. Review configuration, compiled scripts and manual references before applying.")]
public string PreviewObjectRename(string kind, string id, string newName) =>
gateway.Call("previewObjectRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName });
[McpServerTool(Name = "preview_device_rename"), Description("Preview renaming a Cylinders, Robots or Connects ID. Updates the hardware definition and bound lookups across recipes, compiles affected scripts and lists manual references.")]
public string PreviewDeviceRename(string kind, string id, string newName) =>
gateway.Call("previewDeviceRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName });

View File

@ -32,7 +32,7 @@ public partial class GlobalModel
if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。");
string operation = (string)request["operation"];
var args = request["arguments"].AsObject();
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status")
if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status")
{
if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy))
throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。");
@ -74,8 +74,18 @@ public partial class GlobalModel
updateEditorView = Project.PrepareAxisView(axis, ControllersModel, CurrentRecipe.ID);
if (accepted && change.Rename is { IsIo: true } io)
updateEditorView = Project.PrepareIoView(io, ControllersModel, CylindersModel);
if (accepted && change.Rename is { IsMatrixOrGroup: true } matrix && CurrentRecipe.ID == matrix.RecipeId)
{
IEnumerable<object> objects = matrix.Kind switch
{
"Matrices" => ControllersModel.Matrices,
"InterpolationGroups" => ControllersModel.InterpolationGroups,
_ => RobotModel.Robots.SingleOrDefault(r => r.ID == Project.Data.RobotMatrices.Find(matrix.ObjectId).RobotID)?.RobotMatrices
};
if (objects != null) updateEditorView = Project.PreparePointView(matrix, objects, []);
}
if (accepted && change.Rename is { IsVisionAsset: true } asset)
updateEditorView = Project.PrepareAssetView(asset, VisionsModel, CurrentRecipe.ID);
updateEditorView = Project.PrepareAssetView(asset, VisionsModel, CurrentRecipe.ID, CustomControls, VariablesModel.SystemVariables);
if (accepted && change.Rename is { IsDevice: true } device)
updateEditorView = PrepareDeviceView(device);
return accepted;

View File

@ -0,0 +1,51 @@
using System.Text.Json.Nodes;
namespace PLCSharp.Models;
public sealed partial class ProjectDirectory
{
internal ProjectRename PlanObjectRename(string kind, Guid id, string name) => kind switch
{
"Variables" => PlanRename(id, name),
"Workflows" => PlanWorkflowRename(id, name),
"VisionFunctions" => PlanVisionRename(id, name),
"Axes" => PlanAxisRename(id, name),
"AxisPoints" or "RobotPoints" => PlanPointRename(kind, id, name),
"DI" or "DQ" => PlanIoRename(kind, id, name),
"Cylinders" or "Robots" or "Connects" => PlanDeviceRename(kind, id, name),
"Cameras" or "ImageDatas" or "LocalImageDatas" or "SystemVariables" or "CustomControls" => PlanVisionAssetRename(kind, id, name),
"Recipes" or "Matrices" or "RobotMatrices" or "InterpolationGroups" => PlanAdditionalRename(kind, id, name),
_ => throw new ArgumentException($"对象类型 {kind} 没有可修改的名称。")
};
private ProjectRename PlanAdditionalRename(string kind, Guid id, string name)
{
CheckSavedRecipes();
var row = ProjectInspection.Query(this, "get", new() { ["kind"] = kind, ["id"] = id.ToString() });
string before = (string)row["Name"];
CheckAdditionalName(kind, id, before, name);
Guid recipe = kind == "Recipes" ? id : Guid.Parse((string)row["RecipeID"]);
return PlanReferences(kind, id, recipe, before, name) with
{
RobotScope = kind == "RobotMatrices" ? baseline[ConfigPath("hardware")] : null
};
}
private void CheckAdditionalName(string kind, Guid id, string before, string after, bool inverse = false)
{
if ((!inverse && string.IsNullOrWhiteSpace(after)) || after != after?.Trim() || before == after)
throw new ArgumentException("新名称不能为空、重复或带首尾空白。");
if (kind == "Recipes")
{
CheckSavedRecipes();
if (Recipes.Single(r => r.ID == id).Name != before || Recipes.Any(r => r.ID != id && (r.Name == before || r.Name == after)))
throw new ProjectConflictException("配方名称已改变或存在重名。");
return;
}
var rows = ProjectConfiguration.Capture(Data, [kind], false)[kind].AsArray();
var target = rows.Single(r => Guid.Parse((string)r["ID"]) == id);
if ((string)target["Name"] != before || rows.Any(r => r != target && SamePointScope(target, r) &&
(!string.IsNullOrEmpty(before) && (string)r["Name"] == before || !string.IsNullOrEmpty(after) && (string)r["Name"] == after)))
throw new ProjectConflictException("配置名称已改变或在所属范围内重名。");
}
}

View File

@ -26,10 +26,12 @@ public sealed class ProjectChanges
public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite,
Func<ProjectChange, bool> confirm = null)
{
if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewDeviceRename" or "previewUndo")
if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectRename" or "previewDeviceRename" or "previewUndo")
{
ProjectRename plan;
if (operation == "previewVisionAssetRename")
if (operation == "previewObjectRename")
plan = project.PlanObjectRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]);
else if (operation == "previewVisionAssetRename")
plan = project.PlanVisionAssetRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]);
else if (operation == "previewDeviceRename")
plan = project.PlanDeviceRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]);

View File

@ -20,14 +20,17 @@ public sealed record ProjectRename(Guid ObjectId, Guid RecipeId, string OldName,
public string MetadataPath => PathFor(Kind, RecipeId);
internal static string PathFor(string kind, Guid recipe) => kind switch
{
"AxisPoints" or "RobotPoints" => "configuration/points.json",
"Matrices" or "RobotMatrices" or "InterpolationGroups" or "AxisPoints" or "RobotPoints" => "configuration/points.json",
"VisionFunctions" or "ImageDatas" or "LocalImageDatas" => "configuration/vision.json",
"Cameras" or "DI" or "DQ" or "Axes" or "Cylinders" or "Robots" or "Connects" => "configuration/hardware.json",
"Workflows" => $"recipes/{recipe:D}/recipe.json",
"CustomControls" => "configuration/interface.json",
"Recipes" or "Workflows" => $"recipes/{recipe:D}/recipe.json",
_ => ProjectDirectory.VariablesPath
};
public List<PointField> MatrixReferences { get; init; } = [];
public bool IsVisionAsset => Kind is "Cameras" or "ImageDatas" or "LocalImageDatas";
public bool IsMatrixOrGroup => Kind is "Matrices" or "RobotMatrices" or "InterpolationGroups";
internal Guid ScriptScope => Kind == "Recipes" ? Guid.Empty : RecipeId;
public bool IsVisionAsset => Kind is "CustomControls" or "SystemVariables" or "Cameras" or "ImageDatas" or "LocalImageDatas";
public List<VisionStepEdit> VisionReferences { get; init; } = [];
[JsonIgnore] internal string OriginalVision { get; init; }
[JsonIgnore] internal string SavedVision { get; set; }
@ -128,11 +131,11 @@ public sealed partial class ProjectDirectory
WorkflowScriptReview.Create(flow.ID, flow.Code, next)));
}
return new(id, recipeId, oldName, newName, edits, manual, analysis["diagnostics"].AsArray())
{ Kind = kind, Scope = RenameScope(recipeId), OriginalMetadata = baseline[ProjectRename.PathFor(kind, recipeId)] };
{ Kind = kind, Scope = RenameScope(kind == "Recipes" ? Guid.Empty : recipeId), OriginalMetadata = baseline[ProjectRename.PathFor(kind, recipeId)] };
}
internal ProjectRename PlanUndo(Guid operationId, ProjectRename saved)
{
if (saved.SavedScope != RenameScope(saved.RecipeId) || saved.SavedMetadata != baseline[saved.MetadataPath] ||
if (saved.SavedScope != RenameScope(saved.ScriptScope) || saved.SavedMetadata != baseline[saved.MetadataPath] ||
(saved.IsVisionAsset && saved.SavedVision != baseline[ConfigPath("vision")]) ||
(saved.Kind == "Axes" && saved.SavedPoints != baseline[ConfigPath("points")]))
throw new ProjectConflictException("保存后配方脚本或名称文件已改变,无法安全撤销。");
@ -146,7 +149,8 @@ public sealed partial class ProjectDirectory
private void CheckName(ProjectRename plan, string before, string after)
{
if (plan.Kind == "Workflows") CheckWorkflowName(plan.RecipeId, plan.ObjectId, before, after);
if (plan.Kind == "Recipes" || plan.IsMatrixOrGroup) CheckAdditionalName(plan.Kind, plan.ObjectId, before, after, plan.UndoOf.HasValue || plan.SavedMetadata != null);
else if (plan.Kind == "Workflows") CheckWorkflowName(plan.RecipeId, plan.ObjectId, before, after);
else if (plan.Kind == "VisionFunctions") CheckVisionName(plan.RecipeId, plan.ObjectId, before, after);
else if (plan.IsVisionAsset) CheckAssetName(plan.Kind, plan.ObjectId, before, after);
else if (plan.IsIo || plan.IsDevice) CheckHardwareName(plan.Kind, plan.ObjectId, before, after, plan.UndoOf.HasValue || plan.SavedMetadata != null);
@ -160,20 +164,20 @@ public sealed partial class ProjectDirectory
lock (Data.Sync)
{
CheckName(plan, plan.OldName, plan.NewName);
if (RenameScope(plan.RecipeId) != plan.Scope || baseline[plan.MetadataPath] != plan.OriginalMetadata)
if (RenameScope(plan.ScriptScope) != plan.Scope || baseline[plan.MetadataPath] != plan.OriginalMetadata)
throw new ProjectConflictException("变量或工作流已经改变,请重新预览。");
var files = new Dictionary<string, string>(baseline);
bool workflowRename = plan.Kind == "Workflows";
var metadata = JsonNode.Parse(files[plan.MetadataPath]);
var rows = metadata[workflowRename ? "workflows" : plan.Kind].AsArray();
var row = rows.Single(v => Guid.Parse((string)v[workflowRename ? "id" : "ID"]) == plan.ObjectId);
var field = workflowRename ? "name" : "Name";
bool recipeRename = plan.Kind == "Recipes";
var row = recipeRename ? metadata : metadata[workflowRename ? "workflows" : plan.Kind].AsArray().Single(v => Guid.Parse((string)v[workflowRename ? "id" : "ID"]) == plan.ObjectId);
var field = workflowRename || recipeRename ? "name" : "Name";
if ((string)row[field] != plan.OldName)
throw new ProjectConflictException("名称有未保存的编辑,请先保存或还原。");
var scope = new List<string> { "project.json", plan.MetadataPath };
var scripts = new Dictionary<string, PLCSharp.VVMs.Workflows.Workflow>();
foreach (var recipe in RecipeScope(plan.RecipeId))
foreach (var recipe in RecipeScope(plan.ScriptScope))
{
var recipePath = RecipePath(recipe);
var flows = Flows(recipe);
@ -198,19 +202,25 @@ public sealed partial class ProjectDirectory
{
if (baseline[ConfigPath("vision")] != plan.OriginalVision)
throw new ProjectConflictException("视觉配置已经改变,请重新预览。");
var vision = plan.Kind == "Cameras" ? JsonNode.Parse(plan.OriginalVision) : metadata;
bool separate = plan.MetadataPath != ConfigPath("vision");
var vision = separate ? JsonNode.Parse(plan.OriginalVision) : metadata;
foreach (var edit in plan.VisionReferences) edit.Apply(vision);
if (plan.Kind == "Cameras")
{
var parameters = row["Params"].AsObject();
if (parameters["DiscoveryName"] == null) parameters["DiscoveryName"] = plan.OldName;
}
if (separate)
{
scope.Add(ConfigPath("vision"));
files[ConfigPath("vision")] = plan.UndoOf.HasValue ? plan.SavedVision :
plan.VisionReferences.Count == 0 ? plan.OriginalVision : Serialize(vision);
}
}
files[plan.MetadataPath] = plan.UndoOf.HasValue ? plan.SavedMetadata : Serialize(metadata);
if (plan.Kind == "RobotPoints") scope.Add(ConfigPath("hardware"));
if (plan.Kind == "RobotMatrices" && baseline[ConfigPath("hardware")] != plan.RobotScope)
throw new ProjectConflictException("机器人配置已经改变。");
if (plan.Kind is "RobotPoints" or "RobotMatrices") scope.Add(ConfigPath("hardware"));
if (plan.Kind == "Axes")
{
UpdateAxisPointsDocument(plan, files);
@ -230,11 +240,11 @@ public sealed partial class ProjectDirectory
updates = [.. updates, (targetFlow, targetFlow.Code ?? "", targetFlow.Code ?? "")];
PLCSharp.VVMs.Workflows.Workflow.SaveReviewedBatch(updates, () =>
{
using var transaction = workflowRename ? null : Data.Database.BeginTransaction();
using var transaction = workflowRename || recipeRename ? null : Data.Database.BeginTransaction();
if (plan.Kind == "VisionFunctions" && Data.VisionFunctions.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName)
.ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1)
throw new ProjectConflictException("视觉功能已发生变化。");
if (plan.IsPoint || plan.IsIo || plan.IsDevice || plan.Kind == "Axes") WritePointFields(plan);
if (plan.IsMatrixOrGroup || plan.IsPoint || plan.IsIo || plan.IsDevice || plan.Kind == "Axes") WritePointFields(plan);
if (plan.Kind == "Variables" && Data.Variables.Where(v => v.ID == plan.ObjectId && v.Name == plan.OldName)
.ExecuteUpdate(s => s.SetProperty(v => v.Name, plan.NewName)) != 1)
throw new ProjectConflictException("变量已发生变化。");
@ -245,6 +255,11 @@ public sealed partial class ProjectDirectory
{
throw new ProjectConflictException("工程文件已从外部修改,请重新打开并预览。");
}
if (recipeRename)
{
Recipes.Single(r => r.ID == plan.ObjectId).SetReviewedName(plan.NewName);
return;
}
if (workflowRename)
{
targetFlow.SetReviewedName(plan.NewName);
@ -266,7 +281,7 @@ public sealed partial class ProjectDirectory
Data.Entry((object)device).Property("Name").OriginalValue = plan.NewName;
return;
}
if (plan.IsPoint || plan.IsIo || plan.Kind == "Axes")
if (plan.IsMatrixOrGroup || plan.IsPoint || plan.IsIo || plan.Kind == "Axes")
{
AcceptPointFields(plan);
return;
@ -284,7 +299,7 @@ public sealed partial class ProjectDirectory
});
if (plan.Kind == "Axes") plan.SavedPoints = files[ConfigPath("points")];
if (plan.IsVisionAsset) plan.SavedVision = files[ConfigPath("vision")];
plan.SavedScope = RenameScope(plan.RecipeId);
plan.SavedScope = RenameScope(plan.ScriptScope);
plan.SavedMetadata = files[plan.MetadataPath];
}
}

View File

@ -1,6 +1,8 @@
using Microsoft.EntityFrameworkCore;
using PLCSharp.VVMs.Vision;
using PLCSharp.VVMs.Vision.Camera;
using PLCSharp.VVMs.Homepage;
using PLCSharp.VVMs.GlobalVariables;
using System.Text.Json.Nodes;
namespace PLCSharp.Models;
@ -13,7 +15,9 @@ public sealed record VisionStepEdit(Guid FunctionId, int Index, VisionFlowType T
internal void Apply(JsonNode vision)
{
var function = vision["VisionFunctions"].AsArray().Single(f => Guid.Parse((string)f["ID"]) == FunctionId);
ApplyToSteps(function["VisionFlows"]);
if (Index >= 0) ApplyToSteps(function["VisionFlows"]);
else if ((string)function[Key] == Before) function[Key] = After;
else throw new ProjectConflictException("视觉功能的显示控件已改变。");
}
internal void ApplyToSteps(JsonNode steps)
@ -32,14 +36,14 @@ public sealed partial class ProjectDirectory
private static Guid Owner(JsonNode row, string kind) => kind switch
{
"Cameras" => Guid.Empty,
"ImageDatas" => Guid.Parse((string)row["RecipeID"]),
"ImageDatas" or "CustomControls" or "SystemVariables" => Guid.Parse((string)row["RecipeID"]),
"LocalImageDatas" => Guid.Parse((string)row["FuncID"]),
_ => throw new ArgumentException("请选择 Cameras、ImageDatas 或 LocalImageDatas。")
};
private JsonNode CheckAssetName(string kind, Guid id, string before, string after)
{
if (kind is not ("Cameras" or "ImageDatas" or "LocalImageDatas") || string.IsNullOrWhiteSpace(after) ||
if (kind is not ("Cameras" or "ImageDatas" or "LocalImageDatas" or "CustomControls" or "SystemVariables") || string.IsNullOrWhiteSpace(after) ||
after.Trim() != after || after == before) throw new ArgumentException("视觉对象类型或新名称无效。");
var rows = ProjectConfiguration.Capture(Data, [kind], false)[kind].AsArray();
var target = rows.Single(r => Guid.Parse((string)r["ID"]) == id);
@ -51,6 +55,16 @@ public sealed partial class ProjectDirectory
private static (string Key, string Fallback) Parameter(string kind, VisionFlowType type) => (kind, type) switch
{
("CustomControls", VisionFlowType.显示图像到主页) => ("CustomControlName", null),
("SystemVariables", VisionFlowType.坐标转换) => ("TransformMat", null),
("SystemVariables", VisionFlowType.距离) => ("Dist_TransMat", null),
("SystemVariables", VisionFlowType.卡尺寻边) => ("Caliper_TransformMat", null),
("SystemVariables", VisionFlowType.两线交点) => ("TwoLine_TransMat", null),
("SystemVariables", VisionFlowType.灰度模板匹配) => ("GrayMatch_TransMat", null),
("SystemVariables", VisionFlowType.ORB匹配) => ("Orb_TransMat", null),
("SystemVariables", VisionFlowType.SIFT匹配) => ("Sift_TransMat", null),
("SystemVariables", VisionFlowType.卡尺找圆) => ("CircleFind_TransMat", null),
("SystemVariables", VisionFlowType.卡尺找旋转矩形) => ("RectFind_TransMat", null),
("Cameras", VisionFlowType.拍照) => ("Camera", null),
("ImageDatas", VisionFlowType.从全局图像获取图片 or VisionFlowType.存到全局图像) => ("Image", null),
("LocalImageDatas", VisionFlowType.从局部图像获取图片 or VisionFlowType.存到局部图像 or VisionFlowType.图像相减) => ("Image", null),
@ -74,6 +88,8 @@ public sealed partial class ProjectDirectory
var fid = Guid.Parse((string)func["ID"]);
if (kind == "LocalImageDatas" && fid != Owner(target, kind) ||
recipe != Guid.Empty && recipe != Guid.Parse((string)func["RecipeID"])) continue;
if (!string.IsNullOrEmpty(before) && kind == "CustomControls" && (string)func["ControlName"] == before)
edits.Add(new(fid, -1, default, "ControlName", true, before, true, after));
var steps = func["VisionFlows"].AsArray();
for (int i = 0; i < steps.Count; i++)
{
@ -82,7 +98,7 @@ public sealed partial class ProjectDirectory
if (key == null) continue;
var args = steps[i]["StringParams"].AsObject();
var value = (string)args[key];
if ((string.IsNullOrEmpty(value) ? fallback : value) == before)
if (!string.IsNullOrEmpty(before) && (string.IsNullOrEmpty(value) ? fallback : value) == before)
edits.Add(new(fid, i, type, key, args.ContainsKey(key), value, true, after));
}
}
@ -95,6 +111,12 @@ public sealed partial class ProjectDirectory
foreach (var function in functions)
foreach (var edit in plan.VisionReferences.Where(e => e.FunctionId == function.ID))
{
if (edit.Index < 0)
{
if (function.ControlName != edit.Before) throw new ProjectConflictException("显示控件有未保存的编辑。");
actions.Add(() => function.ControlName = edit.After);
continue;
}
var step = function.VisionFlows.ElementAtOrDefault(edit.Index);
if (step?.Type != edit.Type || step.StringParams.TryGetValue(edit.Key, out var previous) != edit.HadValue ||
previous != edit.Before) throw new ProjectConflictException("视觉步骤存在未保存的修改。");
@ -107,11 +129,14 @@ public sealed partial class ProjectDirectory
return () => actions.ForEach(a => a());
}
internal Action PrepareAssetView(ProjectRename plan, VisionsModel model, Guid recipe)
internal Action PrepareAssetView(ProjectRename plan, VisionsModel model, Guid recipe,
IEnumerable<CustomControl> controls, IEnumerable<SystemVariable> systemVariables)
{
if (plan.Kind != "Cameras" && recipe != plan.RecipeId) return null;
IEnumerable<INamedDevice> objects = plan.Kind switch
{
"SystemVariables" => systemVariables,
"CustomControls" => controls,
"Cameras" => model.Cameras,
"ImageDatas" => model.ImageDatas,
_ => model.VisionFunctions.Single(f => f.ID == Data.LocalImageDatas.Find(plan.ObjectId).FuncID).LocalImageDatas
@ -132,6 +157,8 @@ public sealed partial class ProjectDirectory
{
INamedDevice target = plan.Kind switch
{
"SystemVariables" => Data.SystemVariables.Find(plan.ObjectId),
"CustomControls" => Data.CustomControls.Find(plan.ObjectId),
"Cameras" => Data.Cameras.Find(plan.ObjectId),
"ImageDatas" => Data.ImageDatas.Find(plan.ObjectId),
_ => Data.LocalImageDatas.Find(plan.ObjectId)
@ -148,6 +175,10 @@ public sealed partial class ProjectDirectory
count = Data.Cameras.Where(c => c.ID == id && c.Name == plan.OldName)
.ExecuteUpdate(s => s.SetProperty(c => c.Name, plan.NewName).SetProperty(c => c.SerializedParams, json));
}
else if (target is SystemVariable)
count = Data.SystemVariables.Where(i => i.ID == id && i.Name == plan.OldName).ExecuteUpdate(s => s.SetProperty(i => i.Name, plan.NewName));
else if (target is CustomControl)
count = Data.CustomControls.Where(i => i.ID == id && i.Name == plan.OldName).ExecuteUpdate(s => s.SetProperty(i => i.Name, plan.NewName));
else if (target is ImageData)
count = Data.ImageDatas.Where(i => i.ID == id && i.Name == plan.OldName).ExecuteUpdate(s => s.SetProperty(i => i.Name, plan.NewName));
else
@ -157,14 +188,19 @@ public sealed partial class ProjectDirectory
foreach (var group in plan.VisionReferences.GroupBy(e => e.FunctionId))
{
var fid = group.Key;
tracked.Add(Data.VisionFunctions.Find(fid));
foreach (var binding in group.Where(e => e.Index < 0))
if (Data.VisionFunctions.Where(f => f.ID == fid && f.ControlName == binding.Before)
.ExecuteUpdate(s => s.SetProperty(f => f.ControlName, binding.After)) != 1)
throw new ProjectConflictException("视觉功能的控件绑定已改变。");
if (group.All(e => e.Index < 0)) continue;
var raw = Data.VisionFunctions.Where(f => f.ID == fid).Select(f => f.SerializedVisionFlows).Single();
var steps = JsonNode.Parse(raw);
foreach (var edit in group) edit.ApplyToSteps(steps);
foreach (var edit in group.Where(e => e.Index >= 0)) edit.ApplyToSteps(steps);
var json = steps.ToJsonString();
if (Data.VisionFunctions.Where(f => f.ID == fid && f.SerializedVisionFlows == raw)
.ExecuteUpdate(s => s.SetProperty(f => f.SerializedVisionFlows, json)) != 1)
throw new ProjectConflictException("视觉步骤已经改变。");
tracked.Add(Data.VisionFunctions.Find(fid));
}
var update = PrepareSteps(plan, tracked);
return () =>
@ -177,7 +213,13 @@ public sealed partial class ProjectDirectory
Data.Entry(camera).Property(c => c.SerializedParams).OriginalValue = camera.SerializedParams;
}
update();
foreach (var f in tracked) Data.Entry(f).Property(v => v.SerializedVisionFlows).OriginalValue = f.SerializedVisionFlows;
foreach (var f in tracked)
{
if (plan.VisionReferences.Any(e => e.FunctionId == f.ID && e.Index >= 0))
Data.Entry(f).Property(v => v.SerializedVisionFlows).OriginalValue = f.SerializedVisionFlows;
if (plan.VisionReferences.Any(e => e.FunctionId == f.ID && e.Index < 0))
Data.Entry(f).Property(v => v.ControlName).OriginalValue = f.ControlName;
}
};
}
}

View File

@ -34,13 +34,15 @@ internal static class WorkflowReferences
"VisionFunctions" => typeof(VisionFunction), "DI" => typeof(DI), "DQ" => typeof(DQ), "Axes" => typeof(Axis), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint),
"Cylinders" => typeof(Cylinder), "Robots" => typeof(Robot), "Connects" => typeof(Connect),
"Cameras" => typeof(PLCSharp.VVMs.Vision.Camera.CameraBase), "ImageDatas" => typeof(ImageData), "LocalImageDatas" => typeof(LocalImageData),
"Recipes" => typeof(PLCSharp.VVMs.Recipe.Recipe), "CustomControls" => typeof(PLCSharp.VVMs.Homepage.CustomControl),
"Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix), "InterpolationGroups" => typeof(InterpolationGroup),
"Workflows" => typeof(Workflow), _ => throw new ArgumentException("Unsupported reference target.") };
var target = ProjectInspection.Query(project, "get", new() { ["kind"] = kind, ["id"] = id });
bool projectWide = kind is "Axes" or "DI" or "DQ" or "Cylinders" or "Robots" or "Connects" or "Cameras";
bool projectWide = kind is "Axes" or "DI" or "DQ" or "Cylinders" or "Robots" or "Connects" or "Cameras" or "Recipes";
var recipeId = projectWide ? Guid.Empty : Guid.Parse((string)target["RecipeID"]);
var name = (string)target["Name"];
var robotId = kind == "RobotPoints" ? Guid.Parse((string)target["RobotID"]) : Guid.Empty;
var robots = kind == "RobotPoints" ? project.Data.Robots.Select(r => new { r.ID, r.Name }).ToList() : [];
var robotId = kind is "RobotPoints" or "RobotMatrices" ? Guid.Parse((string)target["RobotID"]) : Guid.Empty;
var robots = kind is "RobotPoints" or "RobotMatrices" ? project.Data.Robots.Select(r => new { r.ID, r.Name }).ToList() : [];
var ownerId = kind == "LocalImageDatas" ? Guid.Parse((string)target["FuncID"]) : Guid.Empty;
var owners = kind == "LocalImageDatas" ? project.Data.VisionFunctions.Where(f => f.RecipeID == recipeId)
.Select(f => new { f.ID, f.Name }).ToList() : [];
@ -119,7 +121,7 @@ internal static class WorkflowReferences
Record(unresolved.Expression, call, false);
continue;
}
if (methodName != lookup || call.ArgumentList.Arguments.Count != 1) continue;
if ((methodName != lookup && !(kind == "CustomControls" && methodName is "GetImageControl" or "GetCustomControl")) || call.ArgumentList.Arguments.Count != 1) continue;
var symbol = model.GetSymbolInfo(call).Symbol;
if (symbol != null && symbol.ContainingType?.ToDisplayString() != typeof(GlobalModel).FullName) continue;
Record(call.ArgumentList.Arguments[0].Expression, call, symbol != null);
@ -131,9 +133,11 @@ internal static class WorkflowReferences
if (model.GetSymbolInfo(member).Symbol is IPropertySymbol property && property.Name == "Name" &&
property.ContainingType.ToDisplayString() == targetType.FullName)
{
bool? bound = IsRecipePredicate(member, model, kind, kind == "LocalImageDatas" ? LocalOwner : IsTargetRobot);
if (bound != false || kind is not ("RobotPoints" or "LocalImageDatas"))
Record(value, comparison, bound == true || (!forRename && !projectWide && kind is not ("AxisPoints" or "RobotPoints" or "VisionFunctions" or "ImageDatas" or "LocalImageDatas")));
bool? bound = kind == "Recipes" && member is MemberAccessExpressionSyntax access &&
model.GetSymbolInfo(access.Expression).Symbol is IPropertySymbol { Name: nameof(GlobalModel.CurrentRecipe) } current &&
current.ContainingType.ToDisplayString() == typeof(GlobalModel).FullName ? true : IsRecipePredicate(member, model, kind, kind == "LocalImageDatas" ? LocalOwner : IsTargetRobot);
if (bound != false || kind is not ("RobotPoints" or "RobotMatrices" or "LocalImageDatas"))
Record(value, comparison, bound == true || (!forRename && !projectWide && kind is not ("AxisPoints" or "RobotPoints" or "VisionFunctions" or "ImageDatas" or "LocalImageDatas" or "RobotMatrices" or "Matrices" or "InterpolationGroups" or "CustomControls" or "SystemVariables")));
}
}
}
@ -158,6 +162,12 @@ internal static class WorkflowReferences
"LocalImageDatas" when source.Name == kind && source.ContainingType.ToDisplayString() == typeof(VisionFunction).FullName &&
method.Expression is MemberAccessExpressionSyntax collection => robotOwner(collection.Expression),
"LocalImageDatas" => null,
"Recipes" or "CustomControls" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(GlobalModel).FullName,
"Matrices" or "InterpolationGroups" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(ControllersModel).FullName,
"SystemVariables" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(VariablesModel).FullName,
"RobotMatrices" when source.Name == kind && source.ContainingType.ToDisplayString() == typeof(Robot).FullName &&
method.Expression is MemberAccessExpressionSyntax matrices => robotOwner(matrices.Expression),
"RobotMatrices" => null,
"Cylinders" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(CylinderModel).FullName,
"Robots" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(RobotModel).FullName,
"Connects" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(ConnectsModel).FullName,

View File

@ -1,4 +1,4 @@
using PLCSharp.Models;
using PLCSharp.Models;
using Prism.Mvvm;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
@ -187,7 +187,7 @@ namespace PLCSharp.VVMs.GlobalVariables
/// <summary>
/// 系统全局变量
/// </summary>
public class SystemVariable : BindableBase
public class SystemVariable : BindableBase, PLCSharp.Models.INamedDevice
{
/// <summary>
/// _DatasContext
@ -209,7 +209,9 @@ namespace PLCSharp.VVMs.GlobalVariables
/// <summary>
/// 变量名
/// </summary>
public string Name { get; set; }
private string _systemName;
public string Name { get => _systemName; set => SetProperty(ref _systemName, value); }
void PLCSharp.Models.INamedDevice.SetReviewedName(string value) => Name = value;
/// <summary>
/// 备注

View File

@ -1,4 +1,4 @@
using OpenCvSharp;
using OpenCvSharp;
using OpenCvSharp.WpfExtensions;
using PLCSharp.Core.Common;
using PLCSharp.Core.Tools;
@ -23,7 +23,7 @@ namespace PLCSharp.VVMs.Homepage
/// <summary>
/// Custom控件
/// </summary>
public class CustomControl : BindableBase
public class CustomControl : BindableBase, PLCSharp.Models.INamedDevice
{
/// <summary>
/// 唯一标识
@ -36,6 +36,7 @@ namespace PLCSharp.VVMs.Homepage
/// </summary>
public Guid RecipeID { get; set; }
void PLCSharp.Models.INamedDevice.SetReviewedName(string value) => SetProperty(ref _Name, value, nameof(Name));
private string _Name;
/// <summary>

View File

@ -1,4 +1,4 @@
using Prism.Mvvm;
using Prism.Mvvm;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
@ -15,6 +15,7 @@ namespace PLCSharp.VVMs.Recipe
[Key]
public Guid ID { get; set; } = Guid.NewGuid();
internal void SetReviewedName(string value) => SetProperty(ref _Name, value, nameof(Name));
private string _Name;
/// <summary>

View File

@ -11,7 +11,8 @@ public partial class ScriptReviewWindow : Window
InitializeComponent();
if (change.Rename is { } rename)
{
var subject = rename.Kind switch { "Cameras" => "相机", "ImageDatas" => "视觉图像数据", "LocalImageDatas" => "本地图像数据", "Cylinders" => "气缸", "Robots" => "机器人", "Connects" => "通信连接",
var subject = rename.Kind switch { "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件",
"Matrices" => "轴矩阵", "RobotMatrices" => "机器人矩阵", "InterpolationGroups" => "插补组", "Cameras" => "相机", "ImageDatas" => "视觉图像数据", "LocalImageDatas" => "本地图像数据", "Cylinders" => "气缸", "Robots" => "机器人", "Connects" => "通信连接",
"DI" => "数字输入", "DQ" => "数字输出", "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流",
"AxisPoints" or "RobotPoints" => "点位", _ => "变量" };
Title = $"确认{(rename.UndoOf.HasValue ? "撤销" : "")}{subject}重命名";
@ -20,7 +21,7 @@ public partial class ScriptReviewWindow : Window
CheckResult.Text = $"已通过编译的工作流:{rename.Scripts.Count},需人工核对的引用:{rename.ManualReferences.Count}";
CodeDiff.Text = string.Join("\n", rename.PointReferences.Select(p => $"configuration/points.json · {p.Table}/{p.Id} · {p.Field}:{rename.OldName} → {rename.NewName}")
.Concat(rename.CylinderReferences.Select(p => $"configuration/hardware.json · {p.Table}/{p.Id} · {p.Field}:{rename.OldName} → {rename.NewName}"))
.Concat(rename.VisionReferences.Select(e => $"configuration/vision.json · {e.FunctionId} · 步骤 {e.Index + 1} · {e.Key}:{rename.OldName} → {rename.NewName}"))
.Concat(rename.VisionReferences.Select(e => $"configuration/vision.json · {e.FunctionId} · {(e.Index < 0 ? "功能" : $"步骤 {e.Index + 1}")} · {e.Key}:{rename.OldName} → {rename.NewName}"))
.Concat(rename.MatrixReferences.Select(m => $"{m.Table}/{m.Id} · {m.Field}:{rename.OldName} → {rename.NewName}"))
.Concat(rename.ManualReferences.Select(h =>
$"待核对 [{h["confidence"]}] {h["path"]}:{h["line"]} {h["expression"]}"))

View File

@ -0,0 +1,81 @@
using PLCSharp.Models;
using PLCSharp.VVMs.GlobalVariables;
using PLCSharp.VVMs.Homepage;
using PLCSharp.VVMs.MotionController;
using PLCSharp.VVMs.Robots;
using PLCSharp.VVMs.Vision;
using PLCSharp.VVMs.Workflows;
using System.IO;
namespace PLCSharp.Tests;
public class ObjectRenameTests
{
[Fact]
public void SixRemainingKindsCompileSaveAndUndoAsOneSequence()
{
var root = Directory.CreateTempSubdirectory();
try
{
using var project = ProjectDirectory.New();
var recipe = project.Recipes.Single();
recipe.Name = "Product";
var other = new PLCSharp.VVMs.Recipe.Recipe { Name = "Other" };
project.Recipes.Add(other);
var robot = new Robot { Name = "Robot" };
var matrix = new Matrix { RecipeID = recipe.ID, Name = "Grid" };
var grid = new RobotMatrix { RecipeID = recipe.ID, RobotID = robot.ID, Name = "Grid" };
var group = new InterpolationGroup { RecipeID = recipe.ID, Name = "Path" };
var system = new SystemVariable { RecipeID = recipe.ID, Name = "Transform" };
var control = new CustomControl { RecipeID = recipe.ID, Name = "Display" };
var function = new VisionFunction { RecipeID = recipe.ID, Name = "Inspect", ControlName = "Display" };
var step = new VisionFlow { Type = VisionFlowType.坐标转换 };
step.StringParams["TransformMat"] = system.Name;
function.VisionFlows.Add(step);
var display = new VisionFlow { Type = VisionFlowType.显示图像到主页 };
display.StringParams["CustomControlName"] = control.Name;
function.VisionFlows.Add(display);
project.Data.AddRange(robot, matrix, grid, group, system, control, function);
var flow = new Workflow { RecipeID = recipe.ID, Name = "Check" };
flow.Code = $$"""
using System.Linq;
using PLCSharp.Models;
using PLCSharp.Core.Common;
public class Extension_{{flow.ID:N}} {
public void Run(GlobalModel model, FlowModel flow) {
_ = model.CurrentRecipe.Name == "Product";
_ = model.ControllersModel.Matrices.First(m => m.Name == "Grid");
_ = model.GetRobot("Robot").RobotMatrices.First(m => m.Name == "Grid");
_ = model.ControllersModel.InterpolationGroups.First(g => g.Name == "Path");
_ = model.VariablesModel.SystemVariables.First(v => v.Name == "Transform");
_ = model.GetCustomControl("Display");
_ = model.GetCustomControl(flow.Step.ToString());
}
}
""";
project.Flows(recipe.ID).Add(flow);
project.Save(root.FullName);
var initial = Directory.GetFiles(root.FullName, "*", SearchOption.AllDirectories).ToDictionary(p => p, File.ReadAllBytes);
var history = new Stack<ProjectRename>();
Assert.ThrowsAny<IOException>(() => project.PlanObjectRename("Recipes", recipe.ID, other.Name));
foreach (var (kind, id) in new[] { ("Recipes", recipe.ID), ("Matrices", matrix.ID), ("RobotMatrices", grid.ID),
("InterpolationGroups", group.ID), ("SystemVariables", system.ID), ("CustomControls", control.ID) })
{
var plan = project.PlanObjectRename(kind, id, kind);
Assert.True(plan.Compiled);
Assert.Single(plan.Scripts);
if (kind == "CustomControls") Assert.Single(plan.ManualReferences);
project.ApplyRename(plan);
Assert.Contains($"\"{kind}\"", flow.Code);
history.Push(plan);
}
Assert.Equal("SystemVariables", step.StringParams["TransformMat"]);
Assert.Equal("CustomControls", function.ControlName);
Assert.Equal("CustomControls", display.StringParams["CustomControlName"]);
while (history.TryPop(out var saved)) project.ApplyRename(project.PlanUndo(Guid.NewGuid(), saved));
Assert.Equal(initial.Keys.Order(), Directory.GetFiles(root.FullName, "*", SearchOption.AllDirectories).Order());
foreach (var (path, bytes) in initial) Assert.Equal(bytes, File.ReadAllBytes(path));
}
finally { root.Delete(true); }
}
}