优化了中断功能。

This commit is contained in:
fengjiayi
2024-09-22 17:37:32 +08:00
parent c930c870a6
commit eff0de410b
51 changed files with 5258 additions and 396 deletions

View File

@@ -22,15 +22,29 @@ namespace Serein.Library.Core.NodeFlow
public Task CreateTimingTask(Action action, int time = 100, int count = -1)
{
NodeRunCts ??= SereinIoc.GetOrRegisterInstantiate<NodeRunCts>();
return Task.Factory.StartNew(async () =>
if (NodeRunCts == null)
{
for (int i = 0; i < count; i++)
NodeRunCts = SereinIoc.GetOrRegisterInstantiate<NodeRunCts>();
}
// 使用局部变量,避免捕获外部的 `action`
Action localAction = action;
return Task.Run(async () =>
{
for (int i = 0; i < count && !NodeRunCts.IsCancellationRequested; i++)
{
NodeRunCts.Token.ThrowIfCancellationRequested();
await Task.Delay(time);
action.Invoke();
if (NodeRunCts.IsCancellationRequested) { break; }
//if (FlowEnvironment.IsGlobalInterrupt)
//{
// await FlowEnvironment.GetOrCreateGlobalInterruptAsync();
//}
// 确保对局部变量的引用
localAction?.Invoke();
}
// 清理引用,避免闭包导致的内存泄漏
localAction = null;
});
}
}

View File

@@ -1,6 +1,7 @@
using Serein.Library.Api;
using Serein.Library.Utils;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Serein.Library.Framework.NodeFlow
@@ -17,9 +18,11 @@ namespace Serein.Library.Framework.NodeFlow
SereinIoc = sereinIoc;
FlowEnvironment = flowEnvironment;
}
public NodeRunCts NodeRunCts { get; set; }
public ISereinIOC SereinIoc { get; }
public IFlowEnvironment FlowEnvironment { get; }
public Task CreateTimingTask(Action action, int time = 100, int count = -1)
{
if(NodeRunCts == null)
@@ -31,11 +34,14 @@ namespace Serein.Library.Framework.NodeFlow
return Task.Run(async () =>
{
for (int i = 0; i < count; i++)
for (int i = 0; i < count && !NodeRunCts.IsCancellationRequested; i++)
{
NodeRunCts.Token.ThrowIfCancellationRequested();
await Task.Delay(time);
if (NodeRunCts.IsCancellationRequested) { break; }
//if (FlowEnvironment.IsGlobalInterrupt)
//{
// await FlowEnvironment.GetOrCreateGlobalInterruptAsync();
//}
// 确保对局部变量的引用
localAction?.Invoke();
}

View File

@@ -37,6 +37,9 @@
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />

View File

@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net45" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net461" />
</packages>

View File

@@ -5,6 +5,7 @@ using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using static Serein.Library.Utils.ChannelFlowInterrupt;
namespace Serein.Library.Api
{
@@ -226,7 +227,7 @@ namespace Serein.Library.Api
/// 节点触发中断事件
/// </summary>
/// <param name="eventArgs"></param>
public delegate void NodeInterruptTriggerHandler(NodeInterruptTriggerEventArgs eventArgs);
public delegate void ExpInterruptTriggerHandler(InterruptTriggerEventArgs eventArgs);
/// <summary>
/// 监视的节点数据发生变化
@@ -270,23 +271,54 @@ namespace Serein.Library.Api
/// <summary>
/// 节点触发了中断事件参数
/// </summary>
public class NodeInterruptTriggerEventArgs : FlowEventArgs
public class InterruptTriggerEventArgs : FlowEventArgs
{
public NodeInterruptTriggerEventArgs(string nodeGuid)
public enum InterruptTriggerType
{
NodeGuid = nodeGuid;
/// <summary>
/// 主动监视中断
/// </summary>
Monitor,
/// <summary>
/// 表达式中断
/// </summary>
Exp,
}
public InterruptTriggerEventArgs(string nodeGuid, string expression, InterruptTriggerType type)
{
this.NodeGuid = nodeGuid;
this.Expression = expression;
this.Type = type;
}
/// <summary>
/// 中断的节点Guid
/// </summary>
public string NodeGuid { get; protected set; }
public string Expression { get; protected set; }
public InterruptTriggerType Type { get; protected set; }
}
public interface IFlowEnvironment
{
ChannelFlowInterrupt ChannelFlowInterrupt { get; set; }
/// <summary>
/// 环境名称
/// </summary>
string EnvName {get;}
/// <summary>
/// 是否全局中断
/// </summary>
bool IsGlobalInterrupt { get; }
/// <summary>
/// 设置中断时的中断级别
/// </summary>
//InterruptClass EnvInterruptClass { get; set; }
/// <summary>
/// 调试管理
/// </summary>
//ChannelFlowInterrupt ChannelFlowInterrupt { get; set; }
/// <summary>
/// 加载Dll
@@ -334,9 +366,9 @@ namespace Serein.Library.Api
event NodeInterruptStateChangeHandler OnNodeInterruptStateChange;
/// <summary>
/// 节点触发中断
/// 触发中断
/// </summary>
event NodeInterruptTriggerHandler OnNodeInterruptTrigger;
event ExpInterruptTriggerHandler OnInterruptTrigger;
/// <summary>
@@ -417,21 +449,51 @@ namespace Serein.Library.Api
/// <param name="nodeGuid">被中断的节点Guid</param>
/// <param name="interruptClass">新的中断级别</param>
/// <returns></returns>
bool NodeInterruptChange(string nodeGuid,InterruptClass interruptClass);
bool SetNodeInterrupt(string nodeGuid, InterruptClass interruptClass);
/// <summary>
/// 添加中断表达式
/// </summary>
/// <param name="nodeGuid"></param>
/// <param name="expression"></param>
/// <returns></returns>
bool AddInterruptExpression(string nodeGuid,string expression);
/// <summary>
/// /// <summary>
/// 设置节点数据监视状态
/// </summary>
/// <param name="nodeGuid">需要监视的节点Guid</param>
/// <param name="isMonitor">是否监视</param>
void SetNodeFLowDataMonitorState(string nodeGuid, bool isMonitor);
/// <summary>
/// 节点数据更新通知
/// 流程启动器调用,节点数据更新通知
/// </summary>
/// <param name="nodeGuid"></param>
void FlowDataUpdateNotification(string nodeGuid, object flowData);
/// <param name="nodeGuid">更新了数据的节点Guid</param>
/// <param name="flowData">更新的数据</param>
void FlowDataNotification(string nodeGuid, object flowData);
/// <summary>
/// 流程启动器调用,节点触发了中断
/// </summary>
/// <param name="nodeGuid">被中断的节点Guid</param>
/// <param name="expression">被触发的表达式</param>
/// <param name="type">中断类型。0主动监视1表达式</param>
void TriggerInterrupt(string nodeGuid,string expression, InterruptTriggerEventArgs.InterruptTriggerType type);
/// <summary>
/// 全局中断
/// </summary>
/// <param name="signal"></param>
/// <param name="interruptClass"></param>
/// <returns></returns>
Task<CancelType> GetOrCreateGlobalInterruptAsync();
}
}

View File

@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using static Serein.Library.Utils.ChannelFlowInterrupt;
namespace Serein.Library.Entity
{
@@ -21,8 +23,21 @@ namespace Serein.Library.Entity
/// </summary>
public InterruptClass InterruptClass { get; set; } = InterruptClass.None;
/// <summary>
/// 中断表达式
/// </summary>
public List<string> InterruptExpressions { get; } = new List<string>();
public List<string> InterruptExpression { get; } = new List<string>();
/// <summary>
/// 取消中断的回调函数
/// </summary>
public Action CancelInterruptCallback { get; set; }
/// <summary>
/// 中断Task
/// </summary>
public Func<Task<CancelType>> GetInterruptTask { get; set; }
}
/// <summary>
@@ -41,7 +56,7 @@ namespace Serein.Library.Entity
/// <summary>
/// 分组中断,中断进入指定节点分组的分支。(暂未实现相关)
/// </summary>
Group,
// Group,
/// <summary>
/// 全局中断,中断全局所有节点的运行。(暂未实现相关)
/// </summary>

View File

@@ -1,4 +1,5 @@
using System;
#region plan 2
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Channels;
@@ -6,125 +7,351 @@ using System.Threading.Tasks;
namespace Serein.Library.Utils
{
public class ChannelFlowInterrupt
/// <summary>
/// 流程中断管理
/// </summary>
public class ChannelFlowInterrupt
{
/// <summary>
/// 中断取消类型
/// </summary>
public enum CancelType
{
Manual,
Error,
Overtime
}
// 使用并发字典管理每个信号对应的 Channel
private readonly ConcurrentDictionary<string, Channel<CancelType>> _channels = new ConcurrentDictionary<string, Channel<CancelType>>();
/// <summary>
/// 创建信号并指定超时时间,到期后自动触发(异步方法)
/// </summary>
/// <param name="signal">信号标识符</param>
/// <param name="outTime">超时时间</param>
/// <returns>等待任务</returns>
public async Task<CancelType> GetCreateChannelWithTimeoutAsync(string signal, TimeSpan outTime)
{
var channel = GetOrCreateChannel(signal);
var cts = new CancellationTokenSource();
// 异步任务:超时后自动触发信号
_ = Task.Run(async () =>
{
/// <summary>
/// 中断取消类型
/// </summary>
public enum CancelType
try
{
Manual,
Overtime
}
// 使用并发字典管理每个信号对应的 Channel
private readonly ConcurrentDictionary<string, Channel<CancelType>> _channels = new ConcurrentDictionary<string, Channel<CancelType>>();
/// <summary>
/// 创建信号并指定超时时间,到期后自动触发(异步方法)
/// </summary>
/// <param name="signal">信号标识符</param>
/// <param name="outTime">超时时间</param>
/// <returns>等待任务</returns>
public async Task<CancelType> CreateChannelWithTimeoutAsync(string signal, TimeSpan outTime)
{
var channel = GetOrCreateChannel(signal);
var cts = new CancellationTokenSource();
// 异步任务:超时后自动触发信号
_ = Task.Run(async () =>
await Task.Delay(outTime, cts.Token);
if (!cts.Token.IsCancellationRequested)
{
try
{
await Task.Delay(outTime, cts.Token);
if(!cts.Token.IsCancellationRequested)
{
await channel.Writer.WriteAsync(CancelType.Overtime);
}
}
catch (OperationCanceledException)
{
// 超时任务被取消
}
finally
{
cts?.Dispose();
}
}, cts.Token);
// 等待信号传入(超时或手动触发)
var result = await channel.Reader.ReadAsync();
return result;
}
/// <summary>
/// 创建信号并指定超时时间,到期后自动触发(同步阻塞方法)
/// </summary>
/// <param name="signal">信号标识符</param>
/// <param name="timeout">超时时间</param>
public CancelType CreateChannelWithTimeoutSync(string signal, TimeSpan timeout)
{
var channel = GetOrCreateChannel(signal);
var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
// 异步任务:超时后自动触发信号
_ = Task.Run(async () =>
{
try
{
await Task.Delay(timeout, token);
await channel.Writer.WriteAsync(CancelType.Overtime);
}
catch (OperationCanceledException)
{
// 任务被取消
}
});
// 同步阻塞直到信号触发或超时
var result = channel.Reader.ReadAsync().AsTask().GetAwaiter().GetResult();
return result;
}
/// <summary>
/// 触发信号
/// </summary>
/// <param name="signal">信号字符串</param>
/// <returns>是否成功触发</returns>
public bool TriggerSignal(string signal)
{
if (_channels.TryGetValue(signal, out var channel))
{
// 手动触发信号
channel.Writer.TryWrite(CancelType.Manual);
return true;
await channel.Writer.WriteAsync(CancelType.Overtime);
}
return false;
}
/// <summary>
/// 取消所有任务
/// </summary>
public void CancelAllTasks()
catch (OperationCanceledException)
{
foreach (var channel in _channels.Values)
{
channel.Writer.Complete();
}
_channels.Clear();
// 超时任务被取消
}
/// <summary>
/// 获取或创建指定信号的 Channel
/// </summary>
/// <param name="signal">信号字符串</param>
/// <returns>对应的 Channel</returns>
private Channel<CancelType> GetOrCreateChannel(string signal)
finally
{
return _channels.GetOrAdd(signal, _ => Channel.CreateUnbounded<CancelType>());
cts?.Dispose();
}
}, cts.Token);
// 等待信号传入(超时或手动触发)
try
{
var result = await channel.Reader.ReadAsync();
return result;
}
catch
{
return CancelType.Error;
}
}
/// <summary>
/// 创建信号,直到手动触发(异步方法)
/// </summary>
/// <param name="signal">信号标识符</param>
/// <param name="outTime">超时时间</param>
/// <returns>等待任务</returns>
public async Task<CancelType> GetOrCreateChannelAsync(string signal)
{
try
{
var channel = GetOrCreateChannel(signal);
// 等待信号传入(超时或手动触发)
var result = await channel.Reader.ReadAsync();
return result;
}
catch
{
return CancelType.Manual;
}
}
/// <summary>
/// 创建信号并指定超时时间,到期后自动触发(同步阻塞方法)
/// </summary>
/// <param name="signal">信号标识符</param>
/// <param name="timeout">超时时间</param>
public CancelType CreateChannelWithTimeoutSync(string signal, TimeSpan timeout)
{
var channel = GetOrCreateChannel(signal);
var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
// 异步任务:超时后自动触发信号
_ = Task.Run(async () =>
{
try
{
await Task.Delay(timeout, token);
await channel.Writer.WriteAsync(CancelType.Overtime);
}
catch (OperationCanceledException ex)
{
// 任务被取消
await Console.Out.WriteLineAsync(ex.Message);
}
});
// 同步阻塞直到信号触发或超时
var result = channel.Reader.ReadAsync().AsTask().GetAwaiter().GetResult();
return result;
}
/// <summary>
/// 触发信号
/// </summary>
/// <param name="signal">信号字符串</param>
/// <returns>是否成功触发</returns>
public bool TriggerSignal(string signal)
{
//if (_channels.TryGetValue(signal, out var channel))
//{
// // 手动触发信号
// channel.Writer.TryWrite(CancelType.Manual);
// return true;
//}
//return false;
try
{
if (_channels.TryGetValue(signal, out var channel))
{
// 手动触发信号
channel.Writer.TryWrite(CancelType.Manual);
// 完成写入,标记该信号通道不再接受新写入
channel.Writer.Complete();
// 触发后移除信号
_channels.TryRemove(signal, out _);
return true;
}
return false;
}
catch
{
return false;
}
}
/// <summary>
/// 取消所有任务
/// </summary>
public void CancelAllTasks()
{
foreach (var channel in _channels.Values)
{
try
{
channel.Writer.Complete();
}
finally
{
}
}
_channels.Clear();
}
/// <summary>
/// 获取或创建指定信号的 Channel
/// </summary>
/// <param name="signal">信号字符串</param>
/// <returns>对应的 Channel</returns>
private Channel<CancelType> GetOrCreateChannel(string signal)
{
return _channels.GetOrAdd(signal, _ => Channel.CreateUnbounded<CancelType>());
}
}
}
#endregion
#region plan 3
//using System;
//using System.Collections.Concurrent;
//using System.Threading;
//using System.Threading.Channels;
//using System.Threading.Tasks;
//namespace Serein.Library.Utils
//{
// /// <summary>
// /// 流程中断管理类,提供了基于 Channel 的异步中断机制
// /// </summary>
// public class ChannelFlowInterrupt
// {
// /// <summary>
// /// 中断取消类型
// /// </summary>
// public enum CancelType
// {
// Manual, // 手动触发
// Overtime, // 超时触发
// Discard // 丢弃触发
// }
// // 使用并发字典管理每个信号对应的 Channel 和状态
// private readonly ConcurrentDictionary<string, (Channel<CancelType> Channel, bool IsCancelled, bool IsDiscardMode)> _channels
// = new ConcurrentDictionary<string, (Channel<CancelType>, bool, bool)>();
// // 锁对象,用于保护并发访问
// private readonly object _lock = new object();
// /// <summary>
// /// 创建带有超时功能的信号,超时后自动触发
// /// </summary>
// public async Task<CancelType> GetCreateChannelWithTimeoutAsync(string signal, TimeSpan outTime)
// {
// var (channel, isCancelled, isDiscardMode) = GetOrCreateChannel(signal);
// // 如果信号已取消或在丢弃模式下,立即返回丢弃类型
// if (isCancelled || isDiscardMode) return CancelType.Discard;
// var cts = new CancellationTokenSource();
// _ = Task.Run(async () =>
// {
// try
// {
// await Task.Delay(outTime, cts.Token);
// if (!cts.Token.IsCancellationRequested && !isCancelled)
// {
// await channel.Writer.WriteAsync(CancelType.Overtime);
// }
// }
// catch (OperationCanceledException)
// {
// // 处理任务取消的情况
// }
// finally
// {
// cts.Dispose();
// }
// }, cts.Token);
// return await channel.Reader.ReadAsync();
// }
// /// <summary>
// /// 创建或获取现有信号,等待手动触发
// /// </summary>
// public async Task<CancelType> GetOrCreateChannelAsync(string signal)
// {
// var (channel, isCancelled, isDiscardMode) = GetOrCreateChannel(signal);
// // 如果信号已取消或在丢弃模式下,立即返回丢弃类型
// if (isCancelled || isDiscardMode) return CancelType.Discard;
// return await channel.Reader.ReadAsync();
// }
// /// <summary>
// /// 触发信号并将其移除
// /// </summary>
// public bool TriggerSignal(string signal)
// {
// lock (_lock)
// {
// if (_channels.TryGetValue(signal, out var channelInfo))
// {
// var (channel, isCancelled, isDiscardMode) = channelInfo;
// // 如果信号未被取消,则触发并标记为已取消
// if (!isCancelled)
// {
// channel.Writer.TryWrite(CancelType.Manual);
// _channels[signal] = (channel, true, false); // 标记为已取消
// _channels.TryRemove(signal, out _); // 从字典中移除信号
// return true;
// }
// }
// }
// return false;
// }
// /// <summary>
// /// 启用丢弃模式,所有后续获取的信号将直接返回丢弃类型
// /// </summary>
// /// <param name="signal">信号标识符</param>
// public void EnableDiscardMode(string signal,bool state = true)
// {
// lock (_lock)
// {
// if (_channels.TryGetValue(signal, out var channelInfo))
// {
// var (channel, isCancelled, _) = channelInfo;
// _channels[signal] = (channel, isCancelled, state); // 标记为丢弃模式
// }
// }
// }
// /// <summary>
// /// 取消所有任务
// /// </summary>
// public void CancelAllTasks()
// {
// foreach (var (channel, _, _) in _channels.Values)
// {
// try
// {
// channel.Writer.Complete();
// }
// catch
// {
// // 忽略完成时的异常
// }
// }
// _channels.Clear();
// }
// /// <summary>
// /// 获取或创建指定信号的 Channel 通道
// /// </summary>
// private (Channel<CancelType>, bool, bool) GetOrCreateChannel(string signal)
// {
// lock (_lock)
// {
// return _channels.GetOrAdd(signal, _ => (Channel.CreateUnbounded<CancelType>(), false, false));
// }
// }
// }
//}
#endregion

View File

@@ -68,7 +68,7 @@ namespace Serein.Library.Web
/// </summary>
/// <param name="http"></param>
/// <param name="url"></param>
public WebApiAttribute(API http = API.POST, bool isUrl = false, string url = "")
public WebApiAttribute(API http = API.POST, bool isUrl = true, string url = "")
{
Http = http;
Url = url;

View File

@@ -78,10 +78,42 @@ namespace Serein.NodeFlow.Base
/// </summary>
public Exception RuningException { get; set; } = null;
/// <summary>
/// 当前传递数据(执行了节点对应的方法,才会存在值)
/// 控制FlowData在同一时间只会被同一个线程更改。
/// </summary>
protected object? FlowData { get; set; } = null;
private readonly ReaderWriterLockSlim _flowDataLock = new ReaderWriterLockSlim();
private object? _flowData;
/// <summary>
/// 当前传递数据(执行了节点对应的方法,才会存在值)。
/// </summary>
protected object? FlowData
{
get
{
_flowDataLock.EnterReadLock();
try
{
return _flowData;
}
finally
{
_flowDataLock.ExitReadLock();
}
}
set
{
_flowDataLock.EnterWriteLock();
try
{
_flowData = value;
}
finally
{
_flowDataLock.ExitWriteLock();
}
}
}
}

View File

@@ -27,15 +27,6 @@ namespace Serein.NodeFlow.Base
#region
public Action? CancelInterruptCallback;
/// <summary>
/// 中断节点
/// </summary>
public void Interrupt()
{
this.DebugSetting.InterruptClass = InterruptClass.Branch;
}
/// <summary>
/// 不再中断
@@ -43,9 +34,9 @@ namespace Serein.NodeFlow.Base
public void CancelInterrupt()
{
this.DebugSetting.InterruptClass = InterruptClass.None;
CancelInterruptCallback?.Invoke();
CancelInterruptCallback = null;
DebugSetting.CancelInterruptCallback?.Invoke();
}
#endregion
#region /
@@ -105,12 +96,13 @@ namespace Serein.NodeFlow.Base
/// <returns></returns>
public async Task StartExecute(IDynamicContext context)
{
Stack<NodeModelBase> stack = new Stack<NodeModelBase>();
stack.Push(this);
var cts = context.SereinIoc.Get<CancellationTokenSource>(FlowStarter.FlipFlopCtsName);
while (stack.Count > 0 && !cts.IsCancellationRequested) // 循环中直到栈为空才会退出循环
{
// 节点执行异常时跳过执行
// 从栈中弹出一个节点作为当前节点进行处理
var currentNode = stack.Pop();
@@ -126,45 +118,57 @@ namespace Serein.NodeFlow.Base
var upstreamNodes = currentNode.SuccessorNodes[ConnectionType.Upstream];
for (int i = upstreamNodes.Count - 1; i >= 0; i--)
{
if (upstreamNodes[i].DebugSetting.IsEnable) // 排除未启用的上游节点
// 筛选出启用的节点
if (upstreamNodes[i].DebugSetting.IsEnable)
{
if (upstreamNodes[i].DebugSetting.InterruptClass != InterruptClass.None) // 执行触发前
{
var cancelType = await upstreamNodes[i].DebugSetting.GetInterruptTask();
await Console.Out.WriteLineAsync($"[{upstreamNodes[i].MethodDetails.MethodName}]中断已{cancelType},开始执行后继分支");
}
upstreamNodes[i].PreviousNode = currentNode;
var upNewFlowData = await upstreamNodes[i].ExecutingAsync(context); // 执行流程节点的上游分支
await FlowRefreshDataOrInterrupt(context, upstreamNodes[i], upNewFlowData); // 执行上游分支后刷新上游节点数据
await upstreamNodes[i].StartExecute(context); // 执行流程节点的上游分支
}
}
// 执行当前节点
var newFlowData = await currentNode.ExecutingAsync(context);
await FlowRefreshDataOrInterrupt(context, currentNode, newFlowData); // 执行当前节点后刷新数据
#endregion
#region
object? newFlowData = await currentNode.ExecutingAsync(context);
if (cts == null || cts.IsCancellationRequested || currentNode.NextOrientation == ConnectionType.None)
{
// 不再执行
break;
}
await RefreshFlowDataAndExpInterrupt(context, currentNode, newFlowData); // 执行当前节点后刷新数据
#endregion
#region
// 选择后继分支
var nextNodes = currentNode.SuccessorNodes[currentNode.NextOrientation];
// 将下一个节点集合中的所有节点逆序推入栈中
for (int i = nextNodes.Count - 1; i >= 0; i--)
{
// 排除未启用的节点
if (nextNodes[i].DebugSetting.IsEnable)
// 筛选出启用的节点、未被中断的节点
if (nextNodes[i].DebugSetting.IsEnable /*&& nextNodes[i].DebugSetting.InterruptClass == InterruptClass.None*/)
{
if (nextNodes[i].DebugSetting.InterruptClass != InterruptClass.None) // 执行触发前
{
var cancelType = await nextNodes[i].DebugSetting.GetInterruptTask();
await Console.Out.WriteLineAsync($"[{nextNodes[i].MethodDetails.MethodName}]中断已{cancelType},开始执行后继分支");
}
nextNodes[i].PreviousNode = currentNode;
stack.Push(nextNodes[i]);
}
}
#endregion
}
}
/// <summary>
/// 执行节点对应的方法
/// </summary>
@@ -173,12 +177,16 @@ namespace Serein.NodeFlow.Base
public virtual async Task<object?> ExecutingAsync(IDynamicContext context)
{
#region
if (DebugSetting.InterruptClass != InterruptClass.None && TryCreateInterruptTask(context, this, out Task<CancelType>? task)) // 执行节点前检查中断
if (DebugSetting.InterruptClass != InterruptClass.None) // 执行触发前
{
string guid = this.Guid.ToString();
this.CancelInterruptCallback ??= () => context.FlowEnvironment.ChannelFlowInterrupt.TriggerSignal(guid);
var cancelType = await task!;
await Console.Out.WriteLineAsync($"[{this.MethodDetails.MethodName}]中断已{(cancelType == CancelType.Manual ? "" : "")},开始执行后继分支");
var cancelType = await this.DebugSetting.GetInterruptTask();
//if(cancelType == CancelType.Discard)
//{
// this.NextOrientation = ConnectionType.None;
// return null;
//}
await Console.Out.WriteLineAsync($"[{this.MethodDetails.MethodName}]中断已{cancelType},开始执行后继分支");
}
#endregion
@@ -192,7 +200,7 @@ namespace Serein.NodeFlow.Base
try
{
// Action/Func([方法作用的实例],[可能的参数值],[可能的返回值])
object?[]? parameters = GetParameters(context,this, md);
object?[]? parameters = GetParameters(context, this, md);
object? result = (haveParameter, haveResult) switch
{
(false, false) => Execution((Action<object>)del, instance), // 调用节点方法返回null
@@ -213,7 +221,6 @@ namespace Serein.NodeFlow.Base
}
#region
public static object? Execution(Action<object> del, object instance)
{
@@ -326,64 +333,50 @@ namespace Serein.NodeFlow.Base
/// 更新节点数据,并检查监视表达式
/// </summary>
/// <param name="newData"></param>
public static async Task FlowRefreshDataOrInterrupt(IDynamicContext context , NodeModelBase nodeModel, object? newData = null)
public static async Task RefreshFlowDataAndExpInterrupt(IDynamicContext context, NodeModelBase nodeModel, object? newData = null)
{
string guid = nodeModel.Guid;
if (newData is not null)
// 检查是否存在监视表达式
if (newData is not null && nodeModel.DebugSetting.InterruptExpressions.Count > 0)
{
// 判断是否存在表达式
bool isInterrupt = false;
// 判断监视表达式
for (int i = 0; i < nodeModel.DebugSetting.InterruptExpression.Count && !isInterrupt; i++)
// 表达式环境下判断是否需要执行中断
bool isExpInterrupt = false;
string? exp = "";
// 判断执行监视表达式,直到为 true 时退出
for (int i = 0; i < nodeModel.DebugSetting.InterruptExpressions.Count && !isExpInterrupt; i++)
{
string? exp = nodeModel.DebugSetting.InterruptExpression[i];
isInterrupt = SereinConditionParser.To(newData, exp);
exp = nodeModel.DebugSetting.InterruptExpressions[i];
isExpInterrupt = SereinConditionParser.To(newData, exp);
}
if (isInterrupt) // 触发中断
if (isExpInterrupt) // 触发中断
{
nodeModel.Interrupt();
if(TryCreateInterruptTask(context, nodeModel, out Task<CancelType>? task))
InterruptClass interruptClass = InterruptClass.Branch; // 分支中断
if (context.FlowEnvironment.SetNodeInterrupt(nodeModel.Guid, interruptClass))
{
nodeModel.CancelInterruptCallback ??= () => context.FlowEnvironment.ChannelFlowInterrupt.TriggerSignal(guid);
var cancelType = await task!;
await Console.Out.WriteLineAsync($"[{nodeModel.MethodDetails.MethodName}]中断已{(cancelType == CancelType.Manual ? "" : "")},开始执行后继分支");
context.FlowEnvironment.TriggerInterrupt(guid, exp, InterruptTriggerEventArgs.InterruptTriggerType.Exp);
var cancelType = await nodeModel.DebugSetting.GetInterruptTask();
await Console.Out.WriteLineAsync($"[{nodeModel.MethodDetails.MethodName}]中断已{cancelType},开始执行后继分支");
}
}
}
nodeModel.FlowData = newData;
// 节点是否监视了数据,如果是,调用环境接口触发其相关事件。
//else if (nodeModel.DebugSetting.InterruptClass != InterruptClass.None)
//{
// var cancelType = await nodeModel.DebugSetting.InterruptTask;
// await Console.Out.WriteLineAsync($"[{nodeModel.MethodDetails.MethodName}]中断已{(cancelType == CancelType.Manual ? "手动取消" : "自动取消")},开始执行后继分支");
//}
nodeModel.FlowData = newData; // 替换数据
// 节点是否监视了数据,如果是,调用环境接口触发其相关事件。
if (nodeModel.DebugSetting.IsMonitorFlowData)
{
context.FlowEnvironment.FlowDataUpdateNotification(guid, newData);
context.FlowEnvironment.FlowDataNotification(guid, newData);
}
}
public static bool TryCreateInterruptTask(IDynamicContext context, NodeModelBase currentNode, out Task<CancelType>? task)
{
bool haveTask;
Console.WriteLine($"[{currentNode.MethodDetails.MethodName}]在当前分支中断");
if (currentNode.DebugSetting.InterruptClass == InterruptClass.None)
{
haveTask = false;
task = null;
}
else if (currentNode.DebugSetting.InterruptClass == InterruptClass.Branch) // 中断当前分支
{
haveTask = true;
task = context.FlowEnvironment.ChannelFlowInterrupt.CreateChannelWithTimeoutAsync(currentNode.Guid, TimeSpan.FromSeconds(60 * 30)); // 中断30分钟
}
else
{
haveTask = false;
task = null;
}
return haveTask;
}
/// <summary>
/// 释放对象
/// </summary>
@@ -402,7 +395,7 @@ namespace Serein.NodeFlow.Base
/// <returns></returns>
public object? GetFlowData()
{
return this.FlowData ;
return this.FlowData;
}
#endregion

View File

@@ -11,6 +11,7 @@ using Serein.NodeFlow.Tool;
using System.Collections.Concurrent;
using System.Reflection;
using System.Xml.Linq;
using static Serein.Library.Utils.ChannelFlowInterrupt;
using static Serein.NodeFlow.FlowStarter;
namespace Serein.NodeFlow
@@ -57,7 +58,7 @@ namespace Serein.NodeFlow
/// <summary>
/// 节点的命名空间
/// </summary>
public const string NodeSpaceName = $"{nameof(Serein)}.{nameof(Serein.NodeFlow)}.{nameof(Serein.NodeFlow.Model)}";
public const string SpaceName = $"{nameof(Serein)}.{nameof(Serein.NodeFlow)}.{nameof(Serein.NodeFlow.Model)}";
#region
/// <summary>
@@ -108,20 +109,25 @@ namespace Serein.NodeFlow
/// <summary>
/// 节点触发了中断
/// </summary>
public event NodeInterruptTriggerHandler OnNodeInterruptTrigger;
public event ExpInterruptTriggerHandler OnInterruptTrigger;
#endregion
/// <summary>
/// 环境名称
/// </summary>
public string EnvName { get; set; } = SpaceName;
/// <summary>
/// 是否全局中断
/// </summary>
public bool IsGlobalInterrupt { get; set; }
/// <summary>
/// 流程中断器
/// </summary>
public ChannelFlowInterrupt ChannelFlowInterrupt { get; set; }
/// <summary>
/// 是否全局中断
/// </summary>
public bool IsGlobalInterrupt { get; set; }
/// <summary>
/// 存储加载的程序集路径
@@ -198,15 +204,6 @@ namespace Serein.NodeFlow
await flowStarter.RunAsync(this, nodes, initMethods, loadingMethods, exitMethods);
//await flowStarter.RunAsync(StartNode,
// this,
// runMethodDetailess,
// initMethods,
// loadingMethods,
// exitMethods,
// flipflopNodes);
if(flowStarter?.FlipFlopState == RunState.NoStart)
{
this.Exit(); // 未运行触发器时,才会调用结束方法
@@ -466,7 +463,8 @@ namespace Serein.NodeFlow
/// <exception cref="NotImplementedException"></exception>
public void RemoteNode(string nodeGuid)
{
NodeModelBase remoteNode = GuidToModel(nodeGuid);
var remoteNode = GuidToModel(nodeGuid);
if (remoteNode is null) return;
if (remoteNode.IsStart)
{
return;
@@ -498,12 +496,6 @@ namespace Serein.NodeFlow
NodeModelBase? toNode = snc.Value[i];
RemoteConnect(remoteNode, toNode, connectionType);
//remoteNode.SuccessorNodes[connectionType].RemoveAt(i);
//OnNodeConnectChange?.Invoke(new NodeConnectChangeEventArgs(remoteNode.Guid,
// toNode.Guid,
// connectionType,
// NodeConnectChangeEventArgs.ConnectChangeType.Remote)); // 通知UI
}
}
@@ -522,8 +514,10 @@ namespace Serein.NodeFlow
public void ConnectNode(string fromNodeGuid, string toNodeGuid, ConnectionType connectionType)
{
// 获取起始节点与目标节点
NodeModelBase fromNode = GuidToModel(fromNodeGuid);
NodeModelBase toNode = GuidToModel(toNodeGuid);
var fromNode = GuidToModel(fromNodeGuid);
var toNode = GuidToModel(toNodeGuid);
if (fromNode is null) return;
if (toNode is null) return;
// 开始连接
ConnectNode(fromNode, toNode, connectionType); // 外部调用连接方法
@@ -539,16 +533,12 @@ namespace Serein.NodeFlow
public void RemoteConnect(string fromNodeGuid, string toNodeGuid, ConnectionType connectionType)
{
// 获取起始节点与目标节点
NodeModelBase fromNode = GuidToModel(fromNodeGuid);
NodeModelBase toNode = GuidToModel(toNodeGuid);
var fromNode = GuidToModel(fromNodeGuid);
var toNode = GuidToModel(toNodeGuid);
if (fromNode is null) return;
if (toNode is null) return;
RemoteConnect(fromNode, toNode, connectionType);
//fromNode.SuccessorNodes[connectionType].Remove(toNode);
//toNode.PreviousNodes[connectionType].Remove(fromNode);
//OnNodeConnectChange?.Invoke(new NodeConnectChangeEventArgs(fromNodeGuid,
// toNodeGuid,
// connectionType,
// NodeConnectChangeEventArgs.ConnectChangeType.Remote));
}
@@ -606,29 +596,9 @@ namespace Serein.NodeFlow
/// <param name="newNodeGuid"></param>
public void SetStartNode(string newNodeGuid)
{
NodeModelBase newStartNodeModel = GuidToModel(newNodeGuid);
var newStartNodeModel = GuidToModel(newNodeGuid);
if (newStartNodeModel is null) return;
SetStartNode(newStartNodeModel);
//if (string.IsNullOrEmpty(newNodeGuid))
//{
// return;
//}
//if (Nodes.TryGetValue(newNodeGuid, out NodeModelBase? newStartNodeModel))
//{
// if (newStartNodeModel != null)
// {
// SetStartNode(newStartNodeModel);
// //var oldNodeGuid = "";
// //if(StartNode != null)
// //{
// // oldNodeGuid = StartNode.Guid;
// // StartNode.IsStart = false;
// //}
// //newStartNodeModel.IsStart = true;
// //StartNode = newStartNodeModel;
// //OnStartNodeChange?.Invoke(new StartNodeChangeEventArgs(oldNodeGuid, newNodeGuid));
// }
//}
}
/// <summary>
@@ -637,52 +607,149 @@ namespace Serein.NodeFlow
/// <param name="nodeGuid">被中断的目标节点Guid</param>
/// <param name="interruptClass">中断级别</param>
/// <returns>操作是否成功</returns>
public bool NodeInterruptChange(string nodeGuid, InterruptClass interruptClass)
public bool SetNodeInterrupt(string nodeGuid, InterruptClass interruptClass)
{
NodeModelBase nodeModel = GuidToModel(nodeGuid);
var nodeModel = GuidToModel(nodeGuid);
if (nodeModel is null) return false;
if (interruptClass == InterruptClass.None)
{
nodeModel.CancelInterrupt();
}
else if (interruptClass == InterruptClass.Branch)
{
nodeModel.DebugSetting.CancelInterruptCallback?.Invoke();
nodeModel.DebugSetting.GetInterruptTask = () =>
{
TriggerInterrupt(nodeGuid, "", InterruptTriggerEventArgs.InterruptTriggerType.Monitor);
return ChannelFlowInterrupt.GetOrCreateChannelAsync(nodeGuid);
};
nodeModel.DebugSetting.CancelInterruptCallback = () =>
{
ChannelFlowInterrupt.TriggerSignal(nodeGuid);
};
}
else if (interruptClass == InterruptClass.Global) // 全局……做不了omg
{
return false;
}
nodeModel.DebugSetting.InterruptClass = interruptClass;
OnNodeInterruptStateChange.Invoke(new NodeInterruptStateChangeEventArgs(nodeGuid, interruptClass));
return true;
}
/// <summary>
/// 添加表达式中断
/// </summary>
/// <param name="nodeGuid"></param>
/// <param name="expression"></param>
/// <returns></returns>
public bool AddInterruptExpression(string nodeGuid, string expression)
{
var nodeModel = GuidToModel(nodeGuid);
if (nodeModel is null) return false;
if (string.IsNullOrEmpty(expression))
{
nodeModel.DebugSetting.InterruptExpressions.Clear();// 暂时删除等UI做好了
return true;
}
if (nodeModel.DebugSetting.InterruptExpressions.Contains(expression))
{
Console.WriteLine("表达式已存在");
return false;
}
else
{
nodeModel.DebugSetting.InterruptExpressions.Clear();// 暂时删除等UI做好了
nodeModel.DebugSetting.InterruptExpressions.Add(expression);
return true;
}
}
/// <summary>
/// 监视节点的数据
/// </summary>
/// <param name="nodeGuid">需要监视的节点Guid</param>
public void SetNodeFLowDataMonitorState(string nodeGuid, bool isMonitor)
{
NodeModelBase nodeModel = GuidToModel(nodeGuid);
var nodeModel = GuidToModel(nodeGuid);
if (nodeModel is null) return;
nodeModel.DebugSetting.IsMonitorFlowData = isMonitor;
if (isMonitor)
{
var obj = nodeModel.GetFlowData();
if(obj is not null)
{
FlowDataNotification(nodeGuid, obj);
}
}
}
/// <summary>
/// 节点数据更新通知
/// </summary>
/// <param name="nodeGuid"></param>
public void FlowDataUpdateNotification(string nodeGuid, object flowData)
public void FlowDataNotification(string nodeGuid, object flowData)
{
OnMonitorObjectChange?.Invoke(new MonitorObjectEventArgs(nodeGuid, flowData));
}
/// <summary>
///
/// </summary>
/// <param name="nodeGuid">节点</param>
/// <param name="expression">表达式</param>
/// <param name="type">类型0节点1表达式</param>
public void TriggerInterrupt(string nodeGuid, string expression, InterruptTriggerEventArgs.InterruptTriggerType type)
{
OnInterruptTrigger?.Invoke(new InterruptTriggerEventArgs(nodeGuid, expression, type));
}
public Task<CancelType> GetOrCreateGlobalInterruptAsync()
{
IsGlobalInterrupt = true;
return ChannelFlowInterrupt.GetOrCreateChannelAsync(this.EnvName);
}
/// <summary>
/// Guid 转 NodeModel
/// </summary>
/// <param name="nodeGuid">节点Guid</param>
/// <returns>节点Model</returns>
/// <exception cref="ArgumentNullException">无法获取节点、Guid/节点为null时报错</exception>
private NodeModelBase GuidToModel(string nodeGuid)
private NodeModelBase? GuidToModel(string nodeGuid)
{
if (string.IsNullOrEmpty(nodeGuid))
{
throw new ArgumentNullException("not contains - Guid没有对应节点:" + (nodeGuid));
//throw new ArgumentNullException("not contains - Guid没有对应节点:" + (nodeGuid));
return null;
}
if (!Nodes.TryGetValue(nodeGuid, out NodeModelBase? nodeModel) || nodeModel is null)
{
throw new ArgumentNullException("null - Guid存在对应节点,但节点为null:" + (nodeGuid));
//throw new ArgumentNullException("null - Guid存在对应节点,但节点为null:" + (nodeGuid));
return null;
}
return nodeModel;
}
#endregion
#region

View File

@@ -270,6 +270,7 @@ namespace Serein.NodeFlow
catch (Exception ex)
{
await Console.Out.WriteLineAsync(ex.ToString());
// await Console.Out.WriteLineAsync(ex.Message);
}
finally
{
@@ -303,20 +304,27 @@ namespace Serein.NodeFlow
while (!_flipFlopCts.IsCancellationRequested)
{
var newFlowData = await singleFlipFlopNode.ExecutingAsync(context);
await NodeModelBase.FlowRefreshDataOrInterrupt(context, singleFlipFlopNode, newFlowData); // 全局触发器触发后刷新该触发器的节点数据
var newFlowData = await singleFlipFlopNode.ExecutingAsync(context); // 获取触发器等待Task
await NodeModelBase.RefreshFlowDataAndExpInterrupt(context, singleFlipFlopNode, newFlowData); // 全局触发器触发后刷新该触发器的节点数据
if (singleFlipFlopNode.NextOrientation != ConnectionType.None)
{
var nextNodes = singleFlipFlopNode.SuccessorNodes[singleFlipFlopNode.NextOrientation];
for (int i = nextNodes.Count - 1; i >= 0 && !_flipFlopCts.IsCancellationRequested; i--)
{
if (nextNodes[i].DebugSetting.IsEnable) // 排除未启用的后继节点
// 筛选出启用的节点
if (nextNodes[i].DebugSetting.IsEnable)
{
nextNodes[i].PreviousNode = singleFlipFlopNode;
if (nextNodes[i].DebugSetting.InterruptClass != InterruptClass.None) // 执行触发前
{
var cancelType = await nextNodes[i].DebugSetting.GetInterruptTask();
await Console.Out.WriteLineAsync($"[{nextNodes[i].MethodDetails.MethodName}]中断已{cancelType},开始执行后继分支");
}
await nextNodes[i].StartExecute(context); // 启动执行触发器后继分支的节点
}
}
}
}
}
catch (Exception ex)

View File

@@ -22,12 +22,16 @@ namespace Serein.NodeFlow.Model
public override async Task<object?> ExecutingAsync(IDynamicContext context)
{
#region
if (DebugSetting.InterruptClass != InterruptClass.None && TryCreateInterruptTask(context, this, out Task<CancelType>? task)) // 执行触发前
if (DebugSetting.InterruptClass != InterruptClass.None) // 执行触发前
{
string guid = this.Guid.ToString();
this.CancelInterruptCallback ??= () => context.FlowEnvironment.ChannelFlowInterrupt.TriggerSignal(guid);
var cancelType = await task!;
await Console.Out.WriteLineAsync($"[{this.MethodDetails.MethodName}]中断已{(cancelType == CancelType.Manual ? "" : "")},开始执行后继分支");
var cancelType = await this.DebugSetting.GetInterruptTask();
//if (cancelType == CancelType.Discard)
//{
// this.NextOrientation = ConnectionType.None;
// return null;
//}
await Console.Out.WriteLineAsync($"[{this.MethodDetails.MethodName}]中断已{cancelType},开始执行后继分支");
}
#endregion

View File

@@ -14,6 +14,8 @@ namespace Serein.NodeFlow.Tool.SereinExpression.Resolver
public T Value { get; set; }
public string ArithmeticExpression { get; set; }
public T RangeEnd { get; internal set; }
public T RangeStart { get; internal set; }
public override bool Evaluate(object? obj)
{
@@ -24,6 +26,8 @@ namespace Serein.NodeFlow.Tool.SereinExpression.Resolver
{
return new ValueTypeConditionResolver<T>
{
RangeStart = RangeStart,
RangeEnd = RangeEnd,
Op = Op,
Value = Value,
ArithmeticExpression = ArithmeticExpression,

View File

@@ -1,4 +1,6 @@
using Serein.NodeFlow.Tool.SereinExpression.Resolver;
using Newtonsoft.Json.Linq;
using Serein.NodeFlow.Tool.SereinExpression.Resolver;
using System.ComponentModel.Design;
using System.Globalization;
using System.Reflection;
@@ -153,15 +155,52 @@ namespace Serein.NodeFlow.Tool.SereinExpression
#region int
if (type == typeof(int))
{
int value = int.Parse(valueStr, CultureInfo.InvariantCulture);
return new MemberConditionResolver<int>
var op = ParseValueTypeOperator<int>(operatorStr);
if (op == ValueTypeConditionResolver<int>.Operator.InRange || op == ValueTypeConditionResolver<int>.Operator.OutOfRange)
{
var temp = valueStr.Split('-');
if (temp.Length < 2)
throw new ArgumentException($"范围无效:{valueStr}。");
int rangeStart = int.Parse(temp[0], CultureInfo.InvariantCulture);
int rangeEnd = int.Parse(temp[1], CultureInfo.InvariantCulture);
return new MemberConditionResolver<int>
{
Op = op,
RangeStart = rangeStart,
RangeEnd = rangeEnd,
TargetObj = targetObj,
ArithmeticExpression = GetArithmeticExpression(parts[0]),
};
}
else
{
int value = int.Parse(valueStr, CultureInfo.InvariantCulture);
return new MemberConditionResolver<int>
{
TargetObj = targetObj,
//MemberPath = memberPath,
//MemberPath = memberPath,
Op = ParseValueTypeOperator<int>(operatorStr),
Value = value,
ArithmeticExpression = GetArithmeticExpression(parts[0])
};
};
}
//int value = int.Parse(valueStr, CultureInfo.InvariantCulture);
//return new MemberConditionResolver<int>
//{
// TargetObj = targetObj,
// //MemberPath = memberPath,
// Op = ParseValueTypeOperator<int>(operatorStr),
// Value = value,
// ArithmeticExpression = GetArithmeticExpression(parts[0])
//};
}
#endregion
#region double

View File

@@ -10,6 +10,7 @@
Closing="Window_Closing">
<Grid>
<TextBox x:Name="LogTextBox"
FontSize="14"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
IsReadOnly="True"

View File

@@ -4,7 +4,7 @@
xmlns:local="clr-namespace:Serein.WorkBench"
xmlns:custom="clr-namespace:Serein.WorkBench.Node.View"
xmlns:themes="clr-namespace:Serein.WorkBench.Themes"
Title="Dynamic Node Flow" Height="700" Width="1200"
Title="Dynamic Node Flow" Height="900" Width="1400"
AllowDrop="True" Drop="Window_Drop" DragOver="Window_DragOver"
Loaded="Window_Loaded"
ContentRendered="Window_ContentRendered"
@@ -26,44 +26,47 @@
</Window.InputBindings>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<DockPanel Grid.Column="0" Background="#F5F5F5">
<DockPanel Grid.Column="0" Background="#F5F5F5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="2*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="3"></RowDefinition>
<RowDefinition Height="3*"></RowDefinition>
</Grid.RowDefinitions>
<Grid Margin="2,2,2,5" Grid.Row="0" >
<Grid Margin="2,2,2,5" Grid.Row="0" Grid.ColumnSpan="2" >
<Button Grid.Row="0" Content="保存项目" Click="ButtonSaveFile_Click" HorizontalAlignment="Left" Margin="5,5,5,5"/>
<!--<Button Grid.Row="0" Content="卸载清空" Click="UnloadAllButton_Click" HorizontalAlignment="Right" Margin="5,5,5,5"/>-->
</Grid>
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto">
<ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto" Grid.ColumnSpan="2">
<StackPanel Orientation="Horizontal">
<custom:ExpOpNodeControl x:Name="ExpOpNodeControl" Margin="10" AllowDrop="True" PreviewMouseMove="BaseNodeControl_PreviewMouseMove"/>
<custom:ConditionNodeControl x:Name="ConditionNodeControl" Margin="10" AllowDrop="True" PreviewMouseMove="BaseNodeControl_PreviewMouseMove"/>
<custom:ConditionRegionControl x:Name="ConditionRegionControl" Margin="10" AllowDrop="True" PreviewMouseMove="BaseNodeControl_PreviewMouseMove"/>
</StackPanel>
</ScrollViewer>
<ScrollViewer Grid.Row="2" VerticalScrollBarVisibility="Auto" MaxHeight="400">
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" MaxHeight="400" Grid.ColumnSpan="2" Margin="0,72,0,5" Grid.RowSpan="3">
<StackPanel x:Name="DllStackPanel" Margin="5"/>
</ScrollViewer>
<Grid Grid.Row="3" >
<GridSplitter Grid.Row="3" Height="5" HorizontalAlignment="Stretch" VerticalAlignment="Center" ResizeBehavior="PreviousAndNext" Background="Gray" Grid.ColumnSpan="2"/>
<Grid Grid.Row="4" Grid.ColumnSpan="2">
<themes:ObjectViewerControl x:Name="ObjectViewer"/>
</Grid>
</Grid>
</DockPanel>
<GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ResizeBehavior="PreviousAndNext" Background="Gray"/>
<!--<GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ResizeBehavior="PreviousAndNext" Background="Gray" DragDelta="GridSplitter_DragDelta"/>-->
<GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ResizeBehavior="PreviousAndNext" Background="Gray" />
<Grid Grid.Column="2" >
<Grid.ColumnDefinitions>

View File

@@ -144,19 +144,21 @@ namespace Serein.WorkBench
public MainWindow()
{
InitializeComponent();
ViewModel = new MainWindowViewModel(this);
FlowEnvironment = ViewModel.FlowEnvironment;
InitFlowEvent();
ObjectViewer.FlowEnvironment = FlowEnvironment;
InitializeComponent();
InitFlowEnvironmentEvent(); // 配置环境事件
logWindow = new LogWindow();
logWindow.Show();
// 重定向 Console 输出
var logTextWriter = new LogTextWriter(WriteLog,() => logWindow.Clear());;
var logTextWriter = new LogTextWriter(msg => logWindow.AppendText(msg), () => logWindow.Clear());;
Console.SetOut(logTextWriter);
InitUI();
InitCanvasUI();
var project = App.FlowProjectData;
if (project == null)
@@ -164,12 +166,10 @@ namespace Serein.WorkBench
return;
}
InitializeCanvas(project.Basic.Canvas.Width, project.Basic.Canvas.Lenght);// 设置画布大小
FlowEnvironment.LoadProject(project, App.FileDataPath); // 加载项目
}
private void InitFlowEvent()
private void InitFlowEnvironmentEvent()
{
FlowEnvironment.OnDllLoad += FlowEnvironment_DllLoadEvent;
// FlowEnvironment.OnLoadNode += FlowEnvironment_NodeLoadEvent;
@@ -183,13 +183,13 @@ namespace Serein.WorkBench
FlowEnvironment.OnMonitorObjectChange += FlowEnvironment_OnMonitorObjectChange;
FlowEnvironment.OnNodeInterruptStateChange += FlowEnvironment_OnNodeInterruptStateChange;
FlowEnvironment.OnNodeInterruptTrigger += FlowEnvironment_OnNodeInterruptTrigger;
FlowEnvironment.OnInterruptTrigger += FlowEnvironment_OnInterruptTrigger;
}
private void InitUI()
private void InitCanvasUI()
{
canvasTransformGroup = new TransformGroup();
scaleTransform = new ScaleTransform();
@@ -239,10 +239,7 @@ namespace Serein.WorkBench
}
#endregion
public void WriteLog(string message)
{
logWindow.AppendText(message);
}
#region
/// <summary>
@@ -265,7 +262,7 @@ namespace Serein.WorkBench
/// <exception cref="NotImplementedException"></exception>
private void FlowEnvironment_OnFlowRunComplete(FlowEventArgs eventArgs)
{
WriteLog("-------运行完成---------\r\n");
Console.WriteLine("-------运行完成---------\r\n");
}
/// <summary>
@@ -462,20 +459,31 @@ namespace Serein.WorkBench
private void FlowEnvironment_OnMonitorObjectChange(MonitorObjectEventArgs eventArgs)
{
string nodeGuid = eventArgs.NodeGuid;
if (string.IsNullOrEmpty(ObjectViewer.NodeGuid)) // 如果没有加载过
{
ObjectViewer.NodeGuid = nodeGuid;
ObjectViewer.LoadObjectInformation(eventArgs.NewData); // 加载节点
}
else
{
// 加载过,如果显示的对象来源并非同一个节点,则停止监听之前的节点
if (!ObjectViewer.NodeGuid.Equals(nodeGuid))
NodeControlBase nodeControl = GuidToControl(nodeGuid);
ObjectViewer.Dispatcher.BeginInvoke(() => {
if (string.IsNullOrEmpty(ObjectViewer.NodeGuid)) // 如果没有加载过
{
FlowEnvironment.SetNodeFLowDataMonitorState(ObjectViewer.NodeGuid, false);
ObjectViewer.NodeGuid = nodeGuid;
ObjectViewer.LoadObjectInformation(eventArgs.NewData); // 加载节点
//ObjectViewer.LoadObjectInformation(eventArgs.NewData); // 加载节点
}
ObjectViewer.RefreshObjectTree(eventArgs.NewData);
}
else
{
// 加载过,如果显示的对象来源并非同一个节点,则停止监听之前的节点
if (!ObjectViewer.NodeGuid.Equals(nodeGuid))
{
FlowEnvironment.SetNodeFLowDataMonitorState(ObjectViewer.NodeGuid, false);
ObjectViewer.NodeGuid = nodeGuid;
//ObjectViewer.LoadObjectInformation(eventArgs.NewData); // 加载节点
}
else
{
ObjectViewer.RefreshObjectTree(eventArgs.NewData);
}
}
});
}
@@ -491,12 +499,28 @@ namespace Serein.WorkBench
if (eventArgs.Class == InterruptClass.None)
{
nodeControl.ViewModel.IsInterrupt = false;
}
else
{
nodeControl.ViewModel.IsInterrupt = true;
}
foreach (var menuItem in nodeControl.ContextMenu.Items)
{
if (menuItem is MenuItem menu)
{
if ("取消中断".Equals(menu.Header))
{
menu.Header = "在此中断";
}
else if ("在此中断".Equals(menu.Header))
{
menu.Header = "取消中断";
}
}
}
}
@@ -505,12 +529,19 @@ namespace Serein.WorkBench
/// </summary>
/// <param name="eventArgs"></param>
/// <exception cref="NotImplementedException"></exception>
private void FlowEnvironment_OnNodeInterruptTrigger(NodeInterruptTriggerEventArgs eventArgs)
private void FlowEnvironment_OnInterruptTrigger(InterruptTriggerEventArgs eventArgs)
{
string nodeGuid = eventArgs.NodeGuid;
NodeControlBase nodeControl = GuidToControl(nodeGuid);
Console.WriteLine("节点触发了中断");
if (nodeControl is null) return;
if(eventArgs.Type == InterruptTriggerEventArgs.InterruptTriggerType.Exp)
{
Console.WriteLine($"表达式触发了中断:{eventArgs.Expression}");
}
else
{
Console.WriteLine($"节点触发了中断:{nodeGuid}");
}
}
@@ -579,7 +610,7 @@ namespace Serein.WorkBench
var childNodeControl = CreateNodeControlOfNodeInfo(childNode, md);
if (childNodeControl == null)
{
WriteLog($"无法为节点类型创建节点控件: {childNode.MethodName}\r\n");
Console.WriteLine($"无法为节点类型创建节点控件: {childNode.MethodName}\r\n");
continue;
}
@@ -687,13 +718,13 @@ namespace Serein.WorkBench
{
if (nodeControl?.ViewModel?.Node?.DebugSetting?.InterruptClass == InterruptClass.None)
{
FlowEnvironment.NodeInterruptChange(nodeGuid, InterruptClass.Branch);
FlowEnvironment.SetNodeInterrupt(nodeGuid, InterruptClass.Branch);
menuItem.Header = "取消中断";
}
else
{
FlowEnvironment.NodeInterruptChange(nodeGuid, InterruptClass.None);
FlowEnvironment.SetNodeInterrupt(nodeGuid, InterruptClass.None);
menuItem.Header = "在此中断";
}
@@ -707,6 +738,8 @@ namespace Serein.WorkBench
var node = nodeControl?.ViewModel?.Node;
if(node is not null)
{
FlowEnvironment.SetNodeFLowDataMonitorState(ObjectViewer.NodeGuid, false); // 通知环境该节点的数据更新后需要传到UI
ObjectViewer.NodeGuid = node.Guid;
FlowEnvironment.SetNodeFLowDataMonitorState(node.Guid, true); // 通知环境该节点的数据更新后需要传到UI
}
@@ -2533,6 +2566,23 @@ namespace Serein.WorkBench
break;
}
// 计算角落
//switch (localhost)
//{
// case Localhost.Right:
// point = new Point(0, element.ActualHeight / 2); // 左边中心
// break;
// case Localhost.Left:
// point = new Point(element.ActualWidth, element.ActualHeight / 2); // 右边中心
// break;
// case Localhost.Bottom:
// point = new Point(element.ActualWidth / 2, 0); // 上边中心
// break;
// case Localhost.Top:
// point = new Point(element.ActualWidth / 2, element.ActualHeight); // 下边中心
// break;
//}
// 将相对控件的坐标转换到画布中的全局坐标
return element.TranslatePoint(point, canvas);
}

View File

@@ -49,7 +49,7 @@ namespace Serein.WorkBench.Node.ViewModel
if (value != null)
{
Node.DebugSetting = value;
OnPropertyChanged(nameof(DebugSetting));
OnPropertyChanged(/*nameof(DebugSetting)*/);
}
}
}
@@ -62,7 +62,7 @@ namespace Serein.WorkBench.Node.ViewModel
if(value != null)
{
Node.MethodDetails = value;
OnPropertyChanged(nameof(MethodDetails));
OnPropertyChanged(/*nameof(MethodDetails)*/);
}
}
}
@@ -74,7 +74,7 @@ namespace Serein.WorkBench.Node.ViewModel
set
{
isInterrupt = value;
OnPropertyChanged(nameof(IsInterrupt));
OnPropertyChanged(/*nameof(IsInterrupt)*/);
}
}

View File

@@ -24,7 +24,6 @@
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Style.Triggers>
<!-- 当 DebugSetting.IsInterrupt 为 True 时,显示红色边框 -->
<DataTrigger Binding="{Binding IsInterrupt}" Value="True">
<Setter Property="BorderBrush" Value="Red" />
<Setter Property="BorderThickness" Value="2" />

View File

@@ -5,7 +5,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Serein.WorkBench.Themes"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
d:DesignHeight="400" d:DesignWidth="400">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -14,16 +14,18 @@
<!-- 树视图 -->
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<!--Click="RefreshButton_Click"
Click="TimerRefreshButton_Click"-->
<!--<Button Grid.Row="0" HorizontalAlignment="Left" Margin="4,2,4,2" Content="刷新" Width="100" Height="20" Name="RefreshButton"/>-->
<StackPanel Orientation="Horizontal" Grid.Row="0" >
<!---->
<!--<Button Grid.Row="0" HorizontalAlignment="Left" Margin="14,2,4,2" Content="监视" Width="100" Height="20" Name="TimerRefreshButton"/>-->
<Button Grid.Row="0" HorizontalAlignment="Left" Margin="14,2,4,2" Content="添加监视表达式" Width="100" Height="20" Name="AddMonitorExpressionButton" Click="AddMonitorExpressionButton_Click"/>
<!--<Button Grid.Row="0" HorizontalAlignment="Left" Margin="14,2,4,2" Content="添加监视表达式" Width="100" Height="20" Name="AddMonitorExpressionButton" Click="AddMonitorExpressionButton_Click"/>-->
<Button Grid.Row="0" HorizontalAlignment="Left" Margin="4,2,4,2" Content="刷新" Width="40" Height="20" Name="RefreshButton" Click="RefreshButton_Click"/>
<Button Grid.Row="0" HorizontalAlignment="Left" Margin="4,2,4,2" Content="添加监视表达式" Width="80" Height="20" Name="UpMonitorExpressionButton" Click="UpMonitorExpressionButton_Click"/>
<TextBox x:Name="ExpressionTextBox" Margin="4,2,4,2" Width="300"/>
</StackPanel>
<!-- 刷新按钮 -->
<!-- 树视图,用于显示对象属性 -->
<TreeView FontSize="13" x:Name="ObjectTreeView" Grid.Row="1" />
<TreeView FontSize="14" x:Name="ObjectTreeView" Grid.Row="1" />
</Grid>
</UserControl>

View File

@@ -1,10 +1,12 @@
using Serein.NodeFlow.Base;
using Serein.Library.Api;
using Serein.NodeFlow.Base;
using Serein.NodeFlow.Tool.SereinExpression;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
@@ -18,7 +20,6 @@ using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using static Serein.WorkBench.Themes.TypeViewerWindow;
using static System.Collections.Specialized.BitVector32;
namespace Serein.WorkBench.Themes
{
@@ -55,36 +56,89 @@ namespace Serein.WorkBench.Themes
{
private object _objectInstance;
public string NodeGuid { get;set; }
// private NodeModelBase _nodeFlowData;
public string MonitorExpression { get => ExpressionTextBox.Text.ToString(); }
public IFlowEnvironment FlowEnvironment { get;set; }
public NodeModelBase NodeModel { get;set; }
public ObjectViewerControl()
{
InitializeComponent();
}
private DateTime _lastRefreshTime = DateTime.MinValue; // 上次刷新时间
private TimeSpan _refreshInterval = TimeSpan.FromSeconds(0.1); // 刷新间隔2秒
/// <summary>
/// 加载对象信息,展示其成员
/// </summary>
/// <param name="obj">要展示的对象</param>
//public void LoadObjectInformation(NodeModelBase nodeModel)
public void LoadObjectInformation(object obj)
{
if (obj == null)
return;
//IsTimerRefres = false;
//TimerRefreshButton.Content = "定时刷新";
// 当前时间
var currentTime = DateTime.Now;
// 如果上次刷新时间和当前时间之间的差值小于设定的间隔,则跳过
if (currentTime - _lastRefreshTime < _refreshInterval)
{
// 跳过过于频繁的刷新调用
return;
}
// 记录这次的刷新时间
_lastRefreshTime = currentTime;
_objectInstance = obj;
RefreshObjectTree(obj);
}
private void AddMonitorExpressionButton_Click(object sender, RoutedEventArgs e)
///// <summary>
///// 添加表达式
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//private void AddMonitorExpressionButton_Click(object sender, RoutedEventArgs e)
//{
// OpenInputDialog((exp) =>
// {
// FlowEnvironment.AddInterruptExpression(NodeGuid, exp);
// });
//}
private void RefreshButton_Click(object sender, RoutedEventArgs e)
{
//RefreshObjectTree(_objectInstance);
FlowEnvironment.SetNodeFLowDataMonitorState(NodeGuid, true);
}
private void UpMonitorExpressionButton_Click(object sender, RoutedEventArgs e)
{
//MonitorExpression = ExpressionTextBox.Text.ToString();
if(FlowEnvironment.AddInterruptExpression(NodeGuid, MonitorExpression))
{
if (string.IsNullOrEmpty(MonitorExpression))
{
ExpressionTextBox.Text = "表达式已清空";
}
else
{
UpMonitorExpressionButton.Content = "更新监视表达式";
}
}
}
// 用于存储当前展开的节点路径
private HashSet<string> _expandedNodePaths = new HashSet<string>();
/// <summary>
/// 刷新对象属性树
/// </summary>
@@ -92,7 +146,19 @@ namespace Serein.WorkBench.Themes
{
if (obj is null)
return;
// _objectInstance = obj;
// 当前时间
var currentTime = DateTime.Now;
// 如果上次刷新时间和当前时间之间的差值小于设定的间隔,则跳过
if (currentTime - _lastRefreshTime < _refreshInterval)
{
// 跳过过于频繁的刷新调用
return;
}
// 记录这次的刷新时间
_lastRefreshTime = currentTime;
var objectType = obj.GetType();
FlowDataDetails flowDataDetails = new FlowDataDetails
@@ -124,9 +190,23 @@ namespace Serein.WorkBench.Themes
rootNode.Items.Clear();
AddMembersToTreeNode(rootNode, obj, objectType);
}
// 遍历节点,展开之前记录的节点
ExpandPreviouslyExpandedNodes(rootNode);
}
// 遍历并展开之前记录的节点
private void ExpandPreviouslyExpandedNodes(TreeViewItem node)
{
if (_expandedNodePaths.Contains(GetNodeFullPath(node)))
{
node.IsExpanded = true;
}
foreach (TreeViewItem child in node.Items)
{
ExpandPreviouslyExpandedNodes(child);
}
}
@@ -138,7 +218,7 @@ namespace Serein.WorkBench.Themes
/// 添加父节点
/// </summary>
/// <param name="node"></param>
private static void AddPlaceholderNode(TreeViewItem node)
private void AddPlaceholderNode(TreeViewItem node)
{
node.Items.Add(new TreeViewItem { Header = "Loading..." });
}
@@ -148,7 +228,7 @@ namespace Serein.WorkBench.Themes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
{
var item = (TreeViewItem)sender;
@@ -157,6 +237,8 @@ namespace Serein.WorkBench.Themes
item.Items.Clear();
if (item.Tag is FlowDataDetails flowDataDetails) // FlowDataDetails flowDataDetails object obj
{
// 记录当前节点的路径
_expandedNodePaths.Add(GetNodeFullPath(item));
AddMembersToTreeNode(item, flowDataDetails.DataValue, flowDataDetails.DataType);
}
}
@@ -168,7 +250,7 @@ namespace Serein.WorkBench.Themes
/// <param name="treeViewNode"></param>
/// <param name="obj"></param>
/// <param name="type"></param>
private static void AddMembersToTreeNode(TreeViewItem treeViewNode, object obj, Type type)
private void AddMembersToTreeNode(TreeViewItem treeViewNode, object obj, Type type)
{
// 获取属性和字段
var members = type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
@@ -176,11 +258,13 @@ namespace Serein.WorkBench.Themes
{
TreeViewItem memberNode = ConfigureTreeViewItem(obj, member);
treeViewNode.Items.Add(memberNode);
if (ConfigureTreeItemMenu(memberNode, member, out ContextMenu? contextMenu))
{
memberNode.ContextMenu = contextMenu; // 设置子项节点的事件
}
//if (ConfigureTreeItemMenu(memberNode, member, out ContextMenu? contextMenu))
//{
// memberNode.ContextMenu = contextMenu; // 设置子项节点的事件
//}
}
}
@@ -191,23 +275,25 @@ namespace Serein.WorkBench.Themes
/// <param name="obj"></param>
/// <param name="member"></param>
/// <returns></returns>
private static TreeViewItem ConfigureTreeViewItem(object obj, MemberInfo member)
private TreeViewItem ConfigureTreeViewItem(object obj, MemberInfo member)
{
TreeViewItem memberNode = new TreeViewItem { Header = member.Name };
if (member is PropertyInfo property)
{
string propertyValue = GetPropertyValue(obj, property,out object value);
FlowDataDetails flowDataDetails = new FlowDataDetails
{
ItemType = TreeItemType.Property,
DataType = property.PropertyType,
Name = property.Name,
DataValue = property,
DataValue = value,
DataPath = GetNodeFullPath(memberNode),
};
memberNode.Tag = flowDataDetails;
string propertyValue = GetPropertyValue(obj, property);
memberNode.Header = $"{property.Name} : {property.PropertyType.Name} = {propertyValue}";
if (!property.PropertyType.IsPrimitive && property.PropertyType != typeof(string))
@@ -218,18 +304,19 @@ namespace Serein.WorkBench.Themes
}
else if (member is FieldInfo field)
{
string fieldValue = GetFieldValue(obj, field, out object value);
FlowDataDetails flowDataDetails = new FlowDataDetails
{
ItemType = TreeItemType.Field,
DataType = field.FieldType,
Name = field.Name,
DataValue = field,
DataValue = value,
DataPath = GetNodeFullPath(memberNode),
};
memberNode.Tag = flowDataDetails;
string fieldValue = GetFieldValue(obj, field);
memberNode.Header = $"{field.Name} : {field.FieldType.Name} = {fieldValue}";
if (!field.FieldType.IsPrimitive && field.FieldType != typeof(string))
@@ -248,15 +335,22 @@ namespace Serein.WorkBench.Themes
/// <param name="obj"></param>
/// <param name="property"></param>
/// <returns></returns>
private static string GetPropertyValue(object obj, PropertyInfo property)
{
private string GetPropertyValue(object obj, PropertyInfo property,out object value)
{
try
{
var value = property.GetValue(obj);
return value?.ToString() ?? "null";
var properties = obj.GetType().GetProperties();
// 获取实例属性值
value = property.GetValue(obj);
return value?.ToString() ?? "null"; // 返回值或“null”
}
catch
{
value = null;
return "Error";
}
}
@@ -268,15 +362,16 @@ namespace Serein.WorkBench.Themes
/// <param name="obj"></param>
/// <param name="field"></param>
/// <returns></returns>
private static string GetFieldValue(object obj, FieldInfo field)
private string GetFieldValue(object obj, FieldInfo field, out object value)
{
try
{
var value = field.GetValue(obj);
value = field.GetValue(obj);
return value?.ToString() ?? "null";
}
catch
{
value = null;
return "Error";
}
}
@@ -288,13 +383,21 @@ namespace Serein.WorkBench.Themes
/// <param name="member"></param>
/// <param name="contextMenu"></param>
/// <returns></returns>
private static bool ConfigureTreeItemMenu(TreeViewItem memberNode, MemberInfo member, out ContextMenu? contextMenu)
private bool ConfigureTreeItemMenu(TreeViewItem memberNode, MemberInfo member, out ContextMenu? contextMenu)
{
bool isChange = false;
if (member is PropertyInfo property)
{
//isChange = true;
isChange = true;
contextMenu = new ContextMenu();
contextMenu.Items.Add(MainWindow.CreateMenuItem($"表达式", (s, e) =>
{
string fullPath = GetNodeFullPath(memberNode);
string copyValue = /*"@Get " + */fullPath;
ExpressionTextBox.Text = copyValue;
// Clipboard.SetDataObject(copyValue);
}));
}
else if (member is MethodInfo method)
{
@@ -305,29 +408,13 @@ namespace Serein.WorkBench.Themes
{
isChange = true;
contextMenu = new ContextMenu();
contextMenu.Items.Add(MainWindow.CreateMenuItem($"取值表达式", (s, e) =>
contextMenu.Items.Add(MainWindow.CreateMenuItem($"表达式", (s, e) =>
{
string fullPath = ObjectViewerControl.GetNodeFullPath(memberNode);
string copyValue = "@Get " + fullPath;
Clipboard.SetDataObject(copyValue);
string fullPath = GetNodeFullPath(memberNode);
string copyValue = /*"@Get " +*/ fullPath;
ExpressionTextBox.Text = copyValue;
// Clipboard.SetDataObject(copyValue);
}));
//contextMenu.Items.Add(MainWindow.CreateMenuItem($"监视中断", (s, e) =>
//{
// string fullPath = GetNodeFullPath(memberNode);
// Clipboard.SetDataObject(fullPath);
// OpenInputDialog((exp) =>
// {
// if (node.DebugSetting.InterruptExpression.Contains(exp))
// {
// Console.WriteLine("表达式已存在");
// }
// else
// {
// node.DebugSetting.InterruptExpression.Add(exp);
// }
// });
//}));
}
else
{
@@ -336,12 +423,14 @@ namespace Serein.WorkBench.Themes
return isChange;
}
/// <summary>
/// 获取当前节点的完整路径,例如 "node1.node2.node3.node4"
/// </summary>
/// <param name="node">目标节点</param>
/// <returns>节点路径</returns>
private static string GetNodeFullPath(TreeViewItem node)
private string GetNodeFullPath(TreeViewItem node)
{
if (node == null)
return string.Empty;
@@ -366,7 +455,7 @@ namespace Serein.WorkBench.Themes
/// </summary>
/// <param name="node">目标节点</param>
/// <returns>父节点</returns>
private static TreeViewItem GetParentTreeViewItem(TreeViewItem node)
private TreeViewItem GetParentTreeViewItem(TreeViewItem node)
{
DependencyObject parent = VisualTreeHelper.GetParent(node);
while (parent != null && !(parent is TreeViewItem))
@@ -378,7 +467,7 @@ namespace Serein.WorkBench.Themes
private static InputDialog OpenInputDialog(Action<string> action)
private InputDialog OpenInputDialog(Action<string> action)
{
var inputDialog = new InputDialog();
inputDialog.Closed += (s, e) =>
@@ -398,7 +487,6 @@ namespace Serein.WorkBench.Themes
///// <summary>
///// 刷新按钮的点击事件
///// </summary>

View File

@@ -163,8 +163,14 @@ namespace Serein.WorkBench.Themes
bool isChange = false;
if (member is PropertyInfo property)
{
//isChange = true;
isChange = true;
contextMenu = new ContextMenu();
contextMenu.Items.Add(MainWindow.CreateMenuItem($"取值表达式", (s, e) =>
{
string fullPath = GetNodeFullPath(memberNode);
string copyValue = "@Get " + fullPath;
Clipboard.SetDataObject(copyValue);
}));
}
else if (member is MethodInfo method)
{

Binary file not shown.

View File

@@ -0,0 +1,23 @@
The MIT License (MIT)
Copyright (c) .NET Foundation and Contributors
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Binary file not shown.

View File

@@ -0,0 +1,309 @@
.NET Core uses third-party libraries or other resources that may be
distributed under licenses different than the .NET Core software.
In the event that we accidentally failed to list a required notice, please
bring it to our attention. Post an issue or email us:
dotnet@microsoft.com
The attached notices are provided for information only.
License notice for Slicing-by-8
-------------------------------
http://sourceforge.net/projects/slicing-by-8/
Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved
This software program is licensed subject to the BSD License, available at
http://www.opensource.org/licenses/bsd-license.html.
License notice for Unicode data
-------------------------------
http://www.unicode.org/copyright.html#License
Copyright © 1991-2017 Unicode, Inc. All rights reserved.
Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Unicode data files and any associated documentation
(the "Data Files") or Unicode software and any associated documentation
(the "Software") to deal in the Data Files or Software
without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, and/or sell copies of
the Data Files or Software, and to permit persons to whom the Data Files
or Software are furnished to do so, provided that either
(a) this copyright and permission notice appear with all copies
of the Data Files or Software, or
(b) this copyright and permission notice appear in associated
Documentation.
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THE DATA FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale,
use or other dealings in these Data Files or Software without prior
written authorization of the copyright holder.
License notice for Zlib
-----------------------
https://github.com/madler/zlib
http://zlib.net/zlib_license.html
/* zlib.h -- interface of the 'zlib' general purpose compression library
version 1.2.11, January 15th, 2017
Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
*/
License notice for Mono
-------------------------------
http://www.mono-project.com/docs/about-mono/
Copyright (c) .NET Foundation Contributors
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the Software), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
License notice for International Organization for Standardization
-----------------------------------------------------------------
Portions (C) International Organization for Standardization 1986:
Permission to copy in any form is granted for use with
conforming SGML systems and applications as defined in
ISO 8879, provided this notice is included in all copies.
License notice for Intel
------------------------
"Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
License notice for Xamarin and Novell
-------------------------------------
Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Copyright (c) 2011 Novell, Inc (http://www.novell.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Third party notice for W3C
--------------------------
"W3C SOFTWARE AND DOCUMENT NOTICE AND LICENSE
Status: This license takes effect 13 May, 2015.
This work is being provided by the copyright holders under the following license.
License
By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions.
Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the work or portions thereof, including modifications:
The full text of this NOTICE in a location viewable to users of the redistributed or derivative work.
Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included.
Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)."
Disclaimers
THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT.
The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. Title to copyright in this work will at all times remain with copyright holders."
License notice for Bit Twiddling Hacks
--------------------------------------
Bit Twiddling Hacks
By Sean Eron Anderson
seander@cs.stanford.edu
Individually, the code snippets here are in the public domain (unless otherwise
noted) — feel free to use them however you please. The aggregate collection and
descriptions are © 1997-2005 Sean Eron Anderson. The code and descriptions are
distributed in the hope that they will be useful, but WITHOUT ANY WARRANTY and
without even the implied warranty of merchantability or fitness for a particular
purpose.
License notice for Brotli
--------------------------------------
Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
compress_fragment.c:
Copyright (c) 2011, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
decode_fuzzer.c:
Copyright (c) 2015 The Chromium Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."

View File

View File

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>System.ValueTuple</name>
</assembly>
<members>
</members>
</doc>

View File

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

View File

@@ -0,0 +1 @@
30ab651fcb4354552bd4891619a0bdd81e0ebdbf