using Microsoft.CodeAnalysis.CSharp; using Microsoft.EntityFrameworkCore; using System.IO; using Microsoft.CodeAnalysis.Text; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; namespace PLCSharp.Models; public sealed record RenamedScript(Guid Id, string Name, string Path, string Before, string After, WorkflowScriptReview Review); public sealed record ProjectRename(Guid ObjectId, Guid RecipeId, string OldName, string NewName, List Scripts, JsonArray ManualReferences, JsonArray ScanDiagnostics) { public string Kind { get; init; } = "Variables"; public Guid? VariableId => Kind == "Variables" ? ObjectId : null; public bool IsPoint => Kind is "AxisPoints" or "RobotPoints"; public string MetadataPath => PathFor(Kind, RecipeId); internal static string PathFor(string kind, Guid recipe) => kind switch { "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", "ControlMeasurements" or "CustomControls" => "configuration/interface.json", "Recipes" or "Workflows" => $"recipes/{recipe:D}/recipe.json", _ => ProjectDirectory.VariablesPath }; public List 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"; public List VisionReferences { get; init; } = []; [JsonIgnore] internal string OriginalVision { get; init; } [JsonIgnore] internal string SavedVision { get; set; } public bool IsDevice => Kind is "Cylinders" or "Robots" or "Connects"; 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; } [JsonIgnore] internal string RobotScope { get; init; } public bool Compiled => Scripts.All(s => s.Review.Compiled) && ScanDiagnostics.Count == 0; [JsonIgnore] internal string Scope { get; init; } [JsonIgnore] internal string OriginalMetadata { get; init; } [JsonIgnore] internal string SavedScope { get; set; } [JsonIgnore] internal string SavedMetadata { get; set; } public Guid? UndoOf { get; init; } } public sealed partial class ProjectDirectory { internal const string VariablesPath = "configuration/variables.json"; private IEnumerable RecipeScope(Guid recipe) => recipe == Guid.Empty ? Recipes.Select(r => r.ID).OrderBy(id => id) : [recipe]; internal string RenameScope(Guid recipe) { var inputs = RecipeScope(recipe).Select(id => new { id, scripts = Flows(id).OrderBy(w => w.ID).Select(w => new { w.ID, w.Name, w.Code }) }); return Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(inputs))); } internal void CheckVariableName(Guid recipe, Guid id, string oldName, string newName) { if (string.IsNullOrWhiteSpace(newName) || newName != newName.Trim() || newName == oldName) throw new ArgumentException("请输入不同的新名称,首尾不能有空白。"); var rows = Data.Variables.Where(v => v.RecipeID == recipe).ToList(); if (!rows.Any(v => v.ID == id && v.Name == oldName) || rows.Any(v => v.ID != id && (v.Name == oldName || v.Name == newName))) throw new ProjectConflictException("变量已更改或配方内存在重名。"); } internal ProjectRename PlanRename(Guid id, string newName) { var variable = Data.Variables.Single(v => v.ID == id); CheckVariableName(variable.RecipeID, id, variable.Name, newName); return PlanReferences("Variables", id, variable.RecipeID, variable.Name, newName); } internal ProjectRename PlanVisionRename(Guid id, string newName) { var target = Data.VisionFunctions.Single(v => v.ID == id); CheckVisionName(target.RecipeID, id, target.Name, newName); return PlanReferences("VisionFunctions", id, target.RecipeID, target.Name, newName); } private void CheckVisionName(Guid recipe, Guid id, string before, string after) { if (string.IsNullOrWhiteSpace(after) || after != after.Trim() || before == after) throw new ArgumentException("请输入不同的新名称,首尾不能有空白。"); var rows = Data.VisionFunctions.Where(v => v.RecipeID == recipe); if (!rows.Any(v => v.ID == id && v.Name == before) || rows.Any(v => v.ID != id && (v.Name == before || v.Name == after))) throw new ProjectConflictException("视觉功能已改变或配方内存在重名。"); } internal ProjectRename PlanWorkflowRename(Guid id, string newName) { var workflow = Recipes.SelectMany(r => Flows(r.ID)).Single(w => w.ID == id); CheckWorkflowName(workflow.RecipeID, id, workflow.Name, newName); return PlanReferences("Workflows", id, workflow.RecipeID, workflow.Name, newName); } private void CheckWorkflowName(Guid recipeId, Guid id, string oldName, string newName) { if (string.IsNullOrWhiteSpace(newName) || newName != newName.Trim() || newName == oldName) throw new ArgumentException("请输入不同的新名称,首尾不能有空白。"); var flows = Flows(recipeId); if (!flows.Any(w => w.ID == id && w.Name == oldName) || flows.Any(w => w.ID != id && (w.Name == oldName || w.Name == newName))) throw new ProjectConflictException("工作流已更改或配方内存在重名。"); } 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, 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()); var edits = new List(); foreach (var group in hits.Where(h => (string)h["confidence"] == "confirmed").GroupBy(h => (Recipe: (Guid)h["recipeId"], Flow: (Guid)h["workflowId"]))) { var flow = Flows(group.Key.Recipe).Single(w => w.ID == group.Key.Flow); string replacement = SymbolDisplay.FormatLiteral(newName, quote: true); var changes = group.Select(h => new TextChange(new TextSpan((int)h["start"], (int)h["length"]), replacement)) .Distinct().OrderBy(c => c.Span.Start); var next = SourceText.From(flow.Code).WithChanges(changes).ToString(); edits.Add(new(flow.ID, flow.Name, ScriptPath(group.Key.Recipe, flow.ID), flow.Code, next, WorkflowScriptReview.Create(flow.ID, flow.Code, next))); } return new(id, recipeId, oldName, newName, edits, manual, analysis["diagnostics"].AsArray()) { Kind = kind, Nested = nested, 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.ScriptScope) || saved.SavedMetadata != baseline[saved.MetadataPath] || (saved.IsVisionAsset && saved.SavedVision != baseline[ConfigPath("vision")]) || (saved.Kind == "Axes" && saved.SavedPoints != baseline[ConfigPath("points")])) throw new ProjectConflictException("保存后配方脚本或名称文件已改变,无法安全撤销。"); CheckName(saved, saved.NewName, saved.OldName); 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, 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.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); else if (plan.IsIo || plan.IsDevice) CheckHardwareName(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); } internal void ApplyRename(ProjectRename plan) { lock (Data.Sync) { CheckName(plan, plan.OldName, plan.NewName); if (RenameScope(plan.ScriptScope) != plan.Scope || baseline[plan.MetadataPath] != plan.OriginalMetadata) throw new ProjectConflictException("变量或工作流已经改变,请重新预览。"); var files = new Dictionary(baseline); bool workflowRename = plan.Kind == "Workflows"; var metadata = JsonNode.Parse(files[plan.MetadataPath]); bool recipeRename = plan.Kind == "Recipes"; 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 (row != null && (string)row[field] != plan.OldName) throw new ProjectConflictException("名称有未保存的编辑,请先保存或还原。"); var scope = new List { "project.json", plan.MetadataPath }; var scripts = new Dictionary(); foreach (var recipe in RecipeScope(plan.ScriptScope)) { var recipePath = RecipePath(recipe); var flows = Flows(recipe); var persisted = JsonNode.Parse(files[recipePath])["workflows"].AsArray() .ToDictionary(w => Guid.Parse((string)w["id"]), w => (string)w["name"]); if (flows.Count != persisted.Count || flows.Any(w => !persisted.TryGetValue(w.ID, out var name) || w.Name != name)) throw new ProjectConflictException("请先保存工作流列表。"); if (recipePath != plan.MetadataPath) scope.Add(recipePath); foreach (var flow in flows) { var path = ScriptPath(recipe, flow.ID); if (!files.TryGetValue(path, out var code) || code != (flow.Code ?? "")) throw new ProjectConflictException($"工作流 {flow.Name} 有未保存的编辑,请保存后重新预览。"); scope.Add(path); scripts.Add(path, flow); } } 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) { if (baseline[ConfigPath("vision")] != plan.OriginalVision) throw new ProjectConflictException("视觉配置已经改变,请重新预览。"); 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 == "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); scope.Add(ConfigPath("points")); } foreach (var script in plan.Scripts) { if (files[script.Path] != script.Before) throw new ProjectConflictException($"工作流 {script.Name} 存在未保存编辑。"); files[script.Path] = script.After; } // Hold each affected workflow's execution gate through the single multi-file commit. var updates = plan.Scripts.Select(s => (Flow: scripts[s.Path], s.Before, s.After)).ToArray(); var targetFlow = workflowRename ? scripts[ScriptPath(plan.RecipeId, plan.ObjectId)] : null; if (workflowRename && updates.All(edit => edit.Flow != targetFlow)) updates = [.. updates, (targetFlow, targetFlow.Code ?? "", targetFlow.Code ?? "")]; PLCSharp.VVMs.Workflows.Workflow.SaveReviewedBatch(updates, () => { 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.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("变量已发生变化。"); 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])) { throw new ProjectConflictException("工程文件已从外部修改,请重新打开并预览。"); } if (recipeRename) { Recipes.Single(r => r.ID == plan.ObjectId).SetReviewedName(plan.NewName); return; } if (workflowRename) { targetFlow.SetReviewedName(plan.NewName); return; } configuration[plan.MetadataPath] = files[plan.MetadataPath]; if (plan.Kind == "Axes") configuration[ConfigPath("points")] = files[ConfigPath("points")]; if (plan.IsVisionAsset) { configuration[ConfigPath("vision")] = files[ConfigPath("vision")]; 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); device.SetReviewedName(plan.NewName); Data.Entry((object)device).Property("Name").OriginalValue = plan.NewName; return; } if (plan.IsMatrixOrGroup || plan.IsPoint || plan.IsIo || plan.Kind == "Axes") { AcceptPointFields(plan); return; } if (plan.Kind == "VisionFunctions") { var vision = Data.VisionFunctions.Find(plan.ObjectId); vision.SetReviewedName(plan.NewName); Data.Entry(vision).Property(v => v.Name).OriginalValue = plan.NewName; return; } var variable = Data.Variables.Local.Single(v => v.ID == plan.ObjectId); variable.Name = plan.NewName; Data.Entry(variable).Property(v => v.Name).OriginalValue = plan.NewName; }); if (plan.Kind == "Axes") plan.SavedPoints = files[ConfigPath("points")]; if (plan.IsVisionAsset) plan.SavedVision = files[ConfigPath("vision")]; plan.SavedScope = RenameScope(plan.ScriptScope); plan.SavedMetadata = files[plan.MetadataPath]; } } }