Review nested vision variables, measurements, interpolation segments and points

This commit is contained in:
wanglei 2026-12-05 22:51:07 +08:00
parent fadcf27b75
commit 2914116b7e
12 changed files with 406 additions and 36 deletions

View File

@ -15,9 +15,9 @@ 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_object_rename"), Description("Preview a rename of any named project object. Use the kind and ID from list_objects. For VisionLocalVariables, ControlMeasurements, InterpolationSegments or InterpolationPoints pass the parent object ID and memberName, plus segmentName for a point. Review configuration, compiled scripts and manual references before applying.")]
public string PreviewObjectRename(string kind, string id, string newName, string memberName = null, string segmentName = null) =>
gateway.Call("previewObjectRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName, ["memberName"] = memberName, ["segmentName"] = segmentName });
[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) =>
@ -58,8 +58,9 @@ internal sealed class ProjectTools(ProjectGateway gateway)
[McpServerTool(Name = "get_change_status", ReadOnly = true), Description("Inspect a pending, rejected or saved draft.")]
public string GetChangeStatus(string draftId) => gateway.Call("status", new() { ["draftId"] = draftId });
[McpServerTool(Name = "find_references", ReadOnly = true), Description("Find C# references to a Variables, SystemVariables, Workflows, VisionFunctions, AxisPoints or RobotPoints ID within its recipe, or an Axes, DI, DQ, Cylinders, Robots or Connects ID across recipes. Dynamic hits require human review.")]
public string FindReferences(string kind, string id) => gateway.Call("references", new() { ["kind"] = kind, ["id"] = id });
[McpServerTool(Name = "find_references", ReadOnly = true), Description("Find workflow references to a named object or nested member. For members supply the parent ID, memberName and, for interpolation points, segmentName.")]
public string FindReferences(string kind, string id, string memberName = null, string segmentName = null) =>
gateway.Call("references", new() { ["kind"] = kind, ["id"] = id, ["memberName"] = memberName, ["segmentName"] = segmentName });
[McpServerTool(Name = "get_project_summary", ReadOnly = true), Description("Read the bound PLCSharp project, default recipe and available object kinds.")]
public string Summary() => gateway.Call("summary", new());

View File

@ -74,6 +74,16 @@ 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 { Nested: not null } member && CurrentRecipe.ID == member.RecipeId)
{
object owner = member.Kind switch
{
"VisionLocalVariables" => VisionsModel.VisionFunctions.Single(f => f.ID == member.ObjectId),
"ControlMeasurements" => CustomControls.Single(c => c.ID == member.ObjectId),
_ => ControllersModel.InterpolationGroups.Single(g => g.ID == member.ObjectId)
};
updateEditorView = ProjectDirectory.PrepareNestedView(member, owner);
}
if (accepted && change.Rename is { IsMatrixOrGroup: true } matrix && CurrentRecipe.ID == matrix.RecipeId)
{
IEnumerable<object> objects = matrix.Kind switch

View File

@ -0,0 +1,59 @@
using PLCSharp.VVMs.Vision;
using System.Text.Json.Nodes;
using static PLCSharp.VVMs.Vision.VisionFlowType;
namespace PLCSharp.Models;
public sealed partial class ProjectDirectory
{
// Each pair is a local variable parameter and its effective handler default.
private static (string Key, string Fallback)[] LocalParameters(VisionFlowType type) => type switch
{
图像校正 => [("MatrixVar", null)],
坐标转换 => [("InputVar", null), ("OutputVar", null)],
矩阵生成 => [("MatrixVar", "生成矩阵")],
两线交点 => [("Line1Var", "None"), ("Line2Var", "None"), ("IntersectOffsetVar", "两线交点_Offset"),
("IntersectResultVar", "两线交点"), ("TwoLine_TransOutVar", null)],
卡尺寻边 => [("EdgeName", "卡尺寻边_Edge"), ("LineOffsetVar", "找线_Offset"), ("Caliper_TransformOutVar", "找线_转换")],
卡尺找圆 => [("CircleResultVar", "卡尺找圆_Circle"), ("CircleOffsetVar", "找圆_Offset"), ("CircleFind_TransOutVar", null)],
卡尺找旋转矩形 => [("RectResultVar", "卡尺找旋转矩形_Rect"), ("RectOffsetVar", "找矩形_Offset"), ("RectFind_TransOutVar", null)],
距离 => [("Var1", "None"), ("Var2", "None"), ("ResultVar", "距离"), ("Dist_TransOutVar", null)],
ORB匹配 => [("ORBMatch_PosVar", "ORB匹配_Pos"), ("ORBMatch_OffsetVar", "ORB匹配_Offset"),
("Orb_TransOutVar", null), ("OrbMatch_OffsetTransVar", null)],
SIFT匹配 => [("SiftMatch_PosVar", "SIFT匹配_Pos"), ("SiftMatch_OffsetVar", "SIFT匹配_Offset"),
("SiftMatch_MatVar", "SIFT匹配_矩阵"), ("Sift_TransOutVar", null), ("SiftMatch_OffsetTransVar", null)],
灰度模板匹配 => [("GrayTemplateMatch_PosVar", "灰度模板匹配_Pos"), ("GrayMatch_TransOutVar", null),
("GrayMatch_OffsetTransVar", null)],
_ => []
};
private static void PlanLocalBindings(ProjectRename plan, JsonNode function)
{
var steps = function["VisionFlows"].AsArray();
for (int i = 0; i < steps.Count; i++)
{
var type = (VisionFlowType)(int)steps[i]["Type"];
var args = steps[i]["StringParams"].AsObject();
string Value(string key, string fallback) => (string)args[key] is { Length: > 0 } value ? value : fallback;
void Set(string key, string next) => plan.VisionReferences.Add(new(plan.ObjectId, i, type, key,
args.ContainsKey(key), (string)args[key], true, next));
foreach (var (key, fallback) in LocalParameters(type))
if (Value(key, fallback) == plan.OldName) Set(key, plan.NewName);
if (type == 灰度模板匹配)
{
var pos = Value("GrayTemplateMatch_PosVar", "灰度模板匹配_Pos");
var offset = Value("GrayMatch_OffsetVar", pos + "_Offset");
if (offset == plan.OldName) Set("GrayMatch_OffsetVar", plan.NewName);
else if (pos == plan.OldName && string.IsNullOrEmpty((string)args["GrayMatch_OffsetVar"]))
Set("GrayMatch_OffsetVar", offset);
}
if (type is ROI解码 or 微信解码)
{
var prefix = Value("ResultVarName", type == ROI解码 ? "条码解码_Result" : "微信解码_Result");
if (plan.OldName == prefix || plan.OldName.StartsWith(prefix + "_", StringComparison.Ordinal))
plan.ManualReferences.Add(new JsonObject { ["confidence"] = "dynamic", ["path"] = plan.MetadataPath,
["expression"] = $"{function["Name"]} / 步骤 {i + 1} / ResultVarName:解码数量决定输出 {prefix} 或 {prefix}_N" });
}
}
}
}

View File

@ -0,0 +1,132 @@
using Microsoft.EntityFrameworkCore;
using PLCSharp.VVMs.Homepage;
using PLCSharp.VVMs.MotionController;
using PLCSharp.VVMs.Vision;
using System.Text.Json.Nodes;
namespace PLCSharp.Models;
public sealed record NestedName(string Kind, string OwnerName, string SegmentName)
{
internal string Table => Kind switch
{
"ControlMeasurements" => "CustomControls", "VisionLocalVariables" => "VisionFunctions",
"InterpolationSegments" or "InterpolationPoints" => "InterpolationGroups",
_ => throw new ArgumentException("未知子对象类型。")
};
internal string Column => Kind switch
{
"ControlMeasurements" => "RangeValues", "VisionLocalVariables" => "VisionParams", _ => "Interpolations"
};
internal JsonNode OwnerRow(JsonNode doc, Guid id) => doc[Table].AsArray().Single(r => Guid.Parse((string)r["ID"]) == id);
internal static T Select<T>(IEnumerable<T> list, Func<T, string> name, string before, string after)
{
var matches = list.Where(o => name(o) == before).Take(2).ToList();
if (matches.Count != 1 || after != null && list.Any(o => name(o) == after))
throw new ProjectConflictException("子对象不存在、位置已改变或在所属范围内重名。");
return matches[0];
}
private void Patch(JsonNode column, string before, string after, bool write)
{
JsonNode segment = null;
var list = Kind == "VisionLocalVariables" ? column["Variables"].AsArray() : column.AsArray();
if (Kind == "InterpolationPoints")
{
segment = Select(list, r => (string)r["Name"], SegmentName, null);
list = JsonNode.Parse((string)segment["SerializedInterpolations"]).AsArray();
}
var target = Select(list, r => (string)r["Name"], before, after);
if (!write) return;
target["Name"] = after;
if (segment != null) segment["SerializedInterpolations"] = list.ToJsonString();
}
internal void Check(ProjectRename plan, JsonNode doc, string before, string after) =>
Patch(OwnerRow(doc, plan.ObjectId)[Column], before, after, false);
internal void EditDocument(ProjectRename plan, JsonNode doc) =>
Patch(OwnerRow(doc, plan.ObjectId)[Column], plan.OldName, plan.NewName, true);
internal string EditColumn(string raw, ProjectRename plan)
{
var column = JsonNode.Parse(raw);
Patch(column, plan.OldName, plan.NewName, true);
return column.ToJsonString();
}
}
public sealed partial class ProjectDirectory
{
internal NestedName DescribeMember(string kind, Guid id, string segmentName)
{
var member = new NestedName(kind, null, segmentName);
var target = ProjectInspection.Query(this, "get", new() { ["kind"] = member.Table, ["id"] = id.ToString() });
return member with { OwnerName = (string)target["Name"] };
}
private ProjectRename PlanNestedRename(string kind, Guid id, string before, string segment, string after)
{
if (string.IsNullOrWhiteSpace(before) || string.IsNullOrWhiteSpace(after) || after != after.Trim() || after == before)
throw new ArgumentException("请给出子对象的原名称及不同的新名称。");
var nested = DescribeMember(kind, id, segment);
var data = JsonNode.Parse(baseline[ProjectRename.PathFor(kind, Guid.Empty)]);
var row = nested.OwnerRow(data, id);
var recipe = Guid.Parse((string)row["RecipeID"]);
var plan = PlanReferences(kind, id, recipe, before, after, nested);
nested.Check(plan, data, before, after);
if (kind == "VisionLocalVariables") PlanLocalBindings(plan, row);
return plan;
}
internal static Action PrepareNestedView(ProjectRename plan, object owner)
{
Action rename;
if (owner is VisionFunction f)
{
var v = NestedName.Select(f.Params.Variables, x => x.Name, plan.OldName, plan.NewName);
rename = () => v.Name = plan.NewName;
}
else if (owner is CustomControl control)
{
var v = NestedName.Select(control.RangeValues, x => x.Name, plan.OldName, plan.NewName);
rename = () => v.Name = plan.NewName;
}
else
{
var group = (InterpolationGroup)owner;
if (plan.Kind == "InterpolationSegments")
{
var v = NestedName.Select(group.Interpolations, x => x.Name, plan.OldName, plan.NewName);
rename = () => v.Name = plan.NewName;
}
else
{
var segment = NestedName.Select(group.Interpolations, x => x.Name, plan.Nested.SegmentName, null);
var v = NestedName.Select(segment.InterpolationPoints, x => x.Name, plan.OldName, plan.NewName);
rename = () => v.Name = plan.NewName;
}
}
var steps = owner is VisionFunction function ? PrepareSteps(plan, [function]) : null;
return () => { rename(); steps?.Invoke(); };
}
private Action WriteNested(ProjectRename plan)
{
var n = plan.Nested;
var id = plan.ObjectId;
object owner = n.Table switch
{
"CustomControls" => Data.CustomControls.Find(id), "VisionFunctions" => Data.VisionFunctions.Find(id),
_ => Data.InterpolationGroups.Find(id)
};
var entry = Data.Entry(owner);
var property = entry.Property("Serialized" + n.Column);
var raw = (string)entry.GetDatabaseValues()[property.Metadata];
var next = n.EditColumn(raw, plan);
// Table and column are fixed by NestedName, all data values are parameters.
string sql = $"UPDATE \"{n.Table}\" SET \"{n.Column}\" = {{0}} WHERE ID = {{1}} AND \"{n.Column}\" = {{2}}";
var update = PrepareNestedView(plan with { VisionReferences = [] }, owner);
if (Data.Database.ExecuteSqlRaw(sql, next, id, raw) != 1) throw new ProjectConflictException("子对象配置已改变。");
var steps = WriteVisionSteps(plan);
return () => { update(); property.OriginalValue = property.CurrentValue; steps(); };
}
}

View File

@ -4,8 +4,9 @@ namespace PLCSharp.Models;
public sealed partial class ProjectDirectory
{
internal ProjectRename PlanObjectRename(string kind, Guid id, string name) => kind switch
internal ProjectRename PlanObjectRename(string kind, Guid id, string name, string memberName = null, string segmentName = null) => kind switch
{
"VisionLocalVariables" or "ControlMeasurements" or "InterpolationSegments" or "InterpolationPoints" => PlanNestedRename(kind, id, memberName, segmentName, name),
"Variables" => PlanRename(id, name),
"Workflows" => PlanWorkflowRename(id, name),
"VisionFunctions" => PlanVisionRename(id, name),

View File

@ -30,7 +30,7 @@ public sealed class ProjectChanges
{
ProjectRename plan;
if (operation == "previewObjectRename")
plan = project.PlanObjectRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]);
plan = project.PlanObjectRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"], (string)args["memberName"], (string)args["segmentName"]);
else if (operation == "previewVisionAssetRename")
plan = project.PlanVisionAssetRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]);
else if (operation == "previewDeviceRename")

