using PLCSharp.VVMs.Recipe; using PLCSharp.VVMs.Workflows; using System.Collections.ObjectModel; using System.IO; using System.Text.Encodings.Web; using System.Text.Json; namespace PLCSharp.Models; public sealed partial class ProjectDirectory : IDisposable { private sealed record Manifest(int FormatVersion, Guid ProjectId, Guid DefaultRecipeId, Guid[] Recipes); private sealed record RecipeFile(Guid Id, string Name, string Comment, FlowFile[] Workflows); private sealed record FlowFile(Guid Id, string Name, string Comment, bool AutomaticExecution, double CycleDelayTime); private static readonly JsonSerializerOptions Json = new() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; public DatasContext Data { get; } = DatasContext.CreateWorkingCopy(); private readonly Dictionary configuration = new(); private readonly HashSet pendingGroups = new(); private static string ConfigPath(string group) => $"configuration/{group}.json"; private ProjectDirectory() { Data.ConfigurationChanged = PersistConfiguration; } private void Capture(string group) { configuration[ConfigPath(group)] = Serialize(ProjectConfiguration.Capture(Data, ProjectConfiguration.Groups[group])); } private void PersistConfiguration(HashSet tables) { foreach (var (group, members) in ProjectConfiguration.Groups) if (members.Any(tables.Contains)) pendingGroups.Add(group); if (pendingGroups.Count == 0) return; foreach (var group in pendingGroups) Capture(group); if (Root != null) { var files = new Dictionary(baseline); foreach (var group in pendingGroups) files[ConfigPath(group)] = configuration[ConfigPath(group)]; WriteFiles(Root, files, pendingGroups.Select(ConfigPath).ToArray()); } pendingGroups.Clear(); } public void Dispose() => Data.Dispose(); private Dictionary baseline = new(); private readonly Dictionary> workflows = new(); public ObservableCollection Recipes { get; } = new(); public string Root { get; private set; } public Guid Id { get; private set; } = Guid.NewGuid(); public Guid DefaultRecipeId { get; set; } public ObservableCollection Flows(Guid recipeId) { if (!workflows.TryGetValue(recipeId, out var items)) workflows.Add(recipeId, items = new()); return items; } public static ProjectDirectory New() { var project = new ProjectDirectory(); var recipe = new Recipe { Name = "First", Comment = "", Prompt = "", Current = true }; project.Recipes.Add(recipe); project.DefaultRecipeId = recipe.ID; foreach (var group in ProjectConfiguration.Groups.Keys) project.Capture(group); project.baseline = project.Files(); return project; } private static string RecipePath(Guid id) => $"recipes/{id:D}/recipe.json"; private static string ScriptPath(Guid recipe, Guid flow) => $"recipes/{recipe:D}/workflows/{flow:D}.cs"; private static string Serialize(T value) => JsonSerializer.Serialize(value, Json) + "\n"; public static ProjectDirectory Open(string directory) { var project = new ProjectDirectory { Root = Path.GetFullPath(directory) }; try { project.ReadDirectory(); return project; } catch { project.Dispose(); throw; } } private static string ProjectFile(string root, string relative) { var path = root; foreach (var part in relative.Split('/')) { path = Path.Combine(path, part); if (File.Exists(path) || Directory.Exists(path)) { if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) throw new InvalidDataException($"Project files must be inside the directory: {relative}"); } } return path; } private void ReadDirectory() { string Read(string path) { string value = File.ReadAllText(ProjectFile(Root, path)); baseline.Add(path, value); return value; } var manifest = JsonSerializer.Deserialize(Read("project.json"), Json); if (manifest?.FormatVersion != 2 || manifest.ProjectId == Guid.Empty || manifest.Recipes == null) throw new InvalidDataException("工程清单无效或版本不受支持。"); Id = manifest.ProjectId; DefaultRecipeId = manifest.DefaultRecipeId; foreach (var id in manifest.Recipes) { var data = JsonSerializer.Deserialize(Read(RecipePath(id)), Json); if (data == null || data.Id != id || data.Workflows == null) throw new InvalidDataException($"配方文件无效:{id}"); Recipes.Add(new Recipe { ID = id, Name = data.Name, Comment = data.Comment, Current = id == DefaultRecipeId, Prompt = "" }); foreach (var flow in data.Workflows) { Flows(id).Add(new Workflow { ID = flow.Id, RecipeID = id, Name = flow.Name, Comment = flow.Comment, AutomaticExecution = flow.AutomaticExecution, CycleDelayTime = flow.CycleDelayTime, Code = Read(ScriptPath(id, flow.Id)), Prompt = "" }); } } foreach (var (group, tables) in ProjectConfiguration.Groups) { var path = ConfigPath(group); var json = Read(path); ProjectConfiguration.Restore(Data, tables, System.Text.Json.Nodes.JsonNode.Parse(json).AsObject()); configuration.Add(path, json); } Validate(); } private void Validate() { if (!Recipes.Any(r => r.ID == DefaultRecipeId)) throw new InvalidDataException("工程缺少默认配方。"); var ids = new HashSet(); void Check(Guid id, string name, HashSet names) { if (id == Guid.Empty || !ids.Add(id) || string.IsNullOrWhiteSpace(name) || !names.Add(name)) throw new InvalidDataException($"名称为空、名称重复或标识重复:{name}"); } var recipes = new HashSet(); foreach (var recipe in Recipes) { Check(recipe.ID, recipe.Name, recipes); var names = new HashSet(); foreach (var flow in Flows(recipe.ID)) Check(flow.ID, flow.Name, names); } } private Dictionary Files() { var files = new Dictionary(configuration); foreach (var recipe in Recipes) { var flows = Flows(recipe.ID); foreach (var flow in flows) files.Add(ScriptPath(recipe.ID, flow.ID), flow.Code ?? ""); files.Add(RecipePath(recipe.ID), Serialize(new RecipeFile(recipe.ID, recipe.Name, recipe.Comment, flows.Select(f => new FlowFile(f.ID, f.Name, f.Comment, f.AutomaticExecution, f.CycleDelayTime)).ToArray()))); } files.Add("project.json", Serialize(new Manifest(2, Id, DefaultRecipeId, Recipes.Select(r => r.ID).ToArray()))); return files; } public bool HasChanges { get { lock (Data.Sync) return pendingGroups.Count > 0 || Data.ChangeTracker.HasChanges() || !Files().OrderBy(p => p.Key).SequenceEqual(baseline.OrderBy(p => p.Key)); } } public void Save(string newDirectory = null) { lock (Data.Sync) { Validate(); Data.SaveChanges(); foreach (var group in ProjectConfiguration.Groups.Keys) Capture(group); SaveAll(newDirectory); pendingGroups.Clear(); } } private void SaveAll(string newDirectory) { var root = Root ?? Path.GetFullPath(newDirectory ?? throw new InvalidOperationException("请选择工程目录。")); WriteFiles(root, Files()); } private void WriteFiles(string root, Dictionary files, string[] scope = null) { Directory.CreateDirectory(root); // Serialize writers and detect edits made after this instance opened the project. using var gate = new FileStream(Path.Combine(root, ".plcsharp-save.lock"), FileMode.CreateNew, FileAccess.Write, FileShare.None, 1, FileOptions.DeleteOnClose); if (Root == null && Directory.EnumerateFileSystemEntries(root).Any(p => Path.GetFileName(p) != ".plcsharp-save.lock")) throw new IOException("新建工程需要一个空目录。"); var previous = Root == null ? new Dictionary() : baseline; var paths = scope ?? files.Keys.Union(previous.Keys).ToArray(); foreach (var path in paths) { var full = ProjectFile(root, path); var disk = File.Exists(full) ? File.ReadAllText(full) : null; previous.TryGetValue(path, out var original); if (disk != original) throw new IOException($"文件已在外部修改,请重新打开工程:{path}"); } // Stage all writes before replacing files. Keep originals until every change succeeds. var stage = Directory.CreateDirectory(Path.Combine(root, ".save-" + Guid.NewGuid().ToString("N"))).FullName; var backups = new List<(string Target, string Original)>(); var installed = new List(); bool keepBackups = false; try { foreach (var path in paths) { if (!files.TryGetValue(path, out var value)) continue; if (previous.TryGetValue(path, out var old) && old == value) continue; var temp = Path.Combine(stage, path); Directory.CreateDirectory(Path.GetDirectoryName(temp)); File.WriteAllText(temp, value); } foreach (var path in paths) { var temp = Path.Combine(stage, path); if (files.ContainsKey(path) && !File.Exists(temp)) continue; var target = ProjectFile(root, path); if (previous.ContainsKey(path)) { var backup = Path.Combine(stage, Guid.NewGuid().ToString()); File.Move(target, backup); backups.Add((target, backup)); } if (files.ContainsKey(path)) { Directory.CreateDirectory(Path.GetDirectoryName(target)); File.Move(temp, target); installed.Add(target); } } } catch { keepBackups = true; foreach (var path in installed) File.Delete(path); foreach (var (target, original) in backups) File.Move(original, target); keepBackups = false; throw; } finally { if (!keepBackups) Directory.Delete(stage, true); } Root = root; baseline = files; } }