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 ?? "未保存工程"; public bool AllowAiAccess { get; set; } private DelegateCommand copyMcpConfig; public DelegateCommand CopyMcpConfig => copyMcpConfig ??= new DelegateCommand(() => { if (Project.Root == null) { SendInfoDialog("请先保存工程。"); return; } var exe = System.IO.Path.Combine(AppContext.BaseDirectory, "PLCSharp.Mcp.exe"); if (!System.IO.File.Exists(exe)) { var picker = new OpenFileDialog { Title = "选择 MCP 服务程序", Filter = "PLCSharp.Mcp.exe|PLCSharp.Mcp.exe" }; if (picker.ShowDialog() != true) return; exe = picker.FileName; } var config = new { mcpServers = new { plcsharp = new { command = exe, args = new[] { "--project", Project.Root, "--allow-write" } } } }; Clipboard.SetText(System.Text.Json.JsonSerializer.Serialize(config, new System.Text.Json.JsonSerializerOptions { WriteIndented = true })); SendInfoDialog("已复制当前工程的 MCP 配置。仅需读取时可移除 --allow-write。"); }); private readonly ProjectChanges aiChanges = new(); internal System.Text.Json.Nodes.JsonNode HandleAiRequest(System.Text.Json.Nodes.JsonObject request) { if (!AllowAiAccess) throw new InvalidOperationException("请在机种配方页面启用 AI 访问。"); string operation = (string)request["operation"]; var args = request["arguments"].AsObject(); if (operation is "preview" or "previewScript" or "previewRename" or "previewWorkflowRename" or "previewPointRename" or "previewVisionRename" or "previewAxisRename" or "previewIoRename" or "previewVisionAssetRename" or "previewObjectRename" or "previewDeviceRename" or "previewUndo" or "apply" or "status") { if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); Action updateEditorView = null; var resultChange = aiChanges.Execute(Project, operation, args, true, change => { bool accepted = change.Review != null || change.Rename != null ? PLCSharp.VVMs.Workflows.ScriptReviewWindow.Confirm(change, Project.Root, Application.Current.MainWindow) : MessageBox.Show($"{change.Path}\n{change.Kind} / {change.Name}\n\n原备注:{change.Before}\n新备注:{change.After}", "应用 AI 修改", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes; if (accepted && (ModeState.State.Execute || WorkflowsModel.IsBusy)) throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。"); if (accepted && change.Rename is { Kind: "Variables" } rename && CurrentRecipe.ID == rename.RecipeId && (!VariablesModel.Variables.Any(v => v.ID == rename.VariableId && v.Name == rename.OldName) || VariablesModel.Variables.Any(v => v.ID != rename.VariableId && (v.Name == rename.NewName || v.Name == rename.OldName)))) throw new InvalidOperationException("编辑器变量列表存在更改,请先保存并重新预览。"); if (accepted && change.Rename is { Kind: "VisionFunctions" } vision && CurrentRecipe.ID == vision.RecipeId) { var functions = VisionsModel.VisionFunctions; var target = functions.SingleOrDefault(v => v.ID == vision.ObjectId); if (target == null || target.Name != vision.OldName || functions.Any(v => v.ID != vision.ObjectId && (v.Name == vision.OldName || v.Name == vision.NewName))) throw new ProjectConflictException("编辑器视觉功能列表有更改,请先保存并重新预览。"); updateEditorView = () => target.SetReviewedName(vision.NewName); } if (accepted && change.Rename is { IsPoint: true } point && CurrentRecipe.ID == point.RecipeId) { if (point.Kind == "AxisPoints") updateEditorView = Project.PreparePointView(point, ControllersModel.AxisPoints, ControllersModel.Matrices); else { var owner = Project.Data.RobotPoints.Single(p => p.ID == point.ObjectId).RobotID; var robot = RobotModel.Robots.SingleOrDefault(r => r.ID == owner); if (robot != null) updateEditorView = Project.PreparePointView(point, robot.Points, robot.RobotMatrices); } } if (accepted && change.Rename is { Kind: "Axes" } axis) updateEditorView = Project.PrepareAxisView(axis, ControllersModel, CurrentRecipe.ID); if (accepted && change.Rename is { IsIo: true } io) updateEditorView = Project.PrepareIoView(io, ControllersModel, CylindersModel); if (accepted && change.Rename is { Nested: not null } member && CurrentRecipe.ID == member.RecipeId) { object owner = member.Kind switch { "VisionLocalVariables" => VisionsModel.VisionFunctions.Single(f => f.ID == member.ObjectId), "ControlMeasurements" => CustomControls.Single(c => c.ID == member.ObjectId), _ => ControllersModel.InterpolationGroups.Single(g => g.ID == member.ObjectId) }; updateEditorView = ProjectDirectory.PrepareNestedView(member, owner); } if (accepted && change.Rename is { IsMatrixOrGroup: true } matrix && CurrentRecipe.ID == matrix.RecipeId) { IEnumerable objects = matrix.Kind switch { "Matrices" => ControllersModel.Matrices, "InterpolationGroups" => ControllersModel.InterpolationGroups, _ => RobotModel.Robots.SingleOrDefault(r => r.ID == Project.Data.RobotMatrices.Find(matrix.ObjectId).RobotID)?.RobotMatrices }; if (objects != null) updateEditorView = Project.PreparePointView(matrix, objects, []); } if (accepted && change.Rename is { IsVisionAsset: true } asset) updateEditorView = Project.PrepareAssetView(asset, VisionsModel, CurrentRecipe.ID, CustomControls, VariablesModel.SystemVariables); if (accepted && change.Rename is { IsDevice: true } device) updateEditorView = PrepareDeviceView(device); return accepted; }); if ((string)resultChange["Status"] == "saved") updateEditorView?.Invoke(); return resultChange; } var result = ProjectInspection.Query(Project, operation, args); if (operation == "summary") { result["source"] = "editor"; result["currentRecipeId"] = CurrentRecipe.ID.ToString(); } return result; } 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); ((App)Application.Current).AttachProjectPipe(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}"); } } }