Support transactional recipe, workflow and remaining configuration object edits

This commit is contained in:
wanglei 2026-12-05 23:31:57 +08:00
parent 6a0fe33820
commit bcd8c02b85
4 changed files with 401 additions and 13 deletions

View File

@ -11,6 +11,9 @@ public sealed record CheckedFlow(Guid Id, string Name, string Path, bool Compile
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 List<OwnedRow> OwnedRows { get; init; } = [];
[JsonIgnore] internal List<DocumentDelta> Documents { get; init; }
public IEnumerable<string> 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; }
@ -21,12 +24,8 @@ public sealed record ObjectEdit(string Action, string Kind, Guid Id, string Path
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("请选择配方变量、点位或硬件配置对象。")
};
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
{
@ -96,6 +95,7 @@ public sealed partial class ProjectDirectory
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();
@ -108,7 +108,7 @@ public sealed partial class ProjectDirectory
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")
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));
@ -117,15 +117,24 @@ public sealed partial class ProjectDirectory
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<OwnedRow> 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 InspectEdit(action, kind, id, path, before, after, baseline[path], Serialize(doc));
return WithOwnedImpact(InspectEdit(action, kind, id, path, before, after, baseline[path], Serialize(doc)), owned);
}
private static void CheckSuppliedFields(JsonNode supplied, JsonNode actual, string path)
@ -151,20 +160,27 @@ public sealed partial class ProjectDirectory
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")
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["RecipeID"] == (string)after["RecipeID"] && (string)r["RobotID"] == (string)after["RobotID"] && (string)r["FuncID"] == (string)after["FuncID"]))
throw new ArgumentException("名称为空、带首尾空白或在所属范围内重名。");
}
if (kind == "Variables" && (Changed("Type") || Changed("DefaultValueStr") || Changed("ValueStr")))
if (kind is "Variables" or "SystemVariables" && (Changed("Type") || Changed("DefaultValueStr") || Changed("ValueStr")))
{
foreach (var field in new[] { "DefaultValueStr", "ValueStr" })
{
@ -196,6 +212,16 @@ public sealed partial class ProjectDirectory
{
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 };
}
@ -206,6 +232,7 @@ public sealed partial class ProjectDirectory
{
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("运行工程的对象已改变。");
@ -223,7 +250,9 @@ public sealed partial class ProjectDirectory
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;
@ -237,7 +266,13 @@ public sealed partial class ProjectDirectory
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 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();
@ -278,7 +313,25 @@ public sealed partial class ProjectDirectory
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,

View File

@ -0,0 +1,269 @@
using Microsoft.EntityFrameworkCore;
using PLCSharp.VVMs.Recipe;
using PLCSharp.VVMs.Workflows;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
namespace PLCSharp.Models;
internal sealed record DocumentDelta(string Path, string Before, string After);
public sealed record OwnedRow(string Kind, Guid Id, string Name, [property: JsonIgnore] JsonObject Row, bool Restore = false);
public sealed partial class ProjectDirectory
{
private static void RemoveOwned(JsonNode document, string table, Func<JsonNode, bool> match, List<OwnedRow> owned)
{
var rows = document[table].AsArray();
foreach (var row in rows.Where(match).ToList())
{
owned.Add(new(table, Guid.Parse((string)row["ID"]), (string)row["Name"], row.AsObject()));
rows.Remove(row);
}
}
private ObjectEdit WithOwnedImpact(ObjectEdit edit, List<OwnedRow> owned)
{
foreach (var child in owned)
{
var impact = InspectEdit("delete", child.Kind, child.Id, ConfigPath(ObjectGroup(child.Kind)), child.Row, null, null, null);
MergeImpact(edit, impact);
}
return edit with { OwnedRows = owned };
}
private static void MergeImpact(ObjectEdit target, ObjectEdit child)
{
foreach (var (list, hits) in new[] { (target.WorkflowReferences, child.WorkflowReferences),
(target.ManualReferences, child.ManualReferences), (target.ConfigReferences, child.ConfigReferences) })
foreach (var hit in hits)
{
var entry = hit.DeepClone();
entry["affectedKind"] = child.Kind;
entry["affectedId"] = child.Id.ToString();
list.Add(entry);
}
foreach (var flow in child.Workflows)
if (target.Workflows.All(w => w.Id != flow.Id)) target.Workflows.Add(flow);
}
private void ApplyOwnedRows(IEnumerable<OwnedRow> rows)
{
foreach (var row in rows)
{
if (row.Restore)
ProjectConfiguration.Restore(Data, [row.Kind], new JsonObject { [row.Kind] = new JsonArray(row.Row.DeepClone()) });
else
{
var type = ProjectConfiguration.Entity(Data, row.Kind);
if (Data.ChangeTracker.Entries().Any(e => e.Metadata == type && (Guid)e.Property("ID").CurrentValue == row.Id && e.State != EntityState.Unchanged))
throw new ProjectConflictException($"子对象 {row.Kind}/{row.Id} 有未保存的编辑。");
string sql = $"DELETE FROM \"{type.GetTableName()}\" WHERE ID = {{0}}";
if (Data.Database.ExecuteSqlRaw(sql, row.Id) != 1) throw new ProjectConflictException("所属配置已改变。");
}
}
}
private void DetachDeletedRows(IEnumerable<OwnedRow> rows)
{
var removed = rows.Where(r => !r.Restore).Select(r => (r.Kind, r.Id)).ToHashSet();
if (removed.Count == 0) return;
foreach (var entry in Data.ChangeTracker.Entries().ToList())
if (entry.Metadata.FindProperty("ID")?.ClrType == typeof(Guid) &&
removed.Contains((entry.Metadata.GetTableName(), (Guid)entry.Property("ID").CurrentValue))) entry.State = EntityState.Detached;
}
private static JsonObject FlowRow(Workflow flow) => new()
{
["ID"] = flow.ID.ToString(), ["RecipeID"] = flow.RecipeID.ToString(), ["Name"] = flow.Name,
["Comment"] = flow.Comment, ["Code"] = flow.Code ?? "", ["AutomaticExecution"] = flow.AutomaticExecution, ["CycleDelayTime"] = flow.CycleDelayTime
};
private static JsonObject RecipeRow(Recipe r) => new() { ["ID"] = r.ID.ToString(), ["Name"] = r.Name, ["Comment"] = r.Comment };
private ObjectEdit PlanStructureEdit(string action, string kind, Guid id, JsonObject patch)
{
bool recipe = kind == "Recipes";
var targetRecipe = Recipes.SingleOrDefault(r => r.ID == id);
var targetFlow = recipe ? null : Recipes.SelectMany(r => Flows(r.ID)).SingleOrDefault(w => w.ID == id);
JsonObject before = recipe ? targetRecipe == null ? null : RecipeRow(targetRecipe) : targetFlow == null ? null : FlowRow(targetFlow);
if ((action == "create") != (before == null)) throw new ArgumentException("工程对象不存在或 ID 已占用。");
Guid owner = recipe ? id : targetFlow?.RecipeID ?? Guid.Parse((string)patch["RecipeID"]);
if (!recipe && !Recipes.Any(r => r.ID == owner)) throw new ArgumentException("所属配方不存在。");
string path = recipe ? "project.json" : RecipePath(owner);
JsonObject after = null;
if (action != "delete")
{
after = before?.DeepClone().AsObject() ?? (recipe ? RecipeRow(new Recipe { ID = id }) : FlowRow(new Workflow { ID = id, RecipeID = owner }));
foreach (var (key, value) in patch)
{
if (!after.ContainsKey(key) || key == "ID" || action == "update" && key is "RecipeID" or "Name")
throw new ArgumentException($"不能通过属性修改 {key}。");
after[key] = value?.DeepClone();
}
var name = (string)after["Name"];
var names = recipe ? Recipes.Where(r => r.ID != id).Select(r => r.Name) : Flows(owner).Where(w => w.ID != id).Select(w => w.Name);
if (string.IsNullOrWhiteSpace(name) || name != name.Trim() || names.Contains(name)) throw new ArgumentException("工程对象名称无效或重复。");
_ = (string)after["Comment"];
if (!recipe)
{
double delay = (double)after["CycleDelayTime"];
if (!double.IsFinite(delay) || delay < 0 || delay > int.MaxValue / 1000.0) throw new ArgumentException("循环间隔超出范围。");
_ = (bool)after["AutomaticExecution"];
string code = (string)after["Code"];
if (action == "create") code = patch.ContainsKey("Code") ? code?.Replace("__WORKFLOW_ID__", id.ToString("N")) :
$"using PLCSharp.Models;\nusing PLCSharp.Core.Common;\npublic class Extension_{id:N} {{ public void Run(GlobalModel model, FlowModel flow) {{ }} }}\n";
after["Code"] = code ?? "";
}
if (JsonNode.DeepEquals(before, after)) throw new ArgumentException("属性没有变化。");
}
if (recipe && action == "delete" && Recipes.Count == 1) throw new ArgumentException("工程必须保留一个配方。");
var files = new Dictionary<string, string>(baseline);
var recipePath = RecipePath(owner);
var meta = action == "create" && recipe ? new JsonObject { ["id"] = id.ToString(), ["workflows"] = new JsonArray() } :
JsonNode.Parse(files[recipePath]).AsObject();
List<OwnedRow> owned = [];
var review = InspectEdit(action, kind, id, path, before, after, baseline[path], null);
if (recipe)
{
var manifest = JsonNode.Parse(files[path]);
var ids = manifest["recipes"].AsArray();
if (action == "delete")
{
foreach (var flow in Flows(owner))
{
string script = ScriptPath(owner, flow.ID);
review.ConfigReferences.Add(new JsonObject { ["path"] = script, ["table"] = "Workflows", ["id"] = flow.ID.ToString(), ["field"] = "RecipeID" });
MergeImpact(review, InspectEdit("delete", "Workflows", flow.ID, script, FlowRow(flow), null, null, null));
CheckFlowCode(review, flow.ID, flow.Name, script, flow.Code, flow.Code);
files.Remove(script);
}
files.Remove(recipePath);
ids.Remove(ids.Single(v => Guid.Parse((string)v) == id));
if (DefaultRecipeId == id) manifest["defaultRecipeId"] = (string)ids[0];
var functions = Data.VisionFunctions.Where(f => f.RecipeID == id).Select(f => f.ID).ToHashSet();
foreach (var (group, tables) in ProjectConfiguration.Groups)
{
var config = ConfigPath(group);
var doc = JsonNode.Parse(files[config]);
int count = owned.Count;
foreach (var table in tables)
RemoveOwned(doc, table, r => Guid.TryParse((string)r["RecipeID"], out var rid) && rid == id ||
table == "LocalImageDatas" && functions.Contains(Guid.Parse((string)r["FuncID"])), owned);
if (count != owned.Count) files[config] = Serialize(doc);
}
}
else
{
if (action == "create") ids.Add(id.ToString());
meta["name"] = (string)after["Name"];
meta["comment"] = (string)after["Comment"];
files[recipePath] = Serialize(meta);
}
if (action != "update") files[path] = Serialize(manifest);
}
else
{
var flows = meta["workflows"].AsArray();
var entry = flows.SingleOrDefault(v => Guid.Parse((string)v["id"]) == id);
var script = ScriptPath(owner, id);
if (action == "delete")
{
flows.Remove(entry);
files.Remove(script);
CheckFlowCode(review, id, targetFlow.Name, script, targetFlow.Code, targetFlow.Code);
}
else
{
var header = JsonSerializer.SerializeToNode(new FlowFile(id, (string)after["Name"], (string)after["Comment"],
(bool)after["AutomaticExecution"], (double)after["CycleDelayTime"]), Json);
if (entry == null) flows.Add(header); else flows[flows.IndexOf(entry)] = header;
files[script] = (string)after["Code"];
CheckFlowCode(review, id, name: (string)after["Name"], script, (string)before?["Code"], files[script]);
}
files[recipePath] = Serialize(meta);
}
var changes = files.Keys.Union(baseline.Keys).Select(p => new DocumentDelta(p, baseline.GetValueOrDefault(p), files.GetValueOrDefault(p)))
.Where(d => d.Before != d.After).ToList();
return WithOwnedImpact(review, owned) with { Destination = files.GetValueOrDefault(path), Documents = changes };
}
private static void CheckFlowCode(ObjectEdit edit, Guid id, string name, string path, string before, string after)
{
var review = WorkflowScriptReview.Create(id, before, after);
edit.Workflows.RemoveAll(f => f.Id == id);
edit.Workflows.Add(new(id, name, path, review.Compiled, review.Diagnostics));
}
private void ApplyStructureEdit(ObjectEdit edit)
{
bool recipe = edit.Kind == "Recipes";
var row = edit.Before ?? edit.After;
Guid owner = recipe ? edit.Id : Guid.Parse((string)row["RecipeID"]);
var collection = Flows(owner);
var affected = collection.Where(f => recipe ? edit.Action == "delete" : f.ID == edit.Id).ToArray();
if (Recipes.Any(r => r.ID == owner))
{
var stored = JsonNode.Parse(baseline[RecipePath(owner)]);
var live = Recipes.Single(r => r.ID == owner);
if (live.Name != (string)stored["name"] || live.Comment != (string)stored["comment"] ||
!stored["workflows"].AsArray().Select(n => Guid.Parse((string)n["id"])).SequenceEqual(collection.Select(f => f.ID)))
throw new ProjectConflictException("配方或工作流列表有未保存编辑。");
foreach (var f in affected)
{
var header = stored["workflows"].AsArray().Single(n => Guid.Parse((string)n["id"]) == f.ID);
if (f.Name != (string)header["name"] || f.Comment != (string)header["comment"] ||
f.AutomaticExecution != (bool)header["automaticExecution"] || f.CycleDelayTime != (double)header["cycleDelayTime"] ||
(f.Code ?? "") != baseline[ScriptPath(owner, f.ID)]) throw new ProjectConflictException("工作流有未保存编辑。");
}
}
var files = new Dictionary<string, string>(baseline);
foreach (var d in edit.Documents)
{
if (files.GetValueOrDefault(d.Path) != d.Before) throw new ProjectConflictException("工程文件已改变。");
if (d.After == null) files.Remove(d.Path); else files[d.Path] = d.After;
}
Workflow.SaveReviewedBatch(affected.Select(f => (f, f.Code ?? "", f.Code ?? "")).ToArray(), () =>
{
using var tx = Data.Database.BeginTransaction();
ApplyOwnedRows(edit.OwnedRows);
WriteFiles(Root, files, baseline.Keys.Union(files.Keys).ToArray(), tx.Commit);
DetachDeletedRows(edit.OwnedRows);
foreach (var d in edit.Documents.Where(d => configuration.ContainsKey(d.Path))) configuration[d.Path] = d.After;
if (edit.Action == "delete") foreach (var f in affected) f.Stop();
var manifest = JsonSerializer.Deserialize<Manifest>(files["project.json"], Json);
DefaultRecipeId = manifest.DefaultRecipeId;
if (recipe && edit.Action == "delete")
{
Recipes.Remove(Recipes.Single(r => r.ID == owner));
workflows.Remove(owner);
}
else
{
var meta = JsonSerializer.Deserialize<RecipeFile>(files[RecipePath(owner)], Json);
if (recipe)
{
var item = Recipes.SingleOrDefault(r => r.ID == owner);
if (item == null)
{
item = new Recipe { ID = owner };
Recipes.Insert(Array.IndexOf(manifest.Recipes, owner), item);
}
item.Name = meta.Name; item.Comment = meta.Comment; item.Prompt = "";
}
if (!recipe && edit.Action == "delete") collection.Remove(affected.Single());
else foreach (var header in meta.Workflows.Where(h => recipe ? edit.Action == "create" : h.Id == edit.Id))
{
var flow = collection.SingleOrDefault(f => f.ID == header.Id);
bool add = flow == null;
flow ??= new Workflow { ID = header.Id, RecipeID = owner };
flow.Name = header.Name; flow.Comment = header.Comment;
flow.CycleDelayTime = header.CycleDelayTime; flow.AutomaticExecution = header.AutomaticExecution;
flow.Code = files[ScriptPath(owner, header.Id)]; flow.Prompt = "";
if (add) collection.Insert(Array.IndexOf(meta.Workflows, header), flow);
}
}
});
edit.SavedScope = ObjectScope();
}
}

View File

@ -32,7 +32,7 @@ internal static class WorkflowReferences
{
var targetType = kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable),
"VisionFunctions" => typeof(VisionFunction), "DI" => typeof(DI), "DQ" => typeof(DQ), "Axes" => typeof(Axis), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint),
"Controllers" => typeof(Controller), "Cylinders" => typeof(Cylinder), "Robots" => typeof(Robot), "Connects" => typeof(Connect),
"CanvasConfigs" => typeof(PLCSharp.VVMs.Homepage.CanvasConfig), "Controllers" => typeof(Controller), "Cylinders" => typeof(Cylinder), "Robots" => typeof(Robot), "Connects" => typeof(Connect),
"Cameras" => typeof(PLCSharp.VVMs.Vision.Camera.CameraBase), "ImageDatas" => typeof(ImageData), "LocalImageDatas" => typeof(LocalImageData),
"ControlMeasurements" => typeof(PLCSharp.VVMs.Homepage.TableControl.RangeValue), "VisionLocalVariables" => typeof(LocalVariableItem),
"InterpolationSegments" => typeof(Interpolation), "InterpolationPoints" => typeof(InterpolationPoint),
@ -80,6 +80,8 @@ internal static class WorkflowReferences
if (model.GetSymbolInfo(access).Symbol is not IPropertySymbol property) continue;
bool singleton = kind == "Controllers" && property.Name == nameof(ControllersModel.Controller) &&
property.ContainingType.ToDisplayString() == typeof(ControllersModel).FullName;
singleton |= kind == "CanvasConfigs" && property.Name == nameof(GlobalModel.CurrentCanvasConfig) &&
property.ContainingType.ToDisplayString() == typeof(GlobalModel).FullName;
bool collection = property.Name == collectionName && property.Type is INamedTypeSymbol list &&
list.TypeArguments.Length == 1 && list.TypeArguments[0].ToDisplayString() == targetType.FullName;
if (!singleton && !collection) continue;

View File

@ -0,0 +1,64 @@
using System.IO;
using System.Text.Json.Nodes;
using PLCSharp.Models;
using PLCSharp.VVMs.Robots;
namespace PLCSharp.Tests;
public class RemainingEditTests
{
[Fact]
public void RemainingObjectTypesAndOwnedDeletesRestoreEverySnapshot()
{
var dir = Directory.CreateTempSubdirectory();
try
{
using var project = ProjectDirectory.New();
var robot = new Robot { Name = "QA" };
project.Data.Add(robot);
project.Save(dir.FullName);
Dictionary<string, byte[]> Snapshot() => Directory.GetFiles(dir.FullName, "*", SearchOption.AllDirectories).ToDictionary(p => p, File.ReadAllBytes);
var history = new Stack<(ObjectEdit, Dictionary<string, byte[]>)>();
ObjectEdit Save(string op, string kind, Guid? id, JsonObject? props)
{
var before = Snapshot();
var draft = project.PlanObjectEdit(op, kind, id, props);
Assert.True(draft.Compiled);
project.ApplyObjectEdit(draft);
history.Push((draft, before));
return draft;
}
var recipe = Save("create", "Recipes", null, new() { ["Name"] = "Product" }).Id;
Save("update", "Recipes", recipe, new() { ["Comment"] = "reviewed" });
Guid function = default;
foreach (var kind in new[] { "Workflows", "VisionFunctions", "LocalImageDatas", "ImageDatas", "SystemVariables",
"CustomControls", "CanvasConfigs", "Matrices", "RobotMatrices", "InterpolationGroups" })
{
var props = new JsonObject();
if (kind != "CanvasConfigs") props["Name"] = kind;
if (kind == "LocalImageDatas") props["FuncID"] = function.ToString();
else props["RecipeID"] = recipe.ToString();
if (kind == "RobotMatrices") props["RobotID"] = robot.ID.ToString();
var add = Save("create", kind, null, props);
if (kind == "VisionFunctions") function = add.Id;
JsonObject patch = kind switch
{
"CanvasConfigs" => new() { ["Rows"] = 3 }, "InterpolationGroups" => new() { ["Params"] = new JsonObject { ["Ahead"] = 1 } },
"Matrices" or "RobotMatrices" => new() { ["XCount"] = 2 }, _ => new() { ["Comment"] = "updated" }
};
Save("update", kind, add.Id, patch);
}
var drop = Save("delete", "Recipes", recipe, null);
Assert.Equal(9, drop.OwnedRows.Count);
using (var opened = ProjectDirectory.Open(dir.FullName)) Assert.Single(opened.Recipes);
while (history.TryPop(out var item))
{
project.ApplyObjectEdit(project.UndoObject(Guid.NewGuid(), item.Item1));
var current = Snapshot();
Assert.Equal(item.Item2.Keys.Order(), current.Keys.Order());
foreach (var (path, bytes) in current) Assert.Equal(item.Item2[path], bytes);
}
}
finally { dir.Delete(true); }
}
}