source: josm/trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/Condition.java@ 8874

Last change on this file since 8874 was 8874, checked in by simon04, 9 years ago

fix #10467 - MapCSS: allow comparisons in regexp key conditions

  • Property svn:eol-style set to native
File size: 23.8 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.Collection;
9import java.util.EnumSet;
10import java.util.Map;
11import java.util.Objects;
12import java.util.Set;
13import java.util.regex.Pattern;
14
15import org.openstreetmap.josm.Main;
16import org.openstreetmap.josm.actions.search.SearchCompiler.InDataSourceArea;
17import org.openstreetmap.josm.data.osm.Node;
18import org.openstreetmap.josm.data.osm.OsmPrimitive;
19import org.openstreetmap.josm.data.osm.OsmUtils;
20import org.openstreetmap.josm.data.osm.Relation;
21import org.openstreetmap.josm.data.osm.Tag;
22import org.openstreetmap.josm.data.osm.Way;
23import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
24import org.openstreetmap.josm.gui.mappaint.Cascade;
25import org.openstreetmap.josm.gui.mappaint.ElemStyles;
26import org.openstreetmap.josm.gui.mappaint.Environment;
27import org.openstreetmap.josm.tools.CheckParameterUtil;
28import org.openstreetmap.josm.tools.Predicate;
29import org.openstreetmap.josm.tools.Predicates;
30import org.openstreetmap.josm.tools.Utils;
31
32public abstract class Condition {
33
34 public abstract boolean applies(Environment e);
35
36 public static Condition createKeyValueCondition(String k, String v, Op op, Context context, boolean considerValAsKey) {
37 switch (context) {
38 case PRIMITIVE:
39 if (KeyValueRegexpCondition.SUPPORTED_OPS.contains(op) && !considerValAsKey)
40 return new KeyValueRegexpCondition(k, v, op, false);
41 if (!considerValAsKey && op.equals(Op.EQ))
42 return new SimpleKeyValueCondition(k, v);
43 return new KeyValueCondition(k, v, op, considerValAsKey);
44 case LINK:
45 if (considerValAsKey)
46 throw new MapCSSException("''considerValAsKey'' not supported in LINK context");
47 if ("role".equalsIgnoreCase(k))
48 return new RoleCondition(v, op);
49 else if ("index".equalsIgnoreCase(k))
50 return new IndexCondition(v, op);
51 else
52 throw new MapCSSException(
53 MessageFormat.format("Expected key ''role'' or ''index'' in link context. Got ''{0}''.", k));
54
55 default: throw new AssertionError();
56 }
57 }
58
59 public static Condition createRegexpKeyRegexpValueCondition(String k, String v, Op op) {
60 return new RegexpKeyValueRegexpCondition(k, v, op);
61 }
62
63 public static Condition createKeyCondition(String k, boolean not, KeyMatchType matchType, Context context) {
64 switch (context) {
65 case PRIMITIVE:
66 return new KeyCondition(k, not, matchType);
67 case LINK:
68 if (matchType != null)
69 throw new MapCSSException("Question mark operator ''?'' and regexp match not supported in LINK context");
70 if (not)
71 return new RoleCondition(k, Op.NEQ);
72 else
73 return new RoleCondition(k, Op.EQ);
74
75 default: throw new AssertionError();
76 }
77 }
78
79 public static PseudoClassCondition createPseudoClassCondition(String id, boolean not, Context context) {
80 return PseudoClassCondition.createPseudoClassCondition(id, not, context);
81 }
82
83 public static ClassCondition createClassCondition(String id, boolean not, Context context) {
84 return new ClassCondition(id, not);
85 }
86
87 public static ExpressionCondition createExpressionCondition(Expression e, Context context) {
88 return new ExpressionCondition(e);
89 }
90
91 /**
92 * This is the operation that {@link KeyValueCondition} uses to match.
93 */
94 public enum Op {
95 /** The value equals the given reference. */
96 EQ,
97 /** The value does not equal the reference. */
98 NEQ,
99 /** The value is greater than or equal to the given reference value (as float). */
100 GREATER_OR_EQUAL,
101 /** The value is greater than the given reference value (as float). */
102 GREATER,
103 /** The value is less than or equal to the given reference value (as float). */
104 LESS_OR_EQUAL,
105 /** The value is less than the given reference value (as float). */
106 LESS,
107 /** The reference is treated as regular expression and the value needs to match it. */
108 REGEX,
109 /** The reference is treated as regular expression and the value needs to not match it. */
110 NREGEX,
111 /** The reference is treated as a list separated by ';'. Spaces around the ; are ignored.
112 * The value needs to be equal one of the list elements. */
113 ONE_OF,
114 /** The value needs to begin with the reference string. */
115 BEGINS_WITH,
116 /** The value needs to end with the reference string. */
117 ENDS_WITH,
118 /** The value needs to contain the reference string. */
119 CONTAINS;
120
121 public static final Set<Op> NEGATED_OPS = EnumSet.of(NEQ, NREGEX);
122
123 /**
124 * Evaluates a value against a reference string.
125 * @param testString The value. May be <code>null</code>
126 * @param prototypeString The reference string-
127 * @return <code>true</code> if and only if this operation matches for the given value/reference pair.
128 */
129 public boolean eval(String testString, String prototypeString) {
130 if (testString == null && !NEGATED_OPS.contains(this))
131 return false;
132 switch (this) {
133 case EQ:
134 return Objects.equals(testString, prototypeString);
135 case NEQ:
136 return !Objects.equals(testString, prototypeString);
137 case REGEX:
138 case NREGEX:
139 final boolean contains = Pattern.compile(prototypeString).matcher(testString).find();
140 return REGEX.equals(this) ? contains : !contains;
141 case ONE_OF:
142 return Arrays.asList(testString.split("\\s*;\\s*")).contains(prototypeString);
143 case BEGINS_WITH:
144 return testString.startsWith(prototypeString);
145 case ENDS_WITH:
146 return testString.endsWith(prototypeString);
147 case CONTAINS:
148 return testString.contains(prototypeString);
149 }
150
151 float test_float;
152 try {
153 test_float = Float.parseFloat(testString);
154 } catch (NumberFormatException e) {
155 return false;
156 }
157 float prototype_float = Float.parseFloat(prototypeString);
158
159 switch (this) {
160 case GREATER_OR_EQUAL:
161 return test_float >= prototype_float;
162 case GREATER:
163 return test_float > prototype_float;
164 case LESS_OR_EQUAL:
165 return test_float <= prototype_float;
166 case LESS:
167 return test_float < prototype_float;
168 default:
169 throw new AssertionError();
170 }
171 }
172 }
173
174 /**
175 * Context, where the condition applies.
176 */
177 public enum Context {
178 /**
179 * normal primitive selector, e.g. way[highway=residential]
180 */
181 PRIMITIVE,
182
183 /**
184 * link between primitives, e.g. relation &gt;[role=outer] way
185 */
186 LINK
187 }
188
189 /**
190 * Most common case of a KeyValueCondition, this is the basic key=value case.
191 *
192 * Extra class for performance reasons.
193 */
194 public static class SimpleKeyValueCondition extends Condition {
195 /**
196 * The key to search for.
197 */
198 public final String k;
199 /**
200 * The value to search for.
201 */
202 public final String v;
203
204 /**
205 * Create a new SimpleKeyValueCondition.
206 * @param k The key
207 * @param v The value.
208 */
209 public SimpleKeyValueCondition(String k, String v) {
210 this.k = k;
211 this.v = v;
212 }
213
214 @Override
215 public boolean applies(Environment e) {
216 return v.equals(e.osm.get(k));
217 }
218
219 public Tag asTag() {
220 return new Tag(k, v);
221 }
222
223 @Override
224 public String toString() {
225 return '[' + k + '=' + v + ']';
226 }
227
228 }
229
230 /**
231 * <p>Represents a key/value condition which is either applied to a primitive.</p>
232 *
233 */
234 public static class KeyValueCondition extends Condition {
235 /**
236 * The key to search for.
237 */
238 public final String k;
239 /**
240 * The value to search for.
241 */
242 public final String v;
243 /**
244 * The key/value match operation.
245 */
246 public final Op op;
247 /**
248 * If this flag is set, {@link #v} is treated as a key and the value is the value set for that key.
249 */
250 public boolean considerValAsKey;
251
252 /**
253 * <p>Creates a key/value-condition.</p>
254 *
255 * @param k the key
256 * @param v the value
257 * @param op the operation
258 * @param considerValAsKey whether to consider {@code v} as another key and compare the values of key {@code k} and key {@code v}.
259 */
260 public KeyValueCondition(String k, String v, Op op, boolean considerValAsKey) {
261 this.k = k;
262 this.v = v;
263 this.op = op;
264 this.considerValAsKey = considerValAsKey;
265 }
266
267 @Override
268 public boolean applies(Environment env) {
269 return op.eval(env.osm.get(k), considerValAsKey ? env.osm.get(v) : v);
270 }
271
272 public Tag asTag() {
273 return new Tag(k, v);
274 }
275
276 @Override
277 public String toString() {
278 return '[' + k + '\'' + op + '\'' + v + ']';
279 }
280 }
281
282 public static class KeyValueRegexpCondition extends KeyValueCondition {
283
284 public final Pattern pattern;
285 public static final Set<Op> SUPPORTED_OPS = EnumSet.of(Op.REGEX, Op.NREGEX);
286
287 public KeyValueRegexpCondition(String k, String v, Op op, boolean considerValAsKey) {
288 super(k, v, op, considerValAsKey);
289 CheckParameterUtil.ensureThat(!considerValAsKey, "considerValAsKey is not supported");
290 CheckParameterUtil.ensureThat(SUPPORTED_OPS.contains(op), "Op must be REGEX or NREGEX");
291 this.pattern = Pattern.compile(v);
292 }
293
294 protected boolean matches(Environment env) {
295 final String value = env.osm.get(k);
296 return value != null && pattern.matcher(value).find();
297 }
298
299 @Override
300 public boolean applies(Environment env) {
301 if (Op.REGEX.equals(op)) {
302 return matches(env);
303 } else if (Op.NREGEX.equals(op)) {
304 return !matches(env);
305 } else {
306 throw new IllegalStateException();
307 }
308 }
309 }
310
311 public static class RegexpKeyValueRegexpCondition extends KeyValueRegexpCondition {
312
313 public final Pattern keyPattern;
314
315 public RegexpKeyValueRegexpCondition(String k, String v, Op op) {
316 super(k, v, op, false);
317 this.keyPattern = Pattern.compile(k);
318 }
319
320 @Override
321 protected boolean matches(Environment env) {
322 for (Map.Entry<String,String> kv: env.osm.getKeys().entrySet()) {
323 if (keyPattern.matcher(kv.getKey()).find() && pattern.matcher(kv.getValue()).find()) {
324 return true;
325 }
326 }
327 return false;
328 }
329 }
330
331 public static class RoleCondition extends Condition {
332 public final String role;
333 public final Op op;
334
335 public RoleCondition(String role, Op op) {
336 this.role = role;
337 this.op = op;
338 }
339
340 @Override
341 public boolean applies(Environment env) {
342 String testRole = env.getRole();
343 if (testRole == null) return false;
344 return op.eval(testRole, role);
345 }
346 }
347
348 public static class IndexCondition extends Condition {
349 public final String index;
350 public final Op op;
351
352 public IndexCondition(String index, Op op) {
353 this.index = index;
354 this.op = op;
355 }
356
357 @Override
358 public boolean applies(Environment env) {
359 if (env.index == null) return false;
360 if (index.startsWith("-")) {
361 return env.count != null && op.eval(Integer.toString(env.index - env.count), index);
362 } else {
363 return op.eval(Integer.toString(env.index + 1), index);
364 }
365 }
366 }
367
368 /**
369 * This defines how {@link KeyCondition} matches a given key.
370 */
371 public enum KeyMatchType {
372 /**
373 * The key needs to be equal to the given label.
374 */
375 EQ,
376 /**
377 * The key needs to have a true value (yes, ...)
378 * @see OsmUtils#isTrue(String)
379 */
380 TRUE,
381 /**
382 * The key needs to have a false value (no, ...)
383 * @see OsmUtils#isFalse(String)
384 */
385 FALSE,
386 /**
387 * The key needs to match the given regular expression.
388 */
389 REGEX
390 }
391
392 /**
393 * <p>KeyCondition represent one of the following conditions in either the link or the
394 * primitive context:</p>
395 * <pre>
396 * ["a label"] PRIMITIVE: the primitive has a tag "a label"
397 * LINK: the parent is a relation and it has at least one member with the role
398 * "a label" referring to the child
399 *
400 * [!"a label"] PRIMITIVE: the primitive doesn't have a tag "a label"
401 * LINK: the parent is a relation but doesn't have a member with the role
402 * "a label" referring to the child
403 *
404 * ["a label"?] PRIMITIVE: the primitive has a tag "a label" whose value evaluates to a true-value
405 * LINK: not supported
406 *
407 * ["a label"?!] PRIMITIVE: the primitive has a tag "a label" whose value evaluates to a false-value
408 * LINK: not supported
409 * </pre>
410 */
411 public static class KeyCondition extends Condition {
412
413 /**
414 * The key name.
415 */
416 public final String label;
417 /**
418 * If we should negate the result of the match.
419 */
420 public final boolean negateResult;
421 /**
422 * Describes how to match the label against the key.
423 * @see KeyMatchType
424 */
425 public final KeyMatchType matchType;
426 /**
427 * A predicate used to match a the regexp against the key. Only used if the match type is regexp.
428 */
429 public final Predicate<String> containsPattern;
430
431 /**
432 * Creates a new KeyCondition
433 * @param label The key name (or regexp) to use.
434 * @param negateResult If we should negate the result.,
435 * @param matchType The match type.
436 */
437 public KeyCondition(String label, boolean negateResult, KeyMatchType matchType) {
438 this.label = label;
439 this.negateResult = negateResult;
440 this.matchType = matchType == null ? KeyMatchType.EQ : matchType;
441 this.containsPattern = KeyMatchType.REGEX.equals(matchType)
442 ? Predicates.stringContainsPattern(Pattern.compile(label))
443 : null;
444 }
445
446 @Override
447 public boolean applies(Environment e) {
448 switch(e.getContext()) {
449 case PRIMITIVE:
450 switch (matchType) {
451 case TRUE:
452 return e.osm.isKeyTrue(label) ^ negateResult;
453 case FALSE:
454 return e.osm.isKeyFalse(label) ^ negateResult;
455 case REGEX:
456 return Utils.exists(e.osm.keySet(), containsPattern) ^ negateResult;
457 default:
458 return e.osm.hasKey(label) ^ negateResult;
459 }
460 case LINK:
461 Utils.ensure(false, "Illegal state: KeyCondition not supported in LINK context");
462 return false;
463 default: throw new AssertionError();
464 }
465 }
466
467 /**
468 * Get the matched key and the corresponding value.
469 * <p>
470 * WARNING: This ignores {@link #negateResult}.
471 * <p>
472 * WARNING: For regexp, the regular expression is returned instead of a key if the match failed.
473 * @param p The primitive to get the value from.
474 * @return The tag.
475 */
476 public Tag asTag(OsmPrimitive p) {
477 String key = label;
478 if (KeyMatchType.REGEX.equals(matchType)) {
479 final Collection<String> matchingKeys = Utils.filter(p.keySet(), containsPattern);
480 if (!matchingKeys.isEmpty()) {
481 key = matchingKeys.iterator().next();
482 }
483 }
484 return new Tag(key, p.get(key));
485 }
486
487 @Override
488 public String toString() {
489 return '[' + (negateResult ? "!" : "") + label + ']';
490 }
491 }
492
493 public static class ClassCondition extends Condition {
494
495 public final String id;
496 public final boolean not;
497
498 public ClassCondition(String id, boolean not) {
499 this.id = id;
500 this.not = not;
501 }
502
503 @Override
504 public boolean applies(Environment env) {
505 return env != null && env.getCascade(env.layer) != null && not ^ env.getCascade(env.layer).containsKey(id);
506 }
507
508 @Override
509 public String toString() {
510 return (not ? "!" : "") + '.' + id;
511 }
512 }
513
514 /**
515 * Like <a href="http://www.w3.org/TR/css3-selectors/#pseudo-classes">CSS pseudo classes</a>, MapCSS pseudo classes
516 * are written in lower case with dashes between words.
517 */
518 static class PseudoClasses {
519
520 /**
521 * {@code closed} tests whether the way is closed or the relation is a closed multipolygon
522 */
523 static boolean closed(Environment e) {
524 if (e.osm instanceof Way && ((Way) e.osm).isClosed())
525 return true;
526 if (e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon())
527 return true;
528 return false;
529 }
530
531 /**
532 * {@code :modified} tests whether the object has been modified.
533 * @see OsmPrimitive#isModified() ()
534 */
535 static boolean modified(Environment e) {
536 return e.osm.isModified() || e.osm.isNewOrUndeleted();
537 }
538
539 /**
540 * {@code ;new} tests whether the object is new.
541 * @see OsmPrimitive#isNew()
542 */
543 static boolean _new(Environment e) {
544 return e.osm.isNew();
545 }
546
547 /**
548 * {@code :connection} tests whether the object is a connection node.
549 * @see Node#isConnectionNode()
550 */
551 static boolean connection(Environment e) {
552 return e.osm instanceof Node && ((Node) e.osm).isConnectionNode();
553 }
554
555 /**
556 * {@code :tagged} tests whether the object is tagged.
557 * @see OsmPrimitive#isTagged()
558 */
559 static boolean tagged(Environment e) {
560 return e.osm.isTagged();
561 }
562
563 /**
564 * {@code :same-tags} tests whether the object has the same tags as its child/parent.
565 * @see OsmPrimitive#hasSameInterestingTags(OsmPrimitive)
566 */
567 static boolean sameTags(Environment e) {
568 return e.osm.hasSameInterestingTags(Utils.firstNonNull(e.child, e.parent));
569 }
570
571 /**
572 * {@code :area-style} tests whether the object has an area style. This is useful for validators.
573 * @see ElemStyles#hasAreaElemStyle(OsmPrimitive, boolean)
574 */
575 static boolean areaStyle(Environment e) {
576 // only for validator
577 return ElemStyles.hasAreaElemStyle(e.osm, false);
578 }
579
580 /**
581 * {@code unconnected}: tests whether the object is a unconnected node.
582 */
583 static boolean unconnected(Environment e) {
584 return e.osm instanceof Node && OsmPrimitive.getFilteredList(e.osm.getReferrers(), Way.class).isEmpty();
585 }
586
587 /**
588 * {@code righthandtraffic} checks if there is right-hand traffic at the current location.
589 * @see ExpressionFactory.Functions#is_right_hand_traffic(Environment)
590 */
591 static boolean righthandtraffic(Environment e) {
592 return ExpressionFactory.Functions.is_right_hand_traffic(e);
593 }
594
595 /**
596 * {@code unclosed-multipolygon} tests whether the object is an unclosed multipolygon.
597 */
598 static boolean unclosed_multipolygon(Environment e) {
599 return e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon() &&
600 !e.osm.isIncomplete() && !((Relation) e.osm).hasIncompleteMembers() &&
601 !MultipolygonCache.getInstance().get(Main.map.mapView, (Relation) e.osm).getOpenEnds().isEmpty();
602 }
603
604 private static final Predicate<OsmPrimitive> IN_DOWNLOADED_AREA = new InDataSourceArea(false);
605
606 /**
607 * {@code in-downloaded-area} tests whether the object is within source area ("downloaded area").
608 * @see InDataSourceArea
609 */
610 static boolean inDownloadedArea(Environment e) {
611 return IN_DOWNLOADED_AREA.evaluate(e.osm);
612 }
613 }
614
615 public static class PseudoClassCondition extends Condition {
616
617 public final Method method;
618 public final boolean not;
619
620 protected PseudoClassCondition(Method method, boolean not) {
621 this.method = method;
622 this.not = not;
623 }
624
625 public static PseudoClassCondition createPseudoClassCondition(String id, boolean not, Context context) {
626 CheckParameterUtil.ensureThat(!"sameTags".equals(id) || Context.LINK.equals(context), "sameTags only supported in LINK context");
627 if ("open_end".equals(id)) {
628 return new OpenEndPseudoClassCondition(not);
629 }
630 final Method method = getMethod(id);
631 if (method != null) {
632 return new PseudoClassCondition(method, not);
633 }
634 throw new MapCSSException("Invalid pseudo class specified: " + id);
635 }
636
637 protected static Method getMethod(String id) {
638 id = id.replaceAll("-|_", "");
639 for (Method method : PseudoClasses.class.getDeclaredMethods()) {
640 // for backwards compatibility, consider :sameTags == :same-tags == :same_tags (#11150)
641 final String methodName = method.getName().replaceAll("-|_", "");
642 if (methodName.equalsIgnoreCase(id)) {
643 return method;
644 }
645 }
646 return null;
647 }
648
649 @Override
650 public boolean applies(Environment e) {
651 try {
652 return not ^ (Boolean) method.invoke(null, e);
653 } catch (IllegalAccessException | InvocationTargetException ex) {
654 throw new RuntimeException(ex);
655 }
656 }
657
658 @Override
659 public String toString() {
660 return (not ? "!" : "") + ':' + method.getName();
661 }
662 }
663
664 public static class OpenEndPseudoClassCondition extends PseudoClassCondition {
665 public OpenEndPseudoClassCondition(boolean not) {
666 super(null, not);
667 }
668
669 @Override
670 public boolean applies(Environment e) {
671 return true;
672 }
673 }
674
675 public static class ExpressionCondition extends Condition {
676
677 private final Expression e;
678
679 public ExpressionCondition(Expression e) {
680 this.e = e;
681 }
682
683 @Override
684 public boolean applies(Environment env) {
685 Boolean b = Cascade.convertTo(e.evaluate(env), Boolean.class);
686 return b != null && b;
687 }
688
689 @Override
690 public String toString() {
691 return "[" + e + ']';
692 }
693 }
694}
Note: See TracBrowser for help on using the repository browser.