plcsharp/PLCSharpWpf/Models/GlobalModel.Project.cs

140 lines
6.8 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.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 "previewUndo" or "apply" or "status")
{
if (operation == "apply" && (ModeState.State.Execute || WorkflowsModel.IsBusy))
throw new InvalidOperationException("运行或切换配方期间无法保存 AI 修改。");
return 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("编辑器变量列表存在更改,请先保存并重新预览。");
return accepted;
});
}
var result = ProjectInspection.Query(Project, operation, args);
if (operation == "summary")
{
result["source"] = "editor";
result["currentRecipeId"] = CurrentRecipe.ID.ToString();
}
return result;
}
private AsyncDelegateCommand<string> projectManage;
public AsyncDelegateCommand<string> ProjectManage => projectManage ??= new AsyncDelegateCommand<string>(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}");
}
}
}