using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using System.Security.Cryptography; using System.Text.Json.Nodes; using System.Text.Json; using System.Text.Json.Serialization; namespace PLCSharp.Models; public sealed record CheckedFlow(Guid Id, string Name, string Path, bool Compiled, List Diagnostics); public sealed record ObjectEdit(string Action, string Kind, Guid Id, string Path, JsonObject Before, JsonObject After, JsonArray WorkflowReferences, JsonArray ConfigReferences, JsonArray ManualReferences, List Workflows) { public List OwnedRows { get; init; } = []; [JsonIgnore] internal List Documents { get; init; } public IEnumerable ChangedFiles => Documents?.Select(d => d.Path) ?? [Path]; public bool Compiled => Workflows.All(f => f.Compiled); public Guid? UndoOf { get; init; } [JsonIgnore] internal string Source { get; init; } [JsonIgnore] internal string Destination { get; init; } [JsonIgnore] internal string Scope { get; init; } [JsonIgnore] internal string SavedScope { get; set; } } public sealed partial class ProjectDirectory { internal static string ObjectGroup(string kind) => ProjectConfiguration.Groups.FirstOrDefault(g => g.Value.Contains(kind)).Key ?? throw new ArgumentException("未知工程配置类型。"); private string ObjectScope() => Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new { files = baseline.OrderBy(k => k.Key), scripts = RenameScope(Guid.Empty) }))); internal static object MaterializeObject(IEntityType entity, JsonObject row) { var item = Activator.CreateInstance(entity.ClrType); foreach (var p in entity.GetProperties()) { var node = row[p.GetColumnName()]; object value; if (node == null) { if (!p.IsNullable) throw new ArgumentException($"{p.GetColumnName()} 不能为空。"); value = null; } else if (ProjectConfiguration.IsJson(p)) { if (node is not (JsonObject or JsonArray)) throw new ArgumentException($"{p.GetColumnName()} 需要对象或数组。"); value = node.ToJsonString(); } else if (p.ClrType == typeof(bool)) value = node.GetValueKind() switch { JsonValueKind.True => true, JsonValueKind.False => false, JsonValueKind.Number when (int)node is 0 or 1 => (int)node == 1, _ => throw new ArgumentException($"{p.GetColumnName()} 需要布尔值。") }; else { value = node.Deserialize(p.ClrType); if (p.ClrType.IsEnum && !Enum.IsDefined(p.ClrType, value)) throw new ArgumentException($"{p.GetColumnName()} 枚举值无效。"); } p.PropertyInfo.SetValue(item, value); } return item; } internal static JsonObject ObjectRow(IEntityType entity, object instance) { var row = new JsonObject(); foreach (var p in entity.GetProperties()) row[p.GetColumnName()] = p.PropertyInfo.GetValue(instance) switch { null => null, Guid g => g.ToString("D").ToUpperInvariant(), bool b => b ? 1 : 0, string s when ProjectConfiguration.IsJson(p) => JsonNode.Parse(s), var val => JsonSerializer.SerializeToNode(val) }; return row; } private static void MergeProperties(JsonObject target, JsonObject patch) { foreach (var (key, value) in patch) { if (target[key] is JsonObject child && value is JsonObject delta) MergeProperties(child, delta); else target[key] = value?.DeepClone(); } } internal ObjectEdit PlanObjectEdit(string action, string kind, Guid? objectId, JsonObject properties) { if (action is not ("create" or "update" or "delete")) throw new ArgumentException("请选择 create、update 或 delete。"); bool create = action == "create"; if (create == objectId.HasValue || (action == "delete" ? properties?.Count > 0 : properties == null)) throw new ArgumentException("新增时由工程分配 ID;修改和删除需要对象 ID。"); var id = objectId ?? Guid.NewGuid(); if (kind is "Recipes" or "Workflows") return PlanStructureEdit(action, kind, id, properties); var path = ConfigPath(ObjectGroup(kind)); var doc = JsonNode.Parse(baseline[path]); var rows = doc[kind].AsArray(); var before = rows.SingleOrDefault(r => Guid.Parse((string)r["ID"]) == id)?.AsObject(); if (!create && before == null) throw new ArgumentException("找不到工程对象。"); var entity = ProjectConfiguration.Entity(Data, kind); JsonObject after = null; if (action != "delete") { after = before?.DeepClone().AsObject() ?? ObjectRow(entity, Activator.CreateInstance(entity.ClrType)); after["ID"] = id.ToString("D").ToUpperInvariant(); foreach (var (key, _) in properties) if (!after.ContainsKey(key) || key == "ID" || !create && key is "Name" or "RecipeID" or "RobotID" or "FuncID") throw new ArgumentException($"不能通过属性修改 {key}。名称请使用重命名工具。"); MergeProperties(after, properties); var normalized = ObjectRow(entity, MaterializeObject(entity, after)); foreach (var p in entity.GetProperties()) { var key = p.GetColumnName(); if (!properties.ContainsKey(key)) continue; if (ProjectConfiguration.IsJson(p)) CheckSuppliedFields(after[key], normalized[key], key); if (p.ClrType == typeof(byte[]) && after[key] != null) { if (Convert.FromBase64String((string)after[key]).Length != 0 && string.IsNullOrEmpty((string)normalized[key])) throw new ArgumentException("图像数据无法解码。"); continue; } after[key] = normalized[key]?.DeepClone(); } ValidateObject(kind, rows, id, before, after); if (JsonNode.DeepEquals(before, after)) throw new ArgumentException("属性没有变化。"); } List owned = []; if (kind == "VisionFunctions" && action == "delete") RemoveOwned(doc, "LocalImageDatas", r => Guid.Parse((string)r["FuncID"]) == id, owned); if (create) rows.Add(after.DeepClone()); else if (after == null) rows.Remove(before); else rows[rows.IndexOf(before)] = after.DeepClone(); return WithOwnedImpact(InspectEdit(action, kind, id, path, before, after, baseline[path], Serialize(doc)), owned); } private static void CheckSuppliedFields(JsonNode supplied, JsonNode actual, string path) { if (supplied is JsonObject obj && actual is JsonObject result) { foreach (var (key, child) in obj) { if (!result.ContainsKey(key)) throw new ArgumentException($"未知字段 {path}.{key}"); CheckSuppliedFields(child, result[key], path + "." + key); } } else if (supplied is JsonArray array && actual is JsonArray saved && array.Count == saved.Count) { for (int i = 0; i < array.Count; i++) CheckSuppliedFields(array[i], saved[i], $"{path}[{i}]"); } else if (!JsonNode.DeepEquals(supplied, actual)) throw new ArgumentException($"字段值无法保存:{path}"); } private void ValidateObject(string kind, JsonArray rows, Guid id, JsonObject before, JsonObject after) { bool Changed(string key) => before == null || !JsonNode.DeepEquals(before[key], after[key]); bool Other(JsonNode r) => Guid.Parse((string)r["ID"]) != id; if (after.ContainsKey("RecipeID") && !Recipes.Any(r => r.ID == Guid.Parse((string)after["RecipeID"]))) throw new ArgumentException("所属配方不存在。"); if (kind is "RobotPoints" or "RobotMatrices") { var owner = Guid.Parse((string)after["RobotID"]); if (!Data.Robots.Any(r => r.ID == owner)) throw new ArgumentException("所属机器人不存在。"); } if (kind == "LocalImageDatas") { var owner = Guid.Parse((string)after["FuncID"]); if (!Data.VisionFunctions.Any(f => f.ID == owner)) throw new ArgumentException("所属视觉功能不存在。"); } if (kind == "CanvasConfigs" && rows.Any(r => Other(r) && (string)r["RecipeID"] == (string)after["RecipeID"])) throw new ArgumentException("一个配方只能配置一张主页画布。"); if (kind == "Controllers" && rows.Any(Other)) throw new ArgumentException("工程只能配置一个运动控制器。"); if (after.ContainsKey("Name") && Changed("Name")) { var name = (string)after["Name"]; if (string.IsNullOrWhiteSpace(name) || name != name.Trim() || rows.Any(r => Other(r) && (string)r["Name"] == name && (string)r["RecipeID"] == (string)after["RecipeID"] && (string)r["RobotID"] == (string)after["RobotID"] && (string)r["FuncID"] == (string)after["FuncID"])) throw new ArgumentException("名称为空、带首尾空白或在所属范围内重名。"); } if (kind is "Variables" or "SystemVariables" && (Changed("Type") || Changed("DefaultValueStr") || Changed("ValueStr"))) { foreach (var field in new[] { "DefaultValueStr", "ValueStr" }) { var text = (string)after[field]; if (!string.IsNullOrEmpty(text) && ((int)after["Type"] switch { 0 => !int.TryParse(text, out _), 1 => !double.TryParse(text, out var number) || !double.IsFinite(number), _ => false })) throw new ArgumentException($"{field} 与变量类型不匹配。"); } } var address = kind switch { "Axes" => "AxisNo", "DI" or "DQ" => "Number", _ => null }; if (address != null && Changed(address) && rows.Any(r => Other(r) && JsonNode.DeepEquals(r[address], after[address]))) throw new ArgumentException($"{address} 在同类设备中重复。"); foreach (var (key, value) in after) { if (!Changed(key) || value is not JsonValue field || !field.TryGetValue(out var name) || string.IsNullOrEmpty(name)) continue; var table = kind switch { "AxisPoints" when AxisNameFields["AxisPoints"].Contains(key) => "Axes", "Cylinders" when key is "InA" or "InB" => "DI", "Cylinders" when key is "OutA" or "OutB" => "DQ", _ => null }; if (table != null && !JsonNode.Parse(baseline[ConfigPath("hardware")])[table].AsArray().Any(r => (string)r["Name"] == name)) throw new ArgumentException($"{key} 引用的 {table} 名称不存在:{name}"); } } internal ObjectEdit UndoObject(Guid operation, ObjectEdit saved) { if (saved.SavedScope != ObjectScope()) throw new ProjectConflictException("工程在保存后已改变,无法撤销。"); var inverse = saved.Action switch { "create" => "delete", "delete" => "create", _ => "update" }; if (saved.Documents != null || saved.OwnedRows.Count != 0) { var undo = saved with { Action = inverse, Workflows = [.. saved.Workflows], Before = saved.After, After = saved.Before, Source = saved.Destination, Destination = saved.Source, Documents = saved.Documents?.Select(d => new DocumentDelta(d.Path, d.After, d.Before)).ToList(), OwnedRows = saved.OwnedRows.Select(r => r with { Restore = !r.Restore }).ToList(), Scope = ObjectScope(), UndoOf = operation }; if (saved.Kind == "Workflows" && undo.After != null) CheckFlowCode(undo, saved.Id, (string)undo.After["Name"], ScriptPath(Guid.Parse((string)undo.After["RecipeID"]), saved.Id), (string)undo.Before?["Code"], (string)undo.After["Code"]); return undo; } return InspectEdit(inverse, saved.Kind, saved.Id, saved.Path, saved.After, saved.Before, saved.Destination, saved.Source) with { UndoOf = operation }; } internal void ApplyObjectEdit(ObjectEdit edit) { lock (Data.Sync) { if (ObjectScope() != edit.Scope || baseline[edit.Path] != edit.Source) throw new ProjectConflictException("配置或脚本已改变,请重新预览。"); if (edit.Documents != null) { ApplyStructureEdit(edit); return; } var current = ProjectConfiguration.Capture(Data, [edit.Kind], false)[edit.Kind].AsArray() .SingleOrDefault(r => Guid.Parse((string)r["ID"]) == edit.Id); if (!JsonNode.DeepEquals(current, edit.Before)) throw new ProjectConflictException("运行工程的对象已改变。"); var entity = ProjectConfiguration.Entity(Data, edit.Kind); var tracked = Data.ChangeTracker.Entries().FirstOrDefault(e => e.Metadata == entity && (Guid)e.Property("ID").CurrentValue == edit.Id); if (tracked != null && tracked.State != EntityState.Unchanged) throw new ProjectConflictException("请先保存对象的编辑。"); var files = new Dictionary(baseline) { [edit.Path] = edit.Destination }; using var tx = Data.Database.BeginTransaction(); if (edit.After != null) ProjectConfiguration.Restore(Data, [edit.Kind], new JsonObject { [edit.Kind] = new JsonArray(edit.After.DeepClone()) }, edit.Before != null); else { // ObjectGroup validates the table against the fixed project schema. string sql = $"DELETE FROM \"{edit.Kind}\" WHERE ID = {{0}}"; if (Data.Database.ExecuteSqlRaw(sql, edit.Id) != 1) throw new ProjectConflictException("对象已删除。"); } ApplyOwnedRows(edit.OwnedRows); WriteFiles(Root, files, baseline.Keys.ToArray(), tx.Commit); DetachDeletedRows(edit.OwnedRows); if (tracked != null) { if (edit.After == null) tracked.State = EntityState.Detached; else tracked.Reload(); } configuration[edit.Path] = edit.Destination; edit.SavedScope = ObjectScope(); } } private ObjectEdit InspectEdit(string action, string kind, Guid id, string path, JsonObject before, JsonObject after, string source, string destination) { var row = before ?? after; var candidate = row.DeepClone().AsObject(); if (kind == "LocalImageDatas") { var owner = Guid.Parse((string)candidate["FuncID"]); candidate["RecipeID"] = Data.VisionFunctions.Where(f => f.ID == owner).Select(f => f.RecipeID).Single().ToString(); } var analysis = Models.WorkflowReferences.Find(this, kind, id.ToString(), forRename: true, candidate: candidate); var hits = analysis["hits"].AsArray(); var confirmed = new JsonArray(); var manual = new JsonArray(); foreach (var hit in hits) ((string)hit["confidence"] == "confirmed" ? confirmed : manual).Add(hit.DeepClone()); var flows = new List(); foreach (var group in hits.GroupBy(h => (Recipe: (Guid)h["recipeId"], Flow: (Guid)h["workflowId"]))) { var flow = Flows(group.Key.Recipe).Single(w => w.ID == group.Key.Flow); var review = WorkflowScriptReview.Create(flow.ID, flow.Code, flow.Code); flows.Add(new(flow.ID, flow.Name, (string)group.First()["path"], review.Compiled, review.Diagnostics)); } foreach (var error in analysis["diagnostics"].AsArray()) { var script = (string)error["path"]; if (flows.Any(f => f.Path == script)) continue; var flowId = Guid.Parse(System.IO.Path.GetFileNameWithoutExtension(script)); var flow = Recipes.SelectMany(r => Flows(r.ID)).Single(w => w.ID == flowId); var review = WorkflowScriptReview.Create(flow.ID, flow.Code, flow.Code); flows.Add(new(flow.ID, flow.Name, script, review.Compiled, review.Diagnostics)); } return new(action, kind, id, path, before, after, confirmed, ConfigurationLinks(kind, row), manual, flows) { Source = source, Destination = destination, Scope = ObjectScope() }; } private JsonArray ConfigurationLinks(string kind, JsonObject target) { var result = new JsonArray(); var name = (string)target["Name"]; foreach (var (group, tables) in ProjectConfiguration.Groups) { var path = ConfigPath(group); var doc = JsonNode.Parse(baseline[path]); foreach (var table in tables) foreach (var row in doc[table].AsArray()) { void Add(string field) => result.Add(new JsonObject { ["path"] = path, ["table"] = table, ["id"] = (string)row["ID"], ["name"] = (string)row["Name"], ["field"] = field }); if (kind == "Controllers" && table is "Axes" or "DI" or "DQ") Add("Controller"); if (kind == "Robots" && table is "RobotPoints" or "RobotMatrices" && string.Equals((string)target["ID"], (string)row["RobotID"], StringComparison.OrdinalIgnoreCase)) Add("RobotID"); bool sameRecipe = string.Equals((string)target["RecipeID"], (string)row["RecipeID"], StringComparison.OrdinalIgnoreCase); if (kind == "CanvasConfigs" && sameRecipe && table == "CustomControls") Add("RecipeID"); if (kind == "VisionFunctions" && table == "LocalImageDatas" && Guid.Parse((string)row["FuncID"]) == Guid.Parse((string)target["ID"])) Add("FuncID"); if (kind == "Recipes" && row["RecipeID"] != null && Guid.Parse((string)row["RecipeID"]) == Guid.Parse((string)target["ID"])) Add("RecipeID"); if (string.IsNullOrEmpty(name)) continue; if (kind == "CustomControls" && table == "VisionFunctions" && sameRecipe && (string)row["ControlName"] == name) Add("ControlName"); if (table == "VisionFunctions" && (sameRecipe || kind == "LocalImageDatas" && Guid.Parse((string)target["FuncID"]) == Guid.Parse((string)row["ID"]))) { var steps = row["VisionFlows"].AsArray(); for (int i = 0; i < steps.Count; i++) { var (key, fallback) = Parameter(kind, (PLCSharp.VVMs.Vision.VisionFlowType)(int)steps[i]["Type"]); if (key == null) continue; var value = (string)steps[i]["StringParams"]?[key]; if ((string.IsNullOrEmpty(value) ? fallback : value) == name) Add($"VisionFlows[{i}].StringParams.{key}"); } } string[] fields = kind switch { "Axes" when AxisNameFields.TryGetValue(table, out var links) => links, "DI" or "DQ" when table == "Cylinders" => CylinderFields(kind), "AxisPoints" when table == "Matrices" && SamePointScope(target, row) => MatrixPointFields, "RobotPoints" when table == "RobotMatrices" && SamePointScope(target, row) => MatrixPointFields, _ => [] }; foreach (var field in fields) if ((string)row[field] == name) Add(field); if (kind == "Cameras" && table == "VisionFunctions") { var steps = row["VisionFlows"].AsArray(); for (int i = 0; i < steps.Count; i++) if ((int)steps[i]["Type"] == (int)PLCSharp.VVMs.Vision.VisionFlowType.拍照 && (string)steps[i]["StringParams"]?["Camera"] == name) Add($"VisionFlows[{i}].StringParams.Camera"); } } } return result; } }