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

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

sonar - squid:S1226 - Method parameters, caught exceptions and foreach variables should not be reassigned

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