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

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

see #10529 - MapCSS: add :unclosed_multipolygon pseudo-class and >:open_end selector to go from relations to their open end nodes

For example, relation:unclosed_multipolygon >:open_end node matches open end nodes of unclosed multipolygon relations.

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