plcsharp/PLCSharpWpf/Models/ObjectEdit.cs

291 lines
16 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<ScriptDiagnostic> Diagnostics);
public sealed record ObjectEdit(string Action, string Kind, Guid Id, string Path, JsonObject Before, JsonObject After,
JsonArray WorkflowReferences, JsonArray ConfigReferences, JsonArray ManualReferences, List<CheckedFlow> Workflows)
{
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) => kind switch
{
"Variables" => "variables", "AxisPoints" or "RobotPoints" => "points",
"Controllers" or "Axes" or "DI" or "DQ" or "Cylinders" or "Robots" or "Connects" or "Cameras" => "hardware",
_ => 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();
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")
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);
after[key] = normalized[key]?.DeepClone();
}
ValidateObject(kind, rows, id, before, after);
if (JsonNode.DeepEquals(before, after)) throw new ArgumentException("属性没有变化。");
}
if (create) rows.Add(after.DeepClone());
else if (after == null) rows.Remove(before);
else rows[rows.IndexOf(before)] = after.DeepClone();
return InspectEdit(action, kind, id, path, before, after, baseline[path], Serialize(doc));
}
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 == "RobotPoints")
{
var owner = Guid.Parse((string)after["RobotID"]);
if (!Data.Robots.Any(r => r.ID == owner)) 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"]))
throw new ArgumentException("名称为空、带首尾空白或在所属范围内重名。");
}
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<string>(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" };
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("配置或脚本已改变,请重新预览。");
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<string, string>(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.
if (Data.Database.ExecuteSqlRaw($"DELETE FROM \"{edit.Kind}\" WHERE ID = {{0}}", edit.Id) != 1)
throw new ProjectConflictException("对象已删除。");
}
WriteFiles(Root, files, baseline.Keys.ToArray(), tx.Commit);
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 analysis = Models.WorkflowReferences.Find(this, kind, id.ToString(), forRename: true, candidate: row);
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<CheckedFlow>();
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");
if (string.IsNullOrEmpty(name)) continue;
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;
}
}