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.Media.Imaging;
using System.Runtime.InteropServices.WindowsRuntime;
using XFEExtension.NetCore.XFEConsole;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Services;

namespace XFEWorkflow.Views;

public sealed partial class MainPage
{
    internal async Task SmokeConnectedTabsAsync(string output)
    {
        await ready.Task;
        var root = (FrameworkElement)App.MainWindow.Content;
        var theme = root.RequestedTheme; var selected = RunPanel.SelectedIndex; var wasCollapsed = outputCollapsed;
        var windowSize = App.MainWindow.AppWindow.Size;
        var evidence = new List<object>(); var colors = new Dictionary<ElementTheme, Windows.UI.Color>();
        try
        {
            // A preceding narrow-window check may have clamped the panel to its
            // minimum height. Give all three content surfaces room for pixel QA.
            var scale = root.XamlRoot.RasterizationScale;
            App.MainWindow.AppWindow.Resize(new((int)(1600 * scale), (int)(1000 * scale))); await Task.Delay(300);
            if (wasCollapsed) ToggleOutput_Click(this, new());
            foreach (var requested in new[] { ElementTheme.Dark, ElementTheme.Light, ElementTheme.Dark })
            {
                root.RequestedTheme = requested;
                foreach (var index in new[] { 0, 1, 2 })
                {
                    RunPanel.SelectedIndex = index; await Task.Delay(300);
                    var tab = (TabViewItem)RunPanel.TabItems[index];
                    var surface = index switch { 0 => OutputSurface, 1 => DiagnosticsSurface, _ => DebugSurface };
                    var path = UiSmokeTest.Descendants<Microsoft.UI.Xaml.Shapes.Path>(tab).Single(x => x.Name == "SelectedBackgroundPath");
                    var color = ((SolidColorBrush)surface.Background).Color;
                    if (path.Fill is not SolidColorBrush fill || fill.Color != color) throw new InvalidOperationException("选中选项卡与内容区背景不一致");
                    var bodyTop = surface.TransformToVisual(RunPanel).TransformPoint(new(0, 0)).Y;
                    var tabBottom = tab.TransformToVisual(RunPanel).TransformPoint(new(0, tab.ActualHeight)).Y;
                    if (Math.Abs(bodyTop - tabBottom) > 1 || surface.ActualHeight < 30) throw new InvalidOperationException($"选项卡与内容区存在间隙或没有铺满面板:top={bodyTop}, bottom={tabBottom}, height={surface.ActualHeight}, loaded={IsLoaded}, document={documentLayout}");
                    var bitmap = new RenderTargetBitmap(); await bitmap.RenderAsync(RunPanel);
                    var pixels = (await bitmap.GetPixelsAsync()).ToArray();
                    var scaleX = bitmap.PixelWidth / RunPanel.ActualWidth; var scaleY = bitmap.PixelHeight / RunPanel.ActualHeight;
                    var sampleX = (int)(tab.TransformToVisual(RunPanel).TransformPoint(new(tab.ActualWidth / 2, 0)).X * scaleX);
                    var seam = (int)Math.Round(bodyTop * scaleY);
                    // Check rendered pixels across the actual header/body boundary,
                    // away from text and icons, to detect a visible separator or gap.
                    for (var y = seam - 3; y <= seam + 3; y++)
                    {
                        var offset = (y * bitmap.PixelWidth + sampleX) * 4;
                        if (Math.Abs(pixels[offset] - color.B) > 1 || Math.Abs(pixels[offset + 1] - color.G) > 1 || Math.Abs(pixels[offset + 2] - color.R) > 1 || pixels[offset + 3] != 255)
                            throw new InvalidOperationException($"选项卡与内容区接缝颜色不连续:{requested}, tab={index}, row={y - seam}");
                    }
                    colors[requested] = color;
                    evidence.Add(new { theme = requested.ToString(), selected = index, background = color.ToString(), bodyTop, tabBottom, seamPixelsMatch = true });
                    await UiSmokeTest.CaptureElementAsync(RunPanel, Path.Combine(output, $"connected-tabs-{requested.ToString().ToLowerInvariant()}-{index}.png"));
                    await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, $"connected-tabs-window-{requested.ToString().ToLowerInvariant()}-{index}.png"));
                }
            }
            if (colors[ElementTheme.Dark] == colors[ElementTheme.Light]) throw new InvalidOperationException("选项卡内容区没有随深浅主题切换");
            await AtomicJson.WriteAsync(Path.Combine(output, "connected-tab-surfaces.json"), evidence);
        }
        finally { RunPanel.SelectedIndex = selected; root.RequestedTheme = theme; if (wasCollapsed) ToggleOutput_Click(this, new()); App.MainWindow.AppWindow.Resize(windowSize); }
    }
    internal Task SmokeWiresAsync(string output) => SmokeCanvasAsync(output, CanvasEditor.SmokeWiresAsync);
    internal Task SmokeReconnectAsync(string output) => SmokeCanvasAsync(output, path => CanvasEditor.SmokeReconnectAsync(path, true));
    internal Task SmokeReconnectStateAsync(string output) => SmokeCanvasAsync(output, path => CanvasEditor.SmokeReconnectAsync(path, false), false);
    internal Task SmokeWirePresentationAsync(string output) => SmokeCanvasAsync(output, CanvasEditor.SmokeWirePresentationAsync);
    private async Task SmokeCanvasAsync(string output, Func<string, Task> verify, bool nativeInput = true)
    {
        await ready.Task; var previous = ViewModel.SelectedWorkflow; var size = App.MainWindow.AppWindow.Size;
        try
        {
            var scale = XamlRoot.RasterizationScale; App.MainWindow.AppWindow.Resize(new((int)(1440 * scale), (int)(960 * scale)));
            if (!documentLayout) await ViewModel.NewAsync(WorkflowTemplates.CreateGraph());
            PropertySplit.IsPaneOpen = false; WorkflowLibraryExpander.IsExpanded = false;
            await Task.Delay(200);
            if (nativeInput) await UiSmokeTest.PrepareNativeInputAsync(output);
            await verify(output);
        }
        finally { if (previous is not null) ViewModel.SelectedWorkflow = previous; App.MainWindow.AppWindow.Resize(size); }
    }
    internal async Task SmokeWorkflowChromeAsync(string output)
    {
        await ready.Task; var previous = ViewModel.SelectedWorkflow; var lines = ViewModel.RunLines.ToArray();
        try
        {
            var workflow = WorkflowTemplates.CreateGraph(); workflow.Name = "触发器与工作流列表验收";
            workflow.Triggers.Add(new() { Kind = TriggerKind.Interval, IntervalSeconds = 3600, Enabled = true });
            await ViewModel.NewAsync(workflow); await services.Scheduler.RefreshAsync(); UpdateWorkflowChrome();
            if (FindName("TriggerSummary") is not null || FindName("TriggerNextRun") is not null) throw new InvalidOperationException("已删除的触发状态横幅仍存在");
            WorkflowLibraryExpander.IsExpanded = true; await Task.Delay(180);
            var expanders = UiSmokeTest.Descendants<Expander>(AllWorkflows).ToArray();
            if (expanders.Length != ViewModel.Workflows.Count) throw new InvalidOperationException("工作流列表没有独立展开项");
            expanders.Single(x => x.Tag as string == workflow.Id).IsExpanded = true; await Task.Delay(120);
            if (!UiSmokeTest.Descendants<TextBlock>(AllWorkflows).Any(x => x.Text.Contains("3600") && x.Text.Contains("下次"))) throw new InvalidOperationException("工作流列表未显示触发状态与下次运行时间");
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "workflow-library-triggers.png"));
            WorkflowLibraryExpander.IsExpanded = false;
            NewWorkflow_Click(this, new()); await Task.Delay(160);
            var dialog = VisualTreeHelper.GetOpenPopupsForXamlRoot(XamlRoot).SelectMany(x => UiSmokeTest.Descendants<ContentDialog>(x.Child)).FirstOrDefault(x => x.Title as string == "新建工作流") ?? throw new InvalidOperationException("新建对话框未显示");
            if (dialog.Content is not TextBox || UiSmokeTest.Descendants<ComboBox>(dialog).Any() || UiSmokeTest.Descendants<RadioButton>(dialog).Any()) throw new InvalidOperationException("新建工作流仍要求选择执行方式");
            dialog.Hide(); await Task.Delay(120);
            foreach (var count in new[] { 0, 8, 126, 1000 })
            {
                ViewModel.RunLines.Clear(); for (var i = 0; i < count; i++) ViewModel.RunLines.Add(new() { LogText = "XFE 输出 " + i, Category = "工作流运行" });
                SetDiagnostics(Enumerable.Range(0, count).Select(i => new WorkflowDiagnostic("XFE 诊断 " + i)).ToArray()); await Task.Delay(80);
                foreach (var badge in new[] { OutputBadge, DiagnosticsBadge }) if (Math.Abs(badge.ActualWidth - badge.ActualHeight) > .1 || Math.Abs(badge.CornerRadius.TopLeft * 2 - badge.ActualWidth) > .1) throw new InvalidOperationException("计数徽章不是正圆");
                if (OutputList.Items.Any(x => x is not XFELogEntry) || DiagnosticsList.Items.Any(x => x is not XFELogEntry)) throw new InvalidOperationException("运行输出或诊断未使用 XFE 日志");
            }
            ViewModel.RunLines.Clear(); for (var i = 0; i < 8; i++) ViewModel.RunLines.Add(new() { LogText = "工作流输出 " + i, WorkflowName = workflow.Name }); SetDiagnostics([]);
            await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "workflow-output-circle-xfe.png"));
        }
        finally
        {
            WorkflowLibraryExpander.IsExpanded = false; if (previous is not null) ViewModel.SelectedWorkflow = previous;
            ViewModel.RunLines.Clear(); foreach (var line in lines) ViewModel.RunLines.Add(line); SetDiagnostics([]);
        }
    }
}