-
Notifications
You must be signed in to change notification settings - Fork 636
/
Copy pathNodeModel.cs
2595 lines (2271 loc) · 92.3 KB
/
NodeModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml;
using Dynamo.Configuration;
using Dynamo.Engine;
using Dynamo.Engine.CodeGeneration;
using Dynamo.Graph.Connectors;
using Dynamo.Graph.Nodes.CustomNodes;
using Dynamo.Graph.Workspaces;
using Dynamo.Migration;
using Dynamo.Scheduler;
using Dynamo.Selection;
using Dynamo.Utilities;
using Dynamo.Visualization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using ProtoCore.AST.AssociativeAST;
using ProtoCore.DSASM;
using ProtoCore.Mirror;
using String = System.String;
using StringNode = ProtoCore.AST.AssociativeAST.StringNode;
namespace Dynamo.Graph.Nodes
{
public abstract class NodeModel : ModelBase, IRenderPackageSource<NodeModel>, IDisposable
{
#region private members
private LacingStrategy argumentLacing = LacingStrategy.Auto;
private bool displayLabels;
private bool isVisible;
private bool isSetAsInput = false;
private bool isSetAsOutput = false;
private bool canUpdatePeriodically;
private string name;
private ElementState state;
private string toolTipText = "";
private string description;
private string persistentWarning = "";
private bool areInputPortsRegistered;
private bool areOutputPortsRegistered;
///A flag indicating whether the node has been explicitly frozen.
internal bool isFrozenExplicitly;
/// <summary>
/// The cached value of this node. The cachedValue object is protected by the cachedValueMutex
/// as it may be accessed from multiple threads concurrently.
///
/// However, generally access to the cachedValue property should be protected by usage
/// of the Scheduler.
/// </summary>
private MirrorData cachedValue;
private readonly object cachedValueMutex = new object();
// Input and output port related data members.
private ObservableCollection<PortModel> inPorts = new ObservableCollection<PortModel>();
private ObservableCollection<PortModel> outPorts = new ObservableCollection<PortModel>();
#endregion
#region public members
private readonly Dictionary<int, Tuple<int, NodeModel>> inputNodes;
private readonly Dictionary<int, HashSet<Tuple<int, NodeModel>>> outputNodes;
/// <summary>
/// The unique name that was created the node by
/// </summary>
[JsonIgnore]
public virtual string CreationName
{
get
{
return getNameFromNodeNameAttribute();
}
}
/// <summary>
/// This property queries all the Upstream Nodes for a given node, ONLY after the graph is loaded.
/// This property is computed in ComputeUpstreamOnDownstreamNodes function
/// </summary>
internal HashSet<NodeModel> UpstreamCache = new HashSet<NodeModel>();
/// <summary>
/// The NodeType property provides a name which maps to the
/// server type for the node. This property should only be
/// used for serialization.
/// </summary>
public virtual string NodeType
{
get
{
return "ExtensionNode";
}
}
#endregion
#region events
//TODO(Steve): Model should not have to worry about UI thread synchronization -- MAGN-5709
/// <summary>
/// Called by nodes for behavior that they want to dispatch on the UI thread
/// Triggers event to be received by the UI. If no UI exists, behavior will not be executed.
/// </summary>
/// <param name="a"></param>
public void DispatchOnUIThread(Action a)
{
OnDispatchedToUI(this, new UIDispatcherEventArgs(a));
}
private void OnDispatchedToUI(object sender, UIDispatcherEventArgs e)
{
if (DispatchedToUI != null)
DispatchedToUI(sender, e);
}
internal event DispatchedToUIThreadHandler DispatchedToUI;
/// <summary>
/// Event triggered when a port is connected.
/// </summary>
public event Action<PortModel, ConnectorModel> PortConnected;
/// <summary>
/// Event triggered when a port is disconnected.
/// </summary>
public event Action<PortModel> PortDisconnected;
#endregion
#region public properties
/// <summary>
/// Id for this node, must be unique within the graph.
/// </summary>
[JsonProperty("Id")]
[JsonConverter(typeof(IdToGuidConverter))]
public override Guid GUID
{
get
{
return base.GUID;
}
set
{
base.GUID = value;
}
}
/// <summary>
/// All of the connectors entering and exiting the NodeModel.
/// </summary>
[JsonIgnore]
public IEnumerable<ConnectorModel> AllConnectors
{
get
{
return inPorts.Concat(outPorts).SelectMany(port => port.Connectors);
}
}
/// <summary>
/// Returns whether this node represents a built-in or custom function.
/// </summary>
[JsonIgnore]
public bool IsCustomFunction
{
get { return this is Function; }
}
/// <summary>
/// Returns whether the node is to be included in visualizations.
/// </summary>
[JsonIgnore]
public bool IsVisible
{
get
{
return isVisible;
}
private set // Private setter, see "ArgumentLacing" for details.
{
if (isVisible != value)
{
isVisible = value;
RaisePropertyChanged("IsVisible");
}
}
}
/// <summary>
/// Input nodes are used in Customizer and Presets. Input nodes can be numbers, number sliders,
/// strings, bool, code blocks and custom nodes, which don't specify path. This property
/// is true for nodes that are potential inputs for Customizers and Presets.
/// </summary>
[JsonIgnore]
public virtual bool IsInputNode
{
get
{
return !inPorts.Any() && !IsCustomFunction;
}
}
/// <summary>
/// This property is user-controllable via a checkbox and is set to true when a user wishes to include
/// this node in a Customizer as an interactive control.
/// </summary>
[JsonIgnore]
public bool IsSetAsInput
{
get
{
if (!IsInputNode)
return false;
return isSetAsInput;
}
set
{
if (isSetAsInput != value)
{
isSetAsInput = value;
RaisePropertyChanged(nameof(IsSetAsInput));
}
}
}
/// <summary>
/// Output nodes are used by applications that consume graphs outside of Dynamo such as Optioneering, Optimization,
/// and Dynamo Player. Output nodes can be any node that returns a single output or a dictionary. Code block nodes and
/// Custom nodes are specifically excluded at this time even though they can return a single output for sake of clarity.
/// </summary>
[JsonIgnore]
public virtual bool IsOutputNode
{
get
{
return !IsCustomFunction;
}
}
/// <summary>
/// This property is user-controllable via a checkbox and is set to true when a user wishes to include
/// this node in the OutputData block of the Dyn file.
/// </summary>
[JsonIgnore]
public bool IsSetAsOutput
{
get
{
if (!IsOutputNode)
return false;
return isSetAsOutput;
}
set
{
if (isSetAsOutput != value)
{
isSetAsOutput = value;
RaisePropertyChanged(nameof(IsSetAsOutput));
}
}
}
/// <summary>
/// The Node's state, which determines the coloring of the Node in the canvas.
/// </summary>
[JsonIgnore]
public ElementState State
{
get { return state; }
set
{
if (value != ElementState.Error && value != ElementState.AstBuildBroken)
ClearTooltipText();
// Check before settings and raising
// a notification.
if (state == value) return;
state = value;
RaisePropertyChanged("State");
}
}
/// <summary>
/// If the state of node is Error or AstBuildBroken
/// </summary>
[JsonIgnore]
public bool IsInErrorState
{
get
{
return state == ElementState.AstBuildBroken || state == ElementState.Error;
}
}
/// <summary>
/// Indicates if node preview is pinned
/// </summary>
[JsonIgnore]
public bool PreviewPinned { get; internal set; }
/// <summary>
/// Text that is displayed as this Node's tooltip.
/// </summary>
[JsonIgnore]
public string ToolTipText
{
get { return toolTipText; }
set
{
toolTipText = value;
RaisePropertyChanged("ToolTipText");
}
}
/// <summary>
/// The name that is displayed in the UI for this NodeModel.
/// </summary>
[JsonIgnore()]
public string Name
{
get { return name; }
set
{
name = value;
RaisePropertyChanged("Name");
}
}
/// <summary>
/// Collection of PortModels representing all Input ports.
/// </summary>
[JsonProperty("Inputs")]
public ObservableCollection<PortModel> InPorts
{
get { return inPorts; }
set
{
inPorts = value;
RaisePropertyChanged("InPorts");
}
}
/// <summary>
/// Collection of PortModels representing all Output ports.
/// </summary>
[JsonProperty("Outputs")]
public ObservableCollection<PortModel> OutPorts
{
get { return outPorts; }
set
{
outPorts = value;
RaisePropertyChanged("OutPorts");
}
}
[JsonIgnore]
public IDictionary<int, Tuple<int, NodeModel>> InputNodes
{
get { return inputNodes; }
}
[JsonIgnore]
public IDictionary<int, HashSet<Tuple<int, NodeModel>>> OutputNodes
{
get { return outputNodes; }
}
/// <summary>
/// Control how arguments lists of various sizes are laced.
/// </summary>
[JsonProperty("Replication"), JsonConverter(typeof(StringEnumConverter))]
public LacingStrategy ArgumentLacing
{
get
{
return argumentLacing;
}
// The property setter is marked as private/protected because it
// should not be set from an external component directly. The ability
// to directly set the property value causes a NodeModel to be altered
// without careful consideration of undo/redo recording. If changing
// this property value should be undo-able, then the caller should use
// "DynamoModel.UpdateModelValueCommand" to set the property value.
// The command ensures changes to the NodeModel is recorded for undo.
//
// In some cases being able to set the property value directly is
// desirable, for example, some unit test scenarios require the given
// NodeModel property to be of certain value. In such cases the
// easiest workaround is to use "NodeModel.UpdateValue" method:
//
// someNode.UpdateValue("ArgumentLacing", "CrossProduct");
//
protected set
{
if (argumentLacing != value)
{
argumentLacing = value;
RaisePropertyChanged("ArgumentLacing");
// Mark node for update
OnNodeModified();
}
}
}
private string ShortenName
{
get
{
Type type = GetType();
object[] attribs = type.GetCustomAttributes(typeof(NodeNameAttribute), false);
if (!string.IsNullOrEmpty(CreationName))
{
// Obtain the node's default name from its creation name.
// e.g. For creation name DSCore.Math.Max@double,double - the name "Max" is obtained and appended to the final link.
int indexAfter = (CreationName.LastIndexOf('@') == -1) ? CreationName.Length : CreationName.LastIndexOf('@');
string s = CreationName.Substring(0, indexAfter);
int indexBefore = s.LastIndexOf(Configurations.CategoryDelimiterString);
int firstChar = (indexBefore == -1) ? 0 : indexBefore + 1;
return s.Substring(firstChar, s.Length - CreationName.Substring(0, firstChar).Length);
}
if (!type.IsAbstract && (attribs.Length > 0))
{
var attrib = attribs[0] as NodeNameAttribute;
if (attrib != null)
{
string name = attrib.Name;
if (!string.IsNullOrEmpty(name)) return name;
}
}
return "";
}
}
/// <summary>
/// Category property
/// </summary>
/// <value>
/// If the node has a category, return it. Other wise return empty string.
/// </value>
[JsonIgnore]
public string Category
{
get
{
category = category ?? GetCategoryStringFromAttributes();
return category;
}
set
{
category = value;
RaisePropertyChanged("Category");
}
}
private string category;
private string GetCategoryStringFromAttributes()
{
Type type = GetType();
object[] attribs = type.GetCustomAttributes(typeof(NodeCategoryAttribute), false);
if (!type.IsAbstract && (attribs.Length > 0) && (attribs[0] is NodeCategoryAttribute))
{
string category = ((NodeCategoryAttribute)attribs[0]).ElementCategory;
if (category != null) return category;
}
if (type.Namespace != "Dynamo.Graph.Nodes" || type.IsAbstract || attribs.Length <= 0
|| !type.IsSubclassOf(typeof(NodeModel)))
return "";
var elCatAttrib = attribs[0] as NodeCategoryAttribute;
return elCatAttrib.ElementCategory;
}
/// <summary>
/// Dictionary Link property
/// </summary>
/// <value>
/// If the node has a name and a category, convert them into a link going to the node's help page on
/// Dynamo Dictionary, and return the link.
/// Otherwise, return the Dynamo Dictionary home page.
/// </value>
[JsonIgnore]
public string DictionaryLink
{
get
{
dictionaryLink = dictionaryLink ?? Configurations.DynamoDictionary;
return dictionaryLink;
}
set
{
dictionaryLink = value;
}
}
private string dictionaryLink;
internal string ConstructDictionaryLinkFromLibrary(LibraryServices libraryServices)
{
string finalLink = Configurations.DynamoDictionary + "#/";
if (IsCustomFunction)
{
return ""; // If it is not a core or Revit function, do not display the dictionary link
}
if (category == null || category == "")
{
return Configurations.DynamoDictionary; // if there is no category, return the link to home page
}
int i = category.LastIndexOf(Configurations.CategoryDelimiterString);
switch (category.Substring(i + 1))
{
case Configurations.CategoryGroupAction:
finalLink += ObtainURL(category.Substring(0, i));
finalLink += "Action/";
break;
case Configurations.CategoryGroupCreate:
finalLink += ObtainURL(category.Substring(0, i));
finalLink += "Create/";
break;
case Configurations.CategoryGroupQuery:
finalLink += ObtainURL(category.Substring(0, i));
finalLink += "Query/";
break;
default:
finalLink += ObtainURL(category);
finalLink += "Action/";
break;
}
finalLink += this.ShortenName;
// Check if the method has overloads
IEnumerable<FunctionDescriptor> descriptors = libraryServices.GetAllFunctionDescriptors(CreationName.Split('@')[0]);
if (descriptors != null && descriptors.Skip(1).Any())
{
// If there are overloads
string parameters = "(";
IEnumerable<Tuple<string, string>> inputParameters = null;
foreach (FunctionDescriptor fd in descriptors)
{
if (fd.MangledName == CreationName) // Find the function descriptor among the overloads and obtain their parameter names
{
inputParameters = fd.InputParameters;
break;
}
}
// Convert the parameters into a valid Dictionary URL format, e.g. (x_double-y_double-z_double)
if (inputParameters != null)
{
int parameterCount = inputParameters.Count();
for (int k = 0; k < parameterCount - 1; k++)
{
parameters += inputParameters.ElementAt(k).Item1 + "_" + inputParameters.ElementAt(k).Item2 + "-";
}
// Append the last parameter without the dash and with the close bracket
var lastInputParam = inputParameters.ElementAt(parameterCount - 1);
parameters += lastInputParam.Item1 + "_" + lastInputParam.Item2 + ")";
finalLink += parameters;
}
}
return finalLink;
}
/// <summary>
/// This method converts the character '.' in the node's category to '/', and append
/// another '/' at the end, to be used as a URL.
/// e.g. Core.Input.Action is converted to Core/Input/Action/
/// </summary>
private string ObtainURL(string category)
{
string result = "";
for (int i = 0; i < category.Length; i++)
{
if (category[i] == '.')
{
result += '/';
}
else
{
result += category[i];
}
}
result += '/';
return result;
}
/// <summary>
/// The value of this node after the most recent computation
///
/// As this property could be modified by the virtual machine, it's dangerous
/// to access this value without using the active Scheduler. Use the Scheduler to
/// remove the possibility of race conditions.
/// </summary>
[JsonIgnore]
public MirrorData CachedValue
{
get
{
lock (cachedValueMutex)
{
return cachedValue;
}
}
private set
{
lock (cachedValueMutex)
{
cachedValue = value;
}
RaisePropertyChanged("CachedValue");
}
}
/// <summary>
/// This flag is used to determine if a node was involved in a recent execution.
/// The primary purpose of this flag is to determine if the node's render packages
/// should be returned to client browser when it requests for them. This is mainly
/// to avoid returning redundant data that has not changed during an execution.
/// </summary>
internal bool WasInvolvedInExecution { get; set; }
/// <summary>
/// This flag indicates if render packages of a NodeModel has been updated
/// since the last execution. UpdateRenderPackageAsyncTask will always be
/// generated for a NodeModel that took part in the evaluation, if this flag
/// is false.
/// </summary>
internal bool WasRenderPackageUpdatedAfterExecution { get; set; }
/// <summary>
/// Search tags for this Node.
/// </summary>
[JsonIgnore]
public List<string> Tags
{
get
{
return
GetType()
.GetCustomAttributes(typeof(NodeSearchTagsAttribute), true)
.Cast<NodeSearchTagsAttribute>()
.SelectMany(x => x.Tags)
.ToList();
}
}
/// <summary>
/// Description of this Node.
/// </summary>
public string Description
{
get
{
description = description ?? GetDescriptionStringFromAttributes();
return description;
}
set
{
description = value;
RaisePropertyChanged("Description");
}
}
[JsonIgnore]
public bool CanUpdatePeriodically
{
get { return canUpdatePeriodically; }
set
{
canUpdatePeriodically = value;
RaisePropertyChanged("CanUpdatePeriodically");
}
}
/// <summary>
/// ProtoAST Identifier for result of the node before any output unpacking has taken place.
/// If there is only one output for the node, this is equivalent to GetAstIdentifierForOutputIndex(0).
/// </summary>
[JsonIgnore]
public IdentifierNode AstIdentifierForPreview
{
get { return AstFactory.BuildIdentifier(AstIdentifierBase); }
}
/// <summary>
/// If this node is allowed to be converted to AST node in nodes to code conversion.
/// </summary>
[JsonIgnore]
public virtual bool IsConvertible
{
get
{
return false;
}
}
/// <summary>
/// Return a variable whose value will be displayed in preview window.
/// Derived nodes may overwrite this function to display default value
/// of this node. E.g., code block node may want to display the value
/// of the left hand side variable of last statement.
/// </summary>
[JsonIgnore]
public virtual string AstIdentifierBase
{
get
{
return AstBuilder.StringConstants.VarPrefix + AstIdentifierGuid;
}
}
/// <summary>
/// A unique ID that will be appended to all identifiers of this node.
/// </summary>
[JsonIgnore]
public string AstIdentifierGuid
{
get
{
return GUID.ToString("N");
}
}
/// <summary>
/// Enable or disable label display. Default is false.
/// </summary>
[JsonIgnore]
public bool DisplayLabels
{
get { return displayLabels; }
set
{
if (displayLabels == value)
return;
displayLabels = value;
RaisePropertyChanged("DisplayLabels");
}
}
/// <summary>
/// Is this node being applied partially, resulting in a partial function?
/// </summary>
[JsonIgnore]
public bool IsPartiallyApplied //TODO(Steve): Move to Graph level -- MAGN-5710
{
get { return !inPorts.All(p => p.IsConnected); }
}
/// <summary>
/// Returns the description from type information
/// </summary>
/// <returns>The value or "No description provided"</returns>
public string GetDescriptionStringFromAttributes()
{
Type t = GetType();
object[] rtAttribs = t.GetCustomAttributes(typeof(NodeDescriptionAttribute), true);
return rtAttribs.Length > 0
? ((NodeDescriptionAttribute)rtAttribs[0]).ElementDescription
: Properties.Resources.NoDescriptionAvailable;
}
/// <summary>
/// Fetches the ProtoAST Identifier for a given output port.
/// </summary>
/// <param name="outputIndex">Index of the output port.</param>
/// <returns>Identifier corresponding to the given output port.</returns>
public virtual IdentifierNode GetAstIdentifierForOutputIndex(int outputIndex)
{
if (outputIndex < 0 || outputIndex > OutPorts.Count)
throw new ArgumentOutOfRangeException("outputIndex", @"Index must correspond to an OutPortData index.");
if (OutPorts.Count <= 1)
return AstIdentifierForPreview;
else
{
string id = AstIdentifierBase + "_out" + outputIndex;
return AstFactory.BuildIdentifier(id);
}
}
/// <summary>
/// The possible type of output at specified port. This
/// type information is not necessary to be accurate.
/// </summary>
/// <returns></returns>
public virtual ProtoCore.Type GetTypeHintForOutput(int index)
{
return ProtoCore.TypeSystem.BuildPrimitiveTypeObject(ProtoCore.PrimitiveType.Var);
}
/// <summary>
/// A flag indicating whether the node is frozen.
/// When a node is frozen, the node, and all nodes downstream will not participate in execution.
/// This will return true if any upstream node is frozen or if the node was explicitly frozen.
/// </summary>
/// <value>
/// <c>true</c> if this node is frozen; otherwise, <c>false</c>.
/// </value>
[JsonIgnore]
public bool IsFrozen
{
get
{
return IsAnyUpstreamFrozen() || isFrozenExplicitly;
}
set
{
bool oldValue = isFrozenExplicitly;
isFrozenExplicitly = value;
//If the node is Unfreezed then Mark all the downstream nodes as
// modified. This is essential recompiling the AST.
if (!value)
{
if (oldValue)
{
MarkDownStreamNodesAsModified(this);
OnNodeModified();
RaisePropertyChanged("IsFrozen");
}
}
//If the node is frozen, then do not execute the graph immediately.
// delete the node and its downstream nodes from AST.
else
{
ComputeUpstreamOnDownstreamNodes();
OnUpdateASTCollection();
}
}
}
/// <summary>
/// The default behavior for ModelBase objects is to not serialize the X and Y
/// properties. This overload allows the serialization of the X property
/// for NodeModel.
/// </summary>
/// <returns>True.</returns>
public override bool ShouldSerializeX()
{
return false;
}
/// <summary>
/// The default behavior for ModelBase objects is to not serialize the X and Y
/// properties. This overload allows the serialization of the Y property
/// for NodeModel.
/// </summary>
/// <returns>True</returns>
public override bool ShouldSerializeY()
{
return false;
}
[JsonIgnore]
public virtual NodeInputData InputData
{
get { return null; }
}
[JsonIgnore]
public virtual NodeOutputData OutputData
{
get
{
// Determine if the output type can be determined at this time
// Current enum supports String, Integer, Float, Boolean, and unknown
// When CachedValue is null, type is set to unknown
// When Concrete type is dictionary or other type not expressed in enum, type is set to unknown
object returnObj = CachedValue?.Data?? new object();
var returnType = NodeOutputData.getNodeOutputTypeFromType(returnObj.GetType());
var returnValue = String.Empty;
// IntialValue is returned when the Type enum does not equal unknown
if(returnType != NodeOutputTypes.unknownOutput)
{
var formattableReturnObj = returnObj as IFormattable;
returnValue = formattableReturnObj != null ? formattableReturnObj.ToString(null, CultureInfo.InvariantCulture) : returnObj.ToString();
}
return new NodeOutputData()
{
Id = this.GUID,
Name = this.Name,
Type = returnType,
Description = this.Description,
InitialValue = returnValue
};
}
}
#endregion
#region freeze execution
/// <summary>
/// Determines whether any of the upstream node is frozen.
/// </summary>
/// <returns></returns>
internal bool IsAnyUpstreamFrozen()
{
return UpstreamCache.Any(x => x.isFrozenExplicitly);
}
/// <summary>
/// For a given node, this function computes all the upstream nodes
/// by gathering the cached upstream nodes on this node's immediate parents.
/// </summary>
internal void ComputeUpstreamCache()
{
this.UpstreamCache = new HashSet<NodeModel>();
var inpNodes = this.InputNodes.Values;
foreach (var inputnode in inpNodes.Where(x => x != null))
{
this.UpstreamCache.Add(inputnode.Item2);
foreach (var upstreamNode in inputnode.Item2.UpstreamCache)
{
this.UpstreamCache.Add(upstreamNode);
}
}
}
/// <summary>
/// For a given node, this function computes all the upstream nodes
/// by gathering the cached upstream nodes on this node's immediate parents.
/// If a node has any downstream nodes, then for all those downstream nodes, upstream
/// nodes will be computed. Essentially this method propogates the UpstreamCache down.
/// Also this function gets called only after the workspace is added.
/// </summary>
internal void ComputeUpstreamOnDownstreamNodes()
{
//first compute upstream nodes for this node
ComputeUpstreamCache();
//then for downstream nodes
//gather downstream nodes and bail if we see an already visited node
HashSet<NodeModel> downStreamNodes = new HashSet<NodeModel>();
this.GetDownstreamNodes(this, downStreamNodes);
foreach (var downstreamNode in AstBuilder.TopologicalSort(downStreamNodes))
{
downstreamNode.UpstreamCache = new HashSet<NodeModel>();
var currentinpNodes = downstreamNode.InputNodes.Values;
foreach (var inputnode in currentinpNodes.Where(x => x != null))
{
downstreamNode.UpstreamCache.Add(inputnode.Item2);
foreach (var upstreamNode in inputnode.Item2.UpstreamCache)
{
downstreamNode.UpstreamCache.Add(upstreamNode);
}
}
}
RaisePropertyChanged("IsFrozen");
}
private void MarkDownStreamNodesAsModified(NodeModel node)
{
HashSet<NodeModel> gathered = new HashSet<NodeModel>();
GetDownstreamNodes(node, gathered);
foreach (var iNode in gathered)
{
iNode.executionHint = ExecutionHints.Modified;
}
}
/// <summary>
/// Returns the downstream nodes for the given node.
/// </summary>
/// <param name="node">The node.</param>
/// <param name="gathered">The gathered.</param>
internal void GetDownstreamNodes(NodeModel node, HashSet<NodeModel> gathered)
{
if (gathered.Contains(node)) // Considered this node before, bail.pu