source: josm/trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/Selector.java@ 7169

Last change on this file since 7169 was 7169, checked in by simon04, 10 years ago

fix #9361 - MapCSS: consider multipolygon when matching outer ring of a multipolygon for the selector

  • Property svn:eol-style set to native
File size: 22.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.mappaint.mapcss;
3
4import java.util.Collection;
5import java.util.Collections;
6import java.util.List;
7import java.util.NoSuchElementException;
8import java.util.regex.PatternSyntaxException;
9
10import org.openstreetmap.josm.Main;
11import org.openstreetmap.josm.data.osm.Node;
12import org.openstreetmap.josm.data.osm.OsmPrimitive;
13import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
14import org.openstreetmap.josm.data.osm.Relation;
15import org.openstreetmap.josm.data.osm.RelationMember;
16import org.openstreetmap.josm.data.osm.Way;
17import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor;
18import org.openstreetmap.josm.gui.mappaint.Environment;
19import org.openstreetmap.josm.gui.mappaint.Range;
20import org.openstreetmap.josm.tools.CheckParameterUtil;
21import org.openstreetmap.josm.tools.Geometry;
22import org.openstreetmap.josm.tools.Pair;
23import org.openstreetmap.josm.tools.Predicates;
24import org.openstreetmap.josm.tools.Utils;
25
26/**
27 * MapCSS selector.
28 *
29 * A rule has two parts, a selector and a declaration block
30 * e.g.
31 * <pre>
32 * way[highway=residential]
33 * { width: 10; color: blue; }
34 * </pre>
35 *
36 * The selector decides, if the declaration block gets applied or not.
37 *
38 * All implementing classes of Selector are immutable.
39 */
40public interface Selector {
41
42 /**
43 * Apply the selector to the primitive and check if it matches.
44 *
45 * @param env the Environment. env.mc and env.layer are read-only when matching a selector.
46 * env.source is not needed. This method will set the matchingReferrers field of env as
47 * a side effect! Make sure to clear it before invoking this method.
48 * @return true, if the selector applies
49 */
50 boolean matches(Environment env);
51
52 String getSubpart();
53
54 Range getRange();
55
56 /**
57 * Create an "optimized" copy of this selector that omits the base check.
58 *
59 * For the style source, the list of rules is preprocessed, such that
60 * there is a separate list of rules for nodes, ways, ...
61 *
62 * This means that the base check does not have to be performed
63 * for each rule, but only once for each primitive.
64 *
65 * @return a selector that is identical to this object, except the base of the
66 * "rightmost" selector is not checked
67 */
68 Selector optimizedBaseCheck();
69
70 public static enum ChildOrParentSelectorType {
71 CHILD, PARENT, ELEMENT_OF, CROSSING, SIBLING
72 }
73
74 /**
75 * <p>Represents a child selector or a parent selector.</p>
76 *
77 * <p>In addition to the standard CSS notation for child selectors, JOSM also supports
78 * an "inverse" notation:</p>
79 * <pre>
80 * selector_a &gt; selector_b { ... } // the standard notation (child selector)
81 * relation[type=route] &gt; way { ... } // example (all ways of a route)
82 *
83 * selector_a &lt; selector_b { ... } // the inverse notation (parent selector)
84 * node[traffic_calming] &lt; way { ... } // example (way that has a traffic calming node)
85 * </pre>
86 *
87 */
88 public static class ChildOrParentSelector implements Selector {
89 public final Selector left;
90 public final LinkSelector link;
91 public final Selector right;
92 public final ChildOrParentSelectorType type;
93
94 /**
95 *
96 * @param a the first selector
97 * @param b the second selector
98 * @param type the selector type
99 */
100 public ChildOrParentSelector(Selector a, LinkSelector link, Selector b, ChildOrParentSelectorType type) {
101 CheckParameterUtil.ensureParameterNotNull(a, "a");
102 CheckParameterUtil.ensureParameterNotNull(b, "b");
103 CheckParameterUtil.ensureParameterNotNull(link, "link");
104 CheckParameterUtil.ensureParameterNotNull(type, "type");
105 this.left = a;
106 this.link = link;
107 this.right = b;
108 this.type = type;
109 }
110
111 /**
112 * <p>Finds the first referrer matching {@link #left}</p>
113 *
114 * <p>The visitor works on an environment and it saves the matching
115 * referrer in {@code e.parent} and its relative position in the
116 * list referrers "child list" in {@code e.index}.</p>
117 *
118 * <p>If after execution {@code e.parent} is null, no matching
119 * referrer was found.</p>
120 *
121 */
122 private class MatchingReferrerFinder extends AbstractVisitor{
123 private Environment e;
124
125 /**
126 * Constructor
127 * @param e the environment against which we match
128 */
129 public MatchingReferrerFinder(Environment e){
130 this.e = e;
131 }
132
133 @Override
134 public void visit(Node n) {
135 // node should never be a referrer
136 throw new AssertionError();
137 }
138
139 @Override
140 public void visit(Way w) {
141 /*
142 * If e.parent is already set to the first matching referrer. We skip any following
143 * referrer injected into the visitor.
144 */
145 if (e.parent != null) return;
146
147 if (!left.matches(e.withPrimitive(w)))
148 return;
149 for (int i=0; i<w.getNodesCount(); i++) {
150 Node n = w.getNode(i);
151 if (n.equals(e.osm)) {
152 if (link.matches(e.withParentAndIndexAndLinkContext(w, i))) {
153 e.parent = w;
154 e.index = i;
155 return;
156 }
157 }
158 }
159 }
160
161 @Override
162 public void visit(Relation r) {
163 /*
164 * If e.parent is already set to the first matching referrer. We skip any following
165 * referrer injected into the visitor.
166 */
167 if (e.parent != null) return;
168
169 if (!left.matches(e.withPrimitive(r)))
170 return;
171 for (int i=0; i < r.getMembersCount(); i++) {
172 RelationMember m = r.getMember(i);
173 if (m.getMember().equals(e.osm)) {
174 if (link.matches(e.withParentAndIndexAndLinkContext(r, i))) {
175 e.parent = r;
176 e.index = i;
177 return;
178 }
179 }
180 }
181 }
182 }
183
184 private abstract class AbstractFinder extends AbstractVisitor {
185 protected final Environment e;
186
187 protected AbstractFinder(Environment e) {
188 this.e = e;
189 }
190
191 @Override
192 public void visit(Node n) {
193 }
194
195 @Override
196 public void visit(Way w) {
197 }
198
199 @Override
200 public void visit(Relation r) {
201 }
202
203 public void visit(Collection<? extends OsmPrimitive> primitives) {
204 for (OsmPrimitive p : primitives) {
205 if (e.child != null) {
206 // abort if first match has been found
207 break;
208 } else if (isPrimitiveUsable(p)) {
209 p.accept(this);
210 }
211 }
212 }
213
214 public boolean isPrimitiveUsable(OsmPrimitive p) {
215 return !e.osm.equals(p) && p.isUsable();
216 }
217 }
218
219 private final class CrossingFinder extends AbstractFinder {
220 private CrossingFinder(Environment e) {
221 super(e);
222 CheckParameterUtil.ensureThat(e.osm instanceof Way, "Only ways are supported");
223 }
224
225 @Override
226 public void visit(Way w) {
227 if (e.child == null && left.matches(e.withPrimitive(w))) {
228 if (e.osm instanceof Way && Geometry.PolygonIntersection.CROSSING.equals(Geometry.polygonIntersection(w.getNodes(), ((Way) e.osm).getNodes()))) {
229 e.child = w;
230 }
231 }
232 }
233 }
234
235 private class ContainsFinder extends AbstractFinder {
236 private ContainsFinder(Environment e) {
237 super(e);
238 CheckParameterUtil.ensureThat(!(e.osm instanceof Node), "Nodes not supported");
239 }
240
241 @Override
242 public void visit(Node n) {
243 if (e.child == null && left.matches(e.withPrimitive(n))) {
244 if (e.osm instanceof Way && Geometry.nodeInsidePolygon(n, ((Way) e.osm).getNodes())
245 || e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon() && Geometry.isNodeInsideMultiPolygon(n, (Relation) e.osm, null)) {
246 e.child = n;
247 }
248 }
249 }
250
251 @Override
252 public void visit(Way w) {
253 if (e.child == null && left.matches(e.withPrimitive(w))) {
254 if (e.osm instanceof Way && Geometry.PolygonIntersection.FIRST_INSIDE_SECOND.equals(Geometry.polygonIntersection(w.getNodes(), ((Way) e.osm).getNodes()))
255 || e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon() && Geometry.isPolygonInsideMultiPolygon(w.getNodes(), (Relation) e.osm, null)) {
256 e.child = w;
257 }
258 }
259 }
260 }
261
262 @Override
263 public boolean matches(Environment e) {
264
265 if (!right.matches(e))
266 return false;
267
268 if (ChildOrParentSelectorType.ELEMENT_OF.equals(type)) {
269
270 if (e.osm instanceof Node || e.osm.getDataSet() == null) {
271 // nodes cannot contain elements
272 return false;
273 }
274
275 ContainsFinder containsFinder;
276 try {
277 // if right selector also matches relations and if matched primitive is a way which is part of a multipolygon,
278 // use the multipolygon for further analysis
279 if (!((GeneralSelector) right).matchesBase(OsmPrimitiveType.RELATION) || !(e.osm instanceof Way)) {
280 throw new NoSuchElementException();
281 }
282 final Collection<Relation> multipolygons = Utils.filteredCollection(Utils.filter(
283 e.osm.getReferrers(), Predicates.hasTag("type", "multipolygon")), Relation.class);
284 final Relation multipolygon = multipolygons.iterator().next();
285 if (multipolygon == null) throw new NoSuchElementException();
286 containsFinder = new ContainsFinder(e.withPrimitive(multipolygon)) {
287 @Override
288 public boolean isPrimitiveUsable(OsmPrimitive p) {
289 return super.isPrimitiveUsable(p) && !multipolygon.getMemberPrimitives().contains(p);
290 }
291 };
292 } catch (NoSuchElementException ignore) {
293 containsFinder = new ContainsFinder(e);
294 }
295 e.parent = e.osm;
296
297 if (left instanceof GeneralSelector) {
298 if (((GeneralSelector) left).matchesBase(OsmPrimitiveType.NODE)) {
299 containsFinder.visit(e.osm.getDataSet().searchNodes(e.osm.getBBox()));
300 }
301 if (((GeneralSelector) left).matchesBase(OsmPrimitiveType.WAY)) {
302 containsFinder.visit(e.osm.getDataSet().searchWays(e.osm.getBBox()));
303 }
304 } else {
305 // use slow test
306 containsFinder.visit(e.osm.getDataSet().allPrimitives());
307 }
308
309 return e.child != null;
310
311 } else if (ChildOrParentSelectorType.CROSSING.equals(type) && e.osm instanceof Way) {
312 e.parent = e.osm;
313 final CrossingFinder crossingFinder = new CrossingFinder(e);
314 if (((GeneralSelector) right).matchesBase(OsmPrimitiveType.WAY)) {
315 crossingFinder.visit(e.osm.getDataSet().searchWays(e.osm.getBBox()));
316 }
317 return e.child != null;
318 } else if (ChildOrParentSelectorType.SIBLING.equals(type)) {
319 if (e.osm instanceof Node) {
320 for (Way w : Utils.filteredCollection(e.osm.getReferrers(true), Way.class)) {
321 final int i = w.getNodes().indexOf(e.osm);
322 if (i - 1 >= 0) {
323 final Node n = w.getNode(i - 1);
324 final Environment e2 = e.withPrimitive(n).withParent(w).withChild(e.osm);
325 if (left.matches(e2) && link.matches(e2.withLinkContext())) {
326 e.child = n;
327 e.index = i;
328 e.parent = w;
329 return true;
330 }
331 }
332 }
333 }
334 } else if (ChildOrParentSelectorType.CHILD.equals(type)) {
335 MatchingReferrerFinder collector = new MatchingReferrerFinder(e);
336 e.osm.visitReferrers(collector);
337 if (e.parent != null)
338 return true;
339 } else if (ChildOrParentSelectorType.PARENT.equals(type)) {
340 if (e.osm instanceof Way) {
341 List<Node> wayNodes = ((Way) e.osm).getNodes();
342 for (int i=0; i<wayNodes.size(); i++) {
343 Node n = wayNodes.get(i);
344 if (left.matches(e.withPrimitive(n))) {
345 if (link.matches(e.withChildAndIndexAndLinkContext(n, i))) {
346 e.child = n;
347 e.index = i;
348 return true;
349 }
350 }
351 }
352 }
353 else if (e.osm instanceof Relation) {
354 List<RelationMember> members = ((Relation) e.osm).getMembers();
355 for (int i=0; i<members.size(); i++) {
356 OsmPrimitive member = members.get(i).getMember();
357 if (left.matches(e.withPrimitive(member))) {
358 if (link.matches(e.withChildAndIndexAndLinkContext(member, i))) {
359 e.child = member;
360 e.index = i;
361 return true;
362 }
363 }
364 }
365 }
366 }
367 return false;
368 }
369
370 @Override
371 public String getSubpart() {
372 return right.getSubpart();
373 }
374
375 @Override
376 public Range getRange() {
377 return right.getRange();
378 }
379
380 @Override
381 public Selector optimizedBaseCheck() {
382 return new ChildOrParentSelector(left, link, right.optimizedBaseCheck(), type);
383 }
384
385 @Override
386 public String toString() {
387 return left + " " + (ChildOrParentSelectorType.PARENT.equals(type) ? "<" : ">") + link + " " + right;
388 }
389 }
390
391 /**
392 * Super class of {@link org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector} and
393 * {@link org.openstreetmap.josm.gui.mappaint.mapcss.Selector.LinkSelector}.
394 * @since 5841
395 */
396 public abstract static class AbstractSelector implements Selector {
397
398 protected final List<Condition> conds;
399
400 protected AbstractSelector(List<Condition> conditions) {
401 if (conditions == null || conditions.isEmpty()) {
402 this.conds = null;
403 } else {
404 this.conds = conditions;
405 }
406 }
407
408 /**
409 * Determines if all conditions match the given environment.
410 * @param env The environment to check
411 * @return {@code true} if all conditions apply, false otherwise.
412 */
413 public boolean matches(Environment env) {
414 if (conds == null) return true;
415 for (Condition c : conds) {
416 try {
417 if (!c.applies(env)) return false;
418 } catch (PatternSyntaxException e) {
419 Main.error("PatternSyntaxException while applying condition" + c +": "+e.getMessage());
420 return false;
421 }
422 }
423 return true;
424 }
425
426 public List<Condition> getConditions() {
427 if (conds == null) {
428 return Collections.emptyList();
429 }
430 return Collections.unmodifiableList(conds);
431 }
432 }
433
434 public static class LinkSelector extends AbstractSelector {
435
436 public LinkSelector(List<Condition> conditions) {
437 super(conditions);
438 }
439
440 @Override
441 public boolean matches(Environment env) {
442 Utils.ensure(env.isLinkContext(), "Requires LINK context in environment, got ''{0}''", env.getContext());
443 return super.matches(env);
444 }
445
446 @Override
447 public String getSubpart() {
448 throw new UnsupportedOperationException("Not supported yet.");
449 }
450
451 @Override
452 public Range getRange() {
453 throw new UnsupportedOperationException("Not supported yet.");
454 }
455
456 @Override
457 public Selector optimizedBaseCheck() {
458 throw new UnsupportedOperationException();
459 }
460
461 @Override
462 public String toString() {
463 return "LinkSelector{" + "conditions=" + conds + '}';
464 }
465 }
466
467 public static class GeneralSelector extends OptimizedGeneralSelector {
468
469 public GeneralSelector(String base, Pair<Integer, Integer> zoom, List<Condition> conds, String subpart) {
470 super(base, zoom, conds, subpart);
471 }
472
473 public boolean matchesBase(OsmPrimitiveType type) {
474 if ("*".equals(base)) {
475 return true;
476 } else if (OsmPrimitiveType.NODE.equals(type)) {
477 return "node".equals(base);
478 } else if (OsmPrimitiveType.WAY.equals(type)) {
479 return "way".equals(base) || "area".equals(base);
480 } else if (OsmPrimitiveType.RELATION.equals(type)) {
481 return "area".equals(base) || "relation".equals(base) || "canvas".equals(base);
482 }
483 return false;
484 }
485
486 public boolean matchesBase(OsmPrimitive p) {
487 if (!matchesBase(p.getType())) {
488 return false;
489 } else {
490 if (p instanceof Relation) {
491 if ("area".equals(base)) {
492 return ((Relation) p).isMultipolygon();
493 } else if ("canvas".equals(base)) {
494 return p.get("#canvas") != null;
495 }
496 }
497 return true;
498 }
499 }
500
501 public boolean matchesBase(Environment e) {
502 return matchesBase(e.osm);
503 }
504
505 public boolean matchesConditions(Environment e) {
506 return super.matches(e);
507 }
508
509 @Override
510 public Selector optimizedBaseCheck() {
511 return new OptimizedGeneralSelector(this);
512 }
513
514 @Override
515 public boolean matches(Environment e) {
516 return matchesBase(e) && super.matches(e);
517 }
518 }
519
520 public static class OptimizedGeneralSelector extends AbstractSelector {
521 public final String base;
522 public final Range range;
523 public final String subpart;
524
525 public OptimizedGeneralSelector(String base, Pair<Integer, Integer> zoom, List<Condition> conds, String subpart) {
526 super(conds);
527 this.base = base;
528 if (zoom != null) {
529 int a = zoom.a == null ? 0 : zoom.a;
530 int b = zoom.b == null ? Integer.MAX_VALUE : zoom.b;
531 if (a <= b) {
532 range = fromLevel(a, b);
533 } else {
534 range = Range.ZERO_TO_INFINITY;
535 }
536 } else {
537 range = Range.ZERO_TO_INFINITY;
538 }
539 this.subpart = subpart;
540 }
541
542 public OptimizedGeneralSelector(String base, Range range, List<Condition> conds, String subpart) {
543 super(conds);
544 this.base = base;
545 this.range = range;
546 this.subpart = subpart;
547 }
548
549 public OptimizedGeneralSelector(GeneralSelector s) {
550 this(s.base, s.range, s.conds, s.subpart);
551 }
552
553 @Override
554 public String getSubpart() {
555 return subpart;
556 }
557
558 @Override
559 public Range getRange() {
560 return range;
561 }
562
563 public String getBase() {
564 return base;
565 }
566
567 @Override
568 public Selector optimizedBaseCheck() {
569 throw new UnsupportedOperationException();
570 }
571
572 public static Range fromLevel(int a, int b) {
573 if (a > b)
574 throw new AssertionError();
575 double lower = 0;
576 double upper = Double.POSITIVE_INFINITY;
577 if (b != Integer.MAX_VALUE) {
578 lower = level2scale(b + 1);
579 }
580 if (a != 0) {
581 upper = level2scale(a);
582 }
583 return new Range(lower, upper);
584 }
585
586 static final double R = 6378135;
587
588 public static double level2scale(int lvl) {
589 if (lvl < 0)
590 throw new IllegalArgumentException();
591 // preliminary formula - map such that mapnik imagery tiles of the same
592 // or similar level are displayed at the given scale
593 return 2.0 * Math.PI * R / Math.pow(2.0, lvl) / 2.56;
594 }
595
596 @Override
597 public String toString() {
598 return base + (Range.ZERO_TO_INFINITY.equals(range) ? "" : range) + Utils.join("", conds) + (subpart != null ? ("::" + subpart) : "");
599 }
600 }
601}
Note: See TracBrowser for help on using the repository browser.