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

Last change on this file since 14484 was 14484, checked in by Don-vip, 5 years ago

fix #17058 - Cannot add assertMatch/assertNoMatch declarations with inside() selector

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