using Windows.Foundation;
using Windows.System;
using Microsoft.UI.Xaml.Media;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Services;
namespace XFEWorkflow.Controls;
public sealed partial class WorkflowCanvas
{
internal async Task SmokeReconnectAsync(string output, bool nativeMouse)
{
var file = nativeMouse ? "wire-target-reconnect" : "wire-target-reconnect-state";
var pointerEvents = new List<object>();
var steps = new List<object>();
var keys = new List<string>();
var root = this;
Microsoft.UI.Xaml.Input.PointerEventHandler Trace(string name) => (_, e) =>
{
var point = e.GetCurrentPoint(this);
pointerEvents.Add(new { name, source = e.OriginalSource.GetType().Name, point.Position, point.Properties.IsLeftButtonPressed,
drag = wireDrag?.Port, reconnect = reconnectingEdge?.Id, wireMoved, panning, captures = PointerCaptures?.Count ?? 0 });
};
var pressed = Trace("pressed"); var moved = Trace("moved"); var released = Trace("released"); var lost = Trace("capture-lost");
root.AddHandler(PointerPressedEvent, pressed, true); root.AddHandler(PointerMovedEvent, moved, true);
root.AddHandler(PointerReleasedEvent, released, true); root.AddHandler(PointerCaptureLostEvent, lost, true);
Microsoft.UI.Xaml.Input.KeyEventHandler key = (_, e) => keys.Add((KeyPressed(VirtualKey.Control) ? "Ctrl+" : "") + e.Key);
root.AddHandler(KeyDownEvent, key, true);
void Record(string stage) => steps.Add(new { stage, edges = Graph.Edges.Select(e => new { e.Id, e.Kind, e.FromNode, e.FromPort, e.ToNode, e.ToPort }).ToArray(), undo = undo.Count, redo = redo.Count });
try
{
var execute = new EdgeDefinition { FromNode = "start", ToNode = "first" };
var data = new EdgeDefinition { Kind = PortKind.Data, FromNode = "start", FromPort = "inputs", ToNode = "end", ToPort = "result" };
SetGraph(new()
{
Nodes = [new() { Id = "start", CapabilityId = "core.start", Name = "开始", X = 0 },
new() { Id = "first", CapabilityId = "core.delay", Name = "原目标", X = 400 },
new() { Id = "second", CapabilityId = "core.log", Name = "新目标", X = 800, Y = 300 },
new() { Id = "end", CapabilityId = "core.end", Name = "结束", X = 400, Y = 550 }],
Edges = [execute, data]
});
await Task.Delay(150); CenterView(true); await Task.Delay(200);
PortAnchor Port(string node, string port, bool outputPort = false) => portElements.Single(p => p.Node == node && p.Port == port && p.Output == outputPort);
EdgeDefinition Edge(string id) => Graph.Edges.Single(e => e.Id == id);
void AssertTarget(string id, string node, string port)
{ if (Edge(id).ToNode != node || Edge(id).ToPort != port || wireDrag is not null || wirePreview is not null) throw new InvalidOperationException("目标改接或预览清理错误"); }
async Task UndoEdit()
{ if (nativeMouse) UiSmokeTest.PressKey(VirtualKey.Z, true); else Undo(); await Task.Delay(160); }
async Task RedoEdit()
{ if (nativeMouse) UiSmokeTest.PressKey(VirtualKey.Y, true); else Redo(); await Task.Delay(160); }
async Task Drag(PortAnchor from, PortAnchor to, Func<Task>? held = null)
{
if (nativeMouse) { await UiSmokeTest.DragFromToAsync(from.Ring, to.Ring, held); return; }
BeginWireDrag(from, PortCenter(from)); wireMoved = true; var point = PortCenter(to); DrawWirePreview(point);
if (held is not null) await held();
FinishWireDrag(point); await Task.Delay(100);
}
await Drag(Port("first", "in"), Port("second", "in"), async () =>
{
if (nativeMouse) await AtomicJson.WriteAsync(System.IO.Path.Combine(output, "native-drag-state.json"), UiSmokeTest.NativeInputState(Port("second", "in").Ring));
await UiSmokeTest.CaptureWindowAsync(System.IO.Path.Combine(output, file + "-preview.png"));
if (reconnectingEdge?.Id != execute.Id || wireDrag?.Node != "start" || lines.Count != 1 || Edge(execute.Id).ToNode != "first")
throw new InvalidOperationException($"目标端点拖动应保留源端点、隐藏旧线,且松开前不修改图:reconnect={reconnectingEdge?.Id}, source={wireDrag?.Node}, lines={lines.Count}, target={Edge(execute.Id).ToNode}, capture={PointerCaptures?.Count ?? 0}");
});
AssertTarget(execute.Id, "second", "in");
Record("execution-reconnected");
await UndoEdit(); AssertTarget(execute.Id, "first", "in");
Record("execution-reconnect-undone");
await RedoEdit(); AssertTarget(execute.Id, "second", "in");
Record("execution-reconnect-redone");
await Drag(Port("second", "in"), Port("end", "in"), () => { if (nativeMouse) UiSmokeTest.PressKey(VirtualKey.Escape); else CancelWire(); return Task.Delay(100); });
AssertTarget(execute.Id, "second", "in");
await Drag(Port("second", "in"), Port("first", "milliseconds"));
AssertTarget(execute.Id, "second", "in");
var checkpoints = undo.Count;
if (nativeMouse) await UiSmokeTest.ClickElementAsync(Port("second", "in").Ring);
else { var port = Port("second", "in"); BeginWireDrag(port, PortCenter(port)); FinishWireDrag(PortCenter(port)); }
AssertTarget(execute.Id, "second", "in");
if (undo.Count != checkpoints) throw new InvalidOperationException("单击目标端点产生了不必要的撤销记录");
async Task DropOnBlank(PortAnchor port)
{
Point? blank = null;
for (var y = ActualHeight - 24; y > 24 && blank is null; y -= 60)
for (var x = ActualWidth - 24; x > 24; x -= 60)
{
var point = new Point(x, y);
if (!IsBlankCanvas(TransformToVisual(surface).TransformPoint(point))) continue;
var host = (FrameworkElement)App.MainWindow.Content;
var hostPoint = TransformToVisual(host).TransformPoint(point);
if (ReferenceEquals(VisualTreeHelper.FindElementsInHostCoordinates(hostPoint, host).FirstOrDefault(), surface)) { blank = point; break; }
}
if (blank is not { } destination) throw new InvalidOperationException("验收画布中没有空白位置");
var origin = port.Ring.TransformToVisual(this).TransformPoint(new(port.Ring.ActualWidth / 2, port.Ring.ActualHeight / 2));
if (nativeMouse) await UiSmokeTest.DragElementAsync(port.Ring, destination.X - origin.X, destination.Y - origin.Y);
else { BeginWireDrag(port, PortCenter(port)); wireMoved = true; FinishWireDrag(TransformToVisual(surface).TransformPoint(destination)); await Task.Delay(100); }
}
await DropOnBlank(Port("second", "in"));
if (Graph.Edges.Any(e => e.Id == execute.Id) || Graph.Edges.Count != 1) throw new InvalidOperationException("松到空白画布没有只断开所拖动的执行线");
Record("execution-disconnected-on-blank");
await UndoEdit(); AssertTarget(execute.Id, "second", "in");
Record("execution-disconnect-undone");
await RedoEdit();
if (Graph.Edges.Any(e => e.Id == execute.Id) || Graph.Edges.Count != 1) throw new InvalidOperationException("重做未断开原执行线");
Record("execution-disconnect-redone");
await UndoEdit(); AssertTarget(execute.Id, "second", "in");
await Drag(Port("end", "result"), Port("second", "message"));
AssertTarget(data.Id, "second", "message");
Record("data-reconnected");
await Drag(Port("second", "message"), Port("first", "milliseconds"));
AssertTarget(data.Id, "second", "message");
ConnectPorts(Port("start", "inputs", true), Port("end", "result"));
var occupied = Graph.Edges.Single(e => e.ToNode == "end" && e.ToPort == "result").Id;
await Drag(Port("second", "message"), Port("end", "result"));
AssertTarget(data.Id, "end", "result");
if (Graph.Edges.Any(e => e.Id == occupied)) throw new InvalidOperationException("改接到已有数据输入时没有替换旧连接");
Record("occupied-data-input-replaced");
await UndoEdit(); AssertTarget(data.Id, "second", "message");
if (!Graph.Edges.Any(e => e.Id == occupied)) throw new InvalidOperationException("一次撤销没有恢复被替换的连接");
Record("occupied-data-input-restored-by-one-undo");
await DropOnBlank(Port("second", "message"));
if (Graph.Edges.Any(e => e.Id == data.Id) || !Graph.Edges.Any(e => e.Id == occupied)) throw new InvalidOperationException("断开数据线影响了其他连接");
Record("data-disconnected-on-blank");
await UndoEdit(); AssertTarget(data.Id, "second", "message");
Record("data-disconnect-undone");
await RedoEdit();
if (Graph.Edges.Any(e => e.Id == data.Id) || !Graph.Edges.Any(e => e.Id == occupied)) throw new InvalidOperationException("重做断开数据线影响了其他连接");
Record("data-disconnect-redone");
await UndoEdit(); AssertTarget(data.Id, "second", "message");
await Drag(Port("second", "message"), Port("end", "result"), () => { if (nativeMouse) ReleasePointerCaptures(); else CancelWire(); return Task.Delay(100); });
AssertTarget(data.Id, "second", "message");
ConnectPorts(Port("first", "next", true), Port("second", "in"));
var join = Graph.Edges.Single(e => e.FromNode == "first" && e.Kind == PortKind.Execution);
ConnectPorts(Port("second", "next", true), Port("end", "in"));
var tail = Graph.Edges.Single(e => e.FromNode == "second" && e.Kind == PortKind.Execution);
checkpoints = undo.Count;
await Drag(Port("end", "in"), Port("first", "in"));
AssertTarget(tail.Id, "end", "in");
if (undo.Count != checkpoints) throw new InvalidOperationException("拒绝环路时污染了撤销记录");
if (nativeMouse)
{
var geometry = WireGeometry(PortCenter(Port("first", "next", true)), PortCenter(Port("second", "in")));
var figure = geometry.Figures[0]; var curve = (BezierSegment)figure.Segments[0];
var middle = new Point((figure.StartPoint.X + 3 * curve.Point1.X + 3 * curve.Point2.X + curve.Point3.X) / 8,
(figure.StartPoint.Y + 3 * curve.Point1.Y + 3 * curve.Point2.Y + curve.Point3.Y) / 8);
await UiSmokeTest.ClickPointAsync(this, surface.TransformToVisual(this).TransformPoint(middle));
if (selectedEdgeId != join.Id) throw new InvalidOperationException("鼠标单击未选中要改接的执行线");
}
else SelectConnection(join);
await Drag(Port("second", "in"), Port("end", "in"));
AssertTarget(join.Id, "end", "in"); AssertTarget(execute.Id, "second", "in");
await UndoEdit(); AssertTarget(join.Id, "second", "in");
Record("selected-incoming-wire-reconnected-and-restored");
if (nativeMouse && (!keys.Contains("Ctrl+Z") || !keys.Contains("Ctrl+Y") || !keys.Contains("Escape") || !pointerEvents.Any())) throw new InvalidOperationException("原生鼠标或键盘事件未到达画布");
await AtomicJson.WriteAsync(System.IO.Path.Combine(output, file + ".json"), new { execute = Edge(execute.Id), data = Edge(data.Id), graphEdges = Graph.Edges.Count, nativeMouse, nativeKeyboard = nativeMouse, keys, pointerEventCount = pointerEvents.Count, steps, undoAndRedo = true, cancellationAndInvalidTypePreserve = true, cycleRejected = true, multipleIncomingSelection = true });
await UiSmokeTest.CaptureWindowAsync(System.IO.Path.Combine(output, file + ".png"));
}
finally
{
root.RemoveHandler(PointerPressedEvent, pressed); root.RemoveHandler(PointerMovedEvent, moved);
root.RemoveHandler(PointerReleasedEvent, released); root.RemoveHandler(PointerCaptureLostEvent, lost);
root.RemoveHandler(KeyDownEvent, key);
await AtomicJson.WriteAsync(System.IO.Path.Combine(output, file + "-pointer-events.json"), pointerEvents);
await AtomicJson.WriteAsync(System.IO.Path.Combine(output, file + "-steps.json"), steps);
}
}
}
using Windows.Foundation;
using Windows.System;
using Microsoft.UI.Xaml.Media;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Services;
namespace XFEWorkflow.Controls;
public sealed partial class WorkflowCanvas
{
internal async Task SmokeReconnectAsync(string output, bool nativeMouse)
{
var file = nativeMouse ? "wire-target-reconnect" : "wire-target-reconnect-state";
var pointerEvents = new List<object>();
var steps = new List<object>();
var keys = new List<string>();
var root = this;
Microsoft.UI.Xaml.Input.PointerEventHandler Trace(string name) => (_, e) =>
{
var point = e.GetCurrentPoint(this);
pointerEvents.Add(new { name, source = e.OriginalSource.GetType().Name, point.Position, point.Properties.IsLeftButtonPressed,
drag = wireDrag?.Port, reconnect = reconnectingEdge?.Id, wireMoved, panning, captures = PointerCaptures?.Count ?? 0 });
};
var pressed = Trace("pressed"); var moved = Trace("moved"); var released = Trace("released"); var lost = Trace("capture-lost");
root.AddHandler(PointerPressedEvent, pressed, true); root.AddHandler(PointerMovedEvent, moved, true);
root.AddHandler(PointerReleasedEvent, released, true); root.AddHandler(PointerCaptureLostEvent, lost, true);
Microsoft.UI.Xaml.Input.KeyEventHandler key = (_, e) => keys.Add((KeyPressed(VirtualKey.Control) ? "Ctrl+" : "") + e.Key);
root.AddHandler(KeyDownEvent, key, true);
void Record(string stage) => steps.Add(new { stage, edges = Graph.Edges.Select(e => new { e.Id, e.Kind, e.FromNode, e.FromPort, e.ToNode, e.ToPort }).ToArray(), undo = undo.Count, redo = redo.Count });
try
{
var execute = new EdgeDefinition { FromNode = "start", ToNode = "first" };
var data = new EdgeDefinition { Kind = PortKind.Data, FromNode = "start", FromPort = "inputs", ToNode = "end", ToPort = "result" };
SetGraph(new()
{
Nodes = [new() { Id = "start", CapabilityId = "core.start", Name = "开始", X = 0 },
new() { Id = "first", CapabilityId = "core.delay", Name = "原目标", X = 400 },
new() { Id = "second", CapabilityId = "core.log", Name = "新目标", X = 800, Y = 300 },
new() { Id = "end", CapabilityId = "core.end", Name = "结束", X = 400, Y = 550 }],
Edges = [execute, data]
});
await Task.Delay(150); CenterView(true); await Task.Delay(200);
PortAnchor Port(string node, string port, bool outputPort = false) => portElements.Single(p => p.Node == node && p.Port == port && p.Output == outputPort);
EdgeDefinition Edge(string id) => Graph.Edges.Single(e => e.Id == id);
void AssertTarget(string id, string node, string port)
{ if (Edge(id).ToNode != node || Edge(id).ToPort != port || wireDrag is not null || wirePreview is not null) throw new InvalidOperationException("目标改接或预览清理错误"); }
async Task UndoEdit()
{ if (nativeMouse) UiSmokeTest.PressKey(VirtualKey.Z, true); else Undo(); await Task.Delay(160); }
async Task RedoEdit()
{ if (nativeMouse) UiSmokeTest.PressKey(VirtualKey.Y, true); else Redo(); await Task.Delay(160); }
async Task Drag(PortAnchor from, PortAnchor to, Func<Task>? held = null)
{
if (nativeMouse) { await UiSmokeTest.DragFromToAsync(from.Ring, to.Ring, held); return; }
BeginWireDrag(from, PortCenter(from)); wireMoved = true; var point = PortCenter(to); DrawWirePreview(point);
if (held is not null) await held();
FinishWireDrag(point); await Task.Delay(100);
}
await Drag(Port("first", "in"), Port("second", "in"), async () =>
{
if (nativeMouse) await AtomicJson.WriteAsync(System.IO.Path.Combine(output, "native-drag-state.json"), UiSmokeTest.NativeInputState(Port("second", "in").Ring));
await UiSmokeTest.CaptureWindowAsync(System.IO.Path.Combine(output, file + "-preview.png"));
if (reconnectingEdge?.Id != execute.Id || wireDrag?.Node != "start" || lines.Count != 1 || Edge(execute.Id).ToNode != "first")
throw new InvalidOperationException($"目标端点拖动应保留源端点、隐藏旧线,且松开前不修改图:reconnect={reconnectingEdge?.Id}, source={wireDrag?.Node}, lines={lines.Count}, target={Edge(execute.Id).ToNode}, capture={PointerCaptures?.Count ?? 0}");
});
AssertTarget(execute.Id, "second", "in");
Record("execution-reconnected");
await UndoEdit(); AssertTarget(execute.Id, "first", "in");
Record("execution-reconnect-undone");
await RedoEdit(); AssertTarget(execute.Id, "second", "in");
Record("execution-reconnect-redone");
await Drag(Port("second", "in"), Port("end", "in"), () => { if (nativeMouse) UiSmokeTest.PressKey(VirtualKey.Escape); else CancelWire(); return Task.Delay(100); });
AssertTarget(execute.Id, "second", "in");
await Drag(Port("second", "in"), Port("first", "milliseconds"));
AssertTarget(execute.Id, "second", "in");
var checkpoints = undo.Count;
if (nativeMouse) await UiSmokeTest.ClickElementAsync(Port("second", "in").Ring);
else { var port = Port("second", "in"); BeginWireDrag(port, PortCenter(port)); FinishWireDrag(PortCenter(port)); }
AssertTarget(execute.Id, "second", "in");
if (undo.Count != checkpoints) throw new InvalidOperationException("单击目标端点产生了不必要的撤销记录");
async Task DropOnBlank(PortAnchor port)
{
Point? blank = null;
for (var y = ActualHeight - 24; y > 24 && blank is null; y -= 60)
for (var x = ActualWidth - 24; x > 24; x -= 60)
{
var point = new Point(x, y);
if (!IsBlankCanvas(TransformToVisual(surface).TransformPoint(point))) continue;
var host = (FrameworkElement)App.MainWindow.Content;
var hostPoint = TransformToVisual(host).TransformPoint(point);
if (ReferenceEquals(VisualTreeHelper.FindElementsInHostCoordinates(hostPoint, host).FirstOrDefault(), surface)) { blank = point; break; }
}
if (blank is not { } destination) throw new InvalidOperationException("验收画布中没有空白位置");
var origin = port.Ring.TransformToVisual(this).TransformPoint(new(port.Ring.ActualWidth / 2, port.Ring.ActualHeight / 2));
if (nativeMouse) await UiSmokeTest.DragElementAsync(port.Ring, destination.X - origin.X, destination.Y - origin.Y);
else { BeginWireDrag(port, PortCenter(port)); wireMoved = true; FinishWireDrag(TransformToVisual(surface).TransformPoint(destination)); await Task.Delay(100); }
}
await DropOnBlank(Port("second", "in"));
if (Graph.Edges.Any(e => e.Id == execute.Id) || Graph.Edges.Count != 1) throw new InvalidOperationException("松到空白画布没有只断开所拖动的执行线");
Record("execution-disconnected-on-blank");
await UndoEdit(); AssertTarget(execute.Id, "second", "in");
Record("execution-disconnect-undone");
await RedoEdit();
if (Graph.Edges.Any(e => e.Id == execute.Id) || Graph.Edges.Count != 1) throw new InvalidOperationException("重做未断开原执行线");
Record("execution-disconnect-redone");
await UndoEdit(); AssertTarget(execute.Id, "second", "in");
await Drag(Port("end", "result"), Port("second", "message"));
AssertTarget(data.Id, "second", "message");
Record("data-reconnected");
await Drag(Port("second", "message"), Port("first", "milliseconds"));
AssertTarget(data.Id, "second", "message");
ConnectPorts(Port("start", "inputs", true), Port("end", "result"));
var occupied = Graph.Edges.Single(e => e.ToNode == "end" && e.ToPort == "result").Id;
await Drag(Port("second", "message"), Port("end", "result"));
AssertTarget(data.Id, "end", "result");
if (Graph.Edges.Any(e => e.Id == occupied)) throw new InvalidOperationException("改接到已有数据输入时没有替换旧连接");
Record("occupied-data-input-replaced");
await UndoEdit(); AssertTarget(data.Id, "second", "message");
if (!Graph.Edges.Any(e => e.Id == occupied)) throw new InvalidOperationException("一次撤销没有恢复被替换的连接");
Record("occupied-data-input-restored-by-one-undo");
await DropOnBlank(Port("second", "message"));
if (Graph.Edges.Any(e => e.Id == data.Id) || !Graph.Edges.Any(e => e.Id == occupied)) throw new InvalidOperationException("断开数据线影响了其他连接");
Record("data-disconnected-on-blank");
await UndoEdit(); AssertTarget(data.Id, "second", "message");
Record("data-disconnect-undone");
await RedoEdit();
if (Graph.Edges.Any(e => e.Id == data.Id) || !Graph.Edges.Any(e => e.Id == occupied)) throw new InvalidOperationException("重做断开数据线影响了其他连接");
Record("data-disconnect-redone");
await UndoEdit(); AssertTarget(data.Id, "second", "message");
await Drag(Port("second", "message"), Port("end", "result"), () => { if (nativeMouse) ReleasePointerCaptures(); else CancelWire(); return Task.Delay(100); });
AssertTarget(data.Id, "second", "message");
ConnectPorts(Port("first", "next", true), Port("second", "in"));
var join = Graph.Edges.Single(e => e.FromNode == "first" && e.Kind == PortKind.Execution);
ConnectPorts(Port("second", "next", true), Port("end", "in"));
var tail = Graph.Edges.Single(e => e.FromNode == "second" && e.Kind == PortKind.Execution);
checkpoints = undo.Count;
await Drag(Port("end", "in"), Port("first", "in"));
AssertTarget(tail.Id, "end", "in");
if (undo.Count != checkpoints) throw new InvalidOperationException("拒绝环路时污染了撤销记录");
if (nativeMouse)
{
var geometry = WireGeometry(PortCenter(Port("first", "next", true)), PortCenter(Port("second", "in")));
var figure = geometry.Figures[0]; var curve = (BezierSegment)figure.Segments[0];
var middle = new Point((figure.StartPoint.X + 3 * curve.Point1.X + 3 * curve.Point2.X + curve.Point3.X) / 8,
(figure.StartPoint.Y + 3 * curve.Point1.Y + 3 * curve.Point2.Y + curve.Point3.Y) / 8);
await UiSmokeTest.ClickPointAsync(this, surface.TransformToVisual(this).TransformPoint(middle));
if (selectedEdgeId != join.Id) throw new InvalidOperationException("鼠标单击未选中要改接的执行线");
}
else SelectConnection(join);
await Drag(Port("second", "in"), Port("end", "in"));
AssertTarget(join.Id, "end", "in"); AssertTarget(execute.Id, "second", "in");
await UndoEdit(); AssertTarget(join.Id, "second", "in");
Record("selected-incoming-wire-reconnected-and-restored");
if (nativeMouse && (!keys.Contains("Ctrl+Z") || !keys.Contains("Ctrl+Y") || !keys.Contains("Escape") || !pointerEvents.Any())) throw new InvalidOperationException("原生鼠标或键盘事件未到达画布");
await AtomicJson.WriteAsync(System.IO.Path.Combine(output, file + ".json"), new { execute = Edge(execute.Id), data = Edge(data.Id), graphEdges = Graph.Edges.Count, nativeMouse, nativeKeyboard = nativeMouse, keys, pointerEventCount = pointerEvents.Count, steps, undoAndRedo = true, cancellationAndInvalidTypePreserve = true, cycleRejected = true, multipleIncomingSelection = true });
await UiSmokeTest.CaptureWindowAsync(System.IO.Path.Combine(output, file + ".png"));
}
finally
{
root.RemoveHandler(PointerPressedEvent, pressed); root.RemoveHandler(PointerMovedEvent, moved);
root.RemoveHandler(PointerReleasedEvent, released); root.RemoveHandler(PointerCaptureLostEvent, lost);
root.RemoveHandler(KeyDownEvent, key);
await AtomicJson.WriteAsync(System.IO.Path.Combine(output, file + "-pointer-events.json"), pointerEvents);
await AtomicJson.WriteAsync(System.IO.Path.Combine(output, file + "-steps.json"), steps);
}
}
}