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

Last change on this file since 16287 was 16287, checked in by Klumbumbus, 4 years ago

see #18802, fix #19069 - Restore display of values from selectors with regexp in validator messages

  • Property svn:eol-style set to native
File size: 32.3 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.INode;
18import org.openstreetmap.josm.data.osm.IPrimitive;
19import org.openstreetmap.josm.data.osm.IRelation;
20import org.openstreetmap.josm.data.osm.IWay;
21import org.openstreetmap.josm.data.osm.Node;
22import org.openstreetmap.josm.data.osm.OsmPrimitive;
23import org.openstreetmap.josm.data.osm.OsmUtils;
24import org.openstreetmap.josm.data.osm.Relation;
25import org.openstreetmap.josm.data.osm.Tag;
26import org.openstreetmap.josm.data.osm.search.SearchCompiler.InDataSourceArea;
27import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
28import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
29import org.openstreetmap.josm.gui.mappaint.Cascade;
30import org.openstreetmap.josm.gui.mappaint.ElemStyles;
31import org.openstreetmap.josm.gui.mappaint.Environment;
32import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.Context;
33import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.ToTagConvertable;
34import org.openstreetmap.josm.tools.CheckParameterUtil;
35import org.openstreetmap.josm.tools.JosmRuntimeException;
36import org.openstreetmap.josm.tools.Utils;
37
38/**
39 * Factory to generate {@link Condition}s.
40 * @since 10837 (Extracted from Condition)
41 */
42public final class ConditionFactory {
43
44 private ConditionFactory() {
45 // Hide default constructor for utils classes
46 }
47
48 /**
49 * Create a new condition that checks the key and the value of the object.
50 * @param k The key.
51 * @param v The reference value
52 * @param op The operation to use when comparing the value
53 * @param context The type of context to use.
54 * @param considerValAsKey whether to consider {@code v} as another key and compare the values of key {@code k} and key {@code v}.
55 * @return The new condition.
56 * @throws MapCSSException if the arguments are incorrect
57 */
58 public static Condition createKeyValueCondition(String k, String v, Op op, Context context, boolean considerValAsKey) {
59 switch (context) {
60 case PRIMITIVE:
61 if (KeyValueRegexpCondition.SUPPORTED_OPS.contains(op) && !considerValAsKey) {
62 try {
63 return new KeyValueRegexpCondition(k, v, op, false);
64 } catch (PatternSyntaxException e) {
65 throw new MapCSSException(e);
66 }
67 }
68 if (!considerValAsKey && op == Op.EQ)
69 return new SimpleKeyValueCondition(k, v);
70 return new KeyValueCondition(k, v, op, considerValAsKey);
71 case LINK:
72 if (considerValAsKey)
73 throw new MapCSSException("''considerValAsKey'' not supported in LINK context");
74 if ("role".equalsIgnoreCase(k))
75 return new RoleCondition(v, op);
76 else if ("index".equalsIgnoreCase(k))
77 return new IndexCondition(v, op);
78 else
79 throw new MapCSSException(
80 MessageFormat.format("Expected key ''role'' or ''index'' in link context. Got ''{0}''.", k));
81
82 default: throw new AssertionError();
83 }
84 }
85
86 /**
87 * Create a condition in which the key and the value need to match a given regexp
88 * @param k The key regexp
89 * @param v The value regexp
90 * @param op The operation to use when comparing the key and the value.
91 * @return The new condition.
92 */
93 public static Condition createRegexpKeyRegexpValueCondition(String k, String v, Op op) {
94 return new RegexpKeyValueRegexpCondition(k, v, op);
95 }
96
97 /**
98 * Creates a condition that checks the given key.
99 * @param k The key to test for
100 * @param not <code>true</code> to invert the match
101 * @param matchType The match type to check for.
102 * @param context The context this rule is found in.
103 * @return the new condition.
104 */
105 public static Condition createKeyCondition(String k, boolean not, KeyMatchType matchType, Context context) {
106 switch (context) {
107 case PRIMITIVE:
108 return new KeyCondition(k, not, matchType);
109 case LINK:
110 if (matchType != null)
111 throw new MapCSSException("Question mark operator ''?'' and regexp match not supported in LINK context");
112 if (not)
113 return new RoleCondition(k, Op.NEQ);
114 else
115 return new RoleCondition(k, Op.EQ);
116
117 default: throw new AssertionError();
118 }
119 }
120
121 /**
122 * Create a new pseudo class condition
123 * @param id The id of the pseudo class
124 * @param not <code>true</code> to invert the condition
125 * @param context The context the class is found in.
126 * @return The new condition
127 */
128 public static PseudoClassCondition createPseudoClassCondition(String id, boolean not, Context context) {
129 return PseudoClassCondition.createPseudoClassCondition(id, not, context);
130 }
131
132 /**
133 * Create a new class condition
134 * @param id The id of the class to match
135 * @param not <code>true</code> to invert the condition
136 * @param context Ignored
137 * @return The new condition
138 */
139 public static ClassCondition createClassCondition(String id, boolean not, Context context) {
140 return new ClassCondition(id, not);
141 }
142
143 /**
144 * Create a new condition that a expression needs to be fulfilled
145 * @param e the expression to check
146 * @param context Ignored
147 * @return The new condition
148 */
149 public static ExpressionCondition createExpressionCondition(Expression e, Context context) {
150 return new ExpressionCondition(e);
151 }
152
153 /**
154 * This is the operation that {@link KeyValueCondition} uses to match.
155 */
156 public enum Op {
157 /** The value equals the given reference. */
158 EQ(Objects::equals),
159 /** The value does not equal the reference. */
160 NEQ(EQ),
161 /** The value is greater than or equal to the given reference value (as float). */
162 GREATER_OR_EQUAL(comparisonResult -> comparisonResult >= 0),
163 /** The value is greater than the given reference value (as float). */
164 GREATER(comparisonResult -> comparisonResult > 0),
165 /** The value is less than or equal to the given reference value (as float). */
166 LESS_OR_EQUAL(comparisonResult -> comparisonResult <= 0),
167 /** The value is less than the given reference value (as float). */
168 LESS(comparisonResult -> comparisonResult < 0),
169 /** The reference is treated as regular expression and the value needs to match it. */
170 REGEX((test, prototype) -> Pattern.compile(prototype).matcher(test).find()),
171 /** The reference is treated as regular expression and the value needs to not match it. */
172 NREGEX(REGEX),
173 /** The reference is treated as a list separated by ';'. Spaces around the ; are ignored.
174 * The value needs to be equal one of the list elements. */
175 ONE_OF((test, prototype) -> OsmUtils.splitMultipleValues(test).anyMatch(prototype::equals)),
176 /** The value needs to begin with the reference string. */
177 BEGINS_WITH(String::startsWith),
178 /** The value needs to end with the reference string. */
179 ENDS_WITH(String::endsWith),
180 /** The value needs to contain the reference string. */
181 CONTAINS(String::contains);
182
183 static final Set<Op> NEGATED_OPS = EnumSet.of(NEQ, NREGEX);
184
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 for (Map.Entry<String, String> kv: env.osm.getKeys().entrySet()) {
411 if (keyPattern.matcher(kv.getKey()).find() && pattern.matcher(kv.getValue()).find()) {
412 return true;
413 }
414 }
415 return false;
416 }
417 }
418
419 /**
420 * Role condition.
421 */
422 public static class RoleCondition implements Condition {
423 final String role;
424 final Op op;
425
426 /**
427 * Constructs a new {@code RoleCondition}.
428 * @param role role
429 * @param op operation
430 */
431 public RoleCondition(String role, Op op) {
432 this.role = role;
433 this.op = op;
434 }
435
436 @Override
437 public boolean applies(Environment env) {
438 String testRole = env.getRole();
439 if (testRole == null) return false;
440 return op.eval(testRole, role);
441 }
442 }
443
444 /**
445 * Index condition.
446 */
447 public static class IndexCondition implements Condition {
448 final String index;
449 final Op op;
450 final boolean isFirstOrLast;
451
452 /**
453 * Constructs a new {@code IndexCondition}.
454 * @param index index
455 * @param op operation
456 */
457 public IndexCondition(String index, Op op) {
458 this.index = index;
459 this.op = op;
460 isFirstOrLast = op == Op.EQ && ("1".equals(index) || "-1".equals(index));
461 }
462
463 @Override
464 public boolean applies(Environment env) {
465 if (env.index == null) return false;
466 if (index.startsWith("-")) {
467 return env.count != null && op.eval(Integer.toString(env.index - env.count), index);
468 } else {
469 return op.eval(Integer.toString(env.index + 1), index);
470 }
471 }
472 }
473
474 /**
475 * This defines how {@link KeyCondition} matches a given key.
476 */
477 public enum KeyMatchType {
478 /**
479 * The key needs to be equal to the given label.
480 */
481 EQ,
482 /**
483 * The key needs to have a true value (yes, ...)
484 * @see OsmUtils#isTrue(String)
485 */
486 TRUE,
487 /**
488 * The key needs to have a false value (no, ...)
489 * @see OsmUtils#isFalse(String)
490 */
491 FALSE,
492 /**
493 * The key needs to match the given regular expression.
494 */
495 REGEX
496 }
497
498 /**
499 * <p>KeyCondition represent one of the following conditions in either the link or the
500 * primitive context:</p>
501 * <pre>
502 * ["a label"] PRIMITIVE: the primitive has a tag "a label"
503 * LINK: the parent is a relation and it has at least one member with the role
504 * "a label" referring to the child
505 *
506 * [!"a label"] PRIMITIVE: the primitive doesn't have a tag "a label"
507 * LINK: the parent is a relation but doesn't have a member with the role
508 * "a label" referring to the child
509 *
510 * ["a label"?] PRIMITIVE: the primitive has a tag "a label" whose value evaluates to a true-value
511 * LINK: not supported
512 *
513 * ["a label"?!] PRIMITIVE: the primitive has a tag "a label" whose value evaluates to a false-value
514 * LINK: not supported
515 * </pre>
516 */
517 public static class KeyCondition implements Condition, ToTagConvertable {
518
519 /**
520 * The key name.
521 */
522 public final String label;
523 /**
524 * If we should negate the result of the match.
525 */
526 public final boolean negateResult;
527 /**
528 * Describes how to match the label against the key.
529 * @see KeyMatchType
530 */
531 public final KeyMatchType matchType;
532 /**
533 * A predicate used to match a the regexp against the key. Only used if the match type is regexp.
534 */
535 public final Predicate<String> containsPattern;
536
537 /**
538 * Creates a new KeyCondition
539 * @param label The key name (or regexp) to use.
540 * @param negateResult If we should negate the result.,
541 * @param matchType The match type.
542 */
543 public KeyCondition(String label, boolean negateResult, KeyMatchType matchType) {
544 this.label = label;
545 this.negateResult = negateResult;
546 this.matchType = matchType == null ? KeyMatchType.EQ : matchType;
547 this.containsPattern = KeyMatchType.REGEX == matchType
548 ? Pattern.compile(label).asPredicate()
549 : null;
550 }
551
552 @Override
553 public boolean applies(Environment e) {
554 switch(e.getContext()) {
555 case PRIMITIVE:
556 switch (matchType) {
557 case TRUE:
558 return e.osm.isKeyTrue(label) ^ negateResult;
559 case FALSE:
560 return e.osm.isKeyFalse(label) ^ negateResult;
561 case REGEX:
562 return e.osm.keySet().stream().anyMatch(containsPattern) ^ negateResult;
563 default:
564 return e.osm.hasKey(label) ^ negateResult;
565 }
566 case LINK:
567 Utils.ensure(false, "Illegal state: KeyCondition not supported in LINK context");
568 return false;
569 default: throw new AssertionError();
570 }
571 }
572
573 /**
574 * Get the matched key and the corresponding value.
575 * <p>
576 * WARNING: This ignores {@link #negateResult}.
577 * <p>
578 * WARNING: For regexp, the regular expression is returned instead of a key if the match failed.
579 * @param p The primitive to get the value from.
580 * @return The tag.
581 */
582 @Override
583 public Tag asTag(OsmPrimitive p) {
584 String key = label;
585 if (KeyMatchType.REGEX == matchType) {
586 key = p.keySet().stream().filter(containsPattern).findAny().orElse(key);
587 }
588 return new Tag(key, p.get(key));
589 }
590
591 @Override
592 public String toString() {
593 return '[' + (negateResult ? "!" : "") + label + ']';
594 }
595 }
596
597 /**
598 * Class condition.
599 */
600 public static class ClassCondition implements Condition {
601
602 /** Class identifier */
603 public final String id;
604 final boolean not;
605
606 /**
607 * Constructs a new {@code ClassCondition}.
608 * @param id id
609 * @param not negation or not
610 */
611 public ClassCondition(String id, boolean not) {
612 this.id = id;
613 this.not = not;
614 }
615
616 @Override
617 public boolean applies(Environment env) {
618 Cascade cascade = env.getCascade(env.layer);
619 return cascade != null && (not ^ cascade.containsKey(id));
620 }
621
622 @Override
623 public String toString() {
624 return (not ? "!" : "") + '.' + id;
625 }
626 }
627
628 /**
629 * Like <a href="http://www.w3.org/TR/css3-selectors/#pseudo-classes">CSS pseudo classes</a>, MapCSS pseudo classes
630 * are written in lower case with dashes between words.
631 */
632 public static final class PseudoClasses {
633
634 private PseudoClasses() {
635 // Hide default constructor for utilities classes
636 }
637
638 /**
639 * {@code closed} tests whether the way is closed or the relation is a closed multipolygon
640 * @param e MapCSS environment
641 * @return {@code true} if the way is closed or the relation is a closed multipolygon
642 */
643 static boolean closed(Environment e) { // NO_UCD (unused code)
644 if (e.osm instanceof IWay<?> && ((IWay<?>) e.osm).isClosed())
645 return true;
646 return e.osm instanceof IRelation<?> && ((IRelation<?>) e.osm).isMultipolygon();
647 }
648
649 /**
650 * {@code :modified} tests whether the object has been modified.
651 * @param e MapCSS environment
652 * @return {@code true} if the object has been modified
653 * @see IPrimitive#isModified()
654 */
655 static boolean modified(Environment e) { // NO_UCD (unused code)
656 return e.osm.isModified() || e.osm.isNewOrUndeleted();
657 }
658
659 /**
660 * {@code ;new} tests whether the object is new.
661 * @param e MapCSS environment
662 * @return {@code true} if the object is new
663 * @see IPrimitive#isNew()
664 */
665 static boolean _new(Environment e) { // NO_UCD (unused code)
666 return e.osm.isNew();
667 }
668
669 /**
670 * {@code :connection} tests whether the object is a connection node.
671 * @param e MapCSS environment
672 * @return {@code true} if the object is a connection node
673 * @see Node#isConnectionNode()
674 */
675 static boolean connection(Environment e) { // NO_UCD (unused code)
676 return e.osm instanceof INode && e.osm.getDataSet() != null && ((INode) e.osm).isConnectionNode();
677 }
678
679 /**
680 * {@code :tagged} tests whether the object is tagged.
681 * @param e MapCSS environment
682 * @return {@code true} if the object is tagged
683 * @see IPrimitive#isTagged()
684 */
685 static boolean tagged(Environment e) { // NO_UCD (unused code)
686 return e.osm.isTagged();
687 }
688
689 /**
690 * {@code :same-tags} tests whether the object has the same tags as its child/parent.
691 * @param e MapCSS environment
692 * @return {@code true} if the object has the same tags as its child/parent
693 * @see IPrimitive#hasSameInterestingTags(IPrimitive)
694 */
695 static boolean sameTags(Environment e) { // NO_UCD (unused code)
696 return e.osm.hasSameInterestingTags(Utils.firstNonNull(e.child, e.parent));
697 }
698
699 /**
700 * {@code :area-style} tests whether the object has an area style. This is useful for validators.
701 * @param e MapCSS environment
702 * @return {@code true} if the object has an area style
703 * @see ElemStyles#hasAreaElemStyle(IPrimitive, boolean)
704 */
705 static boolean areaStyle(Environment e) { // NO_UCD (unused code)
706 // only for validator
707 return ElemStyles.hasAreaElemStyle(e.osm, false);
708 }
709
710 /**
711 * {@code unconnected}: tests whether the object is a unconnected node.
712 * @param e MapCSS environment
713 * @return {@code true} if the object is a unconnected node
714 */
715 static boolean unconnected(Environment e) { // NO_UCD (unused code)
716 return e.osm instanceof Node && ((Node) e.osm).getParentWays().isEmpty();
717 }
718
719 /**
720 * {@code righthandtraffic} checks if there is right-hand traffic at the current location.
721 * @param e MapCSS environment
722 * @return {@code true} if there is right-hand traffic at the current location
723 * @see Functions#is_right_hand_traffic(Environment)
724 */
725 static boolean righthandtraffic(Environment e) { // NO_UCD (unused code)
726 return Functions.is_right_hand_traffic(e);
727 }
728
729 /**
730 * {@code clockwise} whether the way is closed and oriented clockwise,
731 * or non-closed and the 1st, 2nd and last node are in clockwise order.
732 * @param e MapCSS environment
733 * @return {@code true} if the way clockwise
734 * @see Functions#is_clockwise(Environment)
735 */
736 static boolean clockwise(Environment e) { // NO_UCD (unused code)
737 return Functions.is_clockwise(e);
738 }
739
740 /**
741 * {@code anticlockwise} whether the way is closed and oriented anticlockwise,
742 * or non-closed and the 1st, 2nd and last node are in anticlockwise order.
743 * @param e MapCSS environment
744 * @return {@code true} if the way clockwise
745 * @see Functions#is_anticlockwise(Environment)
746 */
747 static boolean anticlockwise(Environment e) { // NO_UCD (unused code)
748 return Functions.is_anticlockwise(e);
749 }
750
751 /**
752 * {@code unclosed-multipolygon} tests whether the object is an unclosed multipolygon.
753 * @param e MapCSS environment
754 * @return {@code true} if the object is an unclosed multipolygon
755 */
756 static boolean unclosed_multipolygon(Environment e) { // NO_UCD (unused code)
757 return e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon() &&
758 !e.osm.isIncomplete() && !((Relation) e.osm).hasIncompleteMembers() &&
759 !MultipolygonCache.getInstance().get((Relation) e.osm).getOpenEnds().isEmpty();
760 }
761
762 private static final Predicate<OsmPrimitive> IN_DOWNLOADED_AREA = new InDataSourceArea(false);
763
764 /**
765 * {@code in-downloaded-area} tests whether the object is within source area ("downloaded area").
766 * @param e MapCSS environment
767 * @return {@code true} if the object is within source area ("downloaded area")
768 * @see InDataSourceArea
769 */
770 static boolean inDownloadedArea(Environment e) { // NO_UCD (unused code)
771 return e.osm instanceof OsmPrimitive && IN_DOWNLOADED_AREA.test((OsmPrimitive) e.osm);
772 }
773
774 static boolean completely_downloaded(Environment e) { // NO_UCD (unused code)
775 if (e.osm instanceof IRelation<?>) {
776 return !((IRelation<?>) e.osm).hasIncompleteMembers();
777 } else {
778 return true;
779 }
780 }
781
782 static boolean closed2(Environment e) { // NO_UCD (unused code)
783 if (e.osm instanceof IWay<?> && ((IWay<?>) e.osm).isClosed())
784 return true;
785 if (e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon()) {
786 Multipolygon multipolygon = MultipolygonCache.getInstance().get((Relation) e.osm);
787 return multipolygon != null && multipolygon.getOpenEnds().isEmpty();
788 }
789 return false;
790 }
791
792 static boolean selected(Environment e) { // NO_UCD (unused code)
793 if (e.mc != null) {
794 e.mc.getCascade(e.layer).setDefaultSelectedHandling(false);
795 }
796 return e.osm.isSelected();
797 }
798 }
799
800 /**
801 * Pseudo class condition.
802 */
803 public static class PseudoClassCondition implements Condition {
804
805 final Method method;
806 final boolean not;
807
808 protected PseudoClassCondition(Method method, boolean not) {
809 this.method = method;
810 this.not = not;
811 }
812
813 /**
814 * Create a new pseudo class condition
815 * @param id The id of the pseudo class
816 * @param not <code>true</code> to invert the condition
817 * @param context The context the class is found in.
818 * @return The new condition
819 */
820 public static PseudoClassCondition createPseudoClassCondition(String id, boolean not, Context context) {
821 CheckParameterUtil.ensureThat(!"sameTags".equals(id) || Context.LINK == context, "sameTags only supported in LINK context");
822 if ("open_end".equals(id)) {
823 return new OpenEndPseudoClassCondition(not);
824 }
825 final Method method = getMethod(id);
826 if (method != null) {
827 return new PseudoClassCondition(method, not);
828 }
829 throw new MapCSSException("Invalid pseudo class specified: " + id);
830 }
831
832 protected static Method getMethod(String id) {
833 String cleanId = clean(id);
834 return Arrays.stream(PseudoClasses.class.getDeclaredMethods())
835 .filter(method -> clean(method.getName()).equalsIgnoreCase(cleanId))
836 .findFirst().orElse(null);
837 }
838
839 private static String clean(String id) {
840 // for backwards compatibility, consider :sameTags == :same-tags == :same_tags (#11150)
841 return id.replaceAll("[-_]", "");
842 }
843
844 @Override
845 public boolean applies(Environment e) {
846 try {
847 return not ^ (Boolean) method.invoke(null, e);
848 } catch (ReflectiveOperationException ex) {
849 throw new JosmRuntimeException(ex);
850 }
851 }
852
853 @Override
854 public String toString() {
855 return (not ? "!" : "") + ':' + method.getName();
856 }
857 }
858
859 /**
860 * Open end pseudo class condition.
861 */
862 public static class OpenEndPseudoClassCondition extends PseudoClassCondition {
863 /**
864 * Constructs a new {@code OpenEndPseudoClassCondition}.
865 * @param not negation or not
866 */
867 public OpenEndPseudoClassCondition(boolean not) {
868 super(null, not);
869 }
870
871 @Override
872 public boolean applies(Environment e) {
873 return true;
874 }
875 }
876
877 /**
878 * A condition that is fulfilled whenever the expression is evaluated to be true.
879 */
880 public static class ExpressionCondition implements Condition {
881
882 final Expression e;
883
884 /**
885 * Constructs a new {@code ExpressionFactory}
886 * @param e expression
887 */
888 public ExpressionCondition(Expression e) {
889 this.e = e;
890 }
891
892 /**
893 * Returns the expression.
894 * @return the expression
895 * @since 14484
896 */
897 public final Expression getExpression() {
898 return e;
899 }
900
901 @Override
902 public boolean applies(Environment env) {
903 Boolean b = Cascade.convertTo(e.evaluate(env), Boolean.class);
904 return b != null && b;
905 }
906
907 @Override
908 public String toString() {
909 return '[' + e.toString() + ']';
910 }
911 }
912}
Note: See TracBrowser for help on using the repository browser.