using Microsoft.UI.Xaml.Input; using Microsoft.UI.Xaml.Navigation; using Windows.System; using XFEWorkflow.Abstractions; using XFEWorkflow.Core.Runtime; using XFEWorkflow.Services; namespace XFEWorkflow.Views; public sealed partial class WorkflowEditorPage : Page { public static WorkflowEditorPage? Current { get; private set; } internal TabView Documents { get; } = new() { Name = "WorkflowDocumentTabs", TabWidthMode = TabViewWidthMode.SizeToContent, CanReorderTabs = true, AllowDropTabs = true, VerticalAlignment = VerticalAlignment.Stretch, Padding = new(0) }; public MainPage? ActiveEditor => (Documents.SelectedItem as TabViewItem)?.Content as MainPage; internal Border DocumentSurface { get; } private readonly Grid workspace = new(); private readonly ColumnDefinition paletteColumn = new() { Width = new(0) }; private readonly ColumnDefinition paletteSplitterColumn = new() { Width = new(0) }; private readonly RowDefinition outputSplitterRow = new() { Height = new(0) }; private readonly RowDefinition outputRow = new() { Height = new(0) }; private MainPage? panelOwner; private readonly InfoBar error = new() { Severity = InfoBarSeverity.Error, IsClosable = true, Visibility = Visibility.Collapsed }; private readonly Button run = new() { Content = "▶ 运行", Style = (Style)Application.Current.Resources["AccentButtonStyle"], Padding = new(18, 7, 18, 7) }; private readonly Button stop = new() { Content = "□ 停止" }; private readonly Button stepOver = new() { Content = new SymbolIcon(Symbol.Forward) }; private readonly Button stepInto = new() { Content = new SymbolIcon(Symbol.Download) }; private readonly TextBlock empty = new() { Text = "从工作流列表打开任务,或点击 + 新建工作流", HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Opacity = .6 }; private readonly Dictionary documents = []; private readonly SemaphoreSlim openGate = new(1); public WorkflowEditorPage() { InitializeComponent(); Current = this; NavigationCacheMode = NavigationCacheMode.Required; var root = new Grid { RowSpacing = 6 }; root.RowDefinitions.Add(new() { Height = GridLength.Auto }); root.RowDefinitions.Add(new() { Height = GridLength.Auto }); root.RowDefinitions.Add(new()); var toolbar = new Grid(); toolbar.ColumnDefinitions.Add(new()); toolbar.ColumnDefinitions.Add(new() { Width = GridLength.Auto }); var menus = new MenuBar(); toolbar.Children.Add(menus); MenuBarItem Menu(string title) { var item = new MenuBarItem { Title = title }; menus.Items.Add(item); return item; } void Command(MenuBarItem menu, string title, Func action) { var item = new MenuFlyoutItem { Text = title }; item.Click += async (_, _) => await GuardAsync(action); menu.Items.Add(item); } void Edit(MenuBarItem menu, string title, string command) => Command(menu, title, async () => { if (ActiveEditor is { } editor) await editor.ExecuteEditorCommandAsync(command); }); var file = Menu("文件"); Command(file, "新建工作流 Ctrl+N", NewAsync); Command(file, "打开工作流列表", ShowListAsync); file.Items.Add(new MenuFlyoutSeparator()); Edit(file, "保存 Ctrl+S", "save"); Command(file, "保存全部", SaveAllAsync); Command(file, "导入工作流", ImportAsync); Edit(file, "导出工作流", "export"); Command(file, "关闭当前标签页 Ctrl+W", async () => { if (Documents.SelectedItem is TabViewItem item) await CloseAsync(item); }); var edit = Menu("编辑"); Edit(edit, "撤销", "undo"); Edit(edit, "重做", "redo"); edit.Items.Add(new MenuFlyoutSeparator()); Edit(edit, "复制节点", "copy"); Edit(edit, "粘贴节点", "paste"); Edit(edit, "删除选中节点或连线 Delete", "delete"); Edit(edit, "全选节点", "selectAll"); Edit(edit, "重命名工作流", "rename"); var workflow = Menu("工作流"); Edit(workflow, "校验", "validate"); Edit(workflow, "参数、返回值与变量", "settings"); Edit(workflow, "封装为节点 / 制作插件", "node"); var debug = Menu("调试"); Edit(debug, "运行 / 继续 F5", "run"); Edit(debug, "暂停到下一节点", "pause"); Edit(debug, "停止 Shift+F5", "stop"); debug.Items.Add(new MenuFlyoutSeparator()); Edit(debug, "设置 / 取消断点 F9", "breakpoint"); Edit(debug, "单步越过 F10", "stepOver"); Edit(debug, "单步进入 F11", "stepInto"); var view = Menu("视图"); Edit(view, "节点属性", "properties"); Edit(view, "运行输出与诊断", "output"); Edit(view, "居中画布", "center"); Edit(view, "重置面板布局", "layout"); var tools = Menu("工具"); Command(tools, "新建 AI → 企微模板", () => TemplateAsync(WorkflowTemplates.AiNotification())); Command(tools, "新建框选 OCR 模板", () => TemplateAsync(WorkflowTemplates.ScreenOcr())); Command(tools, "插件中心", () => { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo(); return Task.CompletedTask; }); ToolTipService.SetToolTip(run, "运行 / 继续 · F5"); ToolTipService.SetToolTip(stop, "停止 · Shift+F5"); ToolTipService.SetToolTip(stepOver, "单步越过 · F10"); ToolTipService.SetToolTip(stepInto, "单步进入 · F11"); Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(stepOver, "单步越过 F10"); Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(stepInto, "单步进入 F11"); var quick = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center }; quick.Children.Add(run); quick.Children.Add(stepOver); quick.Children.Add(stepInto); quick.Children.Add(stop); Grid.SetColumn(quick, 1); toolbar.Children.Add(quick); root.Children.Add(toolbar); run.Click += async (_, _) => await GuardAsync(async () => { if (ActiveEditor is { } editor) await editor.ExecuteEditorCommandAsync("run"); }); stop.Click += async (_, _) => await GuardAsync(async () => { if (ActiveEditor is { } editor) await editor.ExecuteEditorCommandAsync("stop"); }); stepOver.Click += async (_, _) => await GuardAsync(async () => { if (ActiveEditor is { } editor) await editor.ExecuteEditorCommandAsync("stepOver"); }); stepInto.Click += async (_, _) => await GuardAsync(async () => { if (ActiveEditor is { } editor) await editor.ExecuteEditorCommandAsync("stepInto"); }); Grid.SetRow(error, 1); root.Children.Add(error); workspace.ColumnDefinitions.Add(paletteColumn); workspace.ColumnDefinitions.Add(paletteSplitterColumn); workspace.ColumnDefinitions.Add(new()); workspace.RowDefinitions.Add(new()); workspace.RowDefinitions.Add(outputSplitterRow); workspace.RowDefinitions.Add(outputRow); workspace.RowDefinitions.Add(new() { Height = GridLength.Auto }); var documentContent = new Grid(); documentContent.Children.Add(Documents); documentContent.Children.Add(empty); DocumentSurface = new Border { Name = "WorkflowDocumentSurface", Style = (Style)Resources["WorkflowDocumentSurfaceStyle"], Child = documentContent }; Grid.SetColumn(DocumentSurface, 2); workspace.Children.Add(DocumentSurface); Grid.SetRow(workspace, 2); root.Children.Add(workspace); Content = root; Documents.TabItemsChanged += (_, _) => UpdateChrome(); Documents.SelectionChanged += (_, _) => UpdateChrome(); Documents.AddTabButtonClick += async (_, _) => await GuardAsync(NewAsync); Documents.TabCloseRequested += async (_, args) => await GuardAsync(() => CloseAsync(args.Tab)); error.Closed += (_, _) => error.Visibility = Visibility.Collapsed; foreach (var pair in new[] { (VirtualKey.S, (Func)SaveAllAsync), (VirtualKey.N, (Func)NewAsync), (VirtualKey.W, (Func)(async () => { if (Documents.SelectedItem is TabViewItem item) await CloseAsync(item); })), (VirtualKey.K, (Func)(() => ActiveEditor?.ExecuteEditorCommandAsync("search") ?? Task.CompletedTask)) }) { var accelerator = new KeyboardAccelerator { Key = pair.Item1, Modifiers = VirtualKeyModifiers.Control }; accelerator.Invoked += async (_, e) => { e.Handled = true; await GuardAsync(pair.Item2); }; KeyboardAccelerators.Add(accelerator); } foreach (var (key, modifiers, command) in new[] { (VirtualKey.F5, VirtualKeyModifiers.None, "run"), (VirtualKey.F5, VirtualKeyModifiers.Shift, "stop"), (VirtualKey.F9, VirtualKeyModifiers.None, "breakpoint"), (VirtualKey.F10, VirtualKeyModifiers.None, "stepOver"), (VirtualKey.F11, VirtualKeyModifiers.None, "stepInto") }) { var accelerator = new KeyboardAccelerator { Key = key, Modifiers = modifiers }; accelerator.Invoked += async (_, e) => { if (ActiveEditor is not { } editor) return; e.Handled = true; await GuardAsync(() => editor.ExecuteEditorCommandAsync(command)); }; KeyboardAccelerators.Add(accelerator); } Loaded += (_, _) => UpdateChrome(); Unloaded += async (_, _) => { foreach (var tab in documents.Values) ((MainPage)tab.Content).DeactivateDocument(); await GuardAsync(SaveAllAsync); }; UpdateChrome(); } protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); await GuardAsync(async () => { await AppServices.Current.Ready; if (e.Parameter is WorkflowNavigationTarget target) { var editor = await OpenAsync(target.WorkflowId); editor.NavigateToNode(target.NodeId, target.Line, target.Column); } else if (e.Parameter is string runId) { var record = (await AppServices.Current.Runs.HistoryAsync()).FirstOrDefault(x => x.Id == runId); if (record is not null) (await OpenAsync(record.WorkflowId)).NavigateToNode(record.ErrorNodeId); } UpdateChrome(); }); } internal async Task OpenAsync(string id) { await openGate.WaitAsync(); try { if (documents.TryGetValue(id, out var existing)) { Documents.SelectedItem = existing; return (MainPage)existing.Content; } var flow = await AppServices.Current.Workflows.GetAsync(id); var editor = new MainPage(); await editor.OpenDocumentAsync(flow); var tab = new TabViewItem { Header = flow.Name, Content = editor, IconSource = new FontIconSource { Glyph = "\uEF90" }, IsClosable = true, Tag = id, HorizontalContentAlignment = HorizontalAlignment.Stretch, VerticalContentAlignment = VerticalAlignment.Stretch }; editor.ViewModel.PropertyChanged += (_, _) => { tab.Header = (editor.ViewModel.SelectedWorkflow?.Name ?? flow.Name) + (editor.ViewModel.Status.Contains("未保存", StringComparison.Ordinal) ? " •" : ""); if (ReferenceEquals(ActiveEditor, editor)) UpdateRunButtons(); }; documents[id] = tab; Documents.TabItems.Add(tab); Documents.SelectedItem = tab; UpdateChrome(); return editor; } finally { openGate.Release(); } } private void UpdateChrome() { empty.Visibility = documents.Count == 0 ? Visibility.Visible : Visibility.Collapsed; if (!ReferenceEquals(panelOwner, ActiveEditor)) { panelOwner?.DetachDocumentPanels(); panelOwner = ActiveEditor; paletteSplitterColumn.Width = new(panelOwner is null ? 0 : 8); paletteColumn.Width = new(panelOwner is null ? 0 : 260); outputSplitterRow.Height = new(panelOwner is null ? 0 : 8); outputRow.Height = new(panelOwner is null ? 0 : 156); panelOwner?.AttachDocumentPanels(workspace, paletteColumn, outputRow); } foreach (var tab in documents.Values) { var editor = (MainPage)tab.Content; if (ReferenceEquals(editor, ActiveEditor)) editor.ActivateDocument(); else editor.DeactivateDocument(); } UpdateRunButtons(); } private void UpdateRunButtons() { run.Content = ActiveEditor is { ViewModel.IsDebugPaused: true } ? "▶ 继续" : "▶ 运行"; run.IsEnabled = ActiveEditor is { ViewModel.IsRunning: false } or { ViewModel.IsDebugPaused: true }; stop.IsEnabled = ActiveEditor is { ViewModel.IsRunning: true }; stepOver.IsEnabled = stepInto.IsEnabled = ActiveEditor is { } editor && (!editor.ViewModel.IsRunning || AppServices.Current.Runs.IsDebugging(editor.ViewModel.SelectedWorkflow?.Id ?? "")); } public async Task SaveAllAsync() { foreach (var tab in documents.Values.ToArray()) await ((MainPage)tab.Content).SaveDocumentAsync(); } private async Task CloseAsync(TabViewItem item) { if (!documents.ContainsKey((string)item.Tag)) return; await ((MainPage)item.Content).CloseDocumentAsync(); documents.Remove((string)item.Tag); Documents.TabItems.Remove(item); UpdateChrome(); } internal static Task SaveOpenAsync(string id) => Current?.documents.TryGetValue(id, out var tab) == true ? ((MainPage)tab.Content).SaveDocumentAsync() : Task.CompletedTask; internal static Task CloseOpenAsync(string id) => Current?.documents.TryGetValue(id, out var tab) == true ? Current.CloseAsync(tab) : Task.CompletedTask; private Task ShowListAsync() { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo(); return Task.CompletedTask; } private async Task NewAsync() { if (await WorkflowListPage.CreateWorkflowAsync(XamlRoot) is { } workflow) await OpenAsync(workflow.Id); } private async Task TemplateAsync(WorkflowDefinition workflow) { workflow.Enabled = false; await AppServices.Current.Workflows.SaveAsync(workflow); await OpenAsync(workflow.Id); } private async Task ImportAsync() { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.FileTypeFilter.Add(".xfeworkflow"); picker.FileTypeFilter.Add(".json"); WinRT.Interop.InitializeWithWindow.Initialize(picker, WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow)); if (await picker.PickSingleFileAsync() is { } file) await OpenAsync((await AppServices.Current.Workflows.ImportAsync(file.Path)).Id); } private async Task GuardAsync(Func action) { try { error.IsOpen = false; error.Visibility = Visibility.Collapsed; await action(); } catch (Exception ex) { error.Message = AppServices.Current.Redactor.Redact(ex.Message); error.Visibility = Visibility.Visible; error.IsOpen = true; } } }