diff --git a/PLCSharpWpf/App.xaml.cs b/PLCSharpWpf/App.xaml.cs index 006c0e6..4b6a659 100644 --- a/PLCSharpWpf/App.xaml.cs +++ b/PLCSharpWpf/App.xaml.cs @@ -22,6 +22,7 @@ namespace PLCSharp /// public partial class App { + internal bool SwitchingProject { get; set; } private Mutex mutex; //第1执行 @@ -31,7 +32,14 @@ namespace PLCSharp /// Prism 容器注册器 protected override void RegisterTypes(IContainerRegistry containerRegistry) { + var args = Environment.GetCommandLineArgs().Skip(1).ToArray(); + bool switching = args.Length == 2 && args[0] == "--switch-project"; mutex = new Mutex(true, "PLCSharp", out bool ret); + if (!ret && switching) + { + try { ret = mutex.WaitOne(TimeSpan.FromSeconds(30)); } + catch (AbandonedMutexException) { ret = true; } + } if (!ret) { @@ -40,8 +48,20 @@ namespace PLCSharp } LoadConfig(); //数据库 - _ = containerRegistry.RegisterSingleton(); - _ = Container.Resolve(); + ProjectDirectory project; + try + { + project = args.Length == 2 && (switching || args[0] == "--project") + ? ProjectDirectory.Open(args[1]) : ProjectDirectory.New(); + } + catch (Exception ex) + { + MessageBox.Show($"无法打开工程:{ex.Message}", "PLCSharp"); + project = ProjectDirectory.New(); + } + containerRegistry.RegisterInstance(project); + containerRegistry.RegisterInstance(project.Data); + containerRegistry.RegisterSingleton(); RegisterEvents(); // 捕获全局异常 diff --git a/PLCSharpWpf/Models/DatasContext.cs b/PLCSharpWpf/Models/DatasContext.cs index 49eda3a..a7c0a51 100644 --- a/PLCSharpWpf/Models/DatasContext.cs +++ b/PLCSharpWpf/Models/DatasContext.cs @@ -91,11 +91,6 @@ namespace PLCSharp.Models /// public DbSet Users { get; set; } - /// - /// Recipes - /// - public DbSet Recipes { get; set; } - /// /// 系统全局变量集合 /// @@ -106,11 +101,6 @@ namespace PLCSharp.Models /// public DbSet Variables { get; set; } - /// - /// Workflows - /// - public DbSet Workflows { get; set; } - /// /// VisionFunctions /// @@ -220,20 +210,49 @@ namespace PLCSharp.Models ? $"Data Source={DefaultDatabasePath}" : _connectionString); - private object _dbLock = new(); + internal readonly object Sync = new(); + internal Action> ConfigurationChanged; + + internal static DatasContext CreateWorkingCopy() => new DatasContext(true); + + private DatasContext(bool workingCopy) + { + _connectionString = "Data Source=:memory:"; + Database.OpenConnection(); + Database.EnsureCreated(); + } /// /// 保存 /// public void Save() { - lock (_dbLock) + lock (Sync) { + var tables = ConfigurationChanged == null ? null : ChangeTracker.Entries() + .Where(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted) + .Select(e => e.Metadata.GetTableName()).ToHashSet(); SaveChanges(); + if (tables != null) ConfigurationChanged(tables); } } } + // Accounts and logs belong to this installation. They never enter a project directory. + public sealed class MachineDataContext : DatasContext + { + public MachineDataContext() { } + internal MachineDataContext(string path) : base(path) { } + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + var projectTypes = builder.Model.GetEntityTypes().Select(entity => entity.ClrType) + .Where(type => type != typeof(User) && type != typeof(ErrorLog)).ToList(); + foreach (var type in projectTypes) builder.Ignore(type); + } + } + /// /// SQLite 库的增量维护:补建缺失的表、补齐缺失的列。 /// diff --git a/PLCSharpWpf/Models/GlobalModel.Logging.cs b/PLCSharpWpf/Models/GlobalModel.Logging.cs index 7e3c88e..5794b4d 100644 --- a/PLCSharpWpf/Models/GlobalModel.Logging.cs +++ b/PLCSharpWpf/Models/GlobalModel.Logging.cs @@ -11,6 +11,8 @@ namespace PLCSharp.Models /// public partial class GlobalModel { + private readonly MachineDataContext machineData; + #region 日志 private ObservableCollection _ErrorLogs = []; @@ -49,7 +51,8 @@ namespace PLCSharp.Models var newLog = new ErrorLog(message.Content); TitleState.Info = message.Content; TitleState.Background = Brushes.Red; - _DatasContext.ErrorLogs.Add(newLog); + machineData.ErrorLogs.Add(newLog); + machineData.Save(); ShowLog(); } @@ -59,7 +62,7 @@ namespace PLCSharp.Models { lock (loglock) { - var showLog = _DatasContext.ErrorLogs.Where(e => e.Time.AddDays(1) >= DateTime.Now).OrderByDescending(l => l.Time).Take(30).ToList(); + var showLog = machineData.ErrorLogs.Where(e => e.Time.AddDays(1) >= DateTime.Now).OrderByDescending(l => l.Time).Take(30).ToList(); foreach (var item in showLog) { @@ -95,6 +98,7 @@ namespace PLCSharp.Models if (err != null) { err.IsConfirm = true; + machineData.Save(); } } else if (r.Result == ButtonResult.No) diff --git a/PLCSharpWpf/Models/GlobalModel.Project.cs b/PLCSharpWpf/Models/GlobalModel.Project.cs new file mode 100644 index 0000000..eb2ead0 --- /dev/null +++ b/PLCSharpWpf/Models/GlobalModel.Project.cs @@ -0,0 +1,87 @@ +using Microsoft.Win32; +using Prism.Commands; +using System.Windows; + +namespace PLCSharp.Models; + +public partial class GlobalModel +{ + internal ProjectDirectory Project { get; } + public string ProjectLocation => Project.Root ?? "未保存工程"; + private AsyncDelegateCommand projectManage; + public AsyncDelegateCommand ProjectManage => projectManage ??= new AsyncDelegateCommand(ManageProjectAsync); + + private static string ChooseFolder(string title) + { + var dialog = new OpenFolderDialog { Title = title }; + return dialog.ShowDialog() == true ? dialog.FolderName : null; + } + + internal bool SaveProject() + { + try + { + var root = Project.Root ?? ChooseFolder("选择空文件夹以保存工程"); + if (root == null) return false; + Project.Save(root); + RaisePropertyChanged(nameof(ProjectLocation)); + foreach (var recipe in Recipes) + { + recipe.Prompt = ""; + foreach (var flow in Project.Flows(recipe.ID)) + if (flow.Prompt == "已修改,请保存") flow.Prompt = ""; + } + return true; + } + catch (Exception ex) + { + SendErrDialog($"工程保存失败:{ex.Message}"); + return false; + } + } + + private async Task ManageProjectAsync(string action) + { + if (WorkflowsModel.IsBusy || ModeState.State.Execute) + { + SendInfoDialog("请先停止运行并等待配方切换完成。"); + return; + } + if (action == "Save") + { + SaveProject(); + return; + } + try + { + if (Project.HasChanges) + { + var answer = MessageBox.Show("当前工程有未保存的修改。是否保存?", "切换工程", + MessageBoxButton.YesNoCancel, MessageBoxImage.Question); + if (answer == MessageBoxResult.Cancel || (answer == MessageBoxResult.Yes && !SaveProject())) return; + } + var folder = ChooseFolder(action == "New" ? "选择空文件夹以新建工程" : "选择包含 project.json 的工程目录"); + if (folder == null) return; + using var next = action == "New" ? ProjectDirectory.New() : ProjectDirectory.Open(folder); + if (action == "New") next.Save(folder); + // Hardware modules own pollers and vendor handles for their whole process lifetime. + // Start the replacement session after this one has released its single-instance mutex. + await WorkflowsModel.ChangeRecipeAsync(() => + { + var start = new System.Diagnostics.ProcessStartInfo(Environment.ProcessPath) { UseShellExecute = false }; + if (string.Equals(System.IO.Path.GetFileNameWithoutExtension(Environment.ProcessPath), "dotnet", StringComparison.OrdinalIgnoreCase)) + start.ArgumentList.Add(typeof(App).Assembly.Location); + start.ArgumentList.Add("--switch-project"); + start.ArgumentList.Add(next.Root); + System.Diagnostics.Process.Start(start)?.Dispose(); + ((App)Application.Current).SwitchingProject = true; + Application.Current.Shutdown(); + }); + } + catch (Exception ex) + { + SendErrDialog($"工程操作失败:{ex.Message}"); + } + } +} + diff --git a/PLCSharpWpf/Models/GlobalModel.Recipes.cs b/PLCSharpWpf/Models/GlobalModel.Recipes.cs index 32b6695..e3c14e3 100644 --- a/PLCSharpWpf/Models/GlobalModel.Recipes.cs +++ b/PLCSharpWpf/Models/GlobalModel.Recipes.cs @@ -71,7 +71,7 @@ namespace PLCSharp.Models private void ExecuteRecipeManage(string cmd) { - if (WorkflowsModel?.IsChangingRecipe == true) return; + if (WorkflowsModel?.IsBusy == true) return; if (ModeState.State.Execute) { SendInfoDialog($"无法在运行状态操作配方,请先停止"); @@ -84,43 +84,7 @@ namespace PLCSharp.Models break; case "Save": - var names = new List(); - - foreach (var item in Recipes) - { - if (string.IsNullOrEmpty(item.Name)) - { - SendInfoDialog($"保存失败,名称{item.Name}不合适!"); - return; - } - - if (names.Contains(item.Name)) - { - SendInfoDialog($"保存失败,重复的名称{item.Name}!"); - return; - } - else - { - names.Add(item.Name); - } - } - - foreach (var item in Recipes) - { - if (!_DatasContext.Recipes.Any(h => h.ID == item.ID)) - { - _DatasContext.Recipes.Add(item); - } - else - { - var recipe = _DatasContext.Recipes.Where(c => c.ID == item.ID).FirstOrDefault(); - recipe.Name = item.Name; - recipe.Comment = item.Comment; - } - } - RecipeSelected.Prompt = ""; - _DatasContext.Save(); - + SaveProject(); break; case "Remove": @@ -132,10 +96,21 @@ namespace PLCSharp.Models { var recipeId = RecipeSelected.ID; + var removed = RecipeSelected; + var index = Recipes.IndexOf(removed); + var previousDefault = Project.DefaultRecipeId; + if (recipeId == previousDefault) Project.DefaultRecipeId = CurrentRecipe.ID; + Recipes.RemoveAt(index); + if (!SaveProject()) + { + Project.DefaultRecipeId = previousDefault; + Recipes.Insert(index, removed); + RecipeSelected = removed; + return; + } // 级联删除配方关联的所有数据 _DatasContext.Variables.RemoveRange(_DatasContext.Variables.Where(v => v.RecipeID == recipeId)); _DatasContext.SystemVariables.RemoveRange(_DatasContext.SystemVariables.Where(v => v.RecipeID == recipeId)); - _DatasContext.Workflows.RemoveRange(_DatasContext.Workflows.Where(w => w.RecipeID == recipeId)); _DatasContext.ImageDatas.RemoveRange(_DatasContext.ImageDatas.Where(i => i.RecipeID == recipeId)); _DatasContext.AxisPoints.RemoveRange(_DatasContext.AxisPoints.Where(a => a.RecipeID == recipeId)); _DatasContext.Matrices.RemoveRange(_DatasContext.Matrices.Where(m => m.RecipeID == recipeId)); @@ -149,14 +124,7 @@ namespace PLCSharp.Models _DatasContext.LocalImageDatas.RemoveRange(_DatasContext.LocalImageDatas.Where(l => visionFuncIds.Contains(l.FuncID))); _DatasContext.VisionFunctions.RemoveRange(_DatasContext.VisionFunctions.Where(v => v.RecipeID == recipeId)); - var recipe = _DatasContext.Recipes.FirstOrDefault(r => r.ID == recipeId); - if (recipe != null) - { - _DatasContext.Recipes.Remove(recipe); - } - - var name = RecipeSelected.Name; - Recipes.Remove(RecipeSelected); + var name = removed.Name; RecipeSelected = null; _DatasContext.Save(); SendInfoDialog($"已删除配方:{name}"); @@ -171,7 +139,7 @@ namespace PLCSharp.Models case "Current": if (RecipeSelected != null) { - if (CurrentRecipe.Name == RecipeSelected.Name) { + if (CurrentRecipe.ID == RecipeSelected.ID) { SendInfoDialog($"当前配方已经是:{CurrentRecipe.Name},不需要切换。"); break; @@ -179,11 +147,7 @@ namespace PLCSharp.Models if (System.Windows.MessageBox.Show($"确认切换配方 [{RecipeSelected.Name}]?", "确认切换", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes) break; - var selectedId = RecipeSelected.ID; - var current = _DatasContext.Recipes.FirstOrDefault(r => r.ID == selectedId); - if (current == null) break; - - _ = ReloadRecipeAsync(current); + _ = ReloadRecipeAsync(RecipeSelected); } break; @@ -223,8 +187,7 @@ namespace PLCSharp.Models }).ToList(); // 工艺流程 - sheets["工艺流程"] = _DatasContext.Workflows - .Where(w => w.RecipeID == recipeId) + sheets["工艺流程"] = Project.Flows(recipeId) .Select(w => new { ID = w.ID.ToString(), @@ -467,13 +430,13 @@ namespace PLCSharp.Models var idStr = (string)row.ID; if (string.IsNullOrWhiteSpace(idStr)) continue; if (!Guid.TryParse(idStr, out var id)) continue; - if (_DatasContext.Workflows.Any(w => w.ID == id)) continue; + if (Recipes.SelectMany(r => Project.Flows(r.ID)).Any(w => w.ID == id)) continue; var name = (string)row.Name; if (string.IsNullOrWhiteSpace(name)) continue; - if (_DatasContext.Workflows.Any(w => w.Name == name && w.RecipeID == recipeId)) continue; + if (Project.Flows(recipeId).Any(w => w.Name == name)) continue; - _DatasContext.Workflows.Add(new Workflow + Project.Flows(recipeId).Add(new Workflow { ID = id, RecipeID = recipeId, @@ -776,6 +739,7 @@ namespace PLCSharp.Models _DatasContext.CustomControls.Add(cc); } + if (!SaveProject()) return; _DatasContext.Save(); SendInfoDialog($"配方 [{RecipeSelected.Name}] 数据已导入,请切换配方刷新"); } @@ -800,9 +764,6 @@ namespace PLCSharp.Models { if (selected != null) { - foreach (var item in _DatasContext.Recipes) - item.Current = item.ID == selected.ID; - _DatasContext.Save(); foreach (var item in Recipes) item.Current = item.ID == selected.ID; CurrentRecipe = selected; @@ -855,16 +816,11 @@ namespace PLCSharp.Models RobotModel.LoadRecipe(CurrentRecipe.ID); //加载当前配方的任务列表 - WorkflowsModel.Workflows.Clear(); - var currRecipeWorkflows = _DatasContext.Workflows.Where(c => c.RecipeID == CurrentRecipe.ID); - foreach (var item in currRecipeWorkflows) - { - var itemcopy = item.DeepCopy(); - itemcopy.Prompt = ""; - WorkflowsModel.Workflows.Add(itemcopy); - itemcopy.Compile.Execute(); - itemcopy.Start(this); - } + WorkflowsModel.SelectedTask = null; + WorkflowsModel.Workflows = Project.Flows(CurrentRecipe.ID); + // Source from a newly opened directory is compiled only by the editor’s Compile command. + foreach (var workflow in WorkflowsModel.Workflows) + workflow.Start(this); } private void RecipeCopy() @@ -993,21 +949,18 @@ namespace PLCSharp.Models // 任务列表 - var workflows = _DatasContext.Workflows.Where(c => c.RecipeID == RecipeSelected.ID); - foreach (var item in workflows) + foreach (var item in Project.Flows(RecipeSelected.ID)) { - if (item != null) - { - var itemCopy = item.DeepCopy(); - itemCopy.RecipeID = newRecipe.ID; - itemCopy.ID = Guid.NewGuid(); - _DatasContext.Workflows.Add(itemCopy); - } + var copy = new Workflow { RecipeID = newRecipe.ID, Name = item.Name, + Comment = item.Comment, AutomaticExecution = item.AutomaticExecution, + CycleDelayTime = item.CycleDelayTime }; + copy.Code = item.Code?.Replace($"Extension_{item.ID:N}", $"Extension_{copy.ID:N}"); + Project.Flows(newRecipe.ID).Add(copy); } - _DatasContext.Recipes.Add(newRecipe); try { + if (!SaveProject()) return; _DatasContext.Save(); SendInfoDialog($"配方 [{newRecipe.Name}] 复制成功"); } diff --git a/PLCSharpWpf/Models/GlobalModel.cs b/PLCSharpWpf/Models/GlobalModel.cs index b46635c..f0dafc5 100644 --- a/PLCSharpWpf/Models/GlobalModel.cs +++ b/PLCSharpWpf/Models/GlobalModel.cs @@ -38,38 +38,10 @@ namespace PLCSharp.Models //注册域构造器 .Preheating(); - foreach (var item in _DatasContext.Recipes) - { - Recipes.Add(item.DeepCopy()); - } - - if (Recipes.Count == 0) - { - var recipe = new Recipe - { - Name = "First", - Comment = "", - Prompt = "默认配方", - Current = true - }; - Recipes.Add(recipe); - RecipeSelected = recipe; - ExecuteRecipeManage("Save"); - CurrentRecipe = recipe; - } - else - { - CurrentRecipe = Recipes.Where(r => r.Current).FirstOrDefault(); - - if (CurrentRecipe == null) - { - CurrentRecipe = Recipes.FirstOrDefault(); - CurrentRecipe.Current = true; - RecipeSelected = CurrentRecipe; - ExecuteRecipeManage("Save"); - } - RecipeSelected ??= CurrentRecipe; - } + Project = container.Resolve(); + machineData = container.Resolve(); + Recipes = Project.Recipes; + CurrentRecipe = RecipeSelected = Recipes.Single(r => r.ID == Project.DefaultRecipeId); VariablesModel = container.Resolve(); VariablesModel.Init(this); @@ -80,6 +52,8 @@ namespace PLCSharp.Models ControllersModel.Init(this); WorkflowsModel = container.Resolve(); + WorkflowsModel.Init(this); + WorkflowsModel.Workflows = Project.Flows(CurrentRecipe.ID); VisionsModel = container.Resolve(); diff --git a/PLCSharpWpf/Models/ProjectConfiguration.cs b/PLCSharpWpf/Models/ProjectConfiguration.cs new file mode 100644 index 0000000..a883853 --- /dev/null +++ b/PLCSharpWpf/Models/ProjectConfiguration.cs @@ -0,0 +1,127 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using PLCSharp.VVMs.Vision; +using System.Data; +using System.IO; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace PLCSharp.Models; + +// The editor keeps using its EF queries against a private in-memory working copy. +// Only the explicitly listed configuration tables are part of the project format. +internal static class ProjectConfiguration +{ + internal static readonly IReadOnlyDictionary Groups = new Dictionary + { + ["hardware"] = ["Controllers", "Axes", "DI", "DQ", "Connects", "Robots", "Cylinders", "Cameras"], + ["variables"] = ["Variables", "SystemVariables"], + ["points"] = ["AxisPoints", "Matrices", "InterpolationGroups", "RobotPoints", "RobotMatrices"], + ["vision"] = ["VisionFunctions", "ImageDatas", "LocalImageDatas"], + ["interface"] = ["CanvasConfigs", "CustomControls"] + }; + + private static IEntityType Entity(DatasContext db, string table) => + db.Model.GetEntityTypes().Single(e => e.GetTableName() == table); + + private static string Quote(string identifier) => "\"" + identifier.Replace("\"", "\"\"") + "\""; + + internal static JsonObject Capture(DatasContext db, string[] tables) + { + var document = new JsonObject(); + foreach (var table in tables) + { + var entity = Entity(db, table); + var fields = entity.GetProperties().ToArray(); + using var query = db.Database.GetDbConnection().CreateCommand(); + var columns = string.Join(", ", fields.Select(p => Quote(p.GetColumnName()))); + query.CommandText = $"SELECT {columns} FROM {Quote(table)} ORDER BY {Quote(entity.FindPrimaryKey().Properties.Single().GetColumnName())}"; + using var reader = query.ExecuteReader(); + var rows = new JsonArray(); + while (reader.Read()) + { + var row = new JsonObject(); + for (int i = 0; i < fields.Length; i++) + { + var p = fields[i]; + JsonNode value = null; + if (!reader.IsDBNull(i)) + { + var raw = reader.GetValue(i); + value = IsJson(p) ? (JsonNode.Parse((string)raw) ?? JsonValue.Create("null")) : JsonSerializer.SerializeToNode(raw); + if (table == "VisionFunctions" && p.GetColumnName() == "VisionFlows") + EmbedImageInputs(value); + } + row.Add(p.GetColumnName(), value); + } + rows.Add(row); + } + document.Add(table, rows); + } + return document; + } + + private static bool IsJson(IProperty property) => property.ClrType == typeof(string) + && property.Name.StartsWith("Serialized", StringComparison.Ordinal); + + private static void EmbedImageInputs(JsonNode flows) + { + foreach (var flow in flows.AsArray()) + { + if ((int?)flow["Type"] != (int)VisionFlowType.从文件获取图片 || + flow["StringParams"] is not JsonObject args || args["Path"] is not JsonValue path) continue; + if (args["ImageBase64"] == null) + args["ImageBase64"] = Convert.ToBase64String(File.ReadAllBytes(path.GetValue())); + args["Path"] = Path.GetFileName(path.GetValue()); + } + } + + internal static void Restore(DatasContext db, string[] tables, JsonObject document) + { + foreach (var table in tables) + { + var entity = Entity(db, table); + var fields = entity.GetProperties().ToArray(); + if (document[table] is not JsonArray rows) + throw new InvalidDataException($"工程配置缺少 {table}。"); + using var insert = db.Database.GetDbConnection().CreateCommand(); + var columns = string.Join(", ", fields.Select(p => Quote(p.GetColumnName()))); + var parameters = fields.Select((p, i) => "$p" + i).ToArray(); + insert.CommandText = $"INSERT INTO {Quote(table)} ({columns}) VALUES ({string.Join(", ", parameters)})"; + foreach (var name in parameters) + { + var parameter = insert.CreateParameter(); + parameter.ParameterName = name; + insert.Parameters.Add(parameter); + } + foreach (var item in rows) + { + var row = item.AsObject(); + for (int i = 0; i < fields.Length; i++) + { + var p = fields[i]; + if (!row.TryGetPropertyValue(p.GetColumnName(), out var value)) + throw new InvalidDataException($"{table} 缺少字段 {p.GetColumnName()}。"); + object raw = DBNull.Value; + if (value != null) + { + if (IsJson(p)) raw = value.GetValueKind() == JsonValueKind.String && (string)value == "null" ? "null" : value.ToJsonString(); + else if (p.ClrType == typeof(byte[])) raw = Convert.FromBase64String((string)value); + else raw = value.GetValueKind() switch + { + JsonValueKind.String => (string)value, + JsonValueKind.Number when value.AsValue().TryGetValue(out var n) => n, + JsonValueKind.Number => (double)value, + _ => throw new InvalidDataException($"{table}.{p.Name} 类型无效。") + }; + // SQLite stores EF GUID keys in upper-case text. + if (p.ClrType == typeof(Guid)) raw = Guid.Parse((string)raw).ToString("D").ToUpperInvariant(); + } + insert.Parameters[i].Value = raw; + } + insert.ExecuteNonQuery(); + } + } + } +} + diff --git a/PLCSharpWpf/Models/ProjectDirectory.cs b/PLCSharpWpf/Models/ProjectDirectory.cs new file mode 100644 index 0000000..dfc1c33 --- /dev/null +++ b/PLCSharpWpf/Models/ProjectDirectory.cs @@ -0,0 +1,267 @@ +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 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 void ReadDirectory() + { + string Read(string path) + { + string value = File.ReadAllText(Path.Combine(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 = Path.Combine(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 = Path.Combine(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; + } +} + diff --git a/PLCSharpWpf/VVMs/Authority/LoginModel.cs b/PLCSharpWpf/VVMs/Authority/LoginModel.cs index be0f3c2..9ee205a 100644 --- a/PLCSharpWpf/VVMs/Authority/LoginModel.cs +++ b/PLCSharpWpf/VVMs/Authority/LoginModel.cs @@ -21,6 +21,7 @@ namespace PLCSharp.VVMs.Authority /// public LoginModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService) { + _DatasContext = container.Resolve(); //已注册用户 var users = _DatasContext.Users?.ToList(); diff --git a/PLCSharpWpf/VVMs/GlobalVariables/Variable.cs b/PLCSharpWpf/VVMs/GlobalVariables/Variable.cs index 1338ddc..53d2fd8 100644 --- a/PLCSharpWpf/VVMs/GlobalVariables/Variable.cs +++ b/PLCSharpWpf/VVMs/GlobalVariables/Variable.cs @@ -122,8 +122,21 @@ namespace PLCSharp.VVMs.GlobalVariables [Column(TypeName = "INTEGER")] public bool RetainPersistent { get; set; } + internal void RestoreValue(DatasContext context) + { + _DatasContext = context; + // Hydration is a read. Retained values must not trigger a project save while opening it. + var initial = DynamicValue(DefaultValueStr, Type); + _DefaultValue = IsValidValue(initial, Type) ? initial : null; + var saved = RetainPersistent ? DynamicValue(ValueStr, Type) : _DefaultValue; + _Value = IsValidValue(saved, Type) ? saved : null; + RaisePropertyChanged(nameof(Value)); + RaisePropertyChanged(nameof(DefaultValue)); + } + private static bool IsValidValue(dynamic value, VariableDataType type) { + if (value is null) return false; return type switch { VariableDataType.Int32 => int.TryParse(value.ToString(), out int _), @@ -286,8 +299,21 @@ namespace PLCSharp.VVMs.GlobalVariables [Column(TypeName = "INTEGER")] public bool RetainPersistent { get; set; } + internal void RestoreValue(DatasContext context) + { + _DatasContext = context; + // Hydration is a read. Retained values must not trigger a project save while opening it. + var initial = DynamicValue(DefaultValueStr, Type); + _DefaultValue = IsValidValue(initial, Type) ? initial : null; + var saved = RetainPersistent ? DynamicValue(ValueStr, Type) : _DefaultValue; + _Value = IsValidValue(saved, Type) ? saved : null; + RaisePropertyChanged(nameof(Value)); + RaisePropertyChanged(nameof(DefaultValue)); + } + private static bool IsValidValue(dynamic value, VariableDataType type) { + if (value is null) return false; return type switch { VariableDataType.Int32 => int.TryParse(value.ToString(), out int _), diff --git a/PLCSharpWpf/VVMs/GlobalVariables/VariablesModel.cs b/PLCSharpWpf/VVMs/GlobalVariables/VariablesModel.cs index 358d691..4831f78 100644 --- a/PLCSharpWpf/VVMs/GlobalVariables/VariablesModel.cs +++ b/PLCSharpWpf/VVMs/GlobalVariables/VariablesModel.cs @@ -51,16 +51,7 @@ namespace PLCSharp.VVMs.GlobalVariables var variables = _DatasContext.Variables.Where(c => c.RecipeID == CurrentRecipeID); foreach (var item in variables) { - item._DatasContext = _DatasContext; - if (item.RetainPersistent) - { - item.Value = Variable.DynamicValue(item.ValueStr, item.Type); - } - else - { - item.Value = Variable.DynamicValue(item.DefaultValueStr, item.Type); - item.DefaultValue = item.Value; - } + item.RestoreValue(_DatasContext); Variables.Add(item); } @@ -69,16 +60,7 @@ namespace PLCSharp.VVMs.GlobalVariables var systemVariables = _DatasContext.SystemVariables.Where(c => c.RecipeID == CurrentRecipeID); foreach (var item in systemVariables) { - item._DatasContext = _DatasContext; - if (item.RetainPersistent) - { - item.Value = Variable.DynamicValue(item.ValueStr, item.Type); - } - else - { - item.Value = Variable.DynamicValue(item.DefaultValueStr, item.Type); - item.DefaultValue = item.Value; - } + item.RestoreValue(_DatasContext); SystemVariables.Add(item); } } diff --git a/PLCSharpWpf/VVMs/MainWindow/MainWindow.xaml.cs b/PLCSharpWpf/VVMs/MainWindow/MainWindow.xaml.cs index c294c84..d855615 100644 --- a/PLCSharpWpf/VVMs/MainWindow/MainWindow.xaml.cs +++ b/PLCSharpWpf/VVMs/MainWindow/MainWindow.xaml.cs @@ -58,6 +58,7 @@ namespace PLCSharp.VVMs.MainWindow private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { + if (((App)Application.Current).SwitchingProject) return; var vm = this.DataContext as MainWindowViewModel; vm?.Exit.Execute(); e.Cancel = true; diff --git a/PLCSharpWpf/VVMs/Recipe/RecipeEdit.xaml b/PLCSharpWpf/VVMs/Recipe/RecipeEdit.xaml index f863181..dcc9cfa 100644 --- a/PLCSharpWpf/VVMs/Recipe/RecipeEdit.xaml +++ b/PLCSharpWpf/VVMs/Recipe/RecipeEdit.xaml @@ -66,5 +66,11 @@ + +