using System.Text.Json.Nodes;
using Microsoft.UI.Xaml.Media;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Controls;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Plugins.Vision;
using XFEWorkflow.Services;
namespace XFEWorkflow.Views;
public sealed partial class MainPage
{
internal async Task SmokeWheelAsync(string output)
{
await ready.Task; PropertySplit.IsPaneOpen = false; CanvasEditor.CenterView(); await Task.Delay(200);
var root = (FrameworkElement)App.MainWindow.Content; var handle = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
App.MainWindow.Activate(); UiSmokeTest.SetForegroundWindow(handle); await Task.Delay(100);
var anchor = new Windows.Foundation.Point(48, 65);
var position = CanvasEditor.TransformToVisual(root).TransformPoint(anchor);
var origin = new UiSmokeTest.ScreenPoint(); UiSmokeTest.ClientToScreen(handle, ref origin); var scale = root.XamlRoot.RasterizationScale;
var x = origin.X + (int)Math.Round(position.X * scale); var y = origin.Y + (int)Math.Round(position.Y * scale);
var before = CanvasEditor.InspectViewport();
void Wheel(int delta) { if (UiSmokeTest.GetForegroundWindow() != handle) throw new InvalidOperationException("验收窗口失去焦点,已停止滚轮输入"); UiSmokeTest.MouseWheelAt(x, y, delta); }
Wheel(120); await Task.Delay(200); var after = CanvasEditor.InspectViewport();
if (after["zoom"]!.GetValue<double>() <= before["zoom"]!.GetValue<double>() + .01) throw new InvalidOperationException("普通滚轮没有放大画布");
foreach (var (offset, p) in new[] { ("horizontalOffset", anchor.X), ("verticalOffset", anchor.Y) })
{
var oldWorld = (before[offset]!.GetValue<double>() + p) / before["zoom"]!.GetValue<double>();
var newWorld = (after[offset]!.GetValue<double>() + p) / after["zoom"]!.GetValue<double>();
if (Math.Abs(oldWorld - newWorld) > 2) throw new InvalidOperationException("缩放未保持鼠标指向的世界坐标:" + offset);
}
Wheel(-120); await Task.Delay(150); var restored = CanvasEditor.InspectViewport();
if (Math.Abs(restored["zoom"]!.GetValue<double>() - before["zoom"]!.GetValue<double>()) > .001) throw new InvalidOperationException("反向滚轮没有缩小画布");
Wheel(120 * 40); await Task.Delay(150); if (Math.Abs(CanvasEditor.ZoomFactor - 2.5) > .001) throw new InvalidOperationException("最大缩放限制无效");
Wheel(-120 * 80); await Task.Delay(150); if (Math.Abs(CanvasEditor.ZoomFactor - .25) > .001) throw new InvalidOperationException("最小缩放限制无效");
await AtomicJson.WriteAsync(Path.Combine(output, "canvas-wheel.json"), new { before, after, restored }); CanvasEditor.CenterView();
}
internal async Task SmokeImageTemplatesAsync(string output)
{
await ready.Task;
var previous = ViewModel.SelectedWorkflow; var size = App.MainWindow.AppWindow.Size; var wasCollapsed = outputCollapsed;
var root = (FrameworkElement)App.MainWindow.Content;
try
{
using var bitmap = new System.Drawing.Bitmap(600, 360);
using (var graphics = System.Drawing.Graphics.FromImage(bitmap))
{
graphics.Clear(System.Drawing.Color.FromArgb(235, 241, 249));
graphics.FillRectangle(System.Drawing.Brushes.CornflowerBlue, 80, 90, 180, 60);
using var font = new System.Drawing.Font("Microsoft YaHei UI", 24, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
graphics.DrawString("提交订单", font, System.Drawing.Brushes.White, 108, 104);
graphics.FillRectangle(System.Drawing.Brushes.CornflowerBlue, 320, 220, 180, 60);
graphics.DrawString("提交订单", font, System.Drawing.Brushes.White, 348, 234);
}
var sourcePath = Path.Combine(output, "image-match-fixture.png"); bitmap.Save(sourcePath, System.Drawing.Imaging.ImageFormat.Png);
using var frozen = new ScreenFrame((System.Drawing.Bitmap)bitmap.Clone(), new(-1920, -100, 600, 360), "screen");
var template = TemplateImage.Crop(frozen, new(-1840, -10, 180, 60));
var node = new NodeDefinition { CapabilityId = "xfe.vision.findImage", Name = "查找提交订单按钮", X = 430, Y = 120,
Parameters = new() { ["imagePath"] = sourcePath, ["tolerance"] = 0, ["maxMatches"] = 2 } };
var legacy = new NodeDefinition { CapabilityId = "xfe.vision.waitImage", Name = "保留旧容差", Parameters = new() { ["tolerance"] = 6 } };
var loop = new NodeDefinition { CapabilityId = "core.foreach", Parameters = new() { ["items"] = new JsonArray() }, Children = new() { ["body"] = new() { Nodes = [legacy] } } };
var flow = WorkflowTemplates.CreateGraph(); flow.Name = "屏幕模板 → 图像匹配";
flow.PluginVersions["xfe.vision"] = "1.0.0"; flow.Graph.Nodes.InsertRange(1, [node, loop]);
await ViewModel.NewAsync(flow); UpgradeImagePlugin();
if (flow.PluginVersions["xfe.vision"] != "1.1.0" || !node.Parameters.ContainsKey("minimumSimilarity") || node.Parameters["minimumSimilarity"] is not null || !legacy.Parameters.ContainsKey("minimumSimilarity") || legacy.Parameters["minimumSimilarity"] is not null)
throw new InvalidOperationException("升级未保留旧图及子图的颜色容差模式");
flow.Graph.Nodes.Remove(loop); flow.Graph.Edges.Clear();
for (var i = 0; i < flow.Graph.Nodes.Count - 1; i++) flow.Graph.Edges.Add(new() { FromNode = flow.Graph.Nodes[i].Id, ToNode = flow.Graph.Nodes[i + 1].Id });
flow.Graph.Nodes[^1].Parameters["result"] = new JsonObject { ["$node"] = node.Id };
node.Parameters["minimumSimilarity"] = .9; node.Parameters["templatePath"] = template.Value;
CanvasEditor.SetGraph(flow.Graph); ShowProperties(node);
App.MainWindow.AppWindow.Resize(new((int)(1600 * root.XamlRoot.RasterizationScale), (int)(1000 * root.XamlRoot.RasterizationScale)));
PropertySplit.IsPaneOpen = true; await Task.Delay(200);
if (templateEditor is null) throw new InvalidOperationException("找图节点没有模板编辑器");
for (var i = 0; i < 20 && !templateEditor.HasPreview; i++) await Task.Delay(50);
if (!templateEditor.HasPreview) throw new InvalidOperationException("内嵌模板未显示预览");
IEnumerable<DependencyObject> Descendants(DependencyObject element)
{
yield return element;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) foreach (var child in Descendants(VisualTreeHelper.GetChild(element, i))) yield return child;
}
var controls = Descendants(PropertyPanel).ToArray();
if (!controls.OfType<Button>().Any(b => b.Content as string == "重新框选模板") || !controls.OfType<Button>().Any(b => b.Content as string == "预览原图") || !controls.OfType<Button>().Any(b => b.Content as string == "测试匹配…")) throw new InvalidOperationException("模板操作按钮不完整");
var threshold = controls.OfType<NumberBox>().Single(b => b.Header as string == "最低匹配相似度(%)");
threshold.Value = 97; if (Math.Abs(node.Parameters["minimumSimilarity"]!.GetValue<double>() - .97) > .000001) throw new InvalidOperationException("相似度未保存到节点参数");
var selected = new Queue<TemplateImageData?>([null, template]); var applied = 0;
var testEditor = new ImageTemplateEditor(JsonValue.Create(template.Value), () => Task.FromResult(selected.Dequeue()), value => { applied++; node.Parameters["templatePath"] = value; }, _ => { });
await testEditor.CaptureAsync(); if (applied != 0 || testEditor.CurrentValue != template.Value) throw new InvalidOperationException("取消重新框选覆盖了模板");
await testEditor.CaptureAsync(); if (applied != 1) throw new InvalidOperationException("重新框选未应用模板");
await ViewModel.SaveAsync(); var saved = await services.Workflows.GetAsync(flow.Id);
if (saved.Graph.Nodes[1].Parameters.String("templatePath") != template.Value) throw new InvalidOperationException("模板未持久化");
var export = Path.Combine(output, "image-template-portable.xfeworkflow"); await services.Workflows.ExportAsync(flow, export);
var imported = await services.Workflows.ImportAsync(export);
if (imported.Graph.Nodes[1].Parameters.String("templatePath") != template.Value) throw new InvalidOperationException("模板在导入导出后丢失");
var previewPath = Path.Combine(output, "image-match-preview.png");
var result = await RunImageMatchPreviewAsync(node, previewPath, default);
var matches = result.Result["matches"]!.AsArray();
if (matches.Count != 2 || matches[0]!.AsObject().Integer("x") != 80 || matches[0]!.AsObject().Integer("y") != 90 || matches[0]!["score"]!.GetValue<double>() < .999)
throw new InvalidOperationException("实际 Runner 未正确匹配内嵌模板:" + result.Result.ToJsonString());
// Previewing a click node must still execute only a findImage workflow.
node.CapabilityId = "xfe.vision.clickImage"; var safePreview = await RunImageMatchPreviewAsync(node, previewPath, default);
if (!safePreview.Result.Boolean("found")) throw new InvalidOperationException("点击节点的无点击预览失败");
node.CapabilityId = "xfe.vision.findImage";
await AtomicJson.WriteAsync(Path.Combine(output, "image-template-preview.json"), result.Result);
ShowProperties(node); PropertySplit.IsPaneOpen = true; PaletteSearch.Text = "图像";
if (!outputCollapsed) ToggleOutput_Click(this, new RoutedEventArgs());
CanvasEditor.CenterView(true); await Task.Delay(400);
if (!PropertySplit.IsPaneOpen || PropertyPanel.ActualWidth < 200) throw new InvalidOperationException("模板属性面板没有显示");
await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "workflow-image-template.png"));
await ShowImageMatchPreviewAsync(node, Path.Combine(output, "workflow-image-match-dialog.png"));
}
finally { if (wasCollapsed != outputCollapsed) ToggleOutput_Click(this, new RoutedEventArgs()); PaletteSearch.Text = ""; ViewModel.SelectedWorkflow = previous; App.MainWindow.AppWindow.Resize(size); }
}
}
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml.Media;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Controls;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Plugins.Vision;
using XFEWorkflow.Services;
namespace XFEWorkflow.Views;
public sealed partial class MainPage
{
internal async Task SmokeWheelAsync(string output)
{
await ready.Task; PropertySplit.IsPaneOpen = false; CanvasEditor.CenterView(); await Task.Delay(200);
var root = (FrameworkElement)App.MainWindow.Content; var handle = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
App.MainWindow.Activate(); UiSmokeTest.SetForegroundWindow(handle); await Task.Delay(100);
var anchor = new Windows.Foundation.Point(48, 65);
var position = CanvasEditor.TransformToVisual(root).TransformPoint(anchor);
var origin = new UiSmokeTest.ScreenPoint(); UiSmokeTest.ClientToScreen(handle, ref origin); var scale = root.XamlRoot.RasterizationScale;
var x = origin.X + (int)Math.Round(position.X * scale); var y = origin.Y + (int)Math.Round(position.Y * scale);
var before = CanvasEditor.InspectViewport();
void Wheel(int delta) { if (UiSmokeTest.GetForegroundWindow() != handle) throw new InvalidOperationException("验收窗口失去焦点,已停止滚轮输入"); UiSmokeTest.MouseWheelAt(x, y, delta); }
Wheel(120); await Task.Delay(200); var after = CanvasEditor.InspectViewport();
if (after["zoom"]!.GetValue<double>() <= before["zoom"]!.GetValue<double>() + .01) throw new InvalidOperationException("普通滚轮没有放大画布");
foreach (var (offset, p) in new[] { ("horizontalOffset", anchor.X), ("verticalOffset", anchor.Y) })
{
var oldWorld = (before[offset]!.GetValue<double>() + p) / before["zoom"]!.GetValue<double>();
var newWorld = (after[offset]!.GetValue<double>() + p) / after["zoom"]!.GetValue<double>();
if (Math.Abs(oldWorld - newWorld) > 2) throw new InvalidOperationException("缩放未保持鼠标指向的世界坐标:" + offset);
}
Wheel(-120); await Task.Delay(150); var restored = CanvasEditor.InspectViewport();
if (Math.Abs(restored["zoom"]!.GetValue<double>() - before["zoom"]!.GetValue<double>()) > .001) throw new InvalidOperationException("反向滚轮没有缩小画布");
Wheel(120 * 40); await Task.Delay(150); if (Math.Abs(CanvasEditor.ZoomFactor - 2.5) > .001) throw new InvalidOperationException("最大缩放限制无效");
Wheel(-120 * 80); await Task.Delay(150); if (Math.Abs(CanvasEditor.ZoomFactor - .25) > .001) throw new InvalidOperationException("最小缩放限制无效");
await AtomicJson.WriteAsync(Path.Combine(output, "canvas-wheel.json"), new { before, after, restored }); CanvasEditor.CenterView();
}
internal async Task SmokeImageTemplatesAsync(string output)
{
await ready.Task;
var previous = ViewModel.SelectedWorkflow; var size = App.MainWindow.AppWindow.Size; var wasCollapsed = outputCollapsed;
var root = (FrameworkElement)App.MainWindow.Content;
try
{
using var bitmap = new System.Drawing.Bitmap(600, 360);
using (var graphics = System.Drawing.Graphics.FromImage(bitmap))
{
graphics.Clear(System.Drawing.Color.FromArgb(235, 241, 249));
graphics.FillRectangle(System.Drawing.Brushes.CornflowerBlue, 80, 90, 180, 60);
using var font = new System.Drawing.Font("Microsoft YaHei UI", 24, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
graphics.DrawString("提交订单", font, System.Drawing.Brushes.White, 108, 104);
graphics.FillRectangle(System.Drawing.Brushes.CornflowerBlue, 320, 220, 180, 60);
graphics.DrawString("提交订单", font, System.Drawing.Brushes.White, 348, 234);
}
var sourcePath = Path.Combine(output, "image-match-fixture.png"); bitmap.Save(sourcePath, System.Drawing.Imaging.ImageFormat.Png);
using var frozen = new ScreenFrame((System.Drawing.Bitmap)bitmap.Clone(), new(-1920, -100, 600, 360), "screen");
var template = TemplateImage.Crop(frozen, new(-1840, -10, 180, 60));
var node = new NodeDefinition { CapabilityId = "xfe.vision.findImage", Name = "查找提交订单按钮", X = 430, Y = 120,
Parameters = new() { ["imagePath"] = sourcePath, ["tolerance"] = 0, ["maxMatches"] = 2 } };
var legacy = new NodeDefinition { CapabilityId = "xfe.vision.waitImage", Name = "保留旧容差", Parameters = new() { ["tolerance"] = 6 } };
var loop = new NodeDefinition { CapabilityId = "core.foreach", Parameters = new() { ["items"] = new JsonArray() }, Children = new() { ["body"] = new() { Nodes = [legacy] } } };
var flow = WorkflowTemplates.CreateGraph(); flow.Name = "屏幕模板 → 图像匹配";
flow.PluginVersions["xfe.vision"] = "1.0.0"; flow.Graph.Nodes.InsertRange(1, [node, loop]);
await ViewModel.NewAsync(flow); UpgradeImagePlugin();
if (flow.PluginVersions["xfe.vision"] != "1.1.0" || !node.Parameters.ContainsKey("minimumSimilarity") || node.Parameters["minimumSimilarity"] is not null || !legacy.Parameters.ContainsKey("minimumSimilarity") || legacy.Parameters["minimumSimilarity"] is not null)
throw new InvalidOperationException("升级未保留旧图及子图的颜色容差模式");
flow.Graph.Nodes.Remove(loop); flow.Graph.Edges.Clear();
for (var i = 0; i < flow.Graph.Nodes.Count - 1; i++) flow.Graph.Edges.Add(new() { FromNode = flow.Graph.Nodes[i].Id, ToNode = flow.Graph.Nodes[i + 1].Id });
flow.Graph.Nodes[^1].Parameters["result"] = new JsonObject { ["$node"] = node.Id };
node.Parameters["minimumSimilarity"] = .9; node.Parameters["templatePath"] = template.Value;
CanvasEditor.SetGraph(flow.Graph); ShowProperties(node);
App.MainWindow.AppWindow.Resize(new((int)(1600 * root.XamlRoot.RasterizationScale), (int)(1000 * root.XamlRoot.RasterizationScale)));
PropertySplit.IsPaneOpen = true; await Task.Delay(200);
if (templateEditor is null) throw new InvalidOperationException("找图节点没有模板编辑器");
for (var i = 0; i < 20 && !templateEditor.HasPreview; i++) await Task.Delay(50);
if (!templateEditor.HasPreview) throw new InvalidOperationException("内嵌模板未显示预览");
IEnumerable<DependencyObject> Descendants(DependencyObject element)
{
yield return element;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) foreach (var child in Descendants(VisualTreeHelper.GetChild(element, i))) yield return child;
}
var controls = Descendants(PropertyPanel).ToArray();
if (!controls.OfType<Button>().Any(b => b.Content as string == "重新框选模板") || !controls.OfType<Button>().Any(b => b.Content as string == "预览原图") || !controls.OfType<Button>().Any(b => b.Content as string == "测试匹配…")) throw new InvalidOperationException("模板操作按钮不完整");
var threshold = controls.OfType<NumberBox>().Single(b => b.Header as string == "最低匹配相似度(%)");
threshold.Value = 97; if (Math.Abs(node.Parameters["minimumSimilarity"]!.GetValue<double>() - .97) > .000001) throw new InvalidOperationException("相似度未保存到节点参数");
var selected = new Queue<TemplateImageData?>([null, template]); var applied = 0;
var testEditor = new ImageTemplateEditor(JsonValue.Create(template.Value), () => Task.FromResult(selected.Dequeue()), value => { applied++; node.Parameters["templatePath"] = value; }, _ => { });
await testEditor.CaptureAsync(); if (applied != 0 || testEditor.CurrentValue != template.Value) throw new InvalidOperationException("取消重新框选覆盖了模板");
await testEditor.CaptureAsync(); if (applied != 1) throw new InvalidOperationException("重新框选未应用模板");
await ViewModel.SaveAsync(); var saved = await services.Workflows.GetAsync(flow.Id);
if (saved.Graph.Nodes[1].Parameters.String("templatePath") != template.Value) throw new InvalidOperationException("模板未持久化");
var export = Path.Combine(output, "image-template-portable.xfeworkflow"); await services.Workflows.ExportAsync(flow, export);
var imported = await services.Workflows.ImportAsync(export);
if (imported.Graph.Nodes[1].Parameters.String("templatePath") != template.Value) throw new InvalidOperationException("模板在导入导出后丢失");
var previewPath = Path.Combine(output, "image-match-preview.png");
var result = await RunImageMatchPreviewAsync(node, previewPath, default);
var matches = result.Result["matches"]!.AsArray();
if (matches.Count != 2 || matches[0]!.AsObject().Integer("x") != 80 || matches[0]!.AsObject().Integer("y") != 90 || matches[0]!["score"]!.GetValue<double>() < .999)
throw new InvalidOperationException("实际 Runner 未正确匹配内嵌模板:" + result.Result.ToJsonString());
// Previewing a click node must still execute only a findImage workflow.
node.CapabilityId = "xfe.vision.clickImage"; var safePreview = await RunImageMatchPreviewAsync(node, previewPath, default);
if (!safePreview.Result.Boolean("found")) throw new InvalidOperationException("点击节点的无点击预览失败");
node.CapabilityId = "xfe.vision.findImage";
await AtomicJson.WriteAsync(Path.Combine(output, "image-template-preview.json"), result.Result);
ShowProperties(node); PropertySplit.IsPaneOpen = true; PaletteSearch.Text = "图像";
if (!outputCollapsed) ToggleOutput_Click(this, new RoutedEventArgs());
CanvasEditor.CenterView(true); await Task.Delay(400);
if (!PropertySplit.IsPaneOpen || PropertyPanel.ActualWidth < 200) throw new InvalidOperationException("模板属性面板没有显示");
await UiSmokeTest.CaptureWindowAsync(Path.Combine(output, "workflow-image-template.png"));
await ShowImageMatchPreviewAsync(node, Path.Combine(output, "workflow-image-match-dialog.png"));
}
finally { if (wasCollapsed != outputCollapsed) ToggleOutput_Click(this, new RoutedEventArgs()); PaletteSearch.Text = ""; ViewModel.SelectedWorkflow = previous; App.MainWindow.AppWindow.Resize(size); }
}
}