-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathNode.java
More file actions
1754 lines (1569 loc) · 59.6 KB
/
Node.java
File metadata and controls
1754 lines (1569 loc) · 59.6 KB
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
/*
* This file is part of NodeBox.
*
* Copyright (C) 2008 Frederik De Bleser (frederik@pandora.be)
*
* NodeBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NodeBox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NodeBox. If not, see <http://www.gnu.org/licenses/>.
*/
package nodebox.node;
import nodebox.client.NodeBoxDocument;
import nodebox.graphics.Color;
import nodebox.graphics.Point;
import nodebox.handle.Handle;
import nodebox.util.StringUtils;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static nodebox.base.Preconditions.*;
/**
* A Node is a building block in a network and encapsulates specific functionality.
* <p/>
* The operation of the Node is specified through its parameters. The data that flows
* through the node passes through ports.
* <p/>
* Nodes can be nested using parent/child relationships. Then, you can connect them together.
* This allows for many processing possibilities, where you can connect several nodes together forming
* very complicated networks. Networks, in turn, can be rigged up to form sort of black-boxes, with some
* input parameters and an output parameter, so they form a Node themselves, that can be used to form
* even more complicated networks, etc.
* <p/>
* Central in this concept is the directed acyclic graph, or DAG. This is a graph where all the edges
* are directed, and no cycles can be formed, so you do not run into recursive loops. The vertexes of
* the graph are the nodes, and the edges are the connections between them.
* <p/>
* One of the vertexes in the graph is set as the rendered node, and from there on, the processing starts,
* working its way upwards in the network, processing other nodes (and their inputs) as they come along.
*/
public class Node implements NodeCode {
private static final Pattern NODE_NAME_PATTERN = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9_]{0,29}$");
private static final Pattern DOUBLE_UNDERSCORE_PATTERN = Pattern.compile("^__.*$");
private static final Pattern RESERVED_WORD_PATTERN = Pattern.compile("^(node|network|root|context)$");
private static final Pattern NUMBER_AT_THE_END = Pattern.compile("^(.*?)(\\d*)$");
public static final String IMAGE_GENERIC = "__generic";
public static final String OUTPUT_PORT_NAME = "output";
public static final Node ROOT_NODE;
public enum Attribute {
LIBRARY, NAME, POSITION, EXPORT, DESCRIPTION, IMAGE, PARAMETER, PORT
}
static {
ROOT_NODE = new Node(NodeLibrary.BUILTINS, "root", Object.class);
ROOT_NODE.addParameter("_code", Parameter.Type.CODE, ROOT_NODE);
ROOT_NODE.addParameter("_handle", Parameter.Type.CODE, new JavaMethodWrapper(Node.class, "doNothing"));
ROOT_NODE.addParameter("_description", Parameter.Type.STRING, "Base node instance.");
ROOT_NODE.addParameter("_image", Parameter.Type.STRING, IMAGE_GENERIC);
NodeLibrary.BUILTINS.add(ROOT_NODE);
}
/**
* The name of this node.
*/
private String name;
/**
* The library this node is in.
*/
private NodeLibrary library;
/**
* The parent for this node.
*/
private Node parent;
/**
* The children of this node.
*/
private HashMap<String, Node> children = new HashMap<String, Node>();
/**
* The node's prototype. NodeBox uses prototype-based inheritance to blur the lines between classes and instances.
*/
private Node prototype;
/**
* The type of data that will be processed by this node.
*/
private Class dataClass;
/**
* Position of this node in the interface.
*/
private double x, y;
/**
* A flag that indicates whether this node is in need of processing.
* The dirty flag is set using markDirty and cleared while processing.
*/
private transient boolean dirty = true;
/**
* A flag that indicates that this node will be exported.
* This flag only has effect for nodes directly under the root node in a library.
*/
private boolean exported;
/**
* A map of all parameters.
*/
private LinkedHashMap<String, Parameter> parameters = new LinkedHashMap<String, Parameter>();
/**
* A map of all the data ports within the system.
*/
private LinkedHashMap<String, Port> ports = new LinkedHashMap<String, Port>();
/**
* The output port. This port will contain the processed data for this node.
*/
private Port outputPort;
/**
* The child node to render.
*/
private Node renderedChild;
/**
* All child connections within this node.
*/
private List<Connection> connections = new ArrayList<Connection>();
/**
* The processing error. Null if no error occurred during processing.
*/
private Throwable error;
//// Constructors ////
private Node(NodeLibrary library, String name, Class dataClass) {
assert library != null;
this.library = library;
this.name = name;
this.dataClass = dataClass;
this.outputPort = new Port(this, OUTPUT_PORT_NAME, Port.Direction.OUT);
}
//// Naming /////
public String getName() {
return name;
}
public void setName(String name) throws InvalidNameException {
if (this.name.equals(name)) return;
if (this.parent.children.containsKey(name))
throw new InvalidNameException(null, name, "The network already contains a node named " + name);
validateName(name);
this.parent.children.remove(this.name);
this.name = name;
this.parent.children.put(this.name, this);
getLibrary().fireNodeAttributeChanged(this, Attribute.NAME);
}
public NodeLibrary getLibrary() {
return library;
}
public String getIdentifier() {
return library + "." + name;
}
/**
* Get an identifier that is relative to the given node.
* <p/>
* This means that if the node and prototype are in the same library, the identifier
* is just the name of the prototype. Otherwise, the library name is added.
*
* @param relativeTo the instance this prototype is relative to
* @return a short or long identifier
*/
public String getRelativeIdentifier(Node relativeTo) {
if (relativeTo.library == library) {
return name;
} else {
return getIdentifier();
}
}
public String getDescription() {
return asString("_description");
}
public void setDescription(String description) {
setValue("_description", description);
getLibrary().fireNodeAttributeChanged(this, Attribute.DESCRIPTION);
}
public String getImage() {
return asString("_image");
}
public void setImage(String image) {
setValue("_image", image);
getLibrary().fireNodeAttributeChanged(this, Attribute.IMAGE);
}
/**
* Checks if the given name would be valid for this node.
*
* @param name the name to check.
* @throws InvalidNameException if the name was invalid.
*/
public static void validateName(String name) throws InvalidNameException {
Matcher m1 = NODE_NAME_PATTERN.matcher(name);
Matcher m2 = DOUBLE_UNDERSCORE_PATTERN.matcher(name);
Matcher m3 = RESERVED_WORD_PATTERN.matcher(name);
if (!m1.matches()) {
throw new InvalidNameException(null, name, "Names can only contain lowercase letters, numbers, and the underscore. Names cannot be longer than 29 characters.");
}
if (m2.matches()) {
throw new InvalidNameException(null, name, "Names starting with double underscore are reserved for internal use.");
}
if (m3.matches()) {
throw new InvalidNameException(null, name, "Names cannot be a reserved word (network, node, root).");
}
}
//// Parent/child relationship ////
public Node getParent() {
return parent;
}
public Node getRoot() {
Node n = this;
while (n.getParent() != null) {
n = n.getParent();
}
return n;
}
/**
* Reparent the node.
* <p/>
* This breaks all connections.
*
* @param parent the new parent
*/
public void setParent(Node parent) {
// This method is called indirectly by newInstance.
// newInstance has set the parent, but has not added it to
// the library yet. Therefore, we cannot do this.parent == parent,
// but need to check parent.contains()
if (parent != null && parent.containsChildNode(this)) return;
if (parent != null && parent.containsChildNode(name))
throw new InvalidNameException(this, name, "There is already a node named \"" + name + "\" in " + parent);
// Since this node will reside under a different parent, it can no longer maintain connections within
// the previous parent. Break all connections. We need to do this before the parent changes.
disconnect();
if (this.parent != null)
this.parent.remove(this);
this.parent = parent;
if (parent != null) {
parent.children.put(name, this);
// We're on the child node, so we need to fire the child added event
// on the parent with this child as the argument.
getLibrary().fireChildAdded(parent, this);
}
}
public boolean hasParent() {
return parent != null;
}
public boolean isLeaf() {
return isEmpty();
}
public boolean isEmpty() {
return children.isEmpty();
}
public int size() {
return children.size();
}
public void add(Node node) {
if (node == null)
throw new IllegalArgumentException("The node cannot be null.");
node.setParent(this);
}
/**
* Create a child node under this node from the given prototype.
* The name for this child is generated automatically.
*
* @param prototype the prototype node
* @return a new Node
*/
public Node create(Node prototype) {
if (prototype == null) throw new IllegalArgumentException("Prototype cannot be null.");
return create(prototype, null, null);
}
/**
* Create a child node under this node from the given prototype.
*
* @param prototype the prototype node
* @param name the name of the new node
* @return a new Node
*/
public Node create(Node prototype, String name) {
return create(prototype, name, null);
}
/**
* Create a child node under this node from the given prototype.
* The name for this child is generated automatically.
*
* @param prototype the prototype node
* @param dataClass the type of data this new node instance will output.
* @return a new Node
*/
public Node create(Node prototype, Class dataClass) {
return create(prototype, null, dataClass);
}
/**
* Create a child node under this node from the given prototype.
*
* @param prototype the prototype node
* @param name the name of the new node
* @param dataClass the type of data this new node instance will output.
* @return a new Node
*/
public Node create(Node prototype, String name, Class dataClass) {
if (prototype == null) throw new IllegalArgumentException("Prototype cannot be null.");
if (dataClass == null) dataClass = prototype.getDataClass();
if (name == null) name = uniqueName(prototype.getName());
Node newNode = prototype.rawInstance(library, name, dataClass);
add(newNode);
return newNode;
}
public boolean remove(Node node) {
assert (node != null);
if (!containsChildNode(node))
return false;
node.markDirty();
node.disconnect();
node.parent = null;
children.remove(node.getName());
if (node == renderedChild) {
setRenderedChild(null);
}
getLibrary().fireChildRemoved(this, node);
return true;
}
public String uniqueName(String prefix) {
Matcher m = NUMBER_AT_THE_END.matcher(prefix);
m.find();
String namePrefix = m.group(1);
String number = m.group(2);
int counter;
if (number.length() > 0) {
counter = Integer.parseInt(number);
} else {
counter = 1;
}
while (true) {
String suggestedName = namePrefix + counter;
if (!containsChildNode(suggestedName)) {
// We don't use rename here, since it assumes the node will be in
// this network.
return suggestedName;
}
++counter;
}
}
public boolean containsChildNode(String nodeName) {
return children.containsKey(nodeName);
}
public boolean containsChildNode(Node node) {
return children.containsValue(node);
}
public boolean containsChildPort(Port port) {
// TODO: This check will need to change once we move to readonly.
return port.getParentNode() == this;
}
public Node getChild(String nodeName) {
return children.get(nodeName);
}
public Node getExportedChild(String nodeName) {
Node child = getChild(nodeName);
if (child == null) return null;
if (child.isExported()) {
return child;
} else {
return null;
}
}
public Node getChildAt(int index) {
Collection c = children.values();
if (index >= c.size()) return null;
return (Node) c.toArray()[index];
}
public int getChildCount() {
return children.size();
}
public boolean hasChildren() {
return !children.isEmpty();
}
public List<Node> getChildren() {
return new ArrayList<Node>(children.values());
}
//// Rendered ////
public Node getRenderedChild() {
return renderedChild;
}
public void setRenderedChild(Node renderedChild) {
if (renderedChild != null && !containsChildNode(renderedChild)) {
throw new NotFoundException(this, renderedChild.getName(), "Node '" + renderedChild.getAbsolutePath() + "' is not in this network (" + getAbsolutePath() + ")");
}
if (this.renderedChild == renderedChild) return;
this.renderedChild = renderedChild;
markDirty();
getLibrary().fireRenderedChildChanged(this, renderedChild);
}
public boolean isRendered() {
return parent != null && parent.getRenderedChild() == this;
}
public void setRendered() {
if (parent == null) return;
parent.setRenderedChild(this);
}
//// Path ////
public String getAbsolutePath() {
ArrayList<String> parts = new ArrayList<String>();
Node child = this;
Node root = getLibrary().getRootNode();
while (child != null && child != root) {
parts.add(0, child.getName());
child = child.getParent();
}
if (parts.isEmpty()) {
return "/";
} else {
return "/" + StringUtils.join(parts, "/");
}
}
//// Prototype ////
public Node getPrototype() {
return prototype;
}
//// Data Class ////
public Class getDataClass() {
return dataClass;
}
public void validate(Object value) throws IllegalArgumentException {
// Null is accepted as a default value.
if (value == null) return;
if (!getDataClass().isAssignableFrom(value.getClass()))
throw new IllegalArgumentException("Value " + value + " is not of required class (was " + value.getClass() + ", required " + getDataClass());
}
//// Position ////
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
getLibrary().fireNodeAttributeChanged(this, Attribute.POSITION);
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
getLibrary().fireNodeAttributeChanged(this, Attribute.POSITION);
}
public Point getPosition() {
return new Point((float) x, (float) y);
}
public void setPosition(Point p) {
setPosition(p.getX(), p.getY());
}
public void setPosition(double x, double y) {
if (this.x == x && this.y == y) return;
this.x = x;
this.y = y;
getLibrary().fireNodeAttributeChanged(this, Attribute.POSITION);
}
//// Export flag ////
public boolean isExported() {
return exported;
}
public void setExported(boolean exported) {
this.exported = exported;
getLibrary().fireNodeAttributeChanged(this, Attribute.EXPORT);
}
//// Parameters ////
/**
* Get a list of all parameters for this node.
*
* @return a list of all the parameters for this node.
*/
public List<Parameter> getParameters() {
return new ArrayList<Parameter>(parameters.values());
}
public int getParameterCount() {
return parameters.size();
}
public Parameter addParameter(String name, Parameter.Type type) {
Parameter p = new Parameter(this, name, type);
parameters.put(name, p);
getLibrary().fireNodeAttributeChanged(this, Attribute.PARAMETER);
return p;
}
public Parameter addParameter(String name, Parameter.Type type, Object value) {
Parameter p = addParameter(name, type);
p.setValue(value);
getLibrary().fireNodeAttributeChanged(this, Attribute.PARAMETER);
return p;
}
/**
* Remove a parameter with the given name.
* <p/>
* If the parameter does not exist, this method returns false.
*
* @param name the parameter name
* @return true if the parameter exists and was removed.
*/
public boolean removeParameter(String name) {
// First remove all dependencies to and from this parameter.
// Don't rewrite any expressions.
Parameter p = parameters.get(name);
if (p == null) return false;
p.removedEvent();
parameters.remove(name);
getLibrary().fireNodeAttributeChanged(this, Attribute.PARAMETER);
markDirty();
return true;
}
/**
* Get a parameter with the given name
*
* @param name the parameter name
* @return a Parameter or null if the parameter could not be found.
*/
public Parameter getParameter(String name) {
return parameters.get(name);
}
/**
* Checks if this node has a parameter with the given name.
*
* @param name the parameter name
* @return true if a Parameter with that name exists
*/
public boolean hasParameter(String name) {
return getParameter(name) != null;
}
/**
* This method gets called by Parameter.setName().
* At this point, the Parameter already has its new name, but still needs to be stored
* under its new name in parameters.
*
* @param p the parameter to rename.
* @param oldName the old name
* @param newName the new name.
*/
/* package private */ void renameParameter(Parameter p, String oldName, String newName) {
assert (p.getName().equals(newName));
parameters.remove(oldName);
parameters.put(newName, p);
}
//// Parameter values ////
public Object getValue(String parameterName) {
Parameter p = getParameter(parameterName);
if (p == null) return null;
return p.getValue();
}
public int asInt(String parameterName) {
Parameter p = getParameter(parameterName);
if (p.getType() != Parameter.Type.INT) {
throw new RuntimeException("Parameter " + parameterName + " is not an integer.");
}
return p.asInt();
}
public float asFloat(String parameterName) {
Parameter p = getParameter(parameterName);
if (p.getType() != Parameter.Type.FLOAT && p.getType() != Parameter.Type.INT) {
throw new RuntimeException("Parameter " + parameterName + " is not a float.");
}
return p.asFloat();
}
public String asString(String parameterName) {
Parameter p = getParameter(parameterName);
// No type checking is performed here. Any parameter type can be converted to a String.
return p.asString();
}
public Color asColor(String parameterName) {
Parameter p = getParameter(parameterName);
if (p.getType() != Parameter.Type.COLOR) {
throw new RuntimeException("Parameter " + parameterName + " is not a color.");
}
return p.asColor();
}
public NodeCode asCode(String parameterName) {
Parameter p = getParameter(parameterName);
if (p.getType() != Parameter.Type.CODE) {
throw new RuntimeException("Parameter " + parameterName + " is not a string.");
}
return p.asCode();
}
public void setValue(String parameterName, Object value) throws IllegalArgumentException {
Parameter p = parameters.get(parameterName);
if (p == null)
throw new IllegalArgumentException("Parameter " + parameterName + " does not exist.");
p.setValue(value);
}
/**
* Sets a parameter value on this node without raising any errors.
*
* @param parameterName The parameter name.
* @param value The new value.
* @deprecated Will be removed in NodeBox 2.3. Handles should migrate to their own silentSet() method.
*/
public void silentSet(String parameterName, Object value) {
// HACK this method now refers to the current document because otherwise the set will not trigger a network update.
NodeBoxDocument.getCurrentDocument().silentSet(this, parameterName, value);
}
//// Ports ////
public Port addPort(String name) {
return addPort(name, Port.Cardinality.SINGLE);
}
public Port addPort(String name, Port.Cardinality cardinality) {
Port p = new Port(this, name, cardinality);
ports.put(name, p);
// TODO: Test this removal!
// if (parent != null) {
// if (parent.childGraph == null)
// parent.childGraph = new DependencyGraph<Port, Connection>();
// parent.childGraph.addDependency(p, outputPort);
// }
getLibrary().fireNodeAttributeChanged(this, Attribute.PORT);
return p;
}
public void removePort(String name) {
throw new UnsupportedOperationException("removePort is not implemented yet.");
// TODO: Implement, make sure to remove internal dependencies.
// parent.childGraph.removeDependency(p, outputPort);
}
public Port getPort(String name) {
return ports.get(name);
}
public boolean hasPort(String portName) {
return ports.containsKey(portName);
}
public List<Port> getPorts() {
return new ArrayList<Port>(ports.values());
}
public Port getOutputPort() {
return outputPort;
}
/**
* Get the value of a port.
* <p/>
* This only works for ports with single cardinality.
*
* @param name the name of the port
* @return the value of the port
*/
public Object getPortValue(String name) {
return ports.get(name).getValue();
}
/**
* Get the values of a port as a list of objects.
* <p/>
* This only works for ports with multiple cardinality.
*
* @param name the name of the port
* @return the values of the port
*/
public List<Object> getPortValues(String name) {
return ports.get(name).getValues();
}
public Object getOutputValue() {
return outputPort.getValue();
}
public void setPortValue(String name, Object value) {
ports.get(name).setValue(value);
}
public void setOutputValue(Object value) {
outputPort.setValue(value);
}
//// Expression shortcuts ////
public boolean setExpression(String parameterName, String expression) {
Parameter p = parameters.get(parameterName);
if (p == null)
throw new IllegalArgumentException("Parameter " + parameterName + " does not exist.");
return p.setExpression(expression);
}
public void clearExpression(String parameterName) {
Parameter p = parameters.get(parameterName);
if (p == null)
throw new IllegalArgumentException("Parameter " + parameterName + " does not exist.");
p.clearExpression();
}
/**
* Check if one of my parameters uses a stamp expression.
* <p/>
* This method is used to determine if parameters and nodes should be marked as dirty when re-evaluating upstream,
* which is what happens in the copy node.
*
* @return true if one of my parameters uses a stamp expression.
*/
public boolean hasStampExpression() {
for (Parameter p : parameters.values()) {
if (p.hasStampExpression()) return true;
}
return false;
}
//// Connection shortcuts ////
/**
* Check if the child ports can be connected.
*
* @param input the input child port
* @param output the output child port
* @return true if the input port can connect to the output port
*/
public boolean canConnectChildren(Port input, Port output) {
// TODO: Move implementation from Port here once we move to readonly.
checkNotNull(input);
checkNotNull(output);
return input.canConnectTo(output);
}
/**
* Connect the port on the given (input) child node to the output port of the given (output) child node.
*
* @param inputNode the downstream node
* @param portName the downstream (input) port
* @param outputNode the upstream node
* @return the Connection object.
*/
public Connection connectChildren(Node inputNode, String portName, Node outputNode) {
Port inputPort = inputNode.getPort(portName);
Port outputPort = outputNode.getOutputPort();
return connectChildren(inputPort, outputPort);
}
/**
* Connect the downstream input port to the upstream output port.
* <p/>
* Both the output and input ports need to be on child nodes of this node.
* <p/>
* If the input port was already connected, and its cardinality is single, the connection is broken.
*
* @param input the downstream port
* @param output the upstream port
* @return the connection object
* @throws IllegalArgumentException if the two ports could not be connected
*/
public Connection connectChildren(Port input, Port output) {
checkNotNull(input, "The input port cannot be null.");
checkNotNull(output, "The output port cannot be null.");
checkState(containsChildPort(input), "The input port is not on a child node of this parent.");
checkState(containsChildPort(output), "The output port is not on a child node of this parent.");
checkArgument(input.isInputPort(), "The first argument is not an input port.");
checkArgument(output.isOutputPort(), "The second argument is not an output port.");
checkArgument(canConnectChildren(input, output), "The input and output data classes are not compatible.");
// If ports can have only one connection (cardinality == SINGLE), disconnectChildPort the port first.
if (input.getCardinality() == Port.Cardinality.SINGLE) {
disconnectChildPort(input);
}
Connection c = new Connection(output, input);
// Create a new list of connections, and check this list for a cyclic dependency.
// We create a defensive copy of the original list to make sure we don't need to disconnect
// if we discover a cycle.
ArrayList<Connection> newConnections = new ArrayList<Connection>(connections);
newConnections.add(c);
CycleDetector detector = new CycleDetector(newConnections);
// This check will throw an IllegalArgumentException, which is the exception we want.
checkArgument(!detector.hasCycles(), "Creating this connection would cause a cyclic dependency.");
connections = newConnections;
input.getNode().markDirty();
getLibrary().fireConnectionAdded(this, c);
return c;
}
/**
* Changes the ordering of output connections by moving the given connection a specified number of positions.
* <p/>
* To move the specified connection up one position, set the deltaIndex to -1. To move a connection down, set
* the deltaIndex to 1.
* <p/>
* If the delta index is larger or smaller than the number of positions this connection can move, it will
* move the connection to the beginning or end. This will not result in an error.
*
* @param connection the connection to reorder
* @param deltaIndex the number of places to move.
* @return true if changes were made to the ordering.
*/
public boolean reorderConnection(Connection connection, int deltaIndex) {
int index = connections.indexOf(connection);
int newIndex = index + deltaIndex;
newIndex = Math.max(0, Math.min(connections.size() - 1, newIndex));
if (index == newIndex) return false;
connections.remove(connection);
connections.add(newIndex, connection);
connection.getInputNode().markDirty();
return true;
}
/**
* Changes the ordering of output connections by moving the given connection a specified number of positions.
* <p/>
* To move the specified connection up one position, set the deltaIndex to -1. To move a connection down, set
* the deltaIndex to 1.
* <p/>
* If the delta index is larger or smaller than the number of positions this connection can move, it will
* move the connection to the beginning or end. This will not result in an error.
*
* @param connection the connection to reorder
* @param deltaIndex the number of places to move.
* @param multi the connection should only be reordered among connections connected to the same input port (with cardinality MULTIPLE).
* @return true if changes were made to the ordering.
*/
public boolean reorderConnection(Connection connection, int deltaIndex, boolean multi) {
if (multi) {
List<Connection> mConnections = connection.getInput().getConnections();
int index = mConnections.indexOf(connection);
int newIndex = index + deltaIndex;
newIndex = Math.max(0, Math.min(mConnections.size() - 1, newIndex));
if (index == newIndex) return false;
connections.removeAll(mConnections);
mConnections.remove(connection);
mConnections.add(newIndex, connection);
connections.addAll(0, mConnections);
connection.getInputNode().markDirty();
return true;
} else
return reorderConnection(connection, deltaIndex);
}
/**
* Remove all connections to and from the given child node.
*
* @param child the child node on this parent
* @return true if connections were removed
*/
public boolean disconnectChildren(Node child) {
boolean removedSomething = false;
// Disconnect all my inputs.
for (Port p : child.getPorts()) {
// Due to lazy evaluation, removedSomething needs to be at the end.
removedSomething = disconnectChildPort(p) | removedSomething;
}
// Disconnect all my outputs.
removedSomething = disconnectChildPort(child.outputPort) | removedSomething;
return removedSomething;
}
/**
* Remove all connections to and from this node.
*
* @return true if connections were removed.
*/
public boolean disconnect() {
if (!hasParent()) return false;
return parent.disconnectChildren(this);
}
public void disconnect(Connection c) {
checkNotNull(c);
checkArgument(connections.contains(c), "Connection %s is not one of my connections.", c);
connections.remove(c);
Port input = c.getInput();
input.reset();
input.getNode().markDirty();
getLibrary().fireConnectionRemoved(this, c);
}
/**
* Removes all connection from the given (input or output) child port.
*
* @param port the (input or output) port on the child node.
* @return true if a connection was removed.
*/
public boolean disconnectChildPort(Port port) {
checkNotNull(port, "Port cannot be null.");
checkArgument(containsChildPort(port), "Port %s is not on a child node of this parent.", port);
List<Connection> connectionsToRemove = new ArrayList<Connection>();
for (Connection c : connections) {
if (port == c.getInput() || port == c.getOutput()) {
port.reset();
// This port was changed. Mark the node as dirty.
port.getNode().markDirty();
getLibrary().fireConnectionRemoved(this, c);
connectionsToRemove.add(c);
}
}
if (connectionsToRemove.isEmpty()) return false;
for (Connection c : connectionsToRemove) {
connections.remove(c);
}
return true;
}
/**