XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Controls.Primitives;
using Windows.System;
using XFEWorkflow.Controls;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Services;

namespace XFEWorkflow.Views;

public sealed partial class MainPage
{
    internal async Task SmokePaletteLibraryAsync(string output)
    {
        await ready.Task;
        var previousWorkflow = ViewModel.SelectedWorkflow; var state = services.State;
        var favorites = state.FavoriteCapabilities; var recent = state.RecentCapabilities; var expanded = state.ExpandedPaletteCategories;
        var root = (FrameworkElement)App.MainWindow.Content; var theme = root.RequestedTheme; var size = App.MainWindow.AppWindow.Size;
        var keyTrace = new List<string>();
        Microsoft.UI.Xaml.Input.KeyEventHandler traceKey = (_, e) => keyTrace.Add($"{e.Key}: handled={e.Handled}, source={e.OriginalSource?.GetType().Name}, focus={PaletteSearch.FocusState}, text={PaletteSearch.Text}, first={ViewModel.PaletteRows.OfType<PaletteItem>().FirstOrDefault()?.Descriptor.Id}, status={ViewModel.Status}");
        root.AddHandler(PreviewKeyDownEvent, traceKey, true); root.AddHandler(KeyDownEvent, traceKey, true);
        async Task<FrameworkElement> Row(object item)
        {
            PaletteList.ScrollIntoView(item, ScrollIntoViewAlignment.Leading);
            double? previousY = null; var stableFrames = 0;
            for (var i = 0; i < 40; i++)
            {
                await Task.Delay(50);
                if (PaletteList.ContainerFromItem(item) is not FrameworkElement row) continue;
                var y = row.TransformToVisual(PaletteList).TransformPoint(new(0, 0)).Y;
                stableFrames = previousY is { } previous && Math.Abs(y - previous) < .5 && y >= 0 && y + row.ActualHeight <= PaletteList.ActualHeight + 1 ? stableFrames + 1 : 0;
                previousY = y;
                if (stableFrames >= 3) return row;
            }
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "palette-row-failure.png"));
            var lastRow = PaletteList.ContainerFromItem(item) as FrameworkElement;
            throw new InvalidOperationException($"节点库行未滚动至稳定的可见位置:存在={PaletteList.Items.Contains(item)}, y={lastRow?.TransformToVisual(PaletteList).TransformPoint(new(0, 0)).Y}, h={lastRow?.ActualHeight}, viewport={PaletteList.ActualHeight}");
        }
        try
        {
            App.MainWindow.Activate(); UiSmokeTest.SetForegroundWindow(WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow));
            App.MainWindow.AppWindow.Resize(new((int)(1500 * root.XamlRoot.RasterizationScale), (int)(1000 * root.XamlRoot.RasterizationScale)));
            await ViewModel.NewAsync(WorkflowTemplates.CreateGraph());
            state.SetExpandedPaletteCategories(["流程"]); ViewModel.PaletteMode = PaletteMode.All; ViewModel.PalettePluginFilter = ""; PaletteSearch.Text = ""; ViewModel.RefreshPalette();
            await Task.Delay(200);
            if (ViewModel.PaletteRows.OfType<PaletteItem>().Count() >= ViewModel.PaletteGroups.Sum(x => x.Count)) throw new InvalidOperationException("初始分类未折叠");
            var group = ViewModel.PaletteGroups.Single(x => x.Name == "文字识别");
            var header = UiSmokeTest.Descendants(await Row(group)).OfType<Button>().Single(x => x.DataContext == group);
            var graphCount = CanvasEditor.Graph.Nodes.Count;
            await UiSmokeTest.ClickElementAsync(header);
            if (!group.IsExpanded || !ViewModel.PaletteRows.OfType<PaletteItem>().Any(x => x.Descriptor.Id == "xfe.vision.ocr")) throw new InvalidOperationException("点击分类未展开节点");
            header = UiSmokeTest.Descendants(await Row(group)).OfType<Button>().Single(x => x.DataContext == group);
            await UiSmokeTest.ClickElementAsync(header);
            if (group.IsExpanded || ViewModel.PaletteRows.OfType<PaletteItem>().Any(x => x.Descriptor.Id == "xfe.vision.ocr")) throw new InvalidOperationException("点击分类未收起节点");
            if (CanvasEditor.Graph.Nodes.Count != graphCount) throw new InvalidOperationException("分类操作意外添加节点");
            PaletteSearch.Text = "屏幕 OCR";
            for (var i = 0; i < 40 && !ViewModel.PaletteRows.OfType<PaletteItem>().Any(x => x.Descriptor.Id == "xfe.vision.ocr"); i++) await Task.Delay(50);
            var ocr = ViewModel.PaletteRows.OfType<PaletteItem>().Single(x => x.Descriptor.Id == "xfe.vision.ocr");
            if (ViewModel.PaletteGroups.Any(x => !x.IsExpanded)) throw new InvalidOperationException("搜索未展开命中分类");
            var row = await Row(ocr);
            if (row.ActualHeight > 48 || !UiSmokeTest.Descendants(row).OfType<TextBlock>().Any(x => x.Text == "插件 · 屏幕与识别")) throw new InvalidOperationException("节点行不紧凑或插件名称缺失");
            var presenter = UiSmokeTest.Descendants<ListViewItemPresenter>(row).Single();
            var favoriteButton = UiSmokeTest.Descendants<ToggleButton>(row).Single();
            var favoriteRight = favoriteButton.TransformToVisual(presenter).TransformPoint(new(favoriteButton.ActualWidth, 0)).X;
            if (presenter.ActualWidth - favoriteRight < 6 || presenter.ActualWidth < PaletteList.ActualWidth - 20)
                throw new InvalidOperationException("节点行悬停背景未覆盖收藏按钮的完整范围");
            await UiSmokeTest.ClickElementAsync(UiSmokeTest.Descendants(row).OfType<ToggleButton>().Single());
            if (!ocr.IsFavorite || !state.FavoriteCapabilities.Contains(ocr.Descriptor.Id) || CanvasEditor.Graph.Nodes.Count != graphCount) throw new InvalidOperationException("收藏未生效或意外添加节点");
            PaletteSearch.Text = "";
            PalettePluginFilter.SelectedItem = ((IReadOnlyList<PaletteSourceOption>)PalettePluginFilter.ItemsSource).Single(x => x.Id == "xfe.vision");
            if (ViewModel.PaletteGroups.SelectMany(x => x).Any(x => x.Descriptor.PluginId != "xfe.vision")) throw new InvalidOperationException("插件筛选未生效");
            await UiSmokeTest.ClickElementAsync(PaletteFavorites);
            if (!ViewModel.PaletteRows.OfType<PaletteItem>().Any(x => x.Descriptor.Id == "xfe.vision.ocr") || ViewModel.PaletteRows.Any(x => x is PaletteGroup)) throw new InvalidOperationException("收藏视图未显示紧凑结果");
            ocr = ViewModel.PaletteRows.OfType<PaletteItem>().Single(x => x.Descriptor.Id == "xfe.vision.ocr");
            row = await Row(ocr);
            // Click the name, away from the independent favorite button.
            await UiSmokeTest.ClickElementAsync(UiSmokeTest.Descendants(row).OfType<TextBlock>().First(x => x.Text == ocr.Name));
            for (var i = 0; i < 40 && CanvasEditor.Graph.Nodes.Count == graphCount; i++) await Task.Delay(50);
            if (CanvasEditor.Graph.Nodes.Count != graphCount + 1 || state.RecentCapabilities[0] != ocr.Descriptor.Id) throw new InvalidOperationException("单击节点未添加或最近使用未更新");
            await UiSmokeTest.ClickElementAsync(PaletteRecent);
            if (ViewModel.PaletteRows.OfType<PaletteItem>().First().Descriptor.Id != ocr.Descriptor.Id) throw new InvalidOperationException("最近视图顺序错误");
            await UiSmokeTest.ClickElementAsync(PaletteAll);
            PalettePluginFilter.SelectedItem = ((IReadOnlyList<PaletteSourceOption>)PalettePluginFilter.ItemsSource).First();
            UiSmokeTest.PressKey(VirtualKey.K, control: true); await Task.Delay(100);
            if (PaletteSearch.FocusState == FocusState.Unfocused) throw new InvalidOperationException("Ctrl+K 未聚焦节点搜索");
            PaletteSearch.Text = "xfe.vision.ocr"; UiSmokeTest.PressKey(VirtualKey.Enter); await Task.Delay(120);
            if (CanvasEditor.Graph.Nodes.Count != graphCount + 2) throw new InvalidOperationException($"Enter 未添加搜索节点:count={CanvasEditor.Graph.Nodes.Count}, expected={graphCount + 2}, focus={PaletteSearch.FocusState}, rows={ViewModel.PaletteRows.Count}, kind={ViewModel.SelectedWorkflow?.Kind}");
            PaletteSearch.Focus(FocusState.Keyboard); UiSmokeTest.PressKey(VirtualKey.Escape); await Task.Delay(100);
            if (PaletteSearch.Text.Length != 0 || ViewModel.PaletteGroups.Single(x => x.Name == "文字识别").IsExpanded) throw new InvalidOperationException("清空搜索未恢复原有折叠状态");
            CanvasEditor.Undo();
            var nodes = CanvasEditor.Graph.Nodes.OrderBy(x => x.CapabilityId == "core.start" ? 0 : x.CapabilityId == "core.end" ? 2 : 1).ToArray();
            CanvasEditor.Graph.Edges.Clear();
            for (var i = 0; i < nodes.Length; i++) { nodes[i].X = i * 340; nodes[i].Y = 100; if (i > 0) CanvasEditor.Graph.Edges.Add(new() { FromNode = nodes[i - 1].Id, ToNode = nodes[i].Id }); }
            CanvasEditor.Refresh(); CanvasEditor.Locate(nodes[1].Id, true); CanvasEditor.CenterView(true);
            root.RequestedTheme = ElementTheme.Dark; PaletteList.ScrollIntoView(ViewModel.PaletteRows[0]); await Task.Delay(200);
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "node-library-categories-dark.png"));
            root.RequestedTheme = ElementTheme.Light; PaletteSearch.Text = "图像"; await Task.Delay(200); CanvasEditor.CenterView(true); await Task.Delay(120);
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "node-library-search-light.png"));
            PaletteSearch.Text = "__missing__"; await Task.Delay(100);
            if (PaletteEmpty.Visibility != Visibility.Visible) throw new InvalidOperationException("搜索空结果提示未显示");
            await state.SaveAsync();
        }
        finally
        {
            root.RemoveHandler(PreviewKeyDownEvent, traceKey); root.RemoveHandler(KeyDownEvent, traceKey);
            await File.WriteAllLinesAsync(Path.Combine(output, "palette-keyboard.txt"), keyTrace);
            state.Store.Update(p => { p.InstanceFavoriteCapabilities = favorites.ToList(); p.InstanceRecentCapabilities = recent; p.InstanceExpandedPaletteCategories = expanded.ToList(); });
            ViewModel.PaletteMode = PaletteMode.All; ViewModel.PalettePluginFilter = ""; PaletteSearch.Text = ""; ViewModel.RefreshPalette();
            ViewModel.SelectedWorkflow = previousWorkflow; root.RequestedTheme = theme; App.MainWindow.AppWindow.Resize(size); await state.SaveAsync();
        }
    }
    internal async Task SmokeResizablePanelsAsync(string output)
    {
        await ready.Task;
        var root = (FrameworkElement)App.MainWindow.Content; var size = App.MainWindow.AppWindow.Size; var shell = AppShellPage.Current!;
        var previousNavigation = shell.NavigationIsOpenForSmoke; var wasCollapsed = outputCollapsed;
        var preferences = services.State.Store.Read(p => new Dictionary<string, double>(p.InstancePaneSizes));
        var browser = services.Browser!;
        var splitters = new[] { PaletteSplitter, PropertySplitter, OutputSplitter, shell.NavigationSplitterForSmoke, browser.ResultSplitterForSmoke };
        void Resize(double width, double height) => App.MainWindow.AppWindow.Resize(new((int)(width * root.XamlRoot.RasterizationScale), (int)(height * root.XamlRoot.RasterizationScale)));
        void Near(double value, double expected, string message) { if (Math.Abs(value - expected) > 4) throw new InvalidOperationException(message + $":{value:0.0} / {expected:0.0}"); }
        try
        {
            App.MainWindow.Activate(); UiSmokeTest.SetForegroundWindow(WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow));
            Resize(1600, 1000); shell.SetNavigationOpenForSmoke(false); SetCodeVisible(false);
            if (outputCollapsed) ToggleOutput_Click(this, new());
            foreach (var splitter in splitters) splitter.Reset();
            PropertySplit.IsPaneOpen = true; await Task.Delay(300); ApplyPanelSizes(); await Task.Delay(150);
            var palette = PaletteColumn.ActualWidth;
            var paletteTrace = new List<string>();
            var paletteThumb = UiSmokeTest.Descendants<Thumb>(PaletteSplitter).Single();
            DragDeltaEventHandler tracePalette = (_, e) => paletteTrace.Add($"dx={e.HorizontalChange}, dy={e.VerticalChange}, size={PaletteColumn.ActualWidth}, preferred={PaletteSplitter.PreferredSize}");
            paletteThumb.DragDelta += tracePalette;
            try { await UiSmokeTest.DragElementAsync(PaletteSplitter, 64, 0); } finally { paletteThumb.DragDelta -= tracePalette; }
            await Infrastructure.Storage.AtomicJson.WriteAsync(Path.Combine(output, "palette-splitter.json"), new { before = palette, after = PaletteColumn.ActualWidth, editorWidth = EditorLayout.ActualWidth, window = App.MainWindow.AppWindow.Size, preferred = PaletteSplitter.PreferredSize, trace = paletteTrace });
            Near(PaletteColumn.ActualWidth, palette + 64, "节点库分隔条未跟随实际拖动");
            if (!PropertySplit.IsPaneOpen || PropertySplit.DisplayMode != SplitViewDisplayMode.Inline) throw new InvalidOperationException("宽窗口属性面板在拖动节点库后被意外关闭");
            var properties = PropertySplit.OpenPaneLength;
            var target = PropertySplitter.TransformToVisual(root).TransformPoint(new(PropertySplitter.ActualWidth / 2, PropertySplitter.ActualHeight / 2));
            var hits = VisualTreeHelper.FindElementsInHostCoordinates(target, root).OfType<FrameworkElement>().Select(x => x.GetType().Name + "/" + x.Name).Take(12).ToArray();
            var pointerTrace = new List<string>();
            Microsoft.UI.Xaml.Input.PointerEventHandler trace = (_, args) => pointerTrace.Add(args.OriginalSource.GetType().Name + "/" + ((args.OriginalSource as FrameworkElement)?.Name));
            PropertySplitter.AddHandler(PointerPressedEvent, trace, true);
            try { await UiSmokeTest.DragElementAsync(PropertySplitter, -56, 0); }
            finally { PropertySplitter.RemoveHandler(PointerPressedEvent, trace); }
            await Infrastructure.Storage.AtomicJson.WriteAsync(Path.Combine(output, "property-splitter.json"), new { x = target.X, y = target.Y, scale = root.XamlRoot.RasterizationScale, editorWidth = EditorLayout.ActualWidth, mode = PropertySplit.DisplayMode.ToString(), isOpen = PropertySplit.IsPaneOpen, before = properties, after = PropertySplit.OpenPaneLength, hits, pointerTrace });
            if (Math.Abs(PropertySplit.OpenPaneLength - (properties + 56)) > 4) await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "property-splitter-failure.png"));
            Near(PropertySplit.OpenPaneLength, properties + 56, "属性分隔条方向或尺寸错误");
            var height = OutputPanelRow.ActualHeight;
            await UiSmokeTest.DragElementAsync(OutputSplitter, 0, -64); Near(OutputPanelRow.ActualHeight, height + 64, "输出分隔条未调节高度");
            var customPalette = PaletteColumn.ActualWidth; var customProperties = PropertySplit.OpenPaneLength; var customOutput = OutputPanelRow.ActualHeight;
            Resize(1450, 920); await Task.Delay(200);
            Near(PaletteColumn.ActualWidth, customPalette, "窗口变化重置节点库宽度"); Near(PropertySplit.OpenPaneLength, customProperties, "窗口变化重置属性宽度"); Near(OutputPanelRow.ActualHeight, customOutput, "窗口变化重置输出高度");
            OutputSplitter.Focus(FocusState.Keyboard); UiSmokeTest.PressKey(VirtualKey.Down); await Task.Delay(120);
            Near(OutputPanelRow.ActualHeight, customOutput - 8, "方向键未调整分隔条");
            UiSmokeTest.PressKey(VirtualKey.Home); await Task.Delay(120); Near(OutputPanelRow.ActualHeight, 156, "Home 未恢复默认高度");
            Resize(1600, 1000); await Task.Delay(180);
            await UiSmokeTest.DragElementAsync(PaletteSplitter, 300, 0); Near(PaletteColumn.ActualWidth, 440, "节点库最大宽度未限制");
            await UiSmokeTest.DragElementAsync(PropertySplitter, -260, 0);
            if (CanvasEditor.ActualWidth < 356 || PropertySplit.OpenPaneLength > 520) throw new InvalidOperationException("属性拖动挤占了画布最小宽度");
            await UiSmokeTest.DragElementAsync(OutputSplitter, 0, -400);
            if (CanvasEditor.ActualHeight < 212 || OutputPanelRow.ActualHeight > 520) throw new InvalidOperationException("输出拖动挤占了编辑区最小高度");
            var preferredPalette = PaletteSplitter.PreferredSize; var preferredProperties = PropertySplitter.PreferredSize; var preferredOutput = OutputSplitter.PreferredSize;
            Resize(960, 700); await Task.Delay(250);
            if (PropertySplit.DisplayMode != SplitViewDisplayMode.Overlay || CanvasEditor.ActualWidth < 356) throw new InvalidOperationException("窄窗口未保留可用画布");
            Resize(1600, 1000); await Task.Delay(250);
            Near(PaletteColumn.ActualWidth, preferredPalette, "放大窗口未恢复偏好宽度"); Near(PropertySplit.OpenPaneLength, preferredProperties, "放大窗口未恢复属性宽度"); Near(OutputPanelRow.ActualHeight, preferredOutput, "放大窗口未恢复输出高度");
            await services.State.SaveAsync();
            Near(services.State.PaneSize("workflow.palette", 0), preferredPalette, "节点库拖动未保存");
            Near(services.State.PaneSize("workflow.output", 0), preferredOutput, "输出拖动未保存");
            // Double click the actual native separator to reset it.
            await UiSmokeTest.ClickElementAsync(PaletteSplitter); await UiSmokeTest.ClickElementAsync(PaletteSplitter); await Task.Delay(100);
            Near(PaletteColumn.ActualWidth, 260, "双击分隔条未恢复默认宽度");
            PropertySplitter.Reset(); OutputSplitter.Reset(); await Task.Delay(150);
            shell.SetNavigationOpenForSmoke(true); await Task.Delay(300);
            var navigation = shell.NavigationWidthForSmoke;
            await File.WriteAllTextAsync(Path.Combine(output, "navigation-splitter.txt"), shell.NavigationStateForSmoke);
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "navigation-splitter.png"));
            await UiSmokeTest.DragElementAsync(shell.NavigationSplitterForSmoke, 32, 0); Near(shell.NavigationWidthForSmoke, navigation + 32, "导航栏分隔条未调节宽度");
            shell.SetNavigationOpenForSmoke(false); await Task.Delay(160); shell.SetNavigationOpenForSmoke(true); await Task.Delay(200);
            Near(shell.NavigationWidthForSmoke, navigation + 32, "导航收放丢失自定义宽度");
            shell.SetNavigationOpenForSmoke(false); await Task.Delay(200);
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "workflow-resizable-panels.png"));
            shell.ShowBrowser(true); await Task.Delay(200);
            var resultHeight = browser.ResultHeightForSmoke;
            var sideInspector = browser.ResultSplitterForSmoke.Orientation == Orientation.Vertical;
            await UiSmokeTest.DragElementAsync(browser.ResultSplitterForSmoke, sideInspector ? -48 : 0, sideInspector ? 0 : -48); Near(browser.ResultHeightForSmoke, resultHeight + 48, "浏览器拾取详情区未调节大小");
            await services.State.SaveAsync();
        }
        finally
        {
            shell.ShowBrowser(false); services.State.Store.Update(p => p.InstancePaneSizes = preferences);
            foreach (var splitter in splitters) splitter.ReloadPreference();
            if (wasCollapsed != outputCollapsed) ToggleOutput_Click(this, new());
            Resize(size.Width / root.XamlRoot.RasterizationScale, size.Height / root.XamlRoot.RasterizationScale);
            shell.SetNavigationOpenForSmoke(previousNavigation); await services.State.SaveAsync();
        }
    }
}