diff --git a/PLCSharp.Mcp/ProjectGateway.cs b/PLCSharp.Mcp/ProjectGateway.cs index af70ed2..96ab9af 100644 --- a/PLCSharp.Mcp/ProjectGateway.cs +++ b/PLCSharp.Mcp/ProjectGateway.cs @@ -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 "previewUndo" or "apply" or "status") + if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" 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(); diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs index c3fe64b..0c90a38 100644 --- a/PLCSharp.Mcp/ProjectTools.cs +++ b/PLCSharp.Mcp/ProjectTools.cs @@ -11,6 +11,10 @@ internal sealed class ProjectTools(ProjectGateway gateway) public string PreviewVisionFunctionRename(string id, string newName) => gateway.Call("previewVisionRename", new() { ["id"] = id, ["newName"] = newName }); + [McpServerTool(Name = "preview_io_rename"), Description("Preview renaming a DI or DQ channel across the project, including cylinder bindings and compiled workflow references.")] + public string PreviewIoRename(string kind, string id, string newName) => + gateway.Call("previewIoRename", new() { ["kind"] = kind, ["id"] = id, ["newName"] = newName }); + [McpServerTool(Name = "preview_axis_rename"), Description("Preview a project-wide motion axis rename by ID, including point and interpolation configuration, compiled workflow edits and dynamic references.")] public string PreviewAxisRename(string id, string newName) => gateway.Call("previewAxisRename", new() { ["id"] = id, ["newName"] = newName }); @@ -42,7 +46,7 @@ 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 ID across recipes. Dynamic hits require human review.")] + [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 or DQ 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 = "get_project_summary", ReadOnly = true), Description("Read the bound PLCSharp project, default recipe and available object kinds.")] diff --git a/PLCSharpWpf/Models/AxisRename.cs b/PLCSharpWpf/Models/AxisRename.cs index e4acf60..f895ce3 100644 --- a/PLCSharpWpf/Models/AxisRename.cs +++ b/PLCSharpWpf/Models/AxisRename.cs @@ -36,10 +36,7 @@ public sealed partial class ProjectDirectory internal ProjectRename PlanAxisRename(Guid id, string newName) { - var manifest = JsonNode.Parse(baseline["project.json"]); - var savedRecipes = manifest["recipes"].AsArray().Select(r => Guid.Parse((string)r)).ToHashSet(); - if (!savedRecipes.SetEquals(Recipes.Select(r => r.ID))) - throw new ProjectConflictException("请先保存配方列表,再预览工程轴重命名。"); + CheckSavedRecipes(); var axis = Data.Axes.Single(a => a.ID == id); CheckAxisName(id, axis.Name, newName); var points = baseline[ConfigPath("points")]; @@ -50,6 +47,15 @@ public sealed partial class ProjectDirectory }; } + private void CheckSavedRecipes() + { + var manifest = JsonNode.Parse(baseline["project.json"]); + var savedRecipes = manifest["recipes"].AsArray().Select(r => Guid.Parse((string)r)).ToHashSet(); + if (!savedRecipes.SetEquals(Recipes.Select(r => r.ID))) + throw new ProjectConflictException("请先保存配方列表,再预览硬件重命名。"); + + } + private static void UpdateAxisPointsDocument(ProjectRename plan, Dictionary files) { var path = ConfigPath("points"); diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs index 5a3c579..42b3ad5 100644 --- a/PLCSharpWpf/Models/GlobalModel.Project.cs +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -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 "previewUndo" or "apply" or "status") + if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewUndo" or "apply" or "status") { if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); @@ -72,6 +72,8 @@ public partial class GlobalModel } if (accepted && change.Rename is { Kind: "Axes" } axis) updateEditorView = Project.PrepareAxisView(axis, ControllersModel, CurrentRecipe.ID); + if (accepted && change.Rename is { IsIo: true } io) + updateEditorView = Project.PrepareIoView(io, ControllersModel, CylindersModel); return accepted; }); if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke(); diff --git a/PLCSharpWpf/Models/IoRename.cs b/PLCSharpWpf/Models/IoRename.cs new file mode 100644 index 0000000..81bfb9d --- /dev/null +++ b/PLCSharpWpf/Models/IoRename.cs @@ -0,0 +1,70 @@ +using PLCSharp.VVMs.Cylinders; +using PLCSharp.VVMs.MotionController; +using System.Text.Json.Nodes; + +namespace PLCSharp.Models; + +public sealed partial class ProjectDirectory +{ + private static string[] CylinderFields(string kind) => kind switch + { + "DI" => ["InA", "InB"], "DQ" => ["OutA", "OutB"], + _ => throw new ArgumentException("请选择 DI 或 DQ。") + }; + + private void CheckIoName(string kind, Guid id, string before, string after, bool inverse) + { + if ((!inverse && string.IsNullOrWhiteSpace(after)) || after != after?.Trim() || before == after) + throw new ArgumentException("请输入不同的新名称,首尾不能有空白。"); + var rows = kind == "DI" ? Data.DI.Select(p => new { p.ID, p.Name }) : Data.DQ.Select(p => new { p.ID, p.Name }); + if (!rows.Any(p => p.ID == id && p.Name == before) || rows.Any(p => p.ID != id && + ((before != null && before != "" && p.Name == before) || (after != null && after != "" && p.Name == after)))) + throw new ProjectConflictException("通道已更改或同类通道存在重名。"); + } + + internal ProjectRename PlanIoRename(string kind, Guid id, string newName) + { + var fields = CylinderFields(kind); + CheckSavedRecipes(); + var hardware = JsonNode.Parse(baseline[ConfigPath("hardware")]); + var old = (string)new PointField(kind, id, "Name").Row(hardware)["Name"]; + CheckIoName(kind, id, old, newName, false); + var links = new List(); + foreach (var row in hardware["Cylinders"].AsArray()) + foreach (var field in fields) + { + var name = (string)row[field]; + if (name == newName) throw new ProjectConflictException($"气缸 {row["Name"]} 的 {field} 已引用新名称。"); + if (!string.IsNullOrEmpty(old) && name == old) + links.Add(new("Cylinders", Guid.Parse((string)row["ID"]), field)); + } + return PlanReferences(kind, id, Guid.Empty, old, newName) with { CylinderReferences = links }; + } + + internal Action PrepareIoView(ProjectRename plan, ControllersModel controllers, CylinderModel cylinders) + { + IEnumerable channels = plan.Kind == "DI" ? controllers.DI : controllers.DQ; + var entries = channels.Select(c => Data.Entry(c)).ToList(); + var target = entries.SingleOrDefault(e => (Guid)e.Property("ID").CurrentValue == plan.ObjectId); + if (target == null || (string)target.Property("Name").CurrentValue != plan.OldName || + entries.Any(e => e != target && e.Property("Name").CurrentValue is string name && name.Length > 0 && + (name == plan.OldName || name == plan.NewName))) + throw new ProjectConflictException("编辑器中的通道名称已改变,请先保存。"); + + var links = plan.CylinderReferences.ToHashSet(); + var updates = new List { () => target.Property("Name").CurrentValue = plan.NewName }; + foreach (var cylinder in cylinders.Cylinders) + foreach (var field in CylinderFields(plan.Kind)) + { + var property = Data.Entry(cylinder).Property(field); + var name = (string)property.CurrentValue; + bool referencesOld = !string.IsNullOrEmpty(name) && name == plan.OldName; + if ((!string.IsNullOrEmpty(name) && name == plan.NewName) || + links.Remove(new("Cylinders", cylinder.ID, field)) != referencesOld) + throw new ProjectConflictException("编辑器中的气缸绑定已改变,请先保存。"); + if (referencesOld) updates.Add(() => property.CurrentValue = plan.NewName); + } + if (links.Count != 0) throw new ProjectConflictException("气缸列表已改变,请先保存。"); + return () => updates.ForEach(update => update()); + } +} diff --git a/PLCSharpWpf/Models/PointRename.cs b/PLCSharpWpf/Models/PointRename.cs index db7ad21..0755a25 100644 --- a/PLCSharpWpf/Models/PointRename.cs +++ b/PLCSharpWpf/Models/PointRename.cs @@ -11,6 +11,7 @@ public sealed record PointField(string Table, Guid Id, string Field) .Single(row => Guid.Parse((string)row["ID"]) == Id); internal Type EntityType => Table switch { + "DI" => typeof(DI), "DQ" => typeof(DQ), "Cylinders" => typeof(PLCSharp.VVMs.Cylinders.Cylinder), "Axes" => typeof(Axis), "InterpolationGroups" => typeof(InterpolationGroup), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint), "Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix), @@ -69,7 +70,7 @@ public sealed partial class ProjectDirectory } private static IEnumerable PointFields(ProjectRename plan) => - plan.MatrixReferences.Concat(plan.PointReferences).Prepend(new(plan.Kind, plan.ObjectId, "Name")); + plan.MatrixReferences.Concat(plan.PointReferences).Concat(plan.CylinderReferences).Prepend(new(plan.Kind, plan.ObjectId, "Name")); private void WritePointFields(ProjectRename plan) { @@ -79,7 +80,7 @@ public sealed partial class ProjectDirectory if ((string)entry.Property(f.Field).CurrentValue != plan.OldName) throw new ProjectConflictException("点位配置存在未保存的修改。"); // Table and column names come solely from the fixed project schema above. - string sql = $"UPDATE \"{f.Table}\" SET \"{f.Field}\" = {{0}} WHERE ID = {{1}} AND \"{f.Field}\" = {{2}}"; + string sql = $"UPDATE \"{f.Table}\" SET \"{f.Field}\" = {{0}} WHERE ID = {{1}} AND \"{f.Field}\" IS {{2}}"; if (Data.Database.ExecuteSqlRaw(sql, plan.NewName, f.Id, plan.OldName) != 1) throw new ProjectConflictException("点位或矩阵已改变,请重新预览。"); } diff --git a/PLCSharpWpf/Models/ProjectChanges.cs b/PLCSharpWpf/Models/ProjectChanges.cs index f2ac3c0..0401e36 100644 --- a/PLCSharpWpf/Models/ProjectChanges.cs +++ b/PLCSharpWpf/Models/ProjectChanges.cs @@ -26,10 +26,12 @@ public sealed class ProjectChanges public JsonNode Execute(ProjectDirectory project, string operation, JsonObject args, bool allowWrite, Func confirm = null) { - if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewUndo") + if (operation is "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewUndo") { ProjectRename plan; - if (operation == "previewAxisRename") + if (operation == "previewIoRename") + plan = project.PlanIoRename((string)args["kind"], Guid.Parse((string)args["id"]), (string)args["newName"]); + else if (operation == "previewAxisRename") plan = project.PlanAxisRename(Guid.Parse((string)args["id"]), (string)args["newName"]); else if (operation == "previewVisionRename") plan = project.PlanVisionRename(Guid.Parse((string)args["id"]), (string)args["newName"]); diff --git a/PLCSharpWpf/Models/VariableRename.cs b/PLCSharpWpf/Models/VariableRename.cs index c0a41a5..34ff63c 100644 --- a/PLCSharpWpf/Models/VariableRename.cs +++ b/PLCSharpWpf/Models/VariableRename.cs @@ -22,11 +22,13 @@ public sealed record ProjectRename(Guid ObjectId, Guid RecipeId, string OldName, { "AxisPoints" or "RobotPoints" => "configuration/points.json", "VisionFunctions" => "configuration/vision.json", - "Axes" => "configuration/hardware.json", + "DI" or "DQ" or "Axes" => "configuration/hardware.json", "Workflows" => $"recipes/{recipe:D}/recipe.json", _ => ProjectDirectory.VariablesPath }; public List MatrixReferences { get; init; } = []; + public bool IsIo => Kind is "DI" or "DQ"; + public List CylinderReferences { get; init; } = []; public List PointReferences { get; init; } = []; [JsonIgnore] internal string OriginalPoints { get; init; } [JsonIgnore] internal string SavedPoints { get; set; } @@ -132,7 +134,7 @@ 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, 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, 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 }; } @@ -140,6 +142,7 @@ public sealed partial class ProjectDirectory { 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.IsIo) CheckIoName(plan.Kind, plan.ObjectId, before, after, plan.UndoOf.HasValue || plan.SavedMetadata != null); else if (plan.Kind == "Axes") CheckAxisName(plan.ObjectId, before, after); else if (plan.IsPoint) ValidatePoint(plan, before, after); else CheckVariableName(plan.RecipeId, plan.ObjectId, before, after); @@ -182,7 +185,7 @@ public sealed partial class ProjectDirectory } } row[field] = plan.NewName; - foreach (var reference in plan.MatrixReferences) + foreach (var reference in plan.MatrixReferences.Concat(plan.CylinderReferences)) reference.Row(metadata)[reference.Field] = plan.NewName; files[plan.MetadataPath] = plan.UndoOf.HasValue ? plan.SavedMetadata : Serialize(metadata); if (plan.Kind == "RobotPoints") scope.Add(ConfigPath("hardware")); @@ -209,7 +212,7 @@ public sealed partial class ProjectDirectory 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.Kind == "Axes") WritePointFields(plan); + if (plan.IsPoint || plan.IsIo || 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("变量已发生变化。"); @@ -227,7 +230,7 @@ public sealed partial class ProjectDirectory configuration[plan.MetadataPath] = files[plan.MetadataPath]; if (plan.Kind == "Axes") configuration[ConfigPath("points")] = files[ConfigPath("points")]; - if (plan.IsPoint || plan.Kind == "Axes") + if (plan.IsPoint || plan.IsIo || plan.Kind == "Axes") { AcceptPointFields(plan); return; diff --git a/PLCSharpWpf/Models/WorkflowReferences.cs b/PLCSharpWpf/Models/WorkflowReferences.cs index bc2da15..3fa2fa6 100644 --- a/PLCSharpWpf/Models/WorkflowReferences.cs +++ b/PLCSharpWpf/Models/WorkflowReferences.cs @@ -29,16 +29,16 @@ internal static class WorkflowReferences internal static JsonNode Find(ProjectDirectory project, string kind, string id, bool forRename = false) { var targetType = kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable), - "VisionFunctions" => typeof(VisionFunction), "Axes" => typeof(Axis), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint), + "VisionFunctions" => typeof(VisionFunction), "DI" => typeof(DI), "DQ" => typeof(DQ), "Axes" => typeof(Axis), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint), "Workflows" => typeof(Workflow), _ => throw new ArgumentException("Unsupported reference target.") }; var target = ProjectInspection.Query(project, "get", new() { ["kind"] = kind, ["id"] = id }); - var recipeId = kind == "Axes" ? Guid.Empty : Guid.Parse((string)target["RecipeID"]); + var recipeId = kind is "Axes" or "DI" or "DQ" ? 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 hits = new List(); var diagnostics = new List(); - foreach (var recipe in project.Recipes.Where(r => kind == "Axes" || r.ID == recipeId)) + foreach (var recipe in project.Recipes.Where(r => kind is "Axes" or "DI" or "DQ" || r.ID == recipeId)) foreach (var workflow in project.Flows(recipe.ID)) { var tree = CSharpSyntaxTree.ParseText(workflow.Code ?? ""); @@ -51,7 +51,7 @@ internal static class WorkflowReferences void Record(ExpressionSyntax value, SyntaxNode location, bool bound) { var constant = model.GetConstantValue(value); - if (constant.HasValue && !Equals(constant.Value, name)) return; + if (constant.HasValue && (string.IsNullOrEmpty(name) || !Equals(constant.Value, name))) return; var position = location.GetLocation().GetLineSpan().StartLinePosition; hits.Add(new { recipeId = recipe.ID, workflowId = workflow.ID, workflow.Name, path, line = position.Line + 1, column = position.Character + 1, start = value.SpanStart, length = value.Span.Length, expression = location.ToString(), @@ -105,7 +105,7 @@ internal static class WorkflowReferences { bool? bound = IsRecipePredicate(member, model, kind, IsTargetRobot); if (bound != false || kind != "RobotPoints") - Record(value, comparison, bound == true || (!forRename && kind is not ("Axes" or "AxisPoints" or "RobotPoints" or "VisionFunctions"))); + Record(value, comparison, bound == true || (!forRename && kind is not ("DI" or "DQ" or "Axes" or "AxisPoints" or "RobotPoints" or "VisionFunctions"))); } } } @@ -127,7 +127,7 @@ internal static class WorkflowReferences { "VisionFunctions" => source.Name == nameof(VisionsModel.VisionFunctions) && source.ContainingType.ToDisplayString() == typeof(VisionsModel).FullName, - "Axes" => source.Name == nameof(ControllersModel.Axes) && + "DI" or "DQ" or "Axes" => source.Name == kind && (source.ContainingType.ToDisplayString() == typeof(ControllersModel).FullName || source.ContainingType.ToDisplayString() == typeof(Controller).FullName && method.Expression is MemberAccessExpressionSyntax axes && diff --git a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs index 57c560d..42ab47b 100644 --- a/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs +++ b/PLCSharpWpf/VVMs/Workflows/ScriptReviewWindow.xaml.cs @@ -11,13 +11,14 @@ public partial class ScriptReviewWindow : Window InitializeComponent(); if (change.Rename is { } rename) { - var subject = rename.Kind switch { "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流", + var subject = rename.Kind switch { "DI" => "数字输入", "DQ" => "数字输出", "Axes" => "运动轴", "VisionFunctions" => "视觉功能", "Workflows" => "工作流", "AxisPoints" or "RobotPoints" => "点位", _ => "变量" }; Title = $"确认{(rename.UndoOf.HasValue ? "撤销" : "")}{subject}重命名"; WorkflowTitle.Text = $"{rename.OldName} → {rename.NewName}"; Location.Text = System.IO.Path.Combine(root, change.Path); 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.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"]}")) diff --git a/Tests/PLCSharp.Tests/IoRenameTests.cs b/Tests/PLCSharp.Tests/IoRenameTests.cs new file mode 100644 index 0000000..fb7e8f2 --- /dev/null +++ b/Tests/PLCSharp.Tests/IoRenameTests.cs @@ -0,0 +1,43 @@ +using PLCSharp.Models; +using PLCSharp.VVMs.Cylinders; +using PLCSharp.VVMs.MotionController; +using System.IO; + +namespace PLCSharp.Tests; + +public class IoRenameTests +{ + [Fact] + public void SameNamedInputAndOutputKeepSeparateBindingsAndUndoInReverseOrder() + { + var root = Directory.CreateTempSubdirectory(); + try + { + using var p = ProjectDirectory.New(); + var input = new DI { Name = "A" }; + var output = new DQ { Name = "A" }; + var unnamed = new DI(); + var cylinder = new Cylinder { InA = "A", OutA = "A" }; + p.Data.AddRange(input, output, unnamed, cylinder); + p.Save(root.FullName); + var path = Path.Combine(root.FullName, "configuration", "hardware.json"); + var original = File.ReadAllBytes(path); + var a = p.PlanIoRename("DI", input.ID, "Input"); + p.ApplyRename(a); + Assert.Equal("Input", cylinder.InA); + Assert.Equal("A", cylinder.OutA); + var b = p.PlanIoRename("DQ", output.ID, "Output"); + p.ApplyRename(b); + Assert.ThrowsAny(() => p.PlanUndo(Guid.NewGuid(), a)); + p.ApplyRename(p.PlanUndo(Guid.NewGuid(), b)); + p.ApplyRename(p.PlanUndo(Guid.NewGuid(), a)); + var firstName = p.PlanIoRename("DI", unnamed.ID, "New"); + Assert.Empty(firstName.CylinderReferences); + p.ApplyRename(firstName); + p.ApplyRename(p.PlanUndo(Guid.NewGuid(), firstName)); + Assert.Null(unnamed.Name); + Assert.Equal(original, File.ReadAllBytes(path)); + } + finally { root.Delete(true); } + } +}