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

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

fix #17358 - mapcss regular expression matches for key (patch by michael2402, regression from #17021)

  • Property svn:eol-style set to native
File size: 32.1 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 /**
319 * Determines if this condition requires an exact key match.
320 * @return {@code true} if this condition requires an exact key match.
321 * @since 14801
322 */
323 public boolean requiresExactKeyMatch() {
324 return !Op.NEGATED_OPS.contains(op);
325 }
326
327 @Override
328 public boolean applies(Environment env) {
329 return op.eval(env.osm.get(k), considerValAsKey ? env.osm.get(v) : v);
330 }
331
332 @Override
333 public Tag asTag(OsmPrimitive primitive) {
334 return new Tag(k, v);
335 }
336
337 @Override
338 public String toString() {
339 return '[' + k + '\'' + op + '\'' + v + ']';
340 }
341 }
342
343 /**
344 * This condition requires a fixed key to match a given regexp
345 */
346 public static class KeyValueRegexpCondition extends KeyValueCondition {
347 protected static final Set<Op> SUPPORTED_OPS = EnumSet.of(Op.REGEX, Op.NREGEX);
348
349 final Pattern pattern;
350
351 /**
352 * Constructs a new {@code KeyValueRegexpCondition}.
353 * @param k key
354 * @param v value
355 * @param op operation
356 * @param considerValAsKey must be false
357 * @throws PatternSyntaxException if the value syntax is invalid
358 */
359 public KeyValueRegexpCondition(String k, String v, Op op, boolean considerValAsKey) {
360 super(k, v, op, considerValAsKey);
361 CheckParameterUtil.ensureThat(!considerValAsKey, "considerValAsKey is not supported");
362 CheckParameterUtil.ensureThat(SUPPORTED_OPS.contains(op), "Op must be REGEX or NREGEX");
363 this.pattern = Pattern.compile(v);
364 }
365
366 protected boolean matches(Environment env) {
367 final String value = env.osm.get(k);
368 return value != null && pattern.matcher(value).find();
369 }
370
371 @Override
372 public boolean applies(Environment env) {
373 if (Op.REGEX == op) {
374 return matches(env);
375 } else if (Op.NREGEX == op) {
376 return !matches(env);
377 } else {
378 throw new IllegalStateException();
379 }
380 }
381 }
382
383 /**
384 * A condition that checks that a key with the matching pattern has a value with the matching pattern.
385 */
386 public static class RegexpKeyValueRegexpCondition extends KeyValueRegexpCondition {
387
388 final Pattern keyPattern;
389
390 /**
391 * Create a condition in which the key and the value need to match a given regexp
392 * @param k The key regexp
393 * @param v The value regexp
394 * @param op The operation to use when comparing the key and the value.
395 */
396 public RegexpKeyValueRegexpCondition(String k, String v, Op op) {
397 super(k, v, op, false);
398 this.keyPattern = Pattern.compile(k);
399 }
400
401 @Override
402 public boolean requiresExactKeyMatch() {
403 return false;
404 }
405
406 @Override
407 protected boolean matches(Environment env) {
408 for (Map.Entry<String, String> kv: env.osm.getKeys().entrySet()) {
409 if (keyPattern.matcher(kv.getKey()).find() && pattern.matcher(kv.getValue()).find()) {
410 return true;
411 }
412 }
413 return false;
414 }
415 }
416
417 /**
418 * Role condition.
419 */
420 public static class RoleCondition implements Condition {
421 final String role;
422 final Op op;
423
424 /**
425 * Constructs a new {@code RoleCondition}.
426 * @param role role
427 * @param op operation
428 */
429 public RoleCondition(String role, Op op) {
430 this.role = role;
431 this.op = op;
432 }
433
434 @Override
435 public boolean applies(Environment env) {
436 String testRole = env.getRole();
437 if (testRole == null) return false;
438 return op.eval(testRole, role);
439 }
440 }
441
442 /**
443 * Index condition.
444 */
445 public static class IndexCondition implements Condition {
446 final String index;
447 final Op op;
448
449 /**
450 * Constructs a new {@code IndexCondition}.
451 * @param index index
452 * @param op operation
453 */
454 public IndexCondition(String index, Op op) {
455 this.index = index;
456 this.op = op;
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 Way && ((Way) e.osm).isClosed())
641 return true;
642 return e.osm instanceof Relation && ((Relation) 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 Node && e.osm.getDataSet() != null && ((Node) 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 ExpressionFactory.Functions#is_right_hand_traffic(Environment)
720 */
721 static boolean righthandtraffic(Environment e) { // NO_UCD (unused code)
722 return ExpressionFactory.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 ExpressionFactory.Functions#is_clockwise(Environment)
731 */
732 static boolean clockwise(Environment e) { // NO_UCD (unused code)
733 return ExpressionFactory.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 ExpressionFactory.Functions#is_anticlockwise(Environment)
742 */
743 static boolean anticlockwise(Environment e) { // NO_UCD (unused code)
744 return ExpressionFactory.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 Relation) {
772 return !((Relation) 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 Way && ((Way) 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 = id.replaceAll("-|_", "");
830 for (Method method : PseudoClasses.class.getDeclaredMethods()) {
831 // for backwards compatibility, consider :sameTags == :same-tags == :same_tags (#11150)
832 final String methodName = method.getName().replaceAll("-|_", "");
833 if (methodName.equalsIgnoreCase(cleanId)) {
834 return method;
835 }
836 }
837 return null;
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.