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

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

sonar - fb-contrib - minor performance improvements:

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