mirror of
https://github.com/StockSharp/StockSharp.git
synced 2026-12-06 01:22:11 +00:00
"Mark the blocking wrappers obsolete" left several callers of those wrappers under #pragma, because a property, a parameter handler or a state setter could not wait, and a few places that blocked without a wrapper. Each of those chains now runs through callers that can await. The emulation connector. A state change collects what its handlers throw and sends it out once the state lock is released; the disconnect that follows Stopping is awaited there as well. The change to Stopped moved from a handler of Disconnected into OnDisconnectedAsync, a step the connector now awaits before it raises that event. ExpressionIndexSecurity. Expression records the text and reads the instruments it names, which needs no compiler. The formula is compiled by GetFormulaAsync; Formula is an obsolete blocking wrapper over it. IBasketSecurityProcessor gets InitAsync, where the expression processor takes its formula, and CreateProcessorAsync creates a processor and prepares it; CreateProcessor and the IEnumerable ToBasket are obsolete wrappers, and the tests of ToBasket go through the IAsyncEnumerable overload. The index diagram element builds its index in OnPrepareAsync. MathDiagramElement. The inputs are named by the text of the formula; the formula and its validation are compiled in OnPrepareAsync. An element that was reset therefore compiles again at the next start instead of refusing to start. An input that is wired stays while the text is not known to compile, and goes at the preparation if the compiled formula does not name it. A text replaced under a running element is an error on every value until the element is prepared again. Candle patterns. A CandleExpressionCondition compiled its formula in the constructor or, for the registry, at the first evaluation. The formula is now compiled by PrepareAsync: on the condition, on ICandlePattern and, through the new IIndicator.PrepareAsync, on the indicator that holds a pattern. A pattern that was not prepared refuses to recognize instead of compiling on the spot. The checks of a pattern as a whole - a formula reaching outside it, no formulas at all - moved from the first Recognize to the preparation, and a failed check no longer leaves the pattern marked as checked. Whoever feeds an indicator prepares it first: IndicatorDiagramElement in OnPrepareAsync, a strategy for the indicators its start registered, the chart samples when an indicator is added. ICandlePatternProvider.Save became SaveAsync and prepares the pattern before it stores it. The compileOnDemand constructor is gone: no constructor compiles. Stopping a strategy from code that cannot wait. When an element was entered deeper than the overflow limit, DiagramElement.Process stopped the strategy through AsyncHelper.Run. Strategy gets RequestStop for such code: it reports the error, refuses new orders at once and leaves the stop itself to OnNewMessage, which carries it out when the connector hands over the next message. Releasing a connector. Connector.DisposeManaged waited for the disconnect, and for the message that takes the adapters apart, through AsyncHelper.Run. The release is now DisposeManagedAsync, a virtual chain that the connectors derived from Connector override. DisposeAsync awaits it, and the sealed DisposeManaged is the same chain with the caller blocked, as IDisposable requires. IConnector is IAsyncDisposable, so code that holds a connector by its interface releases it by await as well. Diagram elements that waited for their type. A composition read before one of its element types was registered keeps an empty node for each such element. Registering the type started their load unawaited, and a failure lost the settings at the next save. ICompositionRegistry gets LoadNotLoadedElementsAsync, to be awaited by whoever registered the types. It loads what waits in the given composition and in the compositions nested in it, one call at a time. The settings of an element that waits are kept by its node (ICompositionModelNode.ElementSettings). A loaded element joins its model: it is announced as an added one and the links of its node are connected. The sample windows. CombineHistoryRealtime, LiveTerminal and StoreDataLocal, WPF and Avalonia, flushed the storage executor, released the CSV registries and read them at startup through AsyncHelper.Run. A window now refuses the first attempt to close it, awaits the release and closes itself once the queued writes are on the disk. A shutdown that does not honour the refusal - the end of the Windows session, Application.Shutdown - is not waited for: what is still queued then is lost. LiveOptionsQuoting and MultiConnect called the blocking Strategy.Start, Stop and GetTimeFrames under a suppressed obsolete warning; they await the async ones now. What the rework uncovered: - Pausing the optimizer. An iteration that had passed the pause gate but whose connector had not started replaying yet ran to its end through the pause; cloning the strategy asynchronously made that window long enough for PauseHaltsBruteForce to see it on CI. An iteration now waits for its connector to come up and suspends it if the optimizer is paused by then. - Undo of diagram elements. An undo scope opened with no undo manager in sight took the element's level down when it closed, so the level was negative by the time the element reached a composition and no edit was ever reported. The scope remembers whether it was counted. - Undo of a chart panel. A snapshot keeps the series and axes of a panel by reference, since a part can only be saved asynchronously, so undo did not put back what a part was set to. IChartSnapshotPart is an optional interface for a part that can copy its settings in memory; the panel captures and gives back the settings of such parts. No chart part implements it yet - that is for the chart packages to do. - The dummy indicator wrapper was left without a chart element, so indicator values could not be wired into the panel that a run without a window uses. - Settings loaded before a composition existed are applied when the strategy starts; a test pins it. - AsyncMessageChannel looked at its state once per wake-up and then went through the queue until it was empty, so a message sent right after Suspend returned could still be started, and Suspend_PausesProcessing was red from time to time. The state is now read under the queue lock, where the next message is picked; a channel that is being closed stops starting what is queued the same way. DiagramElementParamTests no longer declares a value that persists itself through the obsolete IPersistable: declaring one needs a suppressed warning, and for that contract the parameter relies on SaveEntireAsync and LoadEntireAsync of Ecng, which are tested there.
645 lines
17 KiB
C#
645 lines
17 KiB
C#
namespace StockSharp.Diagram;
|
|
|
|
using System.Drawing;
|
|
|
|
/// <summary>
|
|
/// <see cref="CompositionDiagramElement"/> model.
|
|
/// </summary>
|
|
public interface ICompositionModel
|
|
{
|
|
/// <summary>
|
|
/// Create a copy of the model.
|
|
/// </summary>
|
|
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
|
|
/// <returns>Copy.</returns>
|
|
ValueTask<ICompositionModel> CloneAsync(CancellationToken cancellationToken);
|
|
|
|
/// <summary>
|
|
/// <see cref="ICompositionModelBehavior{TNode, TLink}"/>
|
|
/// </summary>
|
|
object Behavior { get; }
|
|
|
|
/// <summary>
|
|
/// To check the composite element for errors in diagram.
|
|
/// </summary>
|
|
bool HasErrors { get; }
|
|
|
|
/// <summary>
|
|
/// Is it possible to edit a composite element diagram.
|
|
/// </summary>
|
|
bool Modifiable { get; set; }
|
|
|
|
/// <summary>
|
|
/// <see cref="IUndoManager"/>
|
|
/// </summary>
|
|
IUndoManager UndoManager { get; set; }
|
|
|
|
/// <summary>
|
|
/// Undo manager is suspended if this property is set to true.
|
|
/// </summary>
|
|
bool IsUndoManagerSuspended { get; set; }
|
|
|
|
/// <summary>
|
|
/// Child elements.
|
|
/// </summary>
|
|
IEnumerable<DiagramElement> Elements { get; }
|
|
|
|
/// <summary>
|
|
/// Add element.
|
|
/// </summary>
|
|
/// <param name="element">The diagram element.</param>
|
|
/// <param name="location">Element position.</param>
|
|
void AddElement(DiagramElement element, PointF location = default);
|
|
|
|
/// <summary>
|
|
/// Get connected sockets.
|
|
/// </summary>
|
|
/// <param name="element"><see cref="DiagramElement"/></param>
|
|
/// <param name="socket"><see cref="DiagramSocket"/></param>
|
|
/// <returns>Connected sockets.</returns>
|
|
IEnumerable<DiagramSocket> GetConnectedSocketsFor(DiagramElement element, DiagramSocket socket);
|
|
|
|
/// <summary>
|
|
/// Get disconnected sockets.
|
|
/// </summary>
|
|
/// <returns>Disconnected sockets.</returns>
|
|
IEnumerable<(string nodeKey, DiagramSocket socket)> GetDisconnectedSockets();
|
|
|
|
/// <summary>
|
|
/// Get element unique key.
|
|
/// </summary>
|
|
/// <param name="element"><see cref="DiagramElement"/></param>
|
|
/// <returns>Key.</returns>
|
|
string GetElementKey(DiagramElement element);
|
|
|
|
/// <summary>
|
|
/// Find element by unique key.
|
|
/// </summary>
|
|
/// <param name="key">Key.</param>
|
|
/// <returns><see cref="DiagramElement"/></returns>
|
|
DiagramElement FindElementByKey(string key);
|
|
|
|
/// <summary>
|
|
/// Changed event.
|
|
/// </summary>
|
|
event Action ModelChanged;
|
|
|
|
/// <summary>
|
|
/// Child element added event.
|
|
/// </summary>
|
|
event Action<DiagramElement> ElementAdded;
|
|
|
|
/// <summary>
|
|
/// Child element removed event.
|
|
/// </summary>
|
|
event Action<DiagramElement> ElementRemoved;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Default implementation of <see cref="ICompositionModel"/>.
|
|
/// </summary>
|
|
/// <typeparam name="TNode">Node type.</typeparam>
|
|
/// <typeparam name="TLink">Link type.</typeparam>
|
|
public class CompositionModel<TNode, TLink> : ICompositionModel
|
|
where TNode : ICompositionModelNode, new()
|
|
where TLink : ICompositionModelLink, new()
|
|
{
|
|
private const string _transactionName = "AddRemoveTransaction";
|
|
|
|
private readonly ICompositionModelBehavior<TNode, TLink> _behavior;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="CompositionModel{TNode,TLink}"/>.
|
|
/// </summary>
|
|
/// <param name="behavior"><see cref="ICompositionModelBehavior{TNode,TLink}"/></param>
|
|
public CompositionModel(ICompositionModelBehavior<TNode, TLink> behavior)
|
|
{
|
|
_behavior = behavior ?? throw new ArgumentNullException(nameof(behavior));
|
|
_behavior.Modifiable = true;
|
|
_behavior.Parent = this;
|
|
|
|
_behavior.BehaviorChanged += OnBehaviorChanged;
|
|
}
|
|
|
|
object ICompositionModel.Behavior => _behavior;
|
|
bool ICompositionModel.HasErrors => Elements.Any(s => s is null);
|
|
|
|
/// <inheritdoc/>
|
|
public bool Modifiable
|
|
{
|
|
get => _behavior.Modifiable;
|
|
set => _behavior.Modifiable = value;
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public IUndoManager UndoManager
|
|
{
|
|
get => _behavior.UndoManager;
|
|
set => _behavior.UndoManager = value;
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public bool IsUndoManagerSuspended
|
|
{
|
|
get => _behavior.IsUndoManagerSuspended;
|
|
set => _behavior.IsUndoManagerSuspended = value;
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public event Action ModelChanged;
|
|
|
|
/// <inheritdoc/>
|
|
public event Action<DiagramElement> ElementAdded;
|
|
|
|
/// <inheritdoc/>
|
|
public event Action<DiagramElement> ElementRemoved;
|
|
|
|
/// <summary>
|
|
/// Nodes.
|
|
/// </summary>
|
|
public IEnumerable<TNode> Nodes
|
|
{
|
|
get => _behavior.Nodes;
|
|
set => _behavior.Nodes = value;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Links.
|
|
/// </summary>
|
|
public IEnumerable<TLink> Links
|
|
{
|
|
get => _behavior.Links;
|
|
set => _behavior.Links = value;
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public IEnumerable<DiagramElement> Elements => Nodes.Select(e => e.Element);
|
|
|
|
DiagramElement ICompositionModel.FindElementByKey(string key)
|
|
=> _behavior.FindNodeByKey(key)?.Element;
|
|
|
|
string ICompositionModel.GetElementKey(DiagramElement element)
|
|
=> GetNode(element)?.Key;
|
|
|
|
private TNode GetNode(DiagramElement element)
|
|
=> Nodes.FirstOrDefault(e => e.Element == element);
|
|
|
|
private void OnBehaviorChanged((ModelChange change, object data, string propertyName, object oldValue, object oldParam, object newValue, object newParam) t)
|
|
{
|
|
//private bool _isReconnecting;
|
|
|
|
void Disconnect(TLink link)
|
|
{
|
|
if (link.IsReconnecting)
|
|
return;
|
|
|
|
var (from, to) = (link.GetFromSocket(_behavior), link.GetToSocket(_behavior));
|
|
from?.Disconnect(to);
|
|
to?.Disconnect(from);
|
|
|
|
link.IsConnected = false;
|
|
}
|
|
|
|
var changed = false;
|
|
|
|
switch (t.change)
|
|
{
|
|
case ModelChange.AddedNode:
|
|
OnElementAdded((TNode)t.data);
|
|
changed = true;
|
|
break;
|
|
|
|
case ModelChange.RemovedNode:
|
|
OnElementRemoved((TNode)t.data);
|
|
changed = true;
|
|
break;
|
|
|
|
case ModelChange.ChangedNodesSource:
|
|
{
|
|
var oldValues = (IEnumerable<TNode>)t.oldValue;
|
|
oldValues?.ForEach(e => OnElementRemoved(e));
|
|
|
|
var newValues = (IEnumerable<TNode>)t.newValue;
|
|
newValues?.ForEach(e => OnElementAdded(e));
|
|
|
|
changed = true;
|
|
break;
|
|
}
|
|
|
|
case ModelChange.AddedLink:
|
|
Connect((TLink)t.data);
|
|
changed = true;
|
|
break;
|
|
|
|
case ModelChange.RemovedLink:
|
|
Disconnect((TLink)t.data);
|
|
changed = true;
|
|
break;
|
|
|
|
case ModelChange.ChangedLinkToPort:
|
|
{
|
|
var newLink = (TLink)t.data;
|
|
|
|
var oldLink = newLink.TypedClone();
|
|
oldLink.To = (string)t.oldValue;
|
|
oldLink.ToPort = (string)t.oldParam;
|
|
|
|
Disconnect(oldLink);
|
|
Connect(newLink);
|
|
|
|
changed = true;
|
|
break;
|
|
}
|
|
|
|
case ModelChange.ChangedLinkFromPort:
|
|
{
|
|
var newLink = (TLink)t.data;
|
|
|
|
var oldLink = newLink.TypedClone();
|
|
oldLink.From = (string)t.oldValue;
|
|
oldLink.FromPort = (string)t.oldParam;
|
|
|
|
Disconnect(oldLink);
|
|
Connect(newLink);
|
|
|
|
changed = true;
|
|
break;
|
|
}
|
|
|
|
case ModelChange.ChangedLinksSource:
|
|
{
|
|
var oldValues = ((IEnumerable<TLink>)t.oldValue)?.ToArray();
|
|
oldValues?.ForEach(l => Disconnect(l));
|
|
|
|
var newValues = ((IEnumerable<TLink>)t.newValue)?.ToArray();
|
|
newValues?.ForEach(l => Connect(l));
|
|
|
|
changed = true;
|
|
break;
|
|
}
|
|
|
|
case ModelChange.FinishedRedo:
|
|
case ModelChange.FinishedUndo:
|
|
case ModelChange.InvalidateRelationships:
|
|
changed = true;
|
|
break;
|
|
|
|
case ModelChange.Property:
|
|
{
|
|
if (!t.propertyName.IsEmpty() && !t.propertyName.EqualsIgnoreCase(nameof(Modifiable)))
|
|
changed = true;
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (changed)
|
|
ModelChanged?.Invoke();
|
|
}
|
|
|
|
private bool Connect(TLink link, bool checkTypes = false)
|
|
{
|
|
if (link.IsReconnecting)
|
|
return true;
|
|
|
|
try
|
|
{
|
|
link.IsReconnecting = true;
|
|
link.IsConnected = true;
|
|
|
|
var (from, to) = (link.GetFromSocket(_behavior), link.GetToSocket(_behavior));
|
|
|
|
if (from == null || to == null || (checkTypes && !from.CanConnect(to)))
|
|
return false;
|
|
|
|
from.Connect(to);
|
|
to.Connect(from);
|
|
|
|
link.FromPort = from.Id;
|
|
link.ToPort = to.Id;
|
|
}
|
|
finally
|
|
{
|
|
link.IsReconnecting = false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
// A node read before the type of its element was known joins the model without an element.
|
|
// When the element arrives it is announced as if the node were added now, and its links are connected.
|
|
internal void AttachElement(TNode node)
|
|
{
|
|
OnElementAdded(node);
|
|
ConnectLinks(node);
|
|
|
|
ModelChanged?.Invoke();
|
|
}
|
|
|
|
// Connects the links of the node whose sockets are both there by now. A link stays unconnected while
|
|
// the element at its other end is not loaded, or while a composition has not published the socket yet.
|
|
internal void ConnectLinks(TNode node)
|
|
{
|
|
foreach (var link in _behavior.GetLinksForNode(node).ToArray())
|
|
{
|
|
var (from, to) = (link.GetFromSocket(_behavior), link.GetToSocket(_behavior));
|
|
|
|
if (from is null || to is null || from.IsConnectedTo(to))
|
|
continue;
|
|
|
|
Connect(link);
|
|
}
|
|
}
|
|
|
|
private void OnElementAdded(TNode baseElement)
|
|
{
|
|
if (baseElement.Element == null)
|
|
return;
|
|
|
|
var element = baseElement.Element;
|
|
|
|
element.StartedUndoableOperation += OnStartedUndoableOperation;
|
|
element.CommittedUndoableOperation += OnCommittedUndoableOperation;
|
|
element.SocketAdded += OnElementSocketAdded;
|
|
element.SocketRemoved += OnElementSocketRemoved;
|
|
element.SocketChanged += OnElementSocketChanged;
|
|
|
|
ElementAdded?.Invoke(element);
|
|
}
|
|
|
|
private void OnElementRemoved(TNode baseElement)
|
|
{
|
|
if (baseElement.Element == null)
|
|
return;
|
|
|
|
var element = baseElement.Element;
|
|
|
|
element.StartedUndoableOperation -= OnStartedUndoableOperation;
|
|
element.CommittedUndoableOperation -= OnCommittedUndoableOperation;
|
|
element.SocketAdded -= OnElementSocketAdded;
|
|
element.SocketRemoved -= OnElementSocketRemoved;
|
|
element.SocketChanged -= OnElementSocketChanged;
|
|
|
|
ElementRemoved?.Invoke(element);
|
|
}
|
|
|
|
private void OnElementSocketAdded(DiagramSocket socket)
|
|
{
|
|
var node = Nodes.FirstOrDefault(n => n.Element == socket.Parent);
|
|
|
|
if (node == null)
|
|
return;
|
|
|
|
foreach (var link in GetLinks(node, socket).ToArray())
|
|
{
|
|
// a link to a node whose element is not loaded yet waits for it
|
|
if (!IsConnected(link) && !IsWaitingForElement(link))
|
|
_behavior.RemoveLink(link);
|
|
}
|
|
|
|
_behavior.RaiseSocketAdded(node);
|
|
}
|
|
|
|
private void OnElementSocketRemoved(DiagramSocket socket)
|
|
{
|
|
RemoveSocketLinks(socket, false);
|
|
}
|
|
|
|
private void OnElementSocketChanged(DiagramSocket socket)
|
|
{
|
|
RemoveSocketLinks(socket, true);
|
|
}
|
|
|
|
private void RemoveSocketLinks(DiagramSocket socket, bool checkCanConnect)
|
|
{
|
|
var node = Nodes.FirstOrDefault(n => n.Element == socket.Parent);
|
|
|
|
if (node == null)
|
|
return;
|
|
|
|
GetLinks(node, socket)
|
|
.Where(l => !checkCanConnect || !IsConnected(l) || !CanConnect(l))
|
|
.ToArray()
|
|
.ForEach(_behavior.RemoveLink);
|
|
|
|
_behavior.RaiseLinksRemoved(node);
|
|
}
|
|
|
|
private bool CanConnect(ICompositionModelLink link)
|
|
{
|
|
var (from, to) = (link.GetFromSocket(_behavior), link.GetToSocket(_behavior));
|
|
return from != null && to != null && from.CanConnect(to);
|
|
}
|
|
|
|
private bool IsConnected(ICompositionModelLink link)
|
|
=> link.GetFromSocket(_behavior) != null && link.GetToSocket(_behavior) != null;
|
|
|
|
private bool IsWaitingForElement(ICompositionModelLink link)
|
|
=> _behavior.FindNodeByKey(link.From) is { Element: null } || _behavior.FindNodeByKey(link.To) is { Element: null };
|
|
|
|
private bool HasUndoManager => UndoManager is not null;
|
|
|
|
private void OnStartedUndoableOperation()
|
|
{
|
|
if (HasUndoManager)
|
|
_behavior.StartTransaction(DiagramConstants.ElementDataName);
|
|
}
|
|
|
|
private void OnCommittedUndoableOperation(DiagramElement element, IUndoableEdit op)
|
|
{
|
|
if (!HasUndoManager)
|
|
return;
|
|
|
|
var node = Nodes.FirstOrDefault(n => n.Element == element);
|
|
|
|
if (node != null)
|
|
{
|
|
_behavior.RaiseCommited(DiagramConstants.ElementDataName, node, op);
|
|
}
|
|
|
|
_behavior.CommitTransaction(DiagramConstants.ElementDataName);
|
|
}
|
|
|
|
private IEnumerable<TLink> GetLinks(TNode node, DiagramSocket socket)
|
|
{
|
|
var links = _behavior.GetLinksForNode(node)
|
|
.Where(l => socket.IsInput ? l.To == node.Key && l.ToPort.EqualsIgnoreCase(socket.Id) : l.From == node.Key && l.FromPort.EqualsIgnoreCase(socket.Id))
|
|
.ToArray();
|
|
|
|
return links;
|
|
}
|
|
|
|
private IEnumerable<TLink> GetLinks(DiagramElement element, DiagramSocket socket) => GetLinks(GetNode(element), socket);
|
|
|
|
IEnumerable<DiagramSocket> ICompositionModel.GetConnectedSocketsFor(DiagramElement element, DiagramSocket socket)
|
|
{
|
|
var links = GetLinks(element, socket);
|
|
|
|
return socket.IsInput ? links.Select(l => l.GetFromSocket(_behavior)) : links.Select(l => l.GetToSocket(_behavior));
|
|
}
|
|
|
|
void ICompositionModel.AddElement(DiagramElement element, PointF location)
|
|
{
|
|
if (element == null)
|
|
throw new ArgumentNullException(nameof(element));
|
|
|
|
ExecuteTransaction(_transactionName, m => _behavior.AddNode(new() { Element = element, Location = location }));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Add node.
|
|
/// </summary>
|
|
/// <param name="node"><typeparamref name="TNode"/></param>
|
|
public void AddNode(TNode node) => _behavior.AddNode(node);
|
|
|
|
/// <summary>
|
|
/// Remove node.
|
|
/// </summary>
|
|
/// <param name="node"><typeparamref name="TNode"/></param>
|
|
public void RemoveNode(TNode node) => _behavior.RemoveNode(node);
|
|
|
|
/// <summary>
|
|
/// Add link.
|
|
/// </summary>
|
|
/// <param name="from">From node.</param>
|
|
/// <param name="fromPort"><see cref="ICompositionModelLink.FromPort"/></param>
|
|
/// <param name="to">To node.</param>
|
|
/// <param name="toPort"><see cref="ICompositionModelLink.ToPort"/></param>
|
|
public void AddLink(TNode from, string fromPort, TNode to, string toPort)
|
|
=> _behavior.AddLink(from, fromPort, to, toPort);
|
|
|
|
/// <summary>
|
|
/// Remove link.
|
|
/// </summary>
|
|
/// <param name="from">From node.</param>
|
|
/// <param name="fromPort"><see cref="ICompositionModelLink.FromPort"/></param>
|
|
/// <param name="to">To node.</param>
|
|
/// <param name="toPort"><see cref="ICompositionModelLink.ToPort"/></param>
|
|
public void RemoveLink(TNode from, string fromPort, TNode to, string toPort)
|
|
=> _behavior.RemoveLink(from, fromPort, to, toPort);
|
|
|
|
//public void RemoveElement(DiagramElement element)
|
|
//{
|
|
// if (element == null)
|
|
// throw new ArgumentNullException(nameof(element));
|
|
|
|
// ExecuteTransaction(_transactionName, m =>
|
|
// {
|
|
// var tmp = GetNode(element);
|
|
|
|
// if (tmp != null)
|
|
// _behavior.RemoveNode(tmp);
|
|
// });
|
|
//}
|
|
|
|
IEnumerable<(string nodeKey, DiagramSocket socket)> ICompositionModel.GetDisconnectedSockets()
|
|
{
|
|
var sockets = new List<(string nodeKey, DiagramSocket socket)>();
|
|
|
|
foreach (var n in Nodes)
|
|
{
|
|
var node = n;
|
|
|
|
if (node.Element == null || !node.Element.ShowSockets)
|
|
continue;
|
|
|
|
var ports = _behavior.GetLinksForNode(node)
|
|
.Select(l => l.From == node.Key ? l.FromPort : l.ToPort)
|
|
.ToArray();
|
|
|
|
node.Element
|
|
.GetAllSockets()
|
|
.Where(s => ports.All(p => !p.EqualsIgnoreCase(s.Id)))
|
|
.Select(s =>
|
|
{
|
|
var socket = new DiagramSocket(s.Direction, s.Id)
|
|
{
|
|
Name = $"{s.Name} - {node.Element.Name}",
|
|
Type = s.Type,
|
|
LinkableMaximum = s.LinkableMaximum,
|
|
};
|
|
return (node.Key, socket);
|
|
})
|
|
.ForEach(sockets.Add);
|
|
}
|
|
|
|
return sockets;
|
|
}
|
|
|
|
//private void Replace(IEnumerable<DiagramElement> elements, DiagramElement element)
|
|
//{
|
|
// ExecuteTransaction(_transactionName, m =>
|
|
// {
|
|
// _behavior.AddNode(new() { Element = element });
|
|
|
|
// var elementNode = Nodes.First(e => e.Element == element);
|
|
// var nodes = Nodes.Where(e => elements.Any(t => t == e.Element)).ToArray();
|
|
|
|
// var nodeLinks = nodes
|
|
// .Select(node => new
|
|
// {
|
|
// Node = node,
|
|
// InputLinks = _behavior.GetLinksForNode(node).Where(l => l.To == node.Key && nodes.All(n => n.Key != l.From)).ToArray(),
|
|
// OutputLinks = _behavior.GetLinksForNode(node).Where(l => l.From == node.Key && nodes.All(n => n.Key != l.To)).ToArray()
|
|
// })
|
|
// .ToArray();
|
|
|
|
// nodes.ForEach(_behavior.RemoveNode);
|
|
|
|
// var allNodes = Nodes.ToDictionary(s => s.Key);
|
|
|
|
// foreach (var nodeLink in nodeLinks)
|
|
// {
|
|
// nodeLink.InputLinks.ForEach(l => _behavior.AddLink(allNodes[l.From], l.FromPort, elementNode, l.ToPort));
|
|
// nodeLink.OutputLinks.ForEach(l => _behavior.AddLink(elementNode, l.FromPort, allNodes[l.To], l.ToPort));
|
|
// }
|
|
// });
|
|
//}
|
|
|
|
/// <summary>
|
|
/// Execute the specified action in transaction scope.
|
|
/// </summary>
|
|
/// <param name="name">Transaction name.</param>
|
|
/// <param name="action">Action.</param>
|
|
public void ExecuteTransaction(string name, Action<CompositionModel<TNode, TLink>> action)
|
|
{
|
|
if (name.IsEmpty())
|
|
throw new ArgumentNullException(nameof(name));
|
|
|
|
if (action is null)
|
|
throw new ArgumentNullException(nameof(action));
|
|
|
|
_behavior.StartTransaction(name);
|
|
|
|
try
|
|
{
|
|
action(this);
|
|
_behavior.CommitTransaction(name);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
_behavior.RollbackTransaction();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async ValueTask<ICompositionModel> CloneAsync(CancellationToken cancellationToken)
|
|
{
|
|
var model = new CompositionModel<TNode, TLink>((ICompositionModelBehavior<TNode, TLink>)_behavior.Clone());
|
|
|
|
var nodes = new List<TNode>();
|
|
|
|
foreach (var node in Nodes)
|
|
nodes.Add((TNode)await node.CloneAsync(cancellationToken));
|
|
|
|
model.ExecuteTransaction("Clone", m =>
|
|
{
|
|
m.Nodes = new ObservableCollection<TNode>(nodes);
|
|
m.Links = new ObservableCollection<TLink>(Links.Select(l => l.TypedClone()));
|
|
});
|
|
|
|
return model;
|
|
}
|
|
}
|