View File

@ -9,10 +9,19 @@ public static class ProjectInspection
public static JsonNode Query(ProjectDirectory project, string operation, JsonObject args)
{
if (operation == "references") return WorkflowReferences.Find(project, (string)args["kind"], (string)args["id"]);
if (operation == "references")
{
string type = (string)args["kind"], target = (string)args["id"];
var nested = type is "VisionLocalVariables" or "ControlMeasurements" or "InterpolationSegments" or "InterpolationPoints"
? project.DescribeMember(type, Guid.Parse(target), (string)args["segmentName"]) : null;
if (nested != null && string.IsNullOrEmpty((string)args["memberName"])) throw new ArgumentException("请指定子对象名称。");
return WorkflowReferences.Find(project, type, target, nested: nested, memberName: (string)args["memberName"]);
}
if (operation == "summary")
return JsonSerializer.SerializeToNode(new { project.Id, project.DefaultRecipeId, project.Root, source = "directory",
kinds = Kinds, recipes = project.Recipes.Select(r => new { r.ID, r.Name }) });
kinds = Kinds, nestedKinds = new { VisionLocalVariables = "VisionFunctions.VisionParams.Variables",
ControlMeasurements = "CustomControls.RangeValues", InterpolationSegments = "InterpolationGroups.Interpolations",
InterpolationPoints = "InterpolationGroups.Interpolations.SerializedInterpolations" }, recipes = project.Recipes.Select(r => new { r.ID, r.Name }) });
string kind = (string)args["kind"];
if (!Kinds.Contains(kind)) throw new ArgumentException("Unknown object kind.");
var rows = Rows(project, kind);

View File

@ -20,14 +20,15 @@ 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
{
"Matrices" or "RobotMatrices" or "InterpolationGroups" or "AxisPoints" or "RobotPoints" => "configuration/points.json",
"VisionFunctions" or "ImageDatas" or "LocalImageDatas" => "configuration/vision.json",
"InterpolationSegments" or "InterpolationPoints" or "Matrices" or "RobotMatrices" or "InterpolationGroups" or "AxisPoints" or "RobotPoints" => "configuration/points.json",
"VisionLocalVariables" or "VisionFunctions" or "ImageDatas" or "LocalImageDatas" => "configuration/vision.json",
"Cameras" or "DI" or "DQ" or "Axes" or "Cylinders" or "Robots" or "Connects" => "configuration/hardware.json",
"CustomControls" => "configuration/interface.json",
"ControlMeasurements" or "CustomControls" => "configuration/interface.json",
"Recipes" or "Workflows" => $"recipes/{recipe:D}/recipe.json",
_ => ProjectDirectory.VariablesPath
};
public List<PointField> MatrixReferences { get; init; } = [];
public NestedName Nested { get; init; }
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";
@ -113,9 +114,9 @@ public sealed partial class ProjectDirectory
throw new ProjectConflictException("工作流已更改或配方内存在重名。");
}
private ProjectRename PlanReferences(string kind, Guid id, Guid recipeId, string oldName, string newName)
private ProjectRename PlanReferences(string kind, Guid id, Guid recipeId, string oldName, string newName, NestedName nested = null)
{
var analysis = WorkflowReferences.Find(this, kind, id.ToString(), forRename: true);
var analysis = WorkflowReferences.Find(this, kind, id.ToString(), forRename: true, nested: nested, memberName: oldName);
var hits = analysis["hits"].AsArray();
var manual = new JsonArray();
foreach (var hit in hits.Where(h => (string)h["confidence"] != "confirmed")) manual.Add(hit.DeepClone());
@ -131,7 +132,7 @@ 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(kind == "Recipes" ? Guid.Empty : recipeId), OriginalMetadata = baseline[ProjectRename.PathFor(kind, recipeId)] };
{ Kind = kind, Nested = nested, Scope = RenameScope(kind == "Recipes" ? Guid.Empty : recipeId), OriginalMetadata = baseline[ProjectRename.PathFor(kind, recipeId)] };
}
internal ProjectRename PlanUndo(Guid operationId, ProjectRename saved)
{
@ -143,13 +144,14 @@ public sealed partial class ProjectDirectory
var inverse = saved.Scripts.Select(s => s with { Before = s.After, After = s.Before,
Review = WorkflowScriptReview.Create(s.Id, s.After, s.Before) }).ToList();
return new(saved.ObjectId, saved.RecipeId, saved.NewName, saved.OldName, inverse,
saved.ManualReferences, new JsonArray()) { Kind = saved.Kind, VisionReferences = saved.VisionReferences.Select(e => e.Inverse()).ToList(), OriginalVision = saved.SavedVision, SavedVision = saved.OriginalVision, CylinderReferences = saved.CylinderReferences, PointReferences = saved.PointReferences, OriginalPoints = saved.SavedPoints, SavedPoints = saved.OriginalPoints, MatrixReferences = saved.MatrixReferences, RobotScope = saved.RobotScope, UndoOf = operationId, Scope = saved.SavedScope,
saved.ManualReferences, new JsonArray()) { Kind = saved.Kind, Nested = saved.Nested, VisionReferences = saved.VisionReferences.Select(e => e.Inverse()).ToList(), OriginalVision = saved.SavedVision, SavedVision = saved.OriginalVision, CylinderReferences = saved.CylinderReferences, PointReferences = saved.PointReferences, OriginalPoints = saved.SavedPoints, SavedPoints = saved.OriginalPoints, MatrixReferences = saved.MatrixReferences, RobotScope = saved.RobotScope, UndoOf = operationId, Scope = saved.SavedScope,
OriginalMetadata = saved.SavedMetadata, SavedMetadata = saved.OriginalMetadata };
}
private void CheckName(ProjectRename plan, string before, string after)
{
if (plan.Kind == "Recipes" || plan.IsMatrixOrGroup) CheckAdditionalName(plan.Kind, plan.ObjectId, before, after, plan.UndoOf.HasValue || plan.SavedMetadata != null);
if (plan.Nested != null) plan.Nested.Check(plan, JsonNode.Parse(baseline[plan.MetadataPath]), before, after);
else 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);
@ -171,9 +173,9 @@ public sealed partial class ProjectDirectory
var metadata = JsonNode.Parse(files[plan.MetadataPath]);
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 row = plan.Nested != null ? null : 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)
if (row != null && (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>();
@ -195,7 +197,12 @@ public sealed partial class ProjectDirectory
scripts.Add(path, flow);
}
}
row[field] = plan.NewName;
if (plan.Nested == null) row[field] = plan.NewName;
else
{
plan.Nested.EditDocument(plan, metadata);
foreach (var edit in plan.VisionReferences) edit.Apply(metadata);
}
foreach (var reference in plan.MatrixReferences.Concat(plan.CylinderReferences))
reference.Row(metadata)[reference.Field] = plan.NewName;
if (plan.IsVisionAsset)
@ -248,7 +255,7 @@ public sealed partial class ProjectDirectory
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("变量已发生变化。");
var acceptAsset = plan.IsVisionAsset ? WriteVisionAsset(plan, files) : null;
var acceptAsset = plan.IsVisionAsset ? WriteVisionAsset(plan, files) : plan.Nested != null ? WriteNested(plan) : null;
try { WriteFiles(Root, files, scope.ToArray(), transaction == null ? null : transaction.Commit); }
catch (IOException) when (scope.Any(path => !File.Exists(ProjectFile(Root, path)) ||
File.ReadAllText(ProjectFile(Root, path)) != baseline[path]))
@ -274,6 +281,7 @@ public sealed partial class ProjectDirectory
acceptAsset();
return;
}
if (plan.Nested != null) { acceptAsset(); return; }
if (plan.IsDevice)
{
var device = (INamedDevice)Data.Find(new PointField(plan.Kind, plan.ObjectId, "Name").EntityType, plan.ObjectId);

View File

@ -82,6 +82,7 @@ public sealed partial class ProjectDirectory
CheckAssetName(kind, id, before, after);
var recipe = kind == "Cameras" ? Guid.Empty : Guid.Parse((string)target["RecipeID"]);
var vision = baseline[ConfigPath("vision")];
var plan = PlanReferences(kind, id, recipe, before, after);
List<VisionStepEdit> edits = [];
foreach (var func in JsonNode.Parse(vision)["VisionFunctions"].AsArray())
{
@ -98,11 +99,14 @@ public sealed partial class ProjectDirectory
if (key == null) continue;
var args = steps[i]["StringParams"].AsObject();
var value = (string)args[key];
if (kind == "SystemVariables" && type == VisionFlowType.坐标转换 && before == "标定矩阵" && string.IsNullOrEmpty(value))
plan.ManualReferences.Add(new JsonObject { ["confidence"] = "possible", ["path"] = ConfigPath("vision"),
["expression"] = $"{func["Name"]} / 步骤 {i + 1}:标定命令默认写入标定矩阵,运行步骤尚未选择矩阵。" });
if (!string.IsNullOrEmpty(before) && (string.IsNullOrEmpty(value) ? fallback : value) == before)
edits.Add(new(fid, i, type, key, args.ContainsKey(key), value, true, after));
}
}
return PlanReferences(kind, id, recipe, before, after) with { OriginalVision = vision, VisionReferences = edits };
return plan with { OriginalVision = vision, VisionReferences = edits };
}
private static Action PrepareSteps(ProjectRename plan, IEnumerable<VisionFunction> functions)
@ -184,6 +188,22 @@ public sealed partial class ProjectDirectory
else
count = Data.LocalImageDatas.Where(i => i.ID == id && i.Name == plan.OldName).ExecuteUpdate(s => s.SetProperty(i => i.Name, plan.NewName));
if (count != 1) throw new ProjectConflictException("视觉对象已改变。");
var acceptSteps = WriteVisionSteps(plan);
return () =>
{
target.SetReviewedName(plan.NewName);
Data.Entry((object)target).Property("Name").OriginalValue = plan.NewName;
if (target is CameraBase camera)
{
camera.Params.DiscoveryName = discovery;
Data.Entry(camera).Property(c => c.SerializedParams).OriginalValue = camera.SerializedParams;
}
acceptSteps();
};
}
private Action WriteVisionSteps(ProjectRename plan)
{
List<VisionFunction> tracked = [];
foreach (var group in plan.VisionReferences.GroupBy(e => e.FunctionId))
{
@ -205,13 +225,6 @@ public sealed partial class ProjectDirectory
var update = PrepareSteps(plan, tracked);
return () =>
{
target.SetReviewedName(plan.NewName);
Data.Entry((object)target).Property("Name").OriginalValue = plan.NewName;
if (target is CameraBase camera)
{
camera.Params.DiscoveryName = discovery;
Data.Entry(camera).Property(c => c.SerializedParams).OriginalValue = camera.SerializedParams;
}
update();
foreach (var f in tracked)
{

View File

@ -28,19 +28,23 @@ internal static class WorkflowReferences
.Select(p => MetadataReference.CreateFromFile(p)).ToArray();
});
internal static JsonNode Find(ProjectDirectory project, string kind, string id, bool forRename = false)
internal static JsonNode Find(ProjectDirectory project, string kind, string id, bool forRename = false, NestedName nested = null, string memberName = null)
{
var targetType = kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable),
"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),
"ControlMeasurements" => typeof(PLCSharp.VVMs.Homepage.TableControl.RangeValue), "VisionLocalVariables" => typeof(LocalVariableItem),
"InterpolationSegments" => typeof(Interpolation), "InterpolationPoints" => typeof(InterpolationPoint),
"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 });
var target = ProjectInspection.Query(project, "get", new() { ["kind"] = nested?.Table ?? kind, ["id"] = id });
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 name = nested == null ? (string)target["Name"] : memberName;
var uniqueOwner = nested != null && ProjectConfiguration.Capture(project.Data, [nested.Table], false)[nested.Table].AsArray()
.Count(r => Guid.Parse((string)r["RecipeID"]) == recipeId && (string)r["Name"] == nested.OwnerName) == 1;
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;
@ -90,6 +94,24 @@ internal static class WorkflowReferences
return matches.Length == 1 ? matches[0].ID == ownerId : null;
}
bool? MemberOwner(ExpressionSyntax receiver)
{
bool? NamedLookup(ExpressionSyntax expression, string expectedMethod)
{
if (expression is not InvocationExpressionSyntax get || get.ArgumentList.Arguments.Count != 1 ||
model.GetSymbolInfo(get).Symbol is not IMethodSymbol method || method.Name != expectedMethod ||
method.ContainingType.ToDisplayString() != typeof(GlobalModel).FullName ||
model.GetConstantValue(get.ArgumentList.Arguments[0].Expression) is not { HasValue: true, Value: string label }) return null;
return label != nested.OwnerName ? false : uniqueOwner ? true : null;
}
if (kind == "ControlMeasurements") return NamedLookup(receiver, nameof(GlobalModel.GetCustomControl));
if (kind == "VisionLocalVariables" && receiver is MemberAccessExpressionSyntax parameters &&
model.GetSymbolInfo(parameters).Symbol is IPropertySymbol { Name: "Params" } p &&
p.ContainingType.ToDisplayString() == typeof(VisionFunction).FullName)
return NamedLookup(parameters.Expression, nameof(GlobalModel.GetVisionFunction));
return MatchInterpolationOwner(receiver, model, nested, uniqueOwner);
}
var lookup = kind switch { "ImageDatas" => nameof(GlobalModel.GetImageData), "Variables" => "GetVariable", "Workflows" => "GetTask",
"Robots" => nameof(GlobalModel.GetRobot), "Connects" => nameof(GlobalModel.GetConnect),
"VisionFunctions" => nameof(GlobalModel.GetVisionFunction), _ => null };
@ -97,6 +119,15 @@ internal static class WorkflowReferences
{
var methodName = call.Expression switch { MemberAccessExpressionSyntax m => m.Name.Identifier.ValueText,
MemberBindingExpressionSyntax b => b.Name.Identifier.ValueText, IdentifierNameSyntax n => n.Identifier.ValueText, _ => "" };
if (kind == "ControlMeasurements" && methodName == "SetMeasurementValue" &&
model.GetOperation(call) is IInvocationOperation measure &&
measure.TargetMethod.ContainingType.ToDisplayString() == typeof(PLCSharp.VVMs.Homepage.CustomControl).FullName &&
measure.Arguments.FirstOrDefault(a => a.Parameter?.Name == "name")?.Syntax is ArgumentSyntax item)
{
var owner = MemberOwner((call.Expression as MemberAccessExpressionSyntax)?.Expression);
if (owner != false) Record(item.Expression, call, owner == true);
continue;
}
if (kind == "Connects" && methodName is nameof(ConnectsModel.ApplyAllDataToServer) or nameof(ConnectsModel.ApplyDataItemToServer))
{
if (model.GetOperation(call) is IInvocationOperation operation &&
@ -135,15 +166,51 @@ internal static class WorkflowReferences
{
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")));
current.ContainingType.ToDisplayString() == typeof(GlobalModel).FullName ? true : IsRecipePredicate(member, model, kind, nested != null ? MemberOwner : kind == "LocalImageDatas" ? LocalOwner : IsTargetRobot);
if (bound != false || nested == null && kind is not ("RobotPoints" or "RobotMatrices" or "LocalImageDatas"))
Record(value, comparison, bound == true || (nested == null && !forRename && !projectWide && kind is not ("AxisPoints" or "RobotPoints" or "VisionFunctions" or "ImageDatas" or "LocalImageDatas" or "RobotMatrices" or "Matrices" or "InterpolationGroups" or "CustomControls" or "SystemVariables")));
}
}
}
}
return JsonSerializer.SerializeToNode(new { recipeId, targetId = id, name, hits, diagnostics });
}
private static bool? MatchInterpolationOwner(ExpressionSyntax receiver, SemanticModel model, NestedName nested, bool uniqueOwner)
{
// Only a bound LINQ lookup with one direct name equality proves the owner.
bool TryLookup(ExpressionSyntax expr, Type itemType, string collection, out ExpressionSyntax parent, out string name)
{
parent = null;
name = null;
if (expr is not InvocationExpressionSyntax call ||
model.GetSymbolInfo(call).Symbol is not IMethodSymbol { Name: "First" or "FirstOrDefault" or "Single" or "SingleOrDefault" } m ||
m.ReducedFrom?.ContainingType.ToDisplayString() != "System.Linq.Enumerable" ||
call.Expression is not MemberAccessExpressionSyntax { Expression: MemberAccessExpressionSyntax source } ||
model.GetSymbolInfo(source).Symbol is not IPropertySymbol prop || prop.Name != collection ||
call.ArgumentList.Arguments.Count != 1 || call.ArgumentList.Arguments[0].Expression is not SimpleLambdaExpressionSyntax lambda ||
lambda.Body is not BinaryExpressionSyntax eq || !eq.IsKind(SyntaxKind.EqualsExpression)) return false;
foreach (var (field, value) in new[] { (eq.Left, eq.Right), (eq.Right, eq.Left) })
if (field is MemberAccessExpressionSyntax access && model.GetSymbolInfo(field).Symbol is IPropertySymbol { Name: "Name" } n &&
n.ContainingType.ToDisplayString() == itemType.FullName &&
SymbolEqualityComparer.Default.Equals(model.GetSymbolInfo(access.Expression).Symbol, model.GetDeclaredSymbol(lambda.Parameter)) &&
model.GetConstantValue(value) is { HasValue: true, Value: string label })
{
parent = source.Expression;
name = label;
return true;
}
return false;
}
if (nested.Kind == "InterpolationPoints")
{
if (!TryLookup(receiver, typeof(Interpolation), nameof(InterpolationGroup.Interpolations), out receiver, out var segment)) return null;
if (segment != nested.SegmentName) return false;
}
if (!TryLookup(receiver, typeof(InterpolationGroup), nameof(ControllersModel.InterpolationGroups), out var controller, out var group) ||
model.GetTypeInfo(controller).Type?.ToDisplayString() != typeof(ControllersModel).FullName) return null;
return group != nested.OwnerName ? false : uniqueOwner ? true : null;
}
private static bool? IsRecipePredicate(ExpressionSyntax expression, SemanticModel model, string kind, Func<ExpressionSyntax, bool?> robotOwner)
{
if (expression is not MemberAccessExpressionSyntax access ||
@ -157,6 +224,17 @@ internal static class WorkflowReferences
if (model.GetSymbolInfo(method.Expression).Symbol is not IPropertySymbol source) return null;
return kind switch
{
"VisionLocalVariables" or "ControlMeasurements" or "InterpolationSegments" or "InterpolationPoints"
when method.Expression is MemberAccessExpressionSyntax collection &&
(source.Name, source.ContainingType.ToDisplayString()) switch
{
("Variables", "PLCSharp.VVMs.Vision.VisionParams") => true,
("RangeValues", "PLCSharp.VVMs.Homepage.CustomControl") => true,
("Interpolations", "PLCSharp.VVMs.MotionController.InterpolationGroup") => true,
("InterpolationPoints", "PLCSharp.VVMs.MotionController.Interpolation") => true,
_ => false
} => robotOwner(collection.Expression),
"VisionLocalVariables" or "ControlMeasurements" or "InterpolationSegments" or "InterpolationPoints" => null,
"Cameras" or "ImageDatas" when source.Name == kind && source.ContainingType.ToDisplayString() == typeof(VisionsModel).FullName => true,
"ImageDatas" when source.Name == kind && source.ContainingType.ToDisplayString() == typeof(VisionFunction).FullName => true,
"LocalImageDatas" when source.Name == kind && source.ContainingType.ToDisplayString() == typeof(VisionFunction).FullName &&

View File

@ -11,7 +11,8 @@ public partial class ScriptReviewWindow : Window
InitializeComponent();
if (change.Rename is { } rename)
{
var subject = rename.Kind switch { "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件",
var subject = rename.Kind switch { "VisionLocalVariables" => "视觉局部变量", "ControlMeasurements" => "控件测量项",
"InterpolationSegments" => "插补段", "InterpolationPoints" => "插补段内点", "Recipes" => "配方", "SystemVariables" => "系统变量", "CustomControls" => "主页控件",
"Matrices" => "轴矩阵", "RobotMatrices" => "机器人矩阵", "InterpolationGroups" => "插补组", "Cameras" => "相机", "ImageDatas" => "视觉图像数据", "LocalImageDatas" => "本地图像数据", "Cylinders" => "气缸", "Robots" => "机器人", "Connects" => "通信连接",
"DI" => "数字输入", "DQ" => "数字输出", "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流",
"AxisPoints" or "RobotPoints" => "点位", _ => "变量" };

View File

@ -11,6 +11,64 @@ namespace PLCSharp.Tests;
public class ObjectRenameTests
{
[Fact]
public void NestedMembersChangeOnlyTheirOwnerAndReverseExactly()
{
var root = Directory.CreateTempSubdirectory();
try
{
using var project = ProjectDirectory.New();
var recipe = project.Recipes.Single();
var function = new VisionFunction { RecipeID = recipe.ID, Name = "Inspect" };
function.Params.Variables.Add(new LocalVariableItem("Reading", "Double", 7.0));
var coord = new VisionFlow { Type = VisionFlowType.坐标转换 };
coord.StringParams["InputVar"] = "Reading";
function.VisionFlows.Add(coord);
var control = new CustomControl { RecipeID = recipe.ID, Name = "Table" };
control.RangeValues.Add(new() { Name = "Reading" });
var group = new InterpolationGroup { RecipeID = recipe.ID, Name = "Path" };
var segment = new Interpolation { Name = "Line" };
segment.InterpolationPoints.Add(new() { Name = "End" });
group.Interpolations.Add(segment);
project.Data.AddRange(function, control, group);
var flow = new Workflow { Name = "Inspect", RecipeID = recipe.ID };
flow.Code = $$"""
using PLCSharp.Models;
using PLCSharp.Core.Common;
using System.Linq;
public class Extension_{{flow.ID:N}} {
public void Run(GlobalModel model, FlowModel flow) {
_ = model.GetVisionFunction("Inspect").Params.Variables.First(v => v.Name == "Reading");
model.GetCustomControl("Table").SetMeasurementValue("Reading", 2);
model.GetCustomControl("Table").SetMeasurementValue(flow.Step.ToString(), 3);
_ = model.ControllersModel.InterpolationGroups.First(g => g.Name == "Path").Interpolations.First(s => s.Name == "Line").InterpolationPoints.First(p => p.Name == "End");
}
}
""";
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>();
foreach (var (kind, owner, member, parent) in new[] { ("VisionLocalVariables", function.ID, "Reading", ""),
("ControlMeasurements", control.ID, "Reading", ""), ("InterpolationSegments", group.ID, "Line", ""),
("InterpolationPoints", group.ID, "End", "InterpolationSegments") })
{
var plan = project.PlanObjectRename(kind, owner, kind, member, parent);
Assert.True(plan.Compiled);
Assert.Single(plan.Scripts);
if (kind == "ControlMeasurements") Assert.Single(plan.ManualReferences);
project.ApplyRename(plan);
Assert.Contains($"\"{kind}\"", flow.Code);
history.Push(plan);
}
Assert.Equal("VisionLocalVariables", coord.StringParams["InputVar"]);
Assert.Equal("InterpolationPoints", segment.InterpolationPoints[0].Name);
while (history.TryPop(out var saved)) project.ApplyRename(project.PlanUndo(Guid.NewGuid(), saved));
foreach (var (path, bytes) in initial) Assert.Equal(bytes, File.ReadAllBytes(path));
}
finally { root.Delete(true); }
}
[Fact]
public void SixRemainingKindsCompileSaveAndUndoAsOneSequence()
{