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

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

checkstyle: various checks

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