plcsharp/PLCSharpWpf/Models/VariableRename.cs

265 lines
15 KiB
C#

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<RenamedScript> 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
{
"AxisPoints" or "RobotPoints" => "configuration/points.json",
"VisionFunctions" => "configuration/vision.json",
"DI" or "DQ" or "Axes" or "Cylinders" or "Robots" or "Connects" => "configuration/hardware.json",
"Workflows" => $"recipes/{recipe:D}/recipe.json",
_ => ProjectDirectory.VariablesPath
};
public List<PointField> MatrixReferences { get; init; } = [];
public bool IsDevice => Kind is "Cylinders" or "Robots" or "Connects";
public bool IsIo => Kind is "DI" or "DQ";
public List<PointField> CylinderReferences { get; init; } = [];
public List<PointField> 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<Guid> 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)
{
var analysis = WorkflowReferences.Find(this, kind, id.ToString(), forRename: true);
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<RenamedScript>();
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, Scope = RenameScope(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] ||
(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, 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 == "Workflows") CheckWorkflowName(plan.RecipeId, plan.ObjectId, before, after);
else if (plan.Kind == "VisionFunctions") CheckVisionName(plan.RecipeId, 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.RecipeId) != 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";
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))
{
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);
}
}
row[field] = plan.NewName;
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"));
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 ? 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.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("变量已发生变化。");
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 (workflowRename)
{
targetFlow.SetReviewedName(plan.NewName);
return;
}
configuration[plan.MetadataPath] = files[plan.MetadataPath];
if (plan.Kind == "Axes")
configuration[ConfigPath("points")] = files[ConfigPath("points")];
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.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")];
plan.SavedScope = RenameScope(plan.RecipeId);
plan.SavedMetadata = files[plan.MetadataPath];
}
}
}