source: josm/trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/ConditionFactory.java@ 17318

Last change on this file since 17318 was 16626, checked in by simon04, 4 years ago

see #19334 - https://errorprone.info/bugpattern/ImmutableEnumChecker

  • Property svn:eol-style set to native
File size: 32.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.mappaint.mapcss;
3
4import java.lang.reflect.Method;
5import java.text.MessageFormat;
6import java.util.Arrays;
7import java.util.EnumSet;
8import java.util.Objects;
9import java.util.Set;
10import java.util.function.BiPredicate;
11import java.util.function.IntFunction;
12import java.util.function.Predicate;
13import java.util.regex.Pattern;
14import java.util.regex.PatternSyntaxException;
15
16import org.openstreetmap.josm.data.osm.INode;
17import org.openstreetmap.josm.data.osm.IPrimitive;
18import org.openstreetmap.josm.data.osm.IRelation;
19import org.openstreetmap.josm.data.osm.IWay;
20import org.openstreetmap.josm.data.osm.Node;
21import org.openstreetmap.josm.data.osm.OsmPrimitive;
22import org.openstreetmap.josm.data.osm.OsmUtils;
23import org.openstreetmap.josm.data.osm.Relation;
24import org.openstreetmap.josm.data.osm.Tag;
25import org.openstreetmap.josm.data.osm.search.SearchCompiler.InDataSourceArea;
26import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
27import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
28import org.openstreetmap.josm.gui.mappaint.Cascade;
29import org.openstreetmap.josm.gui.mappaint.ElemStyles;
30import org.openstreetmap.josm.gui.mappaint.Environment;
31import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.Context;
32import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.ToTagConvertable;
33import org.openstreetmap.josm.tools.CheckParameterUtil;
34import org.openstreetmap.josm.tools.JosmRuntimeException;
35import org.openstreetmap.josm.tools.Utils;
36
37/**
38 * Factory to generate {@link Condition}s.
39 * @since 10837 (Extracted from Condition)
40 */
41public final class ConditionFactory {
42
43 private ConditionFactory() {
44 // Hide default constructor for utils classes
45 }
46
47 /**
48 * Create a new condition that checks the key and the value of the object.
49 * @param k The key.
50 * @param v The reference value
51 * @param op The operation to use when comparing the value
52 * @param context The type of context to use.
53 * @param considerValAsKey whether to consider {@code v} as another key and compare the values of key {@code k} and key {@code v}.
54 * @return The new condition.
55 * @throws MapCSSException if the arguments are incorrect
56 */
57 public static Condition createKeyValueCondition(String k, String v, Op op, Context context, boolean considerValAsKey) {
58 switch (context) {
59 case PRIMITIVE:
60 if (KeyValueRegexpCondition.SUPPORTED_OPS.contains(op) && !considerValAsKey) {
61 try {
62 return new KeyValueRegexpCondition(k, v, op, false);
63 } catch (PatternSyntaxException e) {
64 throw new MapCSSException(e);
65 }
66 }
67 if (!considerValAsKey && op == Op.EQ)
68 return new SimpleKeyValueCondition(k, v);
69 return new KeyValueCondition(k, v, op, considerValAsKey);
70 case LINK:
71 if (considerValAsKey)
72 throw new MapCSSException("''considerValAsKey'' not supported in LINK context");
73 if ("role".equalsIgnoreCase(k))
74 return new RoleCondition(v, op);
75 else if ("index".equalsIgnoreCase(k))
76 return new IndexCondition(v, op);
77 else
78 throw new MapCSSException(
79 MessageFormat.format("Expected key ''role'' or ''index'' in link context. Got ''{0}''.", k));
80
81 default: throw new AssertionError();
82 }
83 }
84
85 /**
86 * Create a condition in which the key and the value need to match a given regexp
87 * @param k The key regexp
88 * @param v The value regexp
89 * @param op The operation to use when comparing the key and the value.
90 * @return The new condition.
91 */
92 public static Condition createRegexpKeyRegexpValueCondition(String k, String v, Op op) {
93 return new RegexpKeyValueRegexpCondition(k, v, op);
94 }
95
96 /**
97 * Creates a condition that checks the given key.
98 * @param k The key to test for
99 * @param not <code>true</code> to invert the match
100 * @param matchType The match type to check for.
101 * @param context The context this rule is found in.
102 * @return the new condition.
103 */
104 public static Condition createKeyCondition(String k, boolean not, KeyMatchType matchType, Context context) {
105 switch (context) {
106 case PRIMITIVE:
107 return new KeyCondition(k, not, matchType);
108 case LINK:
109 if (matchType != null)
110 throw new MapCSSException("Question mark operator ''?'' and regexp match not supported in LINK context");
111 if (not)
112 return new RoleCondition(k, Op.NEQ);
113 else
114 return new RoleCondition(k, Op.EQ);
115
116 default: throw new AssertionError();
117 }
118 }
119
120 /**
121 * Create a new pseudo class condition
122 * @param id The id of the pseudo class
123 * @param not <code>true</code> to invert the condition
124 * @param context The context the class is found in.
125 * @return The new condition
126 */
127 public static PseudoClassCondition createPseudoClassCondition(String id, boolean not, Context context) {
128 return PseudoClassCondition.createPseudoClassCondition(id, not, context);
129 }
130
131 /**
132 * Create a new class condition
133 * @param id The id of the class to match
134 * @param not <code>true</code> to invert the condition
135 * @param context Ignored
136 * @return The new condition
137 */
138 public static ClassCondition createClassCondition(String id, boolean not, Context context) {
139 return new ClassCondition(id, not);
140 }
141
142 /**
143 * Create a new condition that a expression needs to be fulfilled
144 * @param e the expression to check
145 * @param context Ignored
146 * @return The new condition
147 */
148 public static ExpressionCondition createExpressionCondition(Expression e, Context context) {
149 return new ExpressionCondition(e);
150 }
151
152 /**
153 * This is the operation that {@link KeyValueCondition} uses to match.
154 */
155 public enum Op {
156 /** The value equals the given reference. */
157 EQ(Objects::equals),
158 /** The value does not equal the reference. */
159 NEQ(EQ),
160 /** The value is greater than or equal to the given reference value (as float). */
161 GREATER_OR_EQUAL(comparisonResult -> comparisonResult >= 0),
162 /** The value is greater than the given reference value (as float). */
163 GREATER(comparisonResult -> comparisonResult > 0),
164 /** The value is less than or equal to the given reference value (as float). */
165 LESS_OR_EQUAL(comparisonResult -> comparisonResult <= 0),
166 /** The value is less than the given reference value (as float). */
167 LESS(comparisonResult -> comparisonResult < 0),
168 /** The reference is treated as regular expression and the value needs to match it. */
169 REGEX((test, prototype) -> Pattern.compile(prototype).matcher(test).find()),
170 /** The reference is treated as regular expression and the value needs to not match it. */
171 NREGEX(REGEX),
172 /** The reference is treated as a list separated by ';'. Spaces around the ; are ignored.
173 * The value needs to be equal one of the list elements. */
174 ONE_OF((test, prototype) -> OsmUtils.splitMultipleValues(test).anyMatch(prototype::equals)),
175 /** The value needs to begin with the reference string. */
176 BEGINS_WITH(String::startsWith),
177 /** The value needs to end with the reference string. */
178 ENDS_WITH(String::endsWith),
179 /** The value needs to contain the reference string. */
180 CONTAINS(String::contains);
181
182 static final Set<Op> NEGATED_OPS = EnumSet.of(NEQ, NREGEX);
183
184 @SuppressWarnings("ImmutableEnumChecker")
185 private final BiPredicate<String, String> function;
186
187 private final boolean negated;
188
189 /**
190 * Create a new string operation.
191 * @param func The function to apply during {@link #eval(String, String)}.
192 */
193 Op(BiPredicate<String, String> func) {
194 this.function = func;
195 negated = false;
196 }
197
198 /**
199 * Create a new float operation that compares two float values
200 * @param comparatorResult A function to mapt the result of the comparison
201 */
202 Op(IntFunction<Boolean> comparatorResult) {
203 this.function = (test, prototype) -> {
204 float testFloat;
205 try {
206 testFloat = Float.parseFloat(test);
207 } catch (NumberFormatException e) {
208 return Boolean.FALSE;
209 }
210 float prototypeFloat = Float.parseFloat(prototype);
211
212 int res = Float.compare(testFloat, prototypeFloat);
213 return comparatorResult.apply(res);
214 };
215 negated = false;
216 }
217
218 /**
219 * Create a new Op by negating an other op.
220 * @param negate inverse operation
221 */
222 Op(Op negate) {
223 this.function = (a, b) -> !negate.function.test(a, b);
224 negated = true;
225 }
226
227 /**
228 * Evaluates a value against a reference string.
229 * @param testString The value. May be <code>null</code>
230 * @param prototypeString The reference string-
231 * @return <code>true</code> if and only if this operation matches for the given value/reference pair.
232 */
233 public boolean eval(String testString, String prototypeString) {
234 if (testString == null)
235 return negated;
236 else
237 return function.test(testString, prototypeString);
238 }
239 }
240
241 /**
242 * Most common case of a KeyValueCondition, this is the basic key=value case.
243 *
244 * Extra class for performance reasons.
245 */
246 public static class SimpleKeyValueCondition implements Condition, ToTagConvertable {
247 /**
248 * The key to search for.
249 */
250 public final String k;
251 /**
252 * The value to search for.
253 */
254 public final String v;
255
256 /**
257 * Create a new SimpleKeyValueCondition.
258 * @param k The key
259 * @param v The value.
260 */
261 public SimpleKeyValueCondition(String k, String v) {
262 this.k = k.intern();
263 this.v = v.intern();
264 }
265
266 @Override
267 public boolean applies(Environment e) {
268 return v.equals(e.osm.get(k));
269 }
270
271 @Override
272 public Tag asTag(OsmPrimitive primitive) {
273 return new Tag(k, v);
274 }
275
276 @Override
277 public String toString() {
278 return '[' + k + '=' + v + ']';
279 }
280
281 }
282
283 /**
284 * <p>Represents a key/value condition which is either applied to a primitive.</p>
285 *
286 */
287 public static class KeyValueCondition implements Condition, ToTagConvertable {
288 /**
289 * The key to search for.
290 */
291 public final String k;
292 /**
293 * The value to search for.
294 */
295 public final String v;
296 /**
297 * The key/value match operation.
298 */
299 public final Op op;
300 /**
301 * If this flag is set, {@link #v} is treated as a key and the value is the value set for that key.
302 */
303 public final boolean considerValAsKey;
304
305 /**
306 * <p>Creates a key/value-condition.</p>
307 *
308 * @param k the key
309 * @param v the value
310 * @param op the operation
311 * @param considerValAsKey whether to consider {@code v} as another key and compare the values of key {@code k} and key {@code v}.
312 */
313 public KeyValueCondition(String k, String v, Op op, boolean considerValAsKey) {
314 this.k = k.intern();
315 this.v = v.intern();
316 this.op = op;
317 this.considerValAsKey = considerValAsKey;
318 }
319
320 /**
321 * Determines if this condition requires an exact key match.
322 * @return {@code true} if this condition requires an exact key match.
323 * @since 14801
324 */
325 public boolean requiresExactKeyMatch() {
326 return !Op.NEGATED_OPS.contains(op);
327 }
328
329 @Override
330 public boolean applies(Environment env) {
331 return op.eval(env.osm.get(k), considerValAsKey ? env.osm.get(v) : v);
332 }
333
334 @Override
335 public Tag asTag(OsmPrimitive primitive) {
336 return new Tag(k, v);
337 }
338
339 @Override
340 public String toString() {
341 return '[' + k + '\'' + op + '\'' + v + ']';
342 }
343 }
344
345 /**
346 * This condition requires a fixed key to match a given regexp
347 */
348 public static class KeyValueRegexpCondition extends KeyValueCondition {
349 protected static final Set<Op> SUPPORTED_OPS = EnumSet.of(Op.REGEX, Op.NREGEX);
350
351 final Pattern pattern;
352
353 /**
354 * Constructs a new {@code KeyValueRegexpCondition}.
355 * @param k key
356 * @param v value
357 * @param op operation
358 * @param considerValAsKey must be false
359 * @throws PatternSyntaxException if the value syntax is invalid
360 */
361 public KeyValueRegexpCondition(String k, String v, Op op, boolean considerValAsKey) {
362 super(k, v, op, considerValAsKey); /* value is needed in validator messages */
363 CheckParameterUtil.ensureThat(!considerValAsKey, "considerValAsKey is not supported");
364 CheckParameterUtil.ensureThat(SUPPORTED_OPS.contains(op), "Op must be REGEX or NREGEX");
365 this.pattern = Pattern.compile(v);
366 }
367
368 protected boolean matches(Environment env) {
369 final String value = env.osm.get(k);
370 return value != null && pattern.matcher(value).find();
371 }
372
373 @Override
374 public boolean applies(Environment env) {
375 if (Op.REGEX == op) {
376 return matches(env);
377 } else if (Op.NREGEX == op) {
378 return !matches(env);
379 } else {
380 throw new IllegalStateException();
381 }
382 }
383 }
384
385 /**
386 * A condition that checks that a key with the matching pattern has a value with the matching pattern.
387 */
388 public static class RegexpKeyValueRegexpCondition extends KeyValueRegexpCondition {
389
390 final Pattern keyPattern;
391
392 /**
393 * Create a condition in which the key and the value need to match a given regexp
394 * @param k The key regexp
395 * @param v The value regexp
396 * @param op The operation to use when comparing the key and the value.
397 */
398 public RegexpKeyValueRegexpCondition(String k, String v, Op op) {
399 super(k, v, op, false);
400 this.keyPattern = Pattern.compile(k);
401 }
402
403 @Override
404 public boolean requiresExactKeyMatch() {
405 return false;
406 }
407
408 @Override
409 protected boolean matches(Environment env) {
410 return env.osm.getKeys().entrySet().stream()
411 .anyMatch(kv -> keyPattern.matcher(kv.getKey()).find() && pattern.matcher(kv.getValue()).find());
412 }
413 }
414
415 /**
416 * Role condition.
417 */
418 public static class RoleCondition implements Condition {
419 final String role;
420 final Op op;
421
422 /**
423 * Constructs a new {@code RoleCondition}.
424 * @param role role
425 * @param op operation
426 */
427 public RoleCondition(String role, Op op) {
428 this.role = role;
429 this.op = op;
430 }
431
432 @Override
433 public boolean applies(Environment env) {
434 String testRole = env.getRole();
435 if (testRole == null) return false;
436 return op.eval(testRole, role);
437 }
438 }
439
440 /**
441 * Index condition.
442 */
443 public static class IndexCondition implements Condition {
444 final String index;
445 final Op op;
446 final boolean isFirstOrLast;
447
448 /**
449 * Constructs a new {@code IndexCondition}.
450 * @param index index
451 * @param op operation
452 */
453 public IndexCondition(String index, Op op) {
454 this.index = index;
455 this.op = op;
456 isFirstOrLast = op == Op.EQ && ("1".equals(index) || "-1".equals(index));
457 }
458
459 @Override
460 public boolean applies(Environment env) {
461 if (env.index == null) return false;
462 if (index.startsWith("-")) {
463 return env.count != null && op.eval(Integer.toString(env.index - env.count), index);
464 } else {
465 return op.eval(Integer.toString(env.index + 1), index);
466 }
467 }
468 }
469
470 /**
471 * This defines how {@link KeyCondition} matches a given key.
472 */
473 public enum KeyMatchType {
474 /**
475 * The key needs to be equal to the given label.
476 */
477 EQ,
478 /**
479 * The key needs to have a true value (yes, ...)
480 * @see OsmUtils#isTrue(String)
481 */
482 TRUE,
483 /**
484 * The key needs to have a false value (no, ...)
485 * @see OsmUtils#isFalse(String)
486 */
487 FALSE,
488 /**
489 * The key needs to match the given regular expression.
490 */
491 REGEX
492 }
493
494 /**
495 * <p>KeyCondition represent one of the following conditions in either the link or the
496 * primitive context:</p>
497 * <pre>
498 * ["a label"] PRIMITIVE: the primitive has a tag "a label"
499 * LINK: the parent is a relation and it has at least one member with the role
500 * "a label" referring to the child
501 *
502 * [!"a label"] PRIMITIVE: the primitive doesn't have a tag "a label"
503 * LINK: the parent is a relation but doesn't have a member with the role
504 * "a label" referring to the child
505 *
506 * ["a label"?] PRIMITIVE: the primitive has a tag "a label" whose value evaluates to a true-value
507 * LINK: not supported
508 *
509 * ["a label"?!] PRIMITIVE: the primitive has a tag "a label" whose value evaluates to a false-value
510 * LINK: not supported
511 * </pre>
512 */
513 public static class KeyCondition implements Condition, ToTagConvertable {
514
515 /**
516 * The key name.
517 */
518 public final String label;
519 /**
520 * If we should negate the result of the match.
521 */
522 public final boolean negateResult;
523 /**
524 * Describes how to match the label against the key.
525 * @see KeyMatchType
526 */
527 public final KeyMatchType matchType;
528 /**
529 * A predicate used to match a the regexp against the key. Only used if the match type is regexp.
530 */
531 public final Predicate<String> containsPattern;
532
533 /**
534 * Creates a new KeyCondition
535 * @param label The key name (or regexp) to use.
536 * @param negateResult If we should negate the result.,
537 * @param matchType The match type.
538 */
539 public KeyCondition(String label, boolean negateResult, KeyMatchType matchType) {
540 this.label = label;
541 this.negateResult = negateResult;
542 this.matchType = matchType == null ? KeyMatchType.EQ : matchType;
543 this.containsPattern = KeyMatchType.REGEX == matchType
544 ? Pattern.compile(label).asPredicate()
545 : null;
546 }
547
548 @Override
549 public boolean applies(Environment e) {
550 switch(e.getContext()) {
551 case PRIMITIVE:
552 switch (matchType) {
553 case TRUE:
554 return e.osm.isKeyTrue(label) ^ negateResult;
555 case FALSE:
556 return e.osm.isKeyFalse(label) ^ negateResult;
557 case REGEX:
558 return e.osm.keySet().stream().anyMatch(containsPattern) ^ negateResult;
559 default:
560 return e.osm.hasKey(label) ^ negateResult;
561 }
562 case LINK:
563 Utils.ensure(false, "Illegal state: KeyCondition not supported in LINK context");
564 return false;
565 default: throw new AssertionError();
566 }
567 }
568
569 /**
570 * Get the matched key and the corresponding value.
571 * <p>
572 * WARNING: This ignores {@link #negateResult}.
573 * <p>
574 * WARNING: For regexp, the regular expression is returned instead of a key if the match failed.
575 * @param p The primitive to get the value from.
576 * @return The tag.
577 */
578 @Override
579 public Tag asTag(OsmPrimitive p) {
580 String key = label;
581 if (KeyMatchType.REGEX == matchType) {
582 key = p.keySet().stream().filter(containsPattern).findAny().orElse(key);
583 }
584 return new Tag(key, p.get(key));
585 }
586
587 @Override
588 public String toString() {
589 return '[' + (negateResult ? "!" : "") + label + ']';
590 }
591 }
592
593 /**
594 * Class condition.
595 */
596 public static class ClassCondition implements Condition {
597
598 /** Class identifier */
599 public final String id;
600 final boolean not;
601
602 /**
603 * Constructs a new {@code ClassCondition}.
604 * @param id id
605 * @param not negation or not
606 */
607 public ClassCondition(String id, boolean not) {
608 this.id = id;
609 this.not = not;
610 }
611
612 @Override
613 public boolean applies(Environment env) {
614 Cascade cascade = env.getCascade(env.layer);
615 return cascade != null && (not ^ cascade.containsKey(id));
616 }
617
618 @Override
619 public String toString() {
620 return (not ? "!" : "") + '.' + id;
621 }
622 }
623
624 /**
625 * Like <a href="http://www.w3.org/TR/css3-selectors/#pseudo-classes">CSS pseudo classes</a>, MapCSS pseudo classes
626 * are written in lower case with dashes between words.
627 */
628 public static final class PseudoClasses {
629
630 private PseudoClasses() {
631 // Hide default constructor for utilities classes
632 }
633
634 /**
635 * {@code closed} tests whether the way is closed or the relation is a closed multipolygon
636 * @param e MapCSS environment
637 * @return {@code true} if the way is closed or the relation is a closed multipolygon
638 */
639 static boolean closed(Environment e) { // NO_UCD (unused code)
640 if (e.osm instanceof IWay<?> && ((IWay<?>) e.osm).isClosed())
641 return true;
642 return e.osm instanceof IRelation<?> && ((IRelation<?>) e.osm).isMultipolygon();
643 }
644
645 /**
646 * {@code :modified} tests whether the object has been modified.
647 * @param e MapCSS environment
648 * @return {@code true} if the object has been modified
649 * @see IPrimitive#isModified()
650 */
651 static boolean modified(Environment e) { // NO_UCD (unused code)
652 return e.osm.isModified() || e.osm.isNewOrUndeleted();
653 }
654
655 /**
656 * {@code ;new} tests whether the object is new.
657 * @param e MapCSS environment
658 * @return {@code true} if the object is new
659 * @see IPrimitive#isNew()
660 */
661 static boolean _new(Environment e) { // NO_UCD (unused code)
662 return e.osm.isNew();
663 }
664
665 /**
666 * {@code :connection} tests whether the object is a connection node.
667 * @param e MapCSS environment
668 * @return {@code true} if the object is a connection node
669 * @see Node#isConnectionNode()
670 */
671 static boolean connection(Environment e) { // NO_UCD (unused code)
672 return e.osm instanceof INode && e.osm.getDataSet() != null && ((INode) e.osm).isConnectionNode();
673 }
674
675 /**
676 * {@code :tagged} tests whether the object is tagged.
677 * @param e MapCSS environment
678 * @return {@code true} if the object is tagged
679 * @see IPrimitive#isTagged()
680 */
681 static boolean tagged(Environment e) { // NO_UCD (unused code)
682 return e.osm.isTagged();
683 }
684
685 /**
686 * {@code :same-tags} tests whether the object has the same tags as its child/parent.
687 * @param e MapCSS environment
688 * @return {@code true} if the object has the same tags as its child/parent
689 * @see IPrimitive#hasSameInterestingTags(IPrimitive)
690 */
691 static boolean sameTags(Environment e) { // NO_UCD (unused code)
692 return e.osm.hasSameInterestingTags(Utils.firstNonNull(e.child, e.parent));
693 }
694
695 /**
696 * {@code :area-style} tests whether the object has an area style. This is useful for validators.
697 * @param e MapCSS environment
698 * @return {@code true} if the object has an area style
699 * @see ElemStyles#hasAreaElemStyle(IPrimitive, boolean)
700 */
701 static boolean areaStyle(Environment e) { // NO_UCD (unused code)
702 // only for validator
703 return ElemStyles.hasAreaElemStyle(e.osm, false);
704 }
705
706 /**
707 * {@code unconnected}: tests whether the object is a unconnected node.
708 * @param e MapCSS environment
709 * @return {@code true} if the object is a unconnected node
710 */
711 static boolean unconnected(Environment e) { // NO_UCD (unused code)
712 return e.osm instanceof Node && ((Node) e.osm).getParentWays().isEmpty();
713 }
714
715 /**
716 * {@code righthandtraffic} checks if there is right-hand traffic at the current location.
717 * @param e MapCSS environment
718 * @return {@code true} if there is right-hand traffic at the current location
719 * @see Functions#is_right_hand_traffic(Environment)
720 */
721 static boolean righthandtraffic(Environment e) { // NO_UCD (unused code)
722 return Functions.is_right_hand_traffic(e);
723 }
724
725 /**
726 * {@code clockwise} whether the way is closed and oriented clockwise,
727 * or non-closed and the 1st, 2nd and last node are in clockwise order.
728 * @param e MapCSS environment
729 * @return {@code true} if the way clockwise
730 * @see Functions#is_clockwise(Environment)
731 */
732 static boolean clockwise(Environment e) { // NO_UCD (unused code)
733 return Functions.is_clockwise(e);
734 }
735
736 /**
737 * {@code anticlockwise} whether the way is closed and oriented anticlockwise,
738 * or non-closed and the 1st, 2nd and last node are in anticlockwise order.
739 * @param e MapCSS environment
740 * @return {@code true} if the way clockwise
741 * @see Functions#is_anticlockwise(Environment)
742 */
743 static boolean anticlockwise(Environment e) { // NO_UCD (unused code)
744 return Functions.is_anticlockwise(e);
745 }
746
747 /**
748 * {@code unclosed-multipolygon} tests whether the object is an unclosed multipolygon.
749 * @param e MapCSS environment
750 * @return {@code true} if the object is an unclosed multipolygon
751 */
752 static boolean unclosed_multipolygon(Environment e) { // NO_UCD (unused code)
753 return e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon() &&
754 !e.osm.isIncomplete() && !((Relation) e.osm).hasIncompleteMembers() &&
755 !MultipolygonCache.getInstance().get((Relation) e.osm).getOpenEnds().isEmpty();
756 }
757
758 private static final Predicate<OsmPrimitive> IN_DOWNLOADED_AREA = new InDataSourceArea(false);
759
760 /**
761 * {@code in-downloaded-area} tests whether the object is within source area ("downloaded area").
762 * @param e MapCSS environment
763 * @return {@code true} if the object is within source area ("downloaded area")
764 * @see InDataSourceArea
765 */
766 static boolean inDownloadedArea(Environment e) { // NO_UCD (unused code)
767 return e.osm instanceof OsmPrimitive && IN_DOWNLOADED_AREA.test((OsmPrimitive) e.osm);
768 }
769
770 static boolean completely_downloaded(Environment e) { // NO_UCD (unused code)
771 if (e.osm instanceof IRelation<?>) {
772 return !((IRelation<?>) e.osm).hasIncompleteMembers();
773 } else {
774 return true;
775 }
776 }
777
778 static boolean closed2(Environment e) { // NO_UCD (unused code)
779 if (e.osm instanceof IWay<?> && ((IWay<?>) e.osm).isClosed())
780 return true;
781 if (e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon()) {
782 Multipolygon multipolygon = MultipolygonCache.getInstance().get((Relation) e.osm);
783 return multipolygon != null && multipolygon.getOpenEnds().isEmpty();
784 }
785 return false;
786 }
787
788 static boolean selected(Environment e) { // NO_UCD (unused code)
789 if (e.mc != null) {
790 e.mc.getCascade(e.layer).setDefaultSelectedHandling(false);
791 }
792 return e.osm.isSelected();
793 }
794 }
795
796 /**
797 * Pseudo class condition.
798 */
799 public static class PseudoClassCondition implements Condition {
800
801 final Method method;
802 final boolean not;
803
804 protected PseudoClassCondition(Method method, boolean not) {
805 this.method = method;
806 this.not = not;
807 }
808
809 /**
810 * Create a new pseudo class condition
811 * @param id The id of the pseudo class
812 * @param not <code>true</code> to invert the condition
813 * @param context The context the class is found in.
814 * @return The new condition
815 */
816 public static PseudoClassCondition createPseudoClassCondition(String id, boolean not, Context context) {
817 CheckParameterUtil.ensureThat(!"sameTags".equals(id) || Context.LINK == context, "sameTags only supported in LINK context");
818 if ("open_end".equals(id)) {
819 return new OpenEndPseudoClassCondition(not);
820 }
821 final Method method = getMethod(id);
822 if (method != null) {
823 return new PseudoClassCondition(method, not);
824 }
825 throw new MapCSSException("Invalid pseudo class specified: " + id);
826 }
827
828 protected static Method getMethod(String id) {
829 String cleanId = clean(id);
830 return Arrays.stream(PseudoClasses.class.getDeclaredMethods())
831 .filter(method -> clean(method.getName()).equalsIgnoreCase(cleanId))
832 .findFirst().orElse(null);
833 }
834
835 private static String clean(String id) {
836 // for backwards compatibility, consider :sameTags == :same-tags == :same_tags (#11150)
837 return id.replaceAll("[-_]", "");
838 }
839
840 @Override
841 public boolean applies(Environment e) {
842 try {
843 return not ^ (Boolean) method.invoke(null, e);
844 } catch (ReflectiveOperationException ex) {
845 throw new JosmRuntimeException(ex);
846 }
847 }
848
849 @Override
850 public String toString() {
851 return (not ? "!" : "") + ':' + method.getName();
852 }
853 }
854
855 /**
856 * Open end pseudo class condition.
857 */
858 public static class OpenEndPseudoClassCondition extends PseudoClassCondition {
859 /**
860 * Constructs a new {@code OpenEndPseudoClassCondition}.
861 * @param not negation or not
862 */
863 public OpenEndPseudoClassCondition(boolean not) {
864 super(null, not);
865 }
866
867 @Override
868 public boolean applies(Environment e) {
869 return true;
870 }
871 }
872
873 /**
874 * A condition that is fulfilled whenever the expression is evaluated to be true.
875 */
876 public static class ExpressionCondition implements Condition {
877
878 final Expression e;
879
880 /**
881 * Constructs a new {@code ExpressionFactory}
882 * @param e expression
883 */
884 public ExpressionCondition(Expression e) {
885 this.e = e;
886 }
887
888 /**
889 * Returns the expression.
890 * @return the expression
891 * @since 14484
892 */
893 public final Expression getExpression() {
894 return e;
895 }
896
897 @Override
898 public boolean applies(Environment env) {
899 Boolean b = Cascade.convertTo(e.evaluate(env), Boolean.class);
900 return b != null && b;
901 }
902
903 @Override
904 public String toString() {
905 return '[' + e.toString() + ']';
906 }
907 }
908}
Note: See TracBrowser for help on using the repository browser.