-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathParameter.java
More file actions
1263 lines (1130 loc) · 45.1 KB
/
Parameter.java
File metadata and controls
1263 lines (1130 loc) · 45.1 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.graphics.Color;
import nodebox.util.StringUtils;
import java.util.*;
import java.util.regex.Pattern;
/**
* A parameter controls the operation of a Node. It provide an interface into the workings of a node and allows a user
* to change its behaviour. Parameters are represented by standard user interface controls, such as sliders for numbers,
* text fields for strings, and checkboxes for booleans.
* <p/>
* Parameters implement the observer pattern for expressions. Parameters that are dependent on other parameters because
* of their expressions will observe the parameters they depend on, and marked the node as dirty whenever they receive
* an update event from one of the parameters they depend on.
*/
public class Parameter {
/**
* The primitive type of a parameter. This is different from the control UI that is used to represent this parameter.
*/
public enum Type {
/**
* An integer value
*/
INT,
/**
* A floating-point value
*/
FLOAT,
/**
* A string value
*/
STRING,
/**
* A color
*/
COLOR,
/**
* Executable code
*/
CODE
}
/**
* The UI control for this parameter. This defines how the parameter is represented in the user interface.
*/
public enum Widget {
ANGLE, COLOR, DATA, FILE, FLOAT, FONT, GRADIENT, IMAGE, INT, MENU, SEED, STRING, TEXT, TOGGLE, NODEREF, STAMP_EXPRESSION, CODE
}
/**
* The way in which values will be bound to a minimum and maximum value. Only hard bounding enforces the
* minimum and maximum value.
*/
public enum BoundingMethod {
NONE, SOFT, HARD
}
/**
* The steps where this parameter will be shown. If it is hidden, it will not be shown anywhere.
* If it is in the detail view, it will not show up in the HUD. The HUD is the highest level; this
* means that the control will be shown everywhere.
*/
public enum DisplayLevel {
HIDDEN, DETAIL, HUD
}
public static class MenuItem {
private String key;
private String label;
public MenuItem(String key, String label) {
this.key = key;
this.label = label;
}
public String getKey() {
return key;
}
public String getLabel() {
return label;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MenuItem menuItem = (MenuItem) o;
if (!key.equals(menuItem.key)) return false;
if (!label.equals(menuItem.label)) return false;
return true;
}
@Override
public int hashCode() {
int result = key.hashCode();
result = 31 * result + label.hashCode();
return result;
}
}
public static final HashMap<Type, Class> TYPE_MAPPING;
public static final HashMap<Type, Widget> WIDGET_MAPPING;
public static final HashMap<Widget, Type> REVERSE_WIDGET_MAPPING;
public static final NodeCode emptyCode = new EmptyCode();
private static final Pattern TIME_DEPENDENT_KEYWORDS = Pattern.compile("FRAME|wave|hold|schedule|timeloop");
private static final Pattern CANVAS_DEPENDENT_KEYWORDS = Pattern.compile("TOP|LEFT|BOTTOM|RIGHT|WIDTH|HEIGHT");
static {
TYPE_MAPPING = new HashMap<Type, Class>();
TYPE_MAPPING.put(Type.INT, Integer.class);
TYPE_MAPPING.put(Type.FLOAT, Float.class);
TYPE_MAPPING.put(Type.STRING, String.class);
TYPE_MAPPING.put(Type.COLOR, Color.class);
TYPE_MAPPING.put(Type.CODE, NodeCode.class);
WIDGET_MAPPING = new HashMap<Type, Widget>();
WIDGET_MAPPING.put(Type.INT, Widget.INT);
WIDGET_MAPPING.put(Type.FLOAT, Widget.FLOAT);
WIDGET_MAPPING.put(Type.STRING, Widget.STRING);
WIDGET_MAPPING.put(Type.COLOR, Widget.COLOR);
WIDGET_MAPPING.put(Type.CODE, Widget.CODE);
REVERSE_WIDGET_MAPPING = new HashMap<Widget, Type>();
REVERSE_WIDGET_MAPPING.put(Widget.ANGLE, Type.FLOAT);
REVERSE_WIDGET_MAPPING.put(Widget.COLOR, Type.COLOR);
REVERSE_WIDGET_MAPPING.put(Widget.DATA, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.FILE, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.FLOAT, Type.FLOAT);
REVERSE_WIDGET_MAPPING.put(Widget.FONT, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.GRADIENT, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.IMAGE, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.INT, Type.INT);
REVERSE_WIDGET_MAPPING.put(Widget.MENU, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.SEED, Type.INT);
REVERSE_WIDGET_MAPPING.put(Widget.STRING, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.TEXT, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.TOGGLE, Type.INT);
REVERSE_WIDGET_MAPPING.put(Widget.NODEREF, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.STAMP_EXPRESSION, Type.STRING);
REVERSE_WIDGET_MAPPING.put(Widget.CODE, Type.CODE);
}
private Node node;
private String name;
private String label;
private String helpText;
private Type type;
private Widget widget;
private Object value;
private Expression expression;
private BoundingMethod boundingMethod = BoundingMethod.NONE;
private Float minimumValue, maximumValue; // Objects, because they can be null.
private DisplayLevel displayLevel = DisplayLevel.HUD;
private Expression enableExpression;
private List<MenuItem> menuItems = new ArrayList<MenuItem>(0);
private transient boolean dirty;
private transient boolean hasStampExpression;
public Parameter(Node node, String name, Type type) {
this.node = node;
// Type needs to come first, because validateName can cause toString() to happen which requires the name.
this.type = type;
validateName(name);
this.name = name;
this.widget = getDefaultWidget(type);
this.label = StringUtils.humanizeName(name);
revertToDefault();
}
//// Basic operations ////
public Node getNode() {
return node;
}
public NodeLibrary getLibrary() {
return node.getLibrary();
}
public Parameter getPrototype() {
Node pn = node.getPrototype();
if (pn == null) return null;
return pn.getParameter(name);
}
//// Naming ////
public String getName() {
return name;
}
public void setName(String name) throws InvalidNameException {
if (name != null && getName().equals(name)) return;
validateName(name);
String oldName = this.name;
this.name = name;
node.renameParameter(this, oldName, name);
fireAttributeChanged();
}
public void validateName(String name) {
if (name == null || name.trim().length() == 0)
throw new InvalidNameException(this, name, "Name cannot be null or empty.");
if (node.hasParameter(name))
throw new InvalidNameException(this, name, "There is already a parameter named " + name + ".");
if (node.hasPort(name))
throw new InvalidNameException(this, name, "There is already a port named " + name + ".");
// Use the same validation as for nodes.
Node.validateName(name);
}
public String getAbsolutePath() {
return getNode().getAbsolutePath() + "/" + getName();
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
if (label == null || label.trim().length() == 0)
this.label = StringUtils.humanizeName(name);
else
this.label = label;
fireAttributeChanged();
}
public String getHelpText() {
return helpText;
}
public void setHelpText(String helpText) {
this.helpText = helpText;
fireAttributeChanged();
}
//// Type ////
public Type getType() {
return type;
}
/**
* Change the type of this parameter.
* <p/>
* The existing value will be migrated to the new type. Changing the type to code will
* not try to parse the value, since this can given unexpected results.
* <p/>
* The new value will be clamped to bounds (if bounding method is set to hard), and
* the widget will be set to the default widget for this type.
*
* @param newType the new type
*/
public void setType(Type newType) {
if (this.type == newType) return;
// Try to migrate the value to the new type
if (hasExpression()) {
// Do nothing. It is too hard to change expressions to return a value of the new type.
} else {
try {
value = parseValue(asString(), newType);
} catch (IllegalArgumentException e) {
// If the value could not be parsed, reset it to the default value.
value = getDefaultValue(newType);
}
}
this.type = newType;
clampToBounds();
// The old widget most likely doesn't make any sense for the new type.
this.widget = getDefaultWidget(newType);
fireAttributeChanged();
}
//// Widget ////
public Widget getWidget() {
return widget;
}
public void setWidget(Widget widget) {
if (this.widget == widget) return;
// Changing the widget mostly means changing the type.
Type oldType = getTypeForWidget(this.widget);
Type newType = getTypeForWidget(widget);
// If the old and new type are the same, we don't need to migrate the type.
if (oldType != newType) {
// Setting the type will change the widget to the default widget, so the widget
// will be set *after* the type is migrated.
setType(newType);
}
this.widget = widget;
fireAttributeChanged();
}
public static Widget getDefaultWidget(Type type) {
return WIDGET_MAPPING.get(type);
}
public static Type getTypeForWidget(Widget widget) {
return REVERSE_WIDGET_MAPPING.get(widget);
}
//// Bounding ////
public BoundingMethod getBoundingMethod() {
return boundingMethod;
}
public void setBoundingMethod(BoundingMethod boundingMethod) {
if (this.boundingMethod == boundingMethod) return;
this.boundingMethod = boundingMethod;
if (boundingMethod == BoundingMethod.HARD)
clampToBounds();
fireAttributeChanged();
}
public Float getMinimumValue() {
return minimumValue;
}
public void setMinimumValue(Float minimumValue) {
if (this.minimumValue != null && this.minimumValue.equals(minimumValue)) return;
if (minimumValue != null && this.maximumValue != null && minimumValue > this.maximumValue)
minimumValue = maximumValue;
this.minimumValue = minimumValue;
if (boundingMethod == BoundingMethod.HARD)
clampToBounds();
fireAttributeChanged();
}
public Float getMaximumValue() {
return maximumValue;
}
public void setMaximumValue(Float maximumValue) {
if (this.maximumValue != null && this.maximumValue.equals(maximumValue)) return;
if (maximumValue != null && this.minimumValue != null && maximumValue < this.minimumValue)
maximumValue = minimumValue;
this.maximumValue = maximumValue;
if (boundingMethod == BoundingMethod.HARD)
clampToBounds();
fireAttributeChanged();
}
private void clampToBounds() {
if (type == Type.INT) {
int v = (Integer) value;
if (minimumValue != null && v < minimumValue) {
set(minimumValue.intValue());
} else if (maximumValue != null && v > maximumValue) {
set(maximumValue.intValue());
}
} else if (type == Type.FLOAT) {
float v = (Float) value;
if (minimumValue != null && v < minimumValue) {
set(minimumValue);
} else if (maximumValue != null && v > maximumValue) {
set(maximumValue);
}
}
}
//// Display level ////
public DisplayLevel getDisplayLevel() {
return displayLevel;
}
public void setDisplayLevel(DisplayLevel displayLevel) {
this.displayLevel = displayLevel;
fireAttributeChanged();
}
public void fireAttributeChanged() {
getLibrary().fireNodeAttributeChanged(node, Node.Attribute.PARAMETER);
}
//// Enable expressions ////
/**
* Check if the parameter is enabled.
* <p/>
* This evaluates the enable expression.
* The enable flag has no effect on the behaviour of Parameter: you can still set/get values, change metadata, etc.
* It is the UI's responsibility to react on the enable flag.
* <p/>
* The enabled state is not cached and the disable expression is evaluated every time.
*
* @return true if this parameter is enabled, has no expression or the expression has an error.
*/
public boolean isEnabled() {
if (enableExpression == null) return true;
try {
return enableExpression.asBoolean();
} catch (ExpressionError expressionError) {
return true;
}
}
/**
* Set the expression used for determining if the parameter is disabled.
* <p/>
* Calling isDisabled will now evaluate this expression every time.
*
* @param expression the disable expression.
* @see #isEnabled()
*/
public void setEnableExpression(String expression) {
if (expression == null || expression.trim().length() == 0) {
if (enableExpression == null) return;
enableExpression = null;
} else if (enableExpression != null && enableExpression.getExpression().equals(expression)) {
return;
} else {
enableExpression = new Expression(this, expression);
}
fireAttributeChanged();
}
/**
* Get the disable expression used for determining if the parameter is disabled.
*
* @return the disable expression.
*/
public String getEnableExpression() {
if (enableExpression == null) return "";
return enableExpression.getExpression();
}
public boolean hasEnableExpressionError() {
return enableExpression != null && enableExpression.getError() != null;
}
public Throwable getEnableExpressionError() {
if (enableExpression == null) return null;
return enableExpression.getError();
}
//// Menu items ////
public List<MenuItem> getMenuItems() {
return menuItems;
}
public void addMenuItem(String key, String label) {
menuItems.add(new MenuItem(key, label));
fireAttributeChanged();
}
public void removeMenuItem(String key) {
MenuItem itemToRemove = null;
for (MenuItem item : menuItems) {
if (item.getKey().equals(key)) {
itemToRemove = item;
break;
}
}
if (itemToRemove == null) return;
menuItems.remove(itemToRemove);
fireAttributeChanged();
}
public void removeMenuItem(MenuItem item) {
menuItems.remove(item);
fireAttributeChanged();
}
public void updateMenuItem(int index, String key, String label) {
if (index < 0 || index >= menuItems.size()) return;
menuItems.set(index, new Parameter.MenuItem(key, label));
fireAttributeChanged();
}
public void moveMenuItemDown(int index) {
Parameter.MenuItem item = menuItems.get(index);
menuItems.remove(item);
menuItems.add(index + 1, item);
fireAttributeChanged();
}
public void moveMenuItemUp(int index) {
Parameter.MenuItem item = menuItems.get(index);
menuItems.remove(item);
menuItems.add(index - 1, item);
fireAttributeChanged();
}
//// Values ////
public int asInt() {
if (type == Type.INT) {
return (Integer) value;
} else if (type == Type.FLOAT) {
float v = (Float) value;
return (int) v;
} else {
return 0;
}
}
public float asFloat() {
if (type == Type.INT) {
int v = (Integer) value;
return (float) v;
} else if (type == Type.FLOAT) {
return (Float) value;
} else {
return 0;
}
}
public String asString() {
if (value == null) return null;
if (type == Type.STRING) {
return (String) value;
} else if (type == Type.CODE) {
return ((NodeCode) value).getSource();
} else {
return value.toString();
}
}
public boolean asBoolean() {
if (type == Type.INT) {
int v = (Integer) value;
return v == 1;
} else {
return false;
}
}
public Color asColor() {
if (type == Type.COLOR) {
return (Color) getValue();
} else {
return new Color();
}
}
public NodeCode asCode() {
if (type == Type.CODE) {
return (NodeCode) getValue();
} else {
return null;
}
}
public String asExpression() {
if (type == Type.INT) {
return String.valueOf((Integer) value);
} else if (type == Type.FLOAT) {
return String.valueOf((Float) value);
} else if (type == Type.STRING) {
String v = (String) value;
// Quote the string
v = v.replaceAll("\"", "\\\"");
return "\"" + v + "\"";
} else if (type == Type.COLOR) {
Color v = (Color) value;
return String.format(Locale.US, "color(%.2f, %.2f, %.2f, %.2f)", v.getRed(), v.getGreen(), v.getBlue(), v.getAlpha());
} else if (type == Type.CODE) {
return ((NodeCode) value).getSource();
} else {
throw new AssertionError("Cannot convert parameter value " + asString() + " of type " + getType() + " to expression.");
}
}
/**
* Returns the value of this node. This is a safe copy and you can modify it at will.
* <p/>
* Only Color objects are cloned. The other value types are immutable, so they do not need to be cloned.
*
* @return a clone of the original value.
*/
public Object getValue() {
if (value instanceof Color) {
return ((Color) value).clone();
} else {
return value;
}
}
public void set(Object value) throws IllegalArgumentException {
setValue(value);
}
public void setValue(Object value) throws IllegalArgumentException {
if (hasExpression()) {
throw new IllegalArgumentException("The parameter has an expression set.");
}
// validate throws IllegalArgumentException when the value fails validation.
validate(value);
// As a special exception, integer values can be cast up to floating-point values,
// and double values can be cast down (losing precision).
Object castValue;
if (value instanceof Integer && type == Type.FLOAT) {
castValue = (float) ((Integer) value);
} else if (value instanceof Double && type == Type.FLOAT) {
castValue = (float) ((Double) value).doubleValue();
} else {
castValue = value;
}
if (this.value != null && this.value.equals(castValue)) return;
this.value = castValue;
markDirty();
}
/**
* Mark this parameter and its node as dirty. Also notify dependent parameters.
*/
public void markDirty() {
if (dirty) return;
dirty = true;
fireValueChanged();
}
//// Validation ////
public void validate(Object value) throws IllegalArgumentException {
// Check null
if (value == null)
throw new IllegalArgumentException("Value for parameter " + getName() + " cannot be null.");
// Check if the type matches
switch (type) {
case INT:
if (!(value instanceof Integer))
throw new IllegalArgumentException("Value is not an int.");
break;
case FLOAT:
// As a special exception, we accept integer and double values for float type parameters.
if (!(value instanceof Float || value instanceof Double || value instanceof Integer))
throw new IllegalArgumentException("Value is not a float.");
break;
case STRING:
if (!(value instanceof String))
throw new IllegalArgumentException("Value is not a String.");
break;
case COLOR:
if (!(value instanceof Color))
throw new IllegalArgumentException("Value is not a Color.");
break;
case CODE:
if (!(value instanceof NodeCode))
throw new IllegalArgumentException("Value is not a NodeCode object.");
break;
}
// If hard bounds are set, check if the value falls within the bounds.
if (getBoundingMethod() == BoundingMethod.HARD) {
float floatValue;
if (value instanceof Integer) {
floatValue = (Integer) value;
} else if (value instanceof Float) {
floatValue = (Float) value;
} else if (value instanceof Double) {
floatValue = (float) ((Double) value).doubleValue();
} else {
throw new AssertionError("Bounding set, but value is not integer or float. (type: " + this + " value: " + value + ")");
}
if (minimumValue != null && floatValue < minimumValue) {
throw new IllegalArgumentException("Parameter " + getName() + ": value " + value + " is too small. (minimum=" + minimumValue + ")");
}
if (maximumValue != null && floatValue > maximumValue) {
throw new IllegalArgumentException("Parameter " + getName() + ": value " + value + " is too big. (maximum=" + maximumValue + ")");
}
}
}
//// Expressions ////
public boolean hasExpression() {
return expression != null;
}
public boolean hasExpressionError() {
return hasExpression() && expression.hasError();
}
public Throwable getExpressionError() {
return hasExpression() ? expression.getError() : null;
}
public String getExpression() {
return hasExpression() ? expression.getExpression() : "";
}
public void clearExpression() {
this.expression = null;
hasStampExpression = false;
removeDependencies();
removeExternalDependencies();
markDirty();
}
/**
* Set the expression to the given value.
*
* @param expression the expression, in MVEL format.
* @return false if the expression could not be evaluated.
*/
public boolean setExpression(String expression) {
// We used to check if the expression was equal to the given expression, but this causes problems
// when new parameters are added that are relevant to the expression, i.e. Parameter "a" refers to "b" but
// parameter "b" does not exist yet. The expression becomes valid the moment we add "b", but to make this
// happen, we need to set "a" again to the same expression.
// TODO: This is more of a temporary workaround than a final solution.
// Ideally, the system should detect that the expression becomes valid because a new parameter was created.
// However, this means we can no longer use MVELs dependency detection.
if (expression == null || expression.trim().length() == 0) {
clearExpression();
return true;
}
// Remove the dependencies first in case creating the expression throws an error.
removeDependencies();
// Set the new expression.
this.expression = new Expression(this, expression);
// Reset the stamp flag. It will be set by markStampExpression(), which will be called
// from the expression helper while evaluating the expression.
hasStampExpression = false;
// Evaluate the expression to see if it returns any errors.
try {
this.expression.evaluate();
} catch (ExpressionError ignored) {
// Note that we catch the error, but do not handle it.
// We want to be able to work with erroneous expressions, and only have the error
// happen when the Node is updated, updating parameters and thus expressions.
// We simply return false to indicate that the method has an error.
// You can call hasExpressionError to check if the expression is faulty.
// Note that some expressions can become faulty at runtime, due to the dynamic nature of code.
// Even when an expression fails, the parameter is still marked dirty, since we want to update the
// node as soon as possible to inform the user of the error.
markDirty();
return false;
}
// Setting an expression automatically enables it and marks the parameter as dirty.
markDirty();
try {
updateDependencies();
} catch (IllegalArgumentException e) {
// Whilst updating, we might catch a Connection error meaning you are connecting
// e.g. the parameter to itself. If that happens, we clear out the expression and all of its
// dependencies.
removeDependencies();
this.expression.setError(e);
return false;
}
// Find and set external dependencies.
removeExternalDependencies();
NodeLibrary library = getLibrary();
if (TIME_DEPENDENT_KEYWORDS.matcher(expression).find()) {
library.addExternalDependency(this, NodeLibrary.ExternalEvent.FRAME);
}
if (CANVAS_DEPENDENT_KEYWORDS.matcher(expression).find()) {
library.addExternalDependency(this, NodeLibrary.ExternalEvent.CANVAS);
}
return true;
}
/**
* Check if the parameter has an expression containing the stamp function.
*
* @return true if the parameter has a stamp expression.
*/
public boolean hasStampExpression() {
return hasStampExpression;
}
/**
* Marks this parameter as using the stamp expression.
* <p/>
* Do not call this method yourself. This method is only used by ExpressionUtils.stamp() to indicate
* that the stamp expression was used.
*/
/* package private */ void markStampExpression() {
this.hasStampExpression = true;
}
//// Expression dependencies ////
/**
* The parameter dependencies function like a directed-acyclic graph, just like the node framework itself.
* Parameter dependencies are created by setting expressions that refer to other parameters. Once these parameters
* are changed, the dependent parameters need to be changed as well.
*
* @throws DependencyError when there is an error creating the dependencies.
*/
private void updateDependencies() throws DependencyError {
removeDependencies();
// Because this relates to expressions referring to other expressions, we don't need to remove external
// dependencies here.
for (Parameter p : expression.getDependencies()) {
// Add the parameter I depend on to as a dependency.
// This also makes the reverse connection in the dependency graph.
addDependency(p);
}
}
/**
* Add the given parameter as a dependency.
* <p/>
* This means that whenever this parameter needs to be updated, it needs to update
* the given parameter.
*
* @param p the parameter this node depends on.
*/
private void addDependency(Parameter p) {
getLibrary().addParameterDependency(p, this);
}
/**
* This method gets called whenever the expression was cleared. It removes all dependencies
* for this parameters.
* <p/>
* The dependents (parameters that rely on this parameter) are not changed. They only change
* when their dependencies are cleared.
*/
private void removeDependencies() {
getLibrary().removeParameterDependencies(this);
}
/**
* This method gets called whenever the expression was cleared.
* It removes all external dependencies to frame and canvas.
*/
private void removeExternalDependencies() {
getLibrary().removeExternalDependencies(this);
}
/**
* This method gets called when the parameter is about to be removed. It signal all of its dependent nodes
* that the parameter will no longer be available.
* <p/>
* The dependent parameters will probably all have invalid expressions from now on.
*/
private void removeDependents() {
// Before removing all dependents, inform them first of the fact that one of their dependencies has changed.
for (Parameter p : getDependents()) {
p.dependencyChangedEvent();
}
getLibrary().removeParameterDependents(this);
}
/**
* Get all parameters that rely on this parameter.
* <p/>
* These parameters all have expressions that point to this parameter. Whenever this parameter changes,
* they get notified.
* <p/>
* This list contains all "live" parameters when you call it. Please don't hold on to this list for too long,
* since parameters can be added and removed at will.
*
* @return a list of parameters that depend on this parameter. This list can safely be modified.
*/
public Set<Parameter> getDependents() {
return getLibrary().getParameterDependents(this);
}
/**
* Get all parameters this parameter depends on.
* <p/>
* This list contains all "live" parameters when you call it. Please don't hold on to this list for too long,
* since parameters can be added and removed at will.
*
* @return a list of parameters this parameter depends on. This list can safely be modified.
*/
public Set<Parameter> getDependencies() {
return getLibrary().getParameterDependencies(this);
}
/**
* Check if this parameter depends on the given parameter.
*
* @param other the possibly dependent parameter.
* @return true if this parameter depends on the given parameter.
*/
public boolean dependsOn(Parameter other) {
return getLibrary().getParameterDependencies(this).contains(other);
}
/**
* Called whenever the value of this parameter changes. This method informs the dependent parameters that my value
* has changed.
*/
protected void fireValueChanged() {
getLibrary().fireValueChanged(getNode(), this);
getNode().markDirty();
for (Parameter p : getDependents()) {
p.dependencyChangedEvent();
}
}
private void dependencyChangedEvent() {
markDirty();
}
/**
* This event happens when the parameter is about to be removed.
* <p/>
* We remove all dependencies/dependents here.
*/
public void removedEvent() {
removeDependencies();
removeExternalDependencies();
removeDependents();
}
/**
* Updates the parameter, making sure all dependencies are clean.
* <p/>
* This method can take a long time and should be run in a separate thread.
*
* @param context the processing context
* @throws ExpressionError if an expression fails
*/
public void update(ProcessingContext context) throws ExpressionError {
if (!dirty) return;
context.setNode(node);
// To avoid infinite recursion, we set dirty to false before processing
// any of the dependencies. If we come by this parameter again, we have
// already updated it.
dirty = false;
if (hasExpression()) {
// Update all dependencies.
for (Parameter p : getDependencies()) {
p.update(context);
}
Object expressionValue = expression.evaluate(context);
expressionValue = convertToType(expressionValue);
validate(expressionValue);
value = expressionValue;
fireValueChanged();
}
}
/**
* Convert the given value to the correct type for this parameter.
* <p/>
* This method assumes the value has already been validated, and is only used to convert int and doubles
* to their correct float representation.
*
* @param value a value
* @return the unchanged object, or the value converted to float for parameters with FLOAT type.
*/
private Object convertToType(Object value) {
if (type == Type.INT) {
if (value instanceof Integer) {
return value;
} else if (value instanceof Float) {
return ((Float) value).intValue();
} else if (value instanceof Double) {
return ((Double) value).intValue();
} else {
throw new IllegalArgumentException("Value " + value + " cannot be converted to int.");
}
} else if (type == Type.FLOAT) {
if (value instanceof Float) {
return value;
} else if (value instanceof Integer) {
return ((Integer) value).floatValue();
} else if (value instanceof Double) {
return ((Double) value).floatValue();
} else {
throw new IllegalArgumentException("Value " + value + " cannot be converted to float.");
}
} else if (type == Type.STRING) {
return value.toString();
} else if (type == Type.COLOR) {
if (value instanceof Color) {
return value;