1.优化了平移缩放逻辑

2.优化了触发器的执行,优化了节点执行时的代码逻辑
3.优化了节点方法委托的参数获取
This commit is contained in:
fengjiayi
2024-09-18 16:45:41 +08:00
parent 9041be139f
commit ef54c40d10
13 changed files with 640 additions and 743 deletions

View File

@@ -19,14 +19,14 @@ namespace Serein.Library.Entity
/// 是否为显式参数 /// 是否为显式参数
/// </summary> /// </summary>
public bool IsExplicitData { get; set; } public bool IsExplicitData { get; set; }
/// <summary> ///// <summary>
/// 显式类型 ///// 显式类型
/// </summary> ///// </summary>
public Type ExplicitType { get; set; } //public Type ExplicitType { get; set; }
/// <summary> ///// <summary>
/// 显示类型编号> ///// 显示类型编号>
/// </summary> ///// </summary>
public string ExplicitTypeName { get; set; } public string ExplicitTypeName { get; set; }
/// <summary> /// <summary>
@@ -56,7 +56,7 @@ namespace Serein.Library.Entity
{ {
Index = Index, Index = Index,
IsExplicitData = IsExplicitData, IsExplicitData = IsExplicitData,
ExplicitType = ExplicitType, // ExplicitType = ExplicitType,
DataType = DataType, DataType = DataType,
ParameterName = ParameterName, ParameterName = ParameterName,
ExplicitTypeName = ExplicitTypeName, ExplicitTypeName = ExplicitTypeName,

View File

@@ -1,4 +1,5 @@
using System; using System;
using System.CodeDom;
namespace Serein.Library.Ex namespace Serein.Library.Ex
{ {
@@ -7,6 +8,7 @@ namespace Serein.Library.Ex
/// </summary> /// </summary>
public class FlipflopException: Exception public class FlipflopException: Exception
{ {
public bool IsCancel { get; } public bool IsCancel { get; }
public FlipflopException(string message, bool isCancel = true) :base(message) public FlipflopException(string message, bool isCancel = true) :base(message)
{ {

View File

@@ -40,8 +40,23 @@ namespace Serein.Library.Web
} }
listener.Prefixes.Add(prefixe); // 添加监听前缀 listener.Prefixes.Add(prefixe); // 添加监听前缀
try
listener.Start(); // 开始监听 {
listener.Start(); // 开始监听
Task.Run(async () =>
{
while (listener.IsListening)
{
var context = await listener.GetContextAsync(); // 获取请求上下文
ProcessRequestAsync(context); // 处理请求
}
});
}
catch(Exception ex)
{
listener = null;
Console.WriteLine(ex);
}
//_ = Task.Run(async () => //_ = Task.Run(async () =>
//{ //{
@@ -58,14 +73,7 @@ namespace Serein.Library.Web
// } // }
//}); //});
Task.Run(async () =>
{
while (listener.IsListening)
{
var context = await listener.GetContextAsync(); // 获取请求上下文
ProcessRequestAsync(context); // 处理请求
}
});
return this; return this;
} }
@@ -115,8 +123,8 @@ namespace Serein.Library.Web
// 停止服务器 // 停止服务器
public void Stop() public void Stop()
{ {
listener.Stop(); // 停止监听 listener?.Stop(); // 停止监听
listener.Close(); // 关闭监听器 listener?.Close(); // 关闭监听器
} }
} }

View File

@@ -23,6 +23,12 @@ namespace Serein.NodeFlow.Base
SuccessorNodes[ctType] = []; SuccessorNodes[ctType] = [];
} }
} }
/// <summary>
/// 是否中断(调试中断功能)
/// </summary>
public bool IsInterrupt { get; set; }
/// <summary> /// <summary>
/// 节点对应的控件类型 /// 节点对应的控件类型
/// </summary> /// </summary>
@@ -65,11 +71,6 @@ namespace Serein.NodeFlow.Base
public ConnectionType NextOrientation { get; set; } = ConnectionType.None; public ConnectionType NextOrientation { get; set; } = ConnectionType.None;
/// <summary>
/// 当前执行状态(进入真分支还是假分支,异常分支在异常中确定)
/// </summary>
// public FlowStateType FlowState { get; set; } = FlowStateType.Cancel;
/// <summary> /// <summary>
/// 运行时的异常信息(仅在 FlowState 为 Error 时存在对应值) /// 运行时的异常信息(仅在 FlowState 为 Error 时存在对应值)
/// </summary> /// </summary>
@@ -80,10 +81,17 @@ namespace Serein.NodeFlow.Base
/// </summary> /// </summary>
public object? FlowData { get; set; } = null; public object? FlowData { get; set; } = null;
// public NodeModelBaseBuilder Build() => new NodeModelBaseBuilder(this);
} }
public class DebugInfo
{
/// <summary>
/// 是否中断
/// </summary>
public bool IsInterrupt { get;set; }
}
/// <summary> /// <summary>
/// 节点基类(数据):条件控件,动作控件,条件区域,动作区域 /// 节点基类(数据):条件控件,动作控件,条件区域,动作区域

View File

@@ -1,4 +1,5 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Serein.Library.Api; using Serein.Library.Api;
using Serein.Library.Entity; using Serein.Library.Entity;
using Serein.Library.Enums; using Serein.Library.Enums;
@@ -7,6 +8,7 @@ using Serein.NodeFlow.Tool.SereinExpression;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -18,6 +20,8 @@ namespace Serein.NodeFlow.Base
/// </summary> /// </summary>
public abstract partial class NodeModelBase : IDynamicFlowNode public abstract partial class NodeModelBase : IDynamicFlowNode
{ {
#region /
internal abstract Parameterdata[] GetParameterdatas(); internal abstract Parameterdata[] GetParameterdatas();
internal virtual NodeInfo ToInfo() internal virtual NodeInfo ToInfo()
{ {
@@ -42,7 +46,7 @@ namespace Serein.NodeFlow.Base
UpstreamNodes = upstreamNodes.ToArray(), UpstreamNodes = upstreamNodes.ToArray(),
ParameterData = parameterData.ToArray(), ParameterData = parameterData.ToArray(),
ErrorNodes = errorNodes.ToArray(), ErrorNodes = errorNodes.ToArray(),
}; };
} }
@@ -78,6 +82,7 @@ namespace Serein.NodeFlow.Base
return this; return this;
} }
#endregion
/// <summary> /// <summary>
@@ -89,7 +94,7 @@ namespace Serein.NodeFlow.Base
{ {
var cts = context.SereinIoc.GetOrRegisterInstantiate<CancellationTokenSource>(); var cts = context.SereinIoc.GetOrRegisterInstantiate<CancellationTokenSource>();
Stack<NodeModelBase> stack = []; Stack<NodeModelBase> stack = new Stack<NodeModelBase>();
stack.Push(this); stack.Push(this);
while (stack.Count > 0 && !cts.IsCancellationRequested) // 循环中直到栈为空才会退出循环 while (stack.Count > 0 && !cts.IsCancellationRequested) // 循环中直到栈为空才会退出循环
@@ -98,31 +103,28 @@ namespace Serein.NodeFlow.Base
var currentNode = stack.Pop(); var currentNode = stack.Pop();
// 设置方法执行的对象 // 设置方法执行的对象
if (currentNode.MethodDetails is not null && currentNode.MethodDetails.ActingInstanceType is not null) if (currentNode.MethodDetails?.ActingInstance == null && currentNode.MethodDetails?.ActingInstanceType is not null)
{ {
// currentNode.MethodDetails.ActingInstance ??= context.SereinIoc.GetOrInstantiate(MethodDetails.ActingInstanceType); currentNode.MethodDetails.ActingInstance ??= context.SereinIoc.GetOrRegisterInstantiate(currentNode.MethodDetails.ActingInstanceType);
// currentNode.MethodDetails.ActingInstance = context.SereinIoc.GetOrInstantiate(MethodDetails.ActingInstanceType);
currentNode.MethodDetails.ActingInstance = context.SereinIoc.GetOrRegisterInstantiate(currentNode.MethodDetails.ActingInstanceType);
} }
// 获取上游分支,首先执行一次 // 首先执行上游分支
var upstreamNodes = currentNode.SuccessorNodes[ConnectionType.Upstream]; var upstreamNodes = currentNode.SuccessorNodes[ConnectionType.Upstream];
for (int i = upstreamNodes.Count - 1; i >= 0; i--) for (int i = upstreamNodes.Count - 1; i >= 0; i--)
{ {
upstreamNodes[i].PreviousNode = currentNode; upstreamNodes[i].PreviousNode = currentNode;
await upstreamNodes[i].StartExecution(context); await upstreamNodes[i].StartExecution(context); // 执行上游分支
} }
// 判断是否为触发器节点,如果是,则开始等待。
if (currentNode.MethodDetails != null && currentNode.MethodDetails.MethodDynamicType == NodeType.Flipflop) if (currentNode.MethodDetails != null && currentNode.MethodDetails.MethodDynamicType == NodeType.Flipflop)
{ {
// 触发器节点
currentNode.FlowData = await currentNode.ExecuteAsync(context); currentNode.FlowData = await currentNode.ExecuteAsync(context); // 流程中遇到了触发器
} }
else else
{ {
// 动作节点 currentNode.FlowData = currentNode.Execute(context); // 流程中正常执行
currentNode.FlowData = currentNode.Execute(context);
} }
if(currentNode.NextOrientation == ConnectionType.None) if(currentNode.NextOrientation == ConnectionType.None)
@@ -131,6 +133,7 @@ namespace Serein.NodeFlow.Base
break; break;
} }
// 获取下一分支
var nextNodes = currentNode.SuccessorNodes[currentNode.NextOrientation]; var nextNodes = currentNode.SuccessorNodes[currentNode.NextOrientation];
// 将下一个节点集合中的所有节点逆序推入栈中 // 将下一个节点集合中的所有节点逆序推入栈中
@@ -151,35 +154,21 @@ namespace Serein.NodeFlow.Base
public virtual object? Execute(IDynamicContext context) public virtual object? Execute(IDynamicContext context)
{ {
MethodDetails md = MethodDetails; MethodDetails md = MethodDetails;
object? result = null;
var del = md.MethodDelegate; var del = md.MethodDelegate;
object instance = md.ActingInstance;
var haveParameter = md.ExplicitDatas.Length > 0;
var haveResult = md.ReturnType != typeof(void);
try try
{ {
if (md.ExplicitDatas.Length == 0) // Action/Func([方法作用的实例],[可能的参数值],[可能的返回值])
object? result = (haveParameter, haveResult) switch
{ {
if (md.ReturnType == typeof(void)) (false, false) => Execution((Action<object>)del, instance), // 调用节点方法返回null
{ (true, false) => Execution((Action<object, object?[]?>)del, instance, GetParameters(context, md)), // 调用节点方法返回null
((Action<object>)del).Invoke(md.ActingInstance); (false, true) => Execution((Func<object, object?>)del, instance), // 调用节点方法,返回方法传回类型
} (true, true) => Execution((Func<object, object?[]?, object?>)del, instance, GetParameters(context, md)), // 调用节点方法,获取入参参数,返回方法忏悔类型
else };
{
result = ((Func<object, object>)del).Invoke(md.ActingInstance);
}
}
else
{
object?[]? parameters = GetParameters(context, MethodDetails);
if (md.ReturnType == typeof(void))
{
((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
}
else
{
var func = del as Func<object, object[], object>;
//result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
result = func?.Invoke(md.ActingInstance, parameters);
}
}
NextOrientation = ConnectionType.IsSucceed; NextOrientation = ConnectionType.IsSucceed;
return result; return result;
} }
@@ -187,9 +176,8 @@ namespace Serein.NodeFlow.Base
{ {
NextOrientation = ConnectionType.IsError; NextOrientation = ConnectionType.IsError;
RuningException = ex; RuningException = ex;
return null;
} }
return result;
} }
/// <summary> /// <summary>
@@ -201,41 +189,63 @@ namespace Serein.NodeFlow.Base
public virtual async Task<object?> ExecuteAsync(IDynamicContext context) public virtual async Task<object?> ExecuteAsync(IDynamicContext context)
{ {
MethodDetails md = MethodDetails; MethodDetails md = MethodDetails;
object? result = null; Delegate del = md.MethodDelegate;
object instance = md.ActingInstance;
IFlipflopContext flipflopContext = null; var haveParameter = md.ExplicitDatas.Length >= 0;
try try
{ {
// 调用委托并获取结果 // 调用委托并获取结果
if (md.ExplicitDatas.Length == 0) Task<IFlipflopContext> flipflopTask = haveParameter switch
{ {
flipflopContext = await ((Func<object, Task<IFlipflopContext>>)md.MethodDelegate).Invoke(MethodDetails.ActingInstance); true => ((Func<object, object?[]?, Task<IFlipflopContext>>)del).Invoke(instance, GetParameters(context, md)), // 执行流程中的触发器方法时获取入参参数
} false => ((Func<object, Task<IFlipflopContext>>)del).Invoke(instance),
else };
{
object?[]? parameters = GetParameters(context, MethodDetails); IFlipflopContext flipflopContext = (await flipflopTask) ?? throw new FlipflopException("没有返回上下文");
flipflopContext = await ((Func<object, object[], Task<IFlipflopContext>>)md.MethodDelegate).Invoke(MethodDetails.ActingInstance, parameters);
}
if (flipflopContext == null)
{
throw new FlipflopException("没有返回上下文");
}
NextOrientation = flipflopContext.State.ToContentType(); NextOrientation = flipflopContext.State.ToContentType();
result = flipflopContext.Data; return flipflopContext.Data;
} }
//catch(FlipflopException ex)
//{
// NextOrientation = ConnectionType.IsError;
// RuningException = ex;
// return null;
//}
catch (Exception ex) catch (Exception ex)
{ {
NextOrientation = ConnectionType.IsError; NextOrientation = ConnectionType.IsError;
RuningException = ex; RuningException = ex;
return null;
} }
return result;
} }
#region
public static object? Execution(Action<object> del, object instance)
{
del?.Invoke(instance);
return null;
}
public static object? Execution(Action<object, object?[]?> del, object instance, object?[]? parameters)
{
del?.Invoke(instance, parameters);
return null;
}
public static object? Execution(Func<object, object?> del, object instance)
{
return del?.Invoke(instance);
}
public static object? Execution(Func<object, object?[]?, object?> del, object instance, object?[]? parameters)
{
return del?.Invoke(instance, parameters);
}
#endregion
/// <summary> /// <summary>
/// 获取对应的参数数组 /// 获取对应的参数数组
/// </summary> /// </summary>
public object[]? GetParameters(IDynamicContext context, MethodDetails md) public object?[]? GetParameters(IDynamicContext context, MethodDetails md)
{ {
// 用正确的大小初始化参数数组 // 用正确的大小初始化参数数组
var types = md.ExplicitDatas.Select(it => it.DataType).ToArray(); var types = md.ExplicitDatas.Select(it => it.DataType).ToArray();
@@ -244,151 +254,67 @@ namespace Serein.NodeFlow.Base
return [md.ActingInstance]; return [md.ActingInstance];
} }
object[]? parameters = new object[types.Length]; object?[]? parameters = new object[types.Length];
var flowData = PreviousNode?.FlowData; // 当前传递的数据
var previousDataType = flowData?.GetType();
for (int i = 0; i < types.Length; i++) for (int i = 0; i < types.Length; i++)
{ {
if (flowData is null)
var mdEd = md.ExplicitDatas[i];
Type type = mdEd.DataType;
var f1 = PreviousNode?.FlowData?.GetType();
var f2 = mdEd.DataType;
if (type == typeof(IDynamicContext))
{ {
parameters[i] = context; parameters[i] = md.ExplicitDatas[i].DataType switch
}
else if (type == typeof(MethodDetails))
{
parameters[i] = md;
}
else if (type == typeof(NodeModelBase))
{
parameters[i] = this;
}
else if (mdEd.IsExplicitData) // 显式参数
{
// 判断是否使用表达式解析
if (mdEd.DataValue[0] == '@')
{ {
var expResult = SerinExpressionEvaluator.Evaluate(mdEd.DataValue, PreviousNode?.FlowData, out bool isChange); Type t when t == typeof(IDynamicContext) => context, // 上下文
Type t when t == typeof(MethodDetails) => md, // 节点方法描述
Type t when t == typeof(NodeModelBase) => this, // 节点实体类
if (mdEd.DataType.IsEnum) _ => null,
{ };
var enumValue = Enum.Parse(mdEd.DataType, mdEd.DataValue); continue; // 上一节点数据为空,提前跳过
parameters[i] = enumValue;
}
else if (mdEd.ExplicitType == typeof(string))
{
parameters[i] = Convert.ChangeType(expResult, typeof(string));
}
else if (mdEd.ExplicitType == typeof(bool))
{
parameters[i] = Convert.ChangeType(expResult, typeof(bool));
}
else if (mdEd.ExplicitType == typeof(int))
{
parameters[i] = Convert.ChangeType(expResult, typeof(int));
}
else if (mdEd.ExplicitType == typeof(double))
{
parameters[i] = Convert.ChangeType(expResult, typeof(double));
}
else
{
parameters[i] = expResult;
//parameters[i] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
}
}
else
{
if (mdEd.DataType.IsEnum)
{
var enumValue = Enum.Parse(mdEd.DataType, mdEd.DataValue);
parameters[i] = enumValue;
}
else if (mdEd.ExplicitType == typeof(string))
{
parameters[i] = mdEd.DataValue;
}
else if (mdEd.ExplicitType == typeof(bool))
{
parameters[i] = bool.Parse(mdEd.DataValue);
}
else if (mdEd.ExplicitType == typeof(int))
{
parameters[i] = int.Parse(mdEd.DataValue);
}
else if (mdEd.ExplicitType == typeof(double))
{
parameters[i] = double.Parse(mdEd.DataValue);
}
else
{
parameters[i] = "";
//parameters[i] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
}
}
} }
else if (f1 != null && f2 != null) object? inputParameter; //
{ var ed = md.ExplicitDatas[i]; // 方法入参描述
if (f2.IsAssignableFrom(f1) || f2.FullName.Equals(f1.FullName))
{
parameters[i] = PreviousNode?.FlowData;
} // 检测是否为表达式
if (ed.IsExplicitData && ed.DataValue.StartsWith("@get", StringComparison.OrdinalIgnoreCase))
{
inputParameter = SerinExpressionEvaluator.Evaluate(ed.DataValue, flowData, out _); // 执行表达式从上一节点获取对象
} }
else else
{ {
inputParameter = flowData; // 使用上一节点的对象
var tmpParameter = PreviousNode?.FlowData?.ToString();
if (mdEd.DataType.IsEnum)
{
var enumValue = Enum.Parse(mdEd.DataType, tmpParameter);
parameters[i] = enumValue;
}
else if (mdEd.DataType == typeof(string))
{
parameters[i] = tmpParameter;
}
else if (mdEd.DataType == typeof(bool))
{
parameters[i] = bool.Parse(tmpParameter);
}
else if (mdEd.DataType == typeof(int))
{
parameters[i] = int.Parse(tmpParameter);
}
else if (mdEd.DataType == typeof(double))
{
parameters[i] = double.Parse(tmpParameter);
}
else
{
if (tmpParameter != null && mdEd.DataType != null)
{
parameters[i] = ConvertValue(tmpParameter, mdEd.DataType);
}
}
} }
try
{
parameters[i] = ed.DataType switch
{
Type t when t == previousDataType => context, // 上下文
Type t when t == typeof(IDynamicContext) => context, // 上下文
Type t when t == typeof(MethodDetails) => md, // 节点方法描述
Type t when t == typeof(NodeModelBase) => this, // 节点实体类
Type t when t == typeof(Guid) => new Guid(inputParameter?.ToString()),
Type t when t == typeof(decimal) => decimal.Parse(inputParameter?.ToString()),
Type t when t == typeof(string) => inputParameter?.ToString(),
Type t when t == typeof(char) => char.Parse(inputParameter?.ToString()),
Type t when t == typeof(bool) => bool.Parse(inputParameter?.ToString()),
Type t when t == typeof(byte) => byte.Parse(inputParameter?.ToString()),
Type t when t == typeof(int) => int.Parse(inputParameter?.ToString()),
Type t when t == typeof(long) => long.Parse(inputParameter?.ToString()),
Type t when t == typeof(DateTime) => DateTime.Parse(inputParameter?.ToString()),
Type t when t == typeof(float) => float.Parse(inputParameter?.ToString()),
Type t when t == typeof(double) => double.Parse(inputParameter?.ToString()),
Type t when t.IsEnum => Enum.Parse(ed.DataType, ed.DataValue),// 需要枚举
Type t when t.IsArray => (inputParameter as Array)?.Cast<object>().ToList(),
Type t when t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>) => inputParameter,
Type t when Nullable.GetUnderlyingType(t) != null => inputParameter == null ? null : Convert.ChangeType(inputParameter, Nullable.GetUnderlyingType(t)),
_ => inputParameter,
};
}
catch (Exception ex) // 节点参数类型转换异常
{
parameters[i] = null;
Console.WriteLine(ex);
}
} }
return parameters; return parameters;
} }
@@ -431,92 +357,5 @@ namespace Serein.NodeFlow.Base
return value; return value;
} }
} }
#region ExecuteAsync调用方法
//public virtual async Task<object?> ExecuteAsync(DynamicContext context)
//{
// MethodDetails md = MethodDetails;
// object? result = null;
// if (DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
// {
// if (md.ExplicitDatas.Length == 0)
// {
// if (md.ReturnType == typeof(void))
// {
// ((Action<object>)del).Invoke(md.ActingInstance);
// }
// else if (md.ReturnType == typeof(Task<FlipflopContext>))
// {
// // 调用委托并获取结果
// FlipflopContext flipflopContext = await ((Func<object, Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance);
// if (flipflopContext != null)
// {
// if (flipflopContext.State == FfState.Cancel)
// {
// throw new Exception("this async task is cancel.");
// }
// else
// {
// if (flipflopContext.State == FfState.Succeed)
// {
// CurrentState = true;
// result = flipflopContext.Data;
// }
// else
// {
// CurrentState = false;
// }
// }
// }
// }
// else
// {
// result = ((Func<object, object>)del).Invoke(md.ActingInstance);
// }
// }
// else
// {
// object?[]? parameters = GetParameters(context, MethodDetails);
// if (md.ReturnType == typeof(void))
// {
// ((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
// }
// else if (md.ReturnType == typeof(Task<FlipflopContext>))
// {
// // 调用委托并获取结果
// FlipflopContext flipflopContext = await ((Func<object, object[], Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance, parameters);
// if (flipflopContext != null)
// {
// if (flipflopContext.State == FfState.Cancel)
// {
// throw new Exception("取消此异步");
// }
// else
// {
// CurrentState = flipflopContext.State == FfState.Succeed;
// result = flipflopContext.Data;
// }
// }
// }
// else
// {
// result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
// }
// }
// context.SetFlowData(result);
// }
// return result;
//}
#endregion
} }
} }

View File

@@ -6,6 +6,7 @@ using Serein.Library.Utils;
using Serein.Library.Web; using Serein.Library.Web;
using Serein.NodeFlow.Base; using Serein.NodeFlow.Base;
using Serein.NodeFlow.Model; using Serein.NodeFlow.Model;
using System.ComponentModel.Design;
namespace Serein.NodeFlow namespace Serein.NodeFlow
{ {
@@ -107,10 +108,10 @@ namespace Serein.NodeFlow
#region Ioc容器 #region Ioc容器
// 清除节点使用的对象 // 清除节点使用的对象
var thisRuningMds = new List<MethodDetails>(); var thisRuningMds = new List<MethodDetails>();
thisRuningMds.AddRange(runNodeMd); thisRuningMds.AddRange(runNodeMd.Where(md => md is not null));
thisRuningMds.AddRange(initMethods); thisRuningMds.AddRange(initMethods.Where(md => md is not null));
thisRuningMds.AddRange(loadingMethods); thisRuningMds.AddRange(loadingMethods.Where(md => md is not null));
thisRuningMds.AddRange(exitMethods); thisRuningMds.AddRange(exitMethods.Where(md => md is not null));
// .AddRange(initMethods).AddRange(loadingMethods).a // .AddRange(initMethods).AddRange(loadingMethods).a
foreach (var nodeMd in thisRuningMds) foreach (var nodeMd in thisRuningMds)
@@ -216,7 +217,7 @@ namespace Serein.NodeFlow
}).ToArray(); }).ToArray();
_ = Task.WhenAll(tasks); _ = Task.WhenAll(tasks);
} }
await startNode.StartExecution(Context); await startNode.StartExecution(Context); // 从起始节点开始运行
// 等待结束 // 等待结束
if (FlipFlopCts != null) if (FlipFlopCts != null)
{ {
@@ -242,63 +243,73 @@ namespace Serein.NodeFlow
await FlipflopExecute(singleFlipFlopNode, flowEnvironment); // 启动触发器 await FlipflopExecute(singleFlipFlopNode, flowEnvironment); // 启动触发器
}); });
} }
/// <summary> /// <summary>
/// 启动触发器 /// 启动全局触发器
/// </summary> /// </summary>
private async Task FlipflopExecute(SingleFlipflopNode singleFlipFlopNode, IFlowEnvironment flowEnvironment) private async Task FlipflopExecute(SingleFlipflopNode singleFlipFlopNode, IFlowEnvironment flowEnvironment)
{ {
DynamicContext context = new DynamicContext(SereinIOC, flowEnvironment); var context = new DynamicContext(SereinIOC, flowEnvironment);
MethodDetails md = singleFlipFlopNode.MethodDetails; MethodDetails md = singleFlipFlopNode.MethodDetails;
var del = md.MethodDelegate; var del = md.MethodDelegate;
// 设置方法执行的对象
if (md?.ActingInstance == null && md?.ActingInstanceType is not null)
{
md.ActingInstance ??= context.SereinIoc.GetOrRegisterInstantiate(md.ActingInstanceType);
}
// 设置委托对象
var func = md.ExplicitDatas.Length == 0 ?
(Func<object, object, Task<IFlipflopContext>>)del :
(Func<object, object[], Task<IFlipflopContext>>)del;
try try
{ {
//var func = md.ExplicitDatas.Length == 0 ? (Func<object, object, Task<FlipflopContext<dynamic>>>)del : (Func<object, object[], Task<FlipflopContext<dynamic>>>)del; while (!FlipFlopCts.IsCancellationRequested)
var func = md.ExplicitDatas.Length == 0 ? (Func<object, object, Task<IFlipflopContext>>)del : (Func<object, object[], Task<IFlipflopContext>>)del;
while (!FlipFlopCts.IsCancellationRequested) // 循环中直到栈为空才会退出
{ {
if(singleFlipFlopNode.NotExitPreviousNode() == false) object?[]? parameters = singleFlipFlopNode.GetParameters(context, singleFlipFlopNode.MethodDetails); // 启动全局触发器时获取入参参数
{ IFlipflopContext flipflopContext = await func.Invoke(md.ActingInstance, parameters);// 首先开始等待触发器
// 存在上级节点时,退出触发器 _ = GlobalFlipflopExecute(singleFlipFlopNode, context);
break;
}
object?[]? parameters = singleFlipFlopNode.GetParameters(context, md);
// 调用委托并获取结果
md.ActingInstance = context.SereinIoc.GetOrRegisterInstantiate(md.ActingInstanceType);
IFlipflopContext flipflopContext = await func.Invoke(md.ActingInstance, parameters);
ConnectionType connection = flipflopContext.State.ToContentType();
if (connection != ConnectionType.None)
{
singleFlipFlopNode.NextOrientation = connection;
singleFlipFlopNode.FlowData = flipflopContext.Data;
var upstreamNodeTasks = singleFlipFlopNode.SuccessorNodes[ConnectionType.Upstream].Select(nextNode =>
{
var context = new DynamicContext(SereinIOC, flowEnvironment);
nextNode.PreviousNode = singleFlipFlopNode;
return nextNode.StartExecution(context);
}).ToArray();
var tmpTasks = singleFlipFlopNode.SuccessorNodes[connection].Select(nextNode =>
{
var context = new DynamicContext(SereinIOC,flowEnvironment);
nextNode.PreviousNode = singleFlipFlopNode;
return nextNode.StartExecution(context);
}).ToArray();
Task[] tasks = [..upstreamNodeTasks, .. tmpTasks];
Task.WaitAll(tasks);
}
else
{
break;
}
} }
//while (!FlipFlopCts.IsCancellationRequested)
//{
// if (singleFlipFlopNode.NotExitPreviousNode() == false)
// {
// break;
// }
// object?[]? parameters = singleFlipFlopNode.GetParameters(context, md);
// if (md.ActingInstance == null)
// {
// md.ActingInstance = context.SereinIoc.GetOrRegisterInstantiate(md.ActingInstanceType);
// }
// IFlipflopContext flipflopContext = await func.Invoke(md.ActingInstance, parameters);
// ConnectionType connection = flipflopContext.State.ToContentType();
// if (connection != ConnectionType.None)
// {
// singleFlipFlopNode.NextOrientation = connection;
// singleFlipFlopNode.FlowData = flipflopContext.Data;
// var tasks = singleFlipFlopNode.SuccessorNodes.Values
// .SelectMany(nodeList => nodeList)
// .Select(nextNode =>
// {
// var nextContext = new DynamicContext(SereinIOC, flowEnvironment);
// nextNode.PreviousNode = singleFlipFlopNode;
// return nextNode.StartExecution(nextContext); // 全局触发器收到信号,开始执行
// }).ToArray();
// await Task.WhenAll(tasks);
// }
// else
// {
// break;
// }
//}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -306,6 +317,73 @@ namespace Serein.NodeFlow
} }
} }
public async Task GlobalFlipflopExecute(SingleFlipflopNode singleFlipFlopNode, IDynamicContext context)
{
if (FlipFlopCts.IsCancellationRequested)
{
return;
}
bool skip = true;
var cts = context.SereinIoc.GetOrRegisterInstantiate<CancellationTokenSource>();
Stack<NodeModelBase> stack = new Stack<NodeModelBase>();
stack.Push(singleFlipFlopNode);
ConnectionType connectionType = ConnectionType.IsSucceed;
while (stack.Count > 0 && !cts.IsCancellationRequested) // 循环中直到栈为空才会退出循环
{
// 从栈中弹出一个节点作为当前节点进行处理
var currentNode = stack.Pop();
// 设置方法执行的对象
if (currentNode.MethodDetails?.ActingInstance == null && currentNode.MethodDetails?.ActingInstanceType is not null)
{
currentNode.MethodDetails.ActingInstance ??= context.SereinIoc.GetOrRegisterInstantiate(currentNode.MethodDetails.ActingInstanceType);
}
// 首先执行上游分支
var upstreamNodes = currentNode.SuccessorNodes[ConnectionType.Upstream];
for (int i = upstreamNodes.Count - 1; i >= 0; i--)
{
upstreamNodes[i].PreviousNode = currentNode;
await upstreamNodes[i].StartExecution(context); // 执行上游分支
}
// 当前节点是已经触发了的全局触发器,所以跳过,难道每次都要判断一次?
if (skip)
{
skip = false;
}
else
{
// 判断是否为触发器节点,如果是,则开始等待。
if (currentNode.MethodDetails != null && currentNode.MethodDetails.MethodDynamicType == NodeType.Flipflop)
{
currentNode.FlowData = await currentNode.ExecuteAsync(context); // 流程中遇到了触发器
}
else
{
currentNode.FlowData = currentNode.Execute(context); // 流程中正常执行
}
if (currentNode.NextOrientation == ConnectionType.None)
{
break; // 不再执行
}
connectionType = currentNode.NextOrientation;
}
// 获取下一分支
var nextNodes = currentNode.SuccessorNodes[connectionType];
// 将下一个节点集合中的所有节点逆序推入栈中
for (int i = nextNodes.Count - 1; i >= 0; i--)
{
nextNodes[i].PreviousNode = currentNode;
stack.Push(nextNodes[i]);
}
}
}
public void Exit() public void Exit()
{ {

View File

@@ -1,4 +1,5 @@
using Serein.Library.Entity; using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.Library.Enums; using Serein.Library.Enums;
using Serein.NodeFlow.Base; using Serein.NodeFlow.Base;
@@ -19,7 +20,10 @@ namespace Serein.NodeFlow.Model
ActionNodes = actionNodes; ActionNodes = actionNodes;
} }
public override object? Execute(IDynamicContext context)
{
throw new NotImplementedException("动作区域暂未实现");
}
internal override Parameterdata[] GetParameterdatas() internal override Parameterdata[] GetParameterdatas()
{ {

View File

@@ -26,8 +26,6 @@ namespace Serein.NodeFlow.Model
/// <returns></returns> /// <returns></returns>
public override object? Execute(IDynamicContext context) public override object? Execute(IDynamicContext context)
{ {
// NextOrientation = ConnectionType.IsSucceed;
// 条件区域中遍历每个条件节点 // 条件区域中遍历每个条件节点
foreach (SingleConditionNode? node in ConditionNodes) foreach (SingleConditionNode? node in ConditionNodes)
{ {
@@ -39,9 +37,7 @@ namespace Serein.NodeFlow.Model
break; break;
} }
} }
return PreviousNode?.FlowData; return PreviousNode?.FlowData;
} }

View File

@@ -1,4 +1,5 @@
using Serein.Library.Entity; using Serein.Library.Api;
using Serein.Library.Entity;
using Serein.NodeFlow.Base; using Serein.NodeFlow.Base;
namespace Serein.NodeFlow.Model namespace Serein.NodeFlow.Model
@@ -8,62 +9,7 @@ namespace Serein.NodeFlow.Model
/// </summary> /// </summary>
public class SingleActionNode : NodeModelBase public class SingleActionNode : NodeModelBase
{ {
//public override void Execute(DynamicContext context)
//{
// try
// {
// Execute(context, base.MethodDetails);
// CurrentState = true;
// }
// catch (Exception ex)
// {
// Debug.Write(ex.Message);
// CurrentState = false;
// }
//}
//public void Execute(DynamicContext context, MethodDetails md)
//{
// if (DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
// {
// object? result = null;
// if (md.ExplicitDatas.Length == 0)
// {
// if (md.ReturnType == typeof(void))
// {
// ((Action<object>)del).Invoke(md.ActingInstance);
// }
// else
// {
// result = ((Func<object, object>)del).Invoke(md.ActingInstance);
// }
// }
// else
// {
// object?[]? parameters = GetParameters(context, MethodDetails);
// if (md.ReturnType == typeof(void))
// {
// ((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
// }
// else
// {
// result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
// }
// }
// // 根据 ExplicitDatas.Length 判断委托类型
// //var action = (Action<object, object[]>)del;
// // 调用委托并获取结果
// // action.Invoke(MethodDetails.ActingInstance, parameters);
// //parameters = [md.ActingInstance, "", 123, ""];
// context.SetFlowData(result);
// }
//}
internal override Parameterdata[] GetParameterdatas() internal override Parameterdata[] GetParameterdatas()
{ {
if (base.MethodDetails.ExplicitDatas.Length > 0) if (base.MethodDetails.ExplicitDatas.Length > 0)

View File

@@ -114,7 +114,7 @@ public static class MethodDetailsHelperTmp
{ {
IsExplicitData = it.HasDefaultValue, IsExplicitData = it.HasDefaultValue,
Index = index, Index = index,
ExplicitType = it.ParameterType, // ExplicitType = it.ParameterType,
ExplicitTypeName = explicitTypeName, ExplicitTypeName = explicitTypeName,
DataType = it.ParameterType, DataType = it.ParameterType,
ParameterName = it.Name, ParameterName = it.Name,

View File

@@ -7,6 +7,7 @@ using Serein.Library.Utils;
using Serein.NodeFlow; using Serein.NodeFlow;
using Serein.NodeFlow.Base; using Serein.NodeFlow.Base;
using Serein.NodeFlow.Model; using Serein.NodeFlow.Model;
using Serein.WorkBench.Node;
using Serein.WorkBench.Node.View; using Serein.WorkBench.Node.View;
using Serein.WorkBench.Node.ViewModel; using Serein.WorkBench.Node.ViewModel;
using Serein.WorkBench.Themes; using Serein.WorkBench.Themes;
@@ -66,27 +67,35 @@ namespace Serein.WorkBench
/// </summary> /// </summary>
private List<Connection> Connections { get; } = []; private List<Connection> Connections { get; } = [];
#region #region
/// <summary>
/// 标记是否正在尝试选取控件
/// </summary>
private bool IsSelectControl;
/// <summary>
/// 标记是否正在进行连接操作
/// </summary>
private bool IsConnecting;
/// <summary>
/// 标记是否正在拖动控件
/// </summary>
private bool IsControlDragging;
/// <summary>
/// 标记是否正在拖动画布
/// </summary>
private bool IsCanvasDragging;
/// <summary> /// <summary>
/// 当前选取的控件 /// 当前选取的控件
/// </summary> /// </summary>
private readonly List<NodeControlBase> selectControls = []; private readonly List<NodeControlBase> selectNodeControls = [];
/// <summary>
/// 拖动创建节点控件时的鼠标位置
/// </summary>
// private Point canvasDropPosition;
/// <summary> /// <summary>
/// 记录拖动开始时的鼠标位置 /// 记录拖动开始时的鼠标位置
/// </summary> /// </summary>
private Point startPoint; private Point startPoint;
/// <summary>
/// 流程图起点的控件
/// </summary>
// private NodeControlBase? flowStartBlock;
/// <summary> /// <summary>
/// 记录开始连接的文本块 /// 记录开始连接的文本块
/// </summary> /// </summary>
@@ -99,22 +108,8 @@ namespace Serein.WorkBench
/// 当前正在绘制的真假分支属性 /// 当前正在绘制的真假分支属性
/// </summary> /// </summary>
private ConnectionType currentConnectionType; private ConnectionType currentConnectionType;
/// <summary>
/// 标记是否正在进行连接操作
/// </summary>
private bool IsConnecting;
/// <summary>
/// 标记是否正在尝试选取控件
/// </summary>
private bool IsSelectControl;
/// <summary>
/// 标记是否正在拖动控件
/// </summary>
private bool IsControlDragging;
/// <summary>
/// 标记是否正在拖动画布
/// </summary>
private bool IsCanvasDragging;
/// <summary> /// <summary>
/// 组合变换容器 /// 组合变换容器
/// </summary> /// </summary>
@@ -165,7 +160,6 @@ namespace Serein.WorkBench
} }
private void InitUI() private void InitUI()
{ {
canvasTransformGroup = new TransformGroup(); canvasTransformGroup = new TransformGroup();
@@ -176,8 +170,9 @@ namespace Serein.WorkBench
canvasTransformGroup.Children.Add(translateTransform); canvasTransformGroup.Children.Add(translateTransform);
FlowChartCanvas.RenderTransform = canvasTransformGroup; FlowChartCanvas.RenderTransform = canvasTransformGroup;
FlowChartCanvas.RenderTransformOrigin = new Point(0.5, 0.5); //FlowChartCanvas.RenderTransformOrigin = new Point(0.5, 0.5);
} }
#region Main窗体加载方法 #region Main窗体加载方法
private void Window_Loaded(object sender, RoutedEventArgs e) private void Window_Loaded(object sender, RoutedEventArgs e)
{ {
@@ -210,7 +205,6 @@ namespace Serein.WorkBench
Console.WriteLine((FlowChartStackPanel.ActualWidth, FlowChartStackPanel.ActualHeight)); Console.WriteLine((FlowChartStackPanel.ActualWidth, FlowChartStackPanel.ActualHeight));
} }
/// <summary> /// <summary>
/// 运行完成 /// 运行完成
/// </summary> /// </summary>
@@ -345,13 +339,25 @@ namespace Serein.WorkBench
/// <param name="eventArgs"></param> /// <param name="eventArgs"></param>
private void FlowEnvironment_NodeRemoteEvent(NodeRemoteEventArgs eventArgs) private void FlowEnvironment_NodeRemoteEvent(NodeRemoteEventArgs eventArgs)
{ {
var nodeGuid = eventArgs.NodeGuid;
if (!NodeControls.TryGetValue(nodeGuid, out NodeControlBase nodeControl))
{
return;
}
if(nodeControl is null)
{
return;
}
if (selectNodeControls.Count > 0)
{
if (selectNodeControls.Contains(nodeControl))
{
selectNodeControls.Remove(nodeControl);
}
}
this.Dispatcher.Invoke(() => this.Dispatcher.Invoke(() =>
{ {
var nodeGuid = eventArgs.NodeGuid;
if (!NodeControls.TryGetValue(nodeGuid, out var nodeControl))
{
return;
}
FlowChartCanvas.Children.Remove(nodeControl); FlowChartCanvas.Children.Remove(nodeControl);
NodeControls.Remove(nodeControl.ViewModel.Node.Guid); NodeControls.Remove(nodeControl.ViewModel.Node.Guid);
}); });
@@ -643,10 +649,6 @@ namespace Serein.WorkBench
} }
#endregion
#region
/// <summary> /// <summary>
/// 开始创建连接 True线 操作,设置起始块和绘制连接线。 /// 开始创建连接 True线 操作,设置起始块和绘制连接线。
/// </summary> /// </summary>
@@ -676,6 +678,10 @@ namespace Serein.WorkBench
this.KeyDown += MainWindow_KeyDown; this.KeyDown += MainWindow_KeyDown;
} }
#endregion
#region
/// <summary> /// <summary>
/// 配置连接曲线的右键菜单 /// 配置连接曲线的右键菜单
/// </summary> /// </summary>
@@ -683,7 +689,6 @@ namespace Serein.WorkBench
private void ConfigureLineContextMenu(Connection connection) private void ConfigureLineContextMenu(Connection connection)
{ {
var contextMenu = new ContextMenu(); var contextMenu = new ContextMenu();
contextMenu.Items.Add(CreateMenuItem("删除连线", (s, e) => DeleteConnection(connection))); contextMenu.Items.Add(CreateMenuItem("删除连线", (s, e) => DeleteConnection(connection)));
connection.ArrowPath.ContextMenu = contextMenu; connection.ArrowPath.ContextMenu = contextMenu;
connection.BezierPath.ContextMenu = contextMenu; connection.BezierPath.ContextMenu = contextMenu;
@@ -705,7 +710,6 @@ namespace Serein.WorkBench
FlowEnvironment.RemoteConnect(fromNodeGuid, toNodeGuid, connection.Type); FlowEnvironment.RemoteConnect(fromNodeGuid, toNodeGuid, connection.Type);
} }
/// <summary> /// <summary>
/// 查看返回类型(树形结构展开类型的成员) /// 查看返回类型(树形结构展开类型的成员)
/// </summary> /// </summary>
@@ -762,9 +766,67 @@ namespace Serein.WorkBench
#endregion #endregion
#region #region
/// <summary>
/// 鼠标在画布移动。
/// 选择控件状态下,调整选择框大小
/// 连接状态下,实时更新连接线的终点位置。
/// 移动画布状态下,移动画布。
/// </summary>
private void FlowChartCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (IsSelectControl && e.LeftButton == MouseButtonState.Pressed) // 正在选取节点
{
// 获取当前鼠标位置
Point currentPoint = e.GetPosition(FlowChartCanvas);
// 更新选取矩形的位置和大小
double x = Math.Min(currentPoint.X, startPoint.X);
double y = Math.Min(currentPoint.Y, startPoint.Y);
double width = Math.Abs(currentPoint.X - startPoint.X);
double height = Math.Abs(currentPoint.Y - startPoint.Y);
Canvas.SetLeft(SelectionRectangle, x);
Canvas.SetTop(SelectionRectangle, y);
SelectionRectangle.Width = width;
SelectionRectangle.Height = height;
}
if (IsConnecting) // 正在连接节点
{
Point position = e.GetPosition(FlowChartCanvas);
if (currentLine == null || startConnectNodeControl == null)
{
return;
}
currentLine.X1 = Canvas.GetLeft(startConnectNodeControl) + startConnectNodeControl.ActualWidth / 2;
currentLine.Y1 = Canvas.GetTop(startConnectNodeControl) + startConnectNodeControl.ActualHeight / 2;
currentLine.X2 = position.X;
currentLine.Y2 = position.Y;
}
if (IsCanvasDragging) // 正在移动画布
{
Point currentMousePosition = e.GetPosition(this);
double deltaX = currentMousePosition.X - startPoint.X;
double deltaY = currentMousePosition.Y - startPoint.Y;
translateTransform.X += deltaX;
translateTransform.Y += deltaY;
startPoint = currentMousePosition;
foreach (var line in Connections)
{
line.Refresh();
}
e.Handled = true; // 防止事件传播影响其他控件
}
}
/// <summary> /// <summary>
/// 基础节点的拖拽放置创建 /// 基础节点的拖拽放置创建
/// </summary> /// </summary>
@@ -886,7 +948,6 @@ namespace Serein.WorkBench
} }
} }
/// <summary> /// <summary>
/// 拖动效果,根据拖放数据是否为指定类型设置拖放效果 /// 拖动效果,根据拖放数据是否为指定类型设置拖放效果
/// </summary> /// </summary>
@@ -1093,139 +1154,7 @@ namespace Serein.WorkBench
} }
#endregion #endregion
#region
/// <summary>
/// 在画布中尝试选取控件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FlowChartCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{
IsSelectControl = true;
// 开始选取时,记录鼠标起始点
startPoint = e.GetPosition(FlowChartCanvas);
// 初始化选取矩形的位置和大小
Canvas.SetLeft(SelectionRectangle, startPoint.X);
Canvas.SetTop(SelectionRectangle, startPoint.Y);
SelectionRectangle.Width = 0;
SelectionRectangle.Height = 0;
// 显示选取矩形
SelectionRectangle.Visibility = Visibility.Visible;
// 捕获鼠标以便在鼠标移动到Canvas外部时仍能处理事件
FlowChartCanvas.CaptureMouse();
}
}
/// <summary>
/// 在画布中释放鼠标按下,结束选取状态
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FlowChartCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (IsSelectControl)
{
IsSelectControl = false;
// 释放鼠标捕获
FlowChartCanvas.ReleaseMouseCapture();
// 隐藏选取矩形(如果需要保持选取状态,可以删除此行)
SelectionRectangle.Visibility = Visibility.Collapsed;
// 处理选取区域内的元素(例如,获取选取范围内的控件)
Rect selectionArea = new Rect(Canvas.GetLeft(SelectionRectangle),
Canvas.GetTop(SelectionRectangle),
SelectionRectangle.Width,
SelectionRectangle.Height);
selectControls.Clear();
// 在此处处理选取的逻辑
foreach (UIElement element in FlowChartCanvas.Children)
{
Rect elementBounds = new Rect(Canvas.GetLeft(element), Canvas.GetTop(element),
element.RenderSize.Width, element.RenderSize.Height);
if (selectionArea.Contains(elementBounds))
{
// 选中元素,执行相应操作
if (element is NodeControlBase control)
{
selectControls.Add(control);
}
}
}
Console.WriteLine($"一共选取了{selectControls.Count}个控件");
}
}
/// <summary>
/// 鼠标在画布移动。
/// 选择控件状态下,调整选择框大小
/// 连接状态下,实时更新连接线的终点位置。
/// 移动画布状态下,移动画布。
/// </summary>
private void FlowChartCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (IsSelectControl && e.LeftButton == MouseButtonState.Pressed) // 正在选取节点
{
// 获取当前鼠标位置
Point currentPoint = e.GetPosition(FlowChartCanvas);
// 更新选取矩形的位置和大小
double x = Math.Min(currentPoint.X, startPoint.X);
double y = Math.Min(currentPoint.Y, startPoint.Y);
double width = Math.Abs(currentPoint.X - startPoint.X);
double height = Math.Abs(currentPoint.Y - startPoint.Y);
Canvas.SetLeft(SelectionRectangle, x);
Canvas.SetTop(SelectionRectangle, y);
SelectionRectangle.Width = width;
SelectionRectangle.Height = height;
}
if (IsConnecting) // 正在连接节点
{
Point position = e.GetPosition(FlowChartCanvas);
if (currentLine == null || startConnectNodeControl == null)
{
return;
}
currentLine.X1 = Canvas.GetLeft(startConnectNodeControl) + startConnectNodeControl.ActualWidth / 2;
currentLine.Y1 = Canvas.GetTop(startConnectNodeControl) + startConnectNodeControl.ActualHeight / 2;
currentLine.X2 = position.X;
currentLine.Y2 = position.Y;
}
if (IsCanvasDragging) // 正在移动画布
{
Point currentMousePosition = e.GetPosition(this);
double deltaX = currentMousePosition.X - startPoint.X;
double deltaY = currentMousePosition.Y - startPoint.Y;
translateTransform.X += deltaX;
translateTransform.Y += deltaY;
startPoint = currentMousePosition;
foreach (var line in Connections)
{
line.Refresh();
}
e.Handled = true; // 防止事件传播影响其他控件
}
}
#endregion
#region #region
private void FlowChartCanvas_MouseDown(object sender, MouseButtonEventArgs e) private void FlowChartCanvas_MouseDown(object sender, MouseButtonEventArgs e)
@@ -1251,25 +1180,32 @@ namespace Serein.WorkBench
// 单纯缩放画布,不改变画布大小 // 单纯缩放画布,不改变画布大小
private void FlowChartCanvas_MouseWheel(object sender, MouseWheelEventArgs e) private void FlowChartCanvas_MouseWheel(object sender, MouseWheelEventArgs e)
{ {
//var w = (int)(FlowChartCanvas.Width * scaleTransform.ScaleX);
//var h = (int)(FlowChartCanvas.Height * scaleTransform.ScaleY);
//var TMP1 = w / FlowChartStackPanel.ActualWidth < 0.9;
//var TMP2 = h / FlowChartStackPanel.ActualHeight < 0.9;
//Console.WriteLine("w"+(w, FlowChartStackPanel.ActualWidth, TMP1));
//Console.WriteLine("h"+(h, FlowChartStackPanel.ActualHeight, TMP2));
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{ {
if (e.Delta < 0 && scaleTransform.ScaleX < 0.2) return; if (e.Delta < 0 && scaleTransform.ScaleX < 0.2) return;
if (e.Delta > 0 && scaleTransform.ScaleY > 1.5) return; if (e.Delta > 0 && scaleTransform.ScaleY > 1.5) return;
double scale = e.Delta > 0 ? 0.1 : -0.1; // 获取鼠标在 Canvas 内的相对位置
var mousePosition = e.GetPosition(FlowChartCanvas);
scaleTransform.ScaleX += scale; // 缩放因子,根据滚轮方向调整
scaleTransform.ScaleY += scale; double zoomFactor = e.Delta > 0 ? 0.1 : -0.1;
//double zoomFactor = e.Delta > 0 ? 1.1 : 0.9;
// 当前缩放比例
double oldScale = scaleTransform.ScaleX;
// double newScale = oldScale * zoomFactor;
double newScale = oldScale + zoomFactor;
// 更新缩放比例
scaleTransform.ScaleX = newScale;
scaleTransform.ScaleY = newScale;
// 计算缩放前后鼠标相对于 Canvas 的位置差异
// double offsetX = mousePosition.X - (mousePosition.X * zoomFactor);
// double offsetY = mousePosition.Y - (mousePosition.Y * zoomFactor);
// 更新 TranslateTransform确保以鼠标位置为中心进行缩放
translateTransform.X -= (mousePosition.X * (newScale - oldScale));
translateTransform.Y -= (mousePosition.Y * (newScale - oldScale));
} }
} }
@@ -1278,8 +1214,6 @@ namespace Serein.WorkBench
{ {
FlowChartCanvas.Width = width; FlowChartCanvas.Width = width;
FlowChartCanvas.Height = height; FlowChartCanvas.Height = height;
//FlowChartStackPanel.Width = width;
//FlowChartStackPanel.Height = height;
} }
@@ -1331,21 +1265,10 @@ namespace Serein.WorkBench
double newWidth = Math.Max(FlowChartCanvas.ActualWidth + horizontalChange, 400); double newWidth = Math.Max(FlowChartCanvas.ActualWidth + horizontalChange, 400);
double newHeight = Math.Max(FlowChartCanvas.ActualHeight + verticalChange, 400); double newHeight = Math.Max(FlowChartCanvas.ActualHeight + verticalChange, 400);
// 更新 Canvas 大小 newHeight = newHeight < 400 ? 400 : newHeight;
FlowChartCanvas.Width = newWidth; newWidth = newWidth < 400 ? 400 : newWidth;
FlowChartCanvas.Height = newHeight;
// 如果宽度和高度超过400调整TranslateTransform以保持左上角不动 InitializeCanvas(newWidth, newHeight);
if (newWidth > 400 && newHeight > 400)
{
// 计算平移的变化,保持左上角不动
double deltaX = -horizontalChange / 2; // 水平方向的平移
double deltaY = -verticalChange / 2; // 垂直方向的平移
// 调整TranslateTransform以补偿尺寸变化
translateTransform.X += deltaX;
translateTransform.Y += deltaY;
}
//// 从右下角调整大小 //// 从右下角调整大小
//double newWidth = Math.Max(FlowChartCanvas.ActualWidth + e.HorizontalChange * scaleTransform.ScaleX, 0); //double newWidth = Math.Max(FlowChartCanvas.ActualWidth + e.HorizontalChange * scaleTransform.ScaleX, 0);
@@ -1380,45 +1303,14 @@ namespace Serein.WorkBench
private void Thumb_DragDelta_Right(object sender, DragDeltaEventArgs e) private void Thumb_DragDelta_Right(object sender, DragDeltaEventArgs e)
{ {
//从右侧调整大小 //从右侧调整大小
//double newWidth = Math.Max(FlowChartCanvas.ActualWidth + e.HorizontalChange * scaleTransform.ScaleX, 0); // 获取缩放后的水平变化
//newWidth = newWidth < 400 ? 400 : newWidth;
//if (newWidth > 400)
//{
// FlowChartCanvas.Width = newWidth;
// double x = e.HorizontalChange > 0 ? -0.5 : 0.5;
// double y = 0;
// double deltaX = x * scaleTransform.ScaleX;
// double deltaY = y * 0;
// Test(deltaX, deltaY);
//}
// 获取缩放后的水平和垂直变化
double horizontalChange = e.HorizontalChange * scaleTransform.ScaleX; double horizontalChange = e.HorizontalChange * scaleTransform.ScaleX;
//double verticalChange = e.VerticalChange * scaleTransform.ScaleY;
// 计算新的宽度和高度确保不会小于400 // 计算新的宽度确保不会小于400
double newWidth = Math.Max(FlowChartCanvas.ActualWidth + horizontalChange, 400); double newWidth = Math.Max(FlowChartCanvas.ActualWidth + horizontalChange, 400);
//double newHeight = Math.Max(FlowChartCanvas.ActualHeight + verticalChange, 400);
newWidth = newWidth < 400 ? 400 : newWidth;
// 更新 Canvas 大小 InitializeCanvas(newWidth, FlowChartCanvas.Height);
FlowChartCanvas.Width = newWidth;
//FlowChartCanvas.Height = newHeight;
// 如果宽度和高度超过400调整TranslateTransform以保持左上角不动
if (newWidth > 400 /*&& newHeight > 400*/)
{
// 计算平移的变化,保持左上角不动
double deltaX = -horizontalChange / 2; // 水平方向的平移
//double deltaY = -verticalChange / 2; // 垂直方向的平移
// 调整TranslateTransform以补偿尺寸变化
translateTransform.X += deltaX;
//translateTransform.Y += deltaY;
}
} }
@@ -1433,58 +1325,20 @@ namespace Serein.WorkBench
private void Thumb_DragDelta_Bottom(object sender, DragDeltaEventArgs e) private void Thumb_DragDelta_Bottom(object sender, DragDeltaEventArgs e)
{ {
//// 从底部调整大小 // 获取缩放后的垂直变化
//double oldHeight = FlowChartCanvas.Height;
//double newHeight = Math.Max(FlowChartCanvas.ActualHeight + e.VerticalChange * scaleTransform.ScaleY, 0);
////newHeight = newHeight < 400 ? 400 : newHeight;
//if(newHeight > 400)
//{
// FlowChartCanvas.Height = newHeight;
// double x = 0;
// double y = e.VerticalChange > 0 ? -0.5 : 0.5 ;
// double deltaX = x * 0;
// double deltaY = y * (scaleTransform.ScaleY);
// Test(deltaX, deltaY);
//}
// 获取缩放后的水平和垂直变化
//double horizontalChange = e.HorizontalChange * scaleTransform.ScaleX;
double verticalChange = e.VerticalChange * scaleTransform.ScaleY; double verticalChange = e.VerticalChange * scaleTransform.ScaleY;
// 计算新的高度确保不会小于400
// 计算新的宽度和高度确保不会小于400
//double newWidth = Math.Max(FlowChartCanvas.ActualWidth + horizontalChange, 400);
double newHeight = Math.Max(FlowChartCanvas.ActualHeight + verticalChange, 400); double newHeight = Math.Max(FlowChartCanvas.ActualHeight + verticalChange, 400);
newHeight = newHeight < 400 ? 400 : newHeight;
// 更新 Canvas 大小 InitializeCanvas(FlowChartCanvas.Width, newHeight);
//FlowChartCanvas.Width = newWidth;
FlowChartCanvas.Height = newHeight;
// 如果宽度和高度超过400调整TranslateTransform以保持左上角不动
if (/*newWidth > 400 &&*/ newHeight > 400)
{
// 计算平移的变化,保持左上角不动
//double deltaX = -horizontalChange / 2; // 水平方向的平移
double deltaY = -verticalChange / 2; // 垂直方向的平移
// 调整TranslateTransform以补偿尺寸变化
//translateTransform.X += deltaX;
translateTransform.Y += deltaY;
}
} }
private void Test(double deltaX, double deltaY) private void Test(double deltaX, double deltaY)
{ {
translateTransform.X += deltaX;
translateTransform.Y += deltaY;
//Console.WriteLine((translateTransform.X, translateTransform.Y)); //Console.WriteLine((translateTransform.X, translateTransform.Y));
//translateTransform.X += deltaX;
//translateTransform.Y += deltaY;
} }
#endregion #endregion
@@ -1492,6 +1346,131 @@ namespace Serein.WorkBench
#endregion #endregion
#region
/// <summary>
/// 在画布中尝试选取控件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FlowChartCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{
IsSelectControl = true;
// 开始选取时,记录鼠标起始点
startPoint = e.GetPosition(FlowChartCanvas);
// 初始化选取矩形的位置和大小
Canvas.SetLeft(SelectionRectangle, startPoint.X);
Canvas.SetTop(SelectionRectangle, startPoint.Y);
SelectionRectangle.Width = 0;
SelectionRectangle.Height = 0;
// 显示选取矩形
SelectionRectangle.Visibility = Visibility.Visible;
SelectionRectangle.ContextMenu ??= ConfiguerSelectionRectangle();
// 捕获鼠标以便在鼠标移动到Canvas外部时仍能处理事件
FlowChartCanvas.CaptureMouse();
}
}
private ContextMenu ConfiguerSelectionRectangle()
{
var contextMenu = new ContextMenu();
contextMenu.Items.Add(CreateMenuItem("删除", (s, e) =>
{
if(selectNodeControls.Count > 0)
{
foreach(var node in selectNodeControls.ToArray())
{
var guid = node?.ViewModel?.Node?.Guid;
if (!string.IsNullOrEmpty(guid))
{
FlowEnvironment.RemoteNode(guid);
}
}
}
SelectionRectangle.Visibility = Visibility.Collapsed;
}));
return contextMenu;
// nodeControl.ContextMenu = contextMenu;
}
/// <summary>
/// 在画布中释放鼠标按下,结束选取状态
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FlowChartCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (IsSelectControl)
{
CancelSelectNode(); // 取消之前选择的控件
IsSelectControl = false;
// 释放鼠标捕获
FlowChartCanvas.ReleaseMouseCapture();
// 隐藏选取矩形(如果需要保持选取状态显示,可以删除此行)
// SelectionRectangle.Visibility = Visibility.Collapsed;
// 处理选取区域内的元素(例如,获取选取范围内的控件)
Rect selectionArea = new Rect(Canvas.GetLeft(SelectionRectangle),
Canvas.GetTop(SelectionRectangle),
SelectionRectangle.Width,
SelectionRectangle.Height);
// 在此处处理选取的逻辑
foreach (UIElement element in FlowChartCanvas.Children)
{
Rect elementBounds = new Rect(Canvas.GetLeft(element), Canvas.GetTop(element),
element.RenderSize.Width, element.RenderSize.Height);
if (selectionArea.Contains(elementBounds))
{
// 选中元素,执行相应操作
if (element is NodeControlBase control)
{
selectNodeControls.Add(control);
}
}
}
SelectedNode();// 选择之后需要执行的操作
}
}
private void SelectedNode()
{
if(selectNodeControls.Count == 0)
{
Console.WriteLine($"没有选择控件");
return;
}
Console.WriteLine($"一共选取了{selectNodeControls.Count}个控件");
foreach (var node in selectNodeControls)
{
node.ViewModel.Selected();
node.ViewModel.CancelSelect();
}
}
private void CancelSelectNode()
{
foreach (var node in selectNodeControls)
{
node.ViewModel.CancelSelect();
}
selectNodeControls.Clear();
}
#endregion
/// <summary> /// <summary>
/// 卸载DLL文件清空当前项目 /// 卸载DLL文件清空当前项目

View File

@@ -0,0 +1,73 @@
using Serein.Library.Entity;
using Serein.NodeFlow.Base;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Serein.WorkBench.Node.ViewModel
{
public abstract class NodeControlViewModelBase : INotifyPropertyChanged
{
public NodeControlViewModelBase(NodeModelBase node)
{
Node = node;
MethodDetails = Node.MethodDetails;
}
/// <summary>
/// 对应的节点实体类
/// </summary>
internal NodeModelBase Node { get; }
private bool isSelect;
/// <summary>
/// 表示节点控件是否被选中
/// </summary>
internal bool IsSelect
{
get => isSelect;
set
{
isSelect = value;
// OnPropertyChanged();
}
}
private MethodDetails methodDetails;
public MethodDetails MethodDetails
{
get => methodDetails;
set
{
methodDetails = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
///
/// </summary>
public void Selected()
{
IsSelect = true;
}
public void CancelSelect()
{
IsSelect = false;
}
}
}

View File

@@ -1,6 +1,7 @@
using Serein.Library.Api; using Serein.Library.Api;
using Serein.Library.Entity; using Serein.Library.Entity;
using Serein.NodeFlow.Base; using Serein.NodeFlow.Base;
using Serein.WorkBench.Node.ViewModel;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Collections.Specialized; using System.Collections.Specialized;
using System.ComponentModel; using System.ComponentModel;
@@ -33,44 +34,7 @@ namespace Serein.WorkBench.Node.View
public abstract class NodeControlViewModelBase : INotifyPropertyChanged
{
public NodeControlViewModelBase(NodeModelBase node)
{
this.Node = node;
MethodDetails = this.Node.MethodDetails;
}
/// <summary>
/// 对应的节点实体类
/// </summary>
public NodeModelBase Node { get; }
/// <summary>
/// 表示节点控件是否被选中
/// </summary>
public bool IsSelect { get; set; } = false;
private MethodDetails methodDetails;
public MethodDetails MethodDetails
{
get => methodDetails;
set
{
methodDetails = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}