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

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json.Nodes;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Windows.Storage.Pickers;
using XFEWorkflow.Plugins.Vision;

namespace XFEWorkflow.Controls;

public sealed class ImageTemplateEditor : StackPanel
{
    private readonly Image thumbnail = new() { Stretch = Stretch.Uniform, MaxHeight = 140 };
    private readonly TextBlock caption = new() { FontSize = 12, TextWrapping = TextWrapping.Wrap };
    private readonly Button capture = new() { HorizontalAlignment = HorizontalAlignment.Stretch };
    private readonly Button preview = new() { Content = "预览原图", HorizontalAlignment = HorizontalAlignment.Stretch };
    private readonly Func<Task<TemplateImageData?>> select;
    private readonly Action<JsonNode?> apply;
    private readonly Action<string> status;
    private string? current;
    public ImageTemplateEditor(JsonNode? initial, Func<Task<TemplateImageData?>> select, Action<JsonNode?> apply, Action<string> status)
    {
        this.select = select; this.apply = apply; this.status = status; Spacing = 8;
        var imageBorder = new Border { MinHeight = 72, MaxHeight = 150, Padding = new(6), CornerRadius = new(6), Child = thumbnail,
            Background = (Brush)Application.Current.Resources["LayerFillColorDefaultBrush"], BorderBrush = (Brush)Application.Current.Resources["CardStrokeColorDefaultBrush"], BorderThickness = new(1) };
        var import = new Button { Content = "导入本地图像", HorizontalAlignment = HorizontalAlignment.Stretch };
        var clear = new Button { Content = new FontIcon { Glyph = "\uE711", FontSize = 12 }, Padding = new(8) };
        ToolTipService.SetToolTip(clear, "清除模板"); Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(clear, "清除模板");
        var buttons = new Grid { ColumnSpacing = 6 };
        buttons.ColumnDefinitions.Add(new()); buttons.ColumnDefinitions.Add(new()); buttons.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
        buttons.Children.Add(import); buttons.Children.Add(preview); Grid.SetColumn(preview, 1); buttons.Children.Add(clear); Grid.SetColumn(clear, 2);
        Children.Add(imageBorder); Children.Add(caption); Children.Add(capture); Children.Add(buttons);
        Children.Add(new TextBlock { Text = "框选或导入后,模板随工作流保存和导出。Esc 取消会保留原图。", FontSize = 11, Opacity = .7, TextWrapping = TextWrapping.Wrap });
        capture.Click += async (_, _) => await CaptureAsync();
        import.Click += async (_, _) =>
        {
            try
            {
                var picker = new FileOpenPicker(); foreach (var extension in new[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff" }) picker.FileTypeFilter.Add(extension);
                WinRT.Interop.InitializeWithWindow.Initialize(picker, WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow));
                if (await picker.PickSingleFileAsync() is { } file)
                {
                    var template = await Task.Run(() => TemplateImage.Import(file.Path)); SetTemplate(template);
                }
            }
            catch (Exception ex) { status(ex.Message); }
        };
        preview.Click += async (_, _) =>
        {
            if (thumbnail.Source is not { } source) return;
            var image = new Image { Source = source, Stretch = Stretch.Uniform, MaxHeight = 600, MaxWidth = 850 };
            await new ContentDialog { Title = caption.Text, Content = new ScrollViewer { Content = image, MinWidth = 360, MaxHeight = 620 }, CloseButtonText = "关闭", XamlRoot = XamlRoot }.ShowAsync();
        };
        clear.Click += (_, _) => { apply(null); SetValue(null); };
        SetValue(initial);
    }
    internal async Task CaptureAsync()
    {
        capture.IsEnabled = false;
        try
        {
            var result = await select(); if (result is not null) SetTemplate(result);
            else status("已取消框选,保留原模板");
        }
        catch (OperationCanceledException) { status("已取消框选,保留原模板"); }
        catch (Exception ex) { status(ex.Message); }
        finally { capture.IsEnabled = true; }
    }
    private void SetTemplate(TemplateImageData template) { apply(JsonValue.Create(template.Value)); SetValue(JsonValue.Create(template.Value)); }
    private void SetValue(JsonNode? value)
    {
        current = value is JsonValue scalar && scalar.TryGetValue<string>(out var text) ? text : null;
        thumbnail.Source = null; preview.IsEnabled = false;
        capture.Content = string.IsNullOrWhiteSpace(current) ? "从屏幕框选模板" : "重新框选模板";
        caption.Text = value is JsonObject ? "模板来自变量或上游输出,运行时加载" : string.IsNullOrWhiteSpace(current) ? "尚未设置模板" : "正在载入模板…";
        if (!string.IsNullOrWhiteSpace(current)) _ = LoadPreviewAsync(current);
    }
    private async Task LoadPreviewAsync(string value)
    {
        try
        {
            var template = await Task.Run(() => value.StartsWith(TemplateImage.Prefix, StringComparison.Ordinal) ? value : TemplateImage.Import(value).Value);
            using var stream = new MemoryStream(TemplateImage.Decode(template), false);
            var bitmap = new BitmapImage(); await bitmap.SetSourceAsync(stream.AsRandomAccessStream());
            if (current != value) return;
            thumbnail.Source = bitmap; preview.IsEnabled = true;
            caption.Text = $"{bitmap.PixelWidth} × {bitmap.PixelHeight} 像素 · " + (value.StartsWith(TemplateImage.Prefix, StringComparison.Ordinal) ? "已内嵌到工作流" : "本地文件");
        }
        catch (Exception ex) { if (current == value) caption.Text = "无法预览模板:" + ex.Message; }
    }
    internal string? CurrentValue => current;
    internal bool HasPreview => thumbnail.Source is not null && preview.IsEnabled;
}