source: josm/trunk/src/org/openstreetmap/josm/gui/mappaint/ElemStyles.java@ 11779

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

fix #14572 - Don't index MultipolygonCache by NavigatableComponent

  • Property svn:eol-style set to native
File size: 23.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.mappaint;
3
4import java.awt.Color;
5import java.util.ArrayList;
6import java.util.Collection;
7import java.util.Collections;
8import java.util.HashMap;
9import java.util.List;
10import java.util.Map;
11import java.util.Map.Entry;
12
13import org.openstreetmap.josm.Main;
14import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
15import org.openstreetmap.josm.data.Preferences.PreferenceChangedListener;
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.Way;
20import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon;
21import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
22import org.openstreetmap.josm.gui.NavigatableComponent;
23import org.openstreetmap.josm.gui.mappaint.DividedScale.RangeViolatedError;
24import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
25import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement;
26import org.openstreetmap.josm.gui.mappaint.styleelement.AreaIconElement;
27import org.openstreetmap.josm.gui.mappaint.styleelement.BoxTextElement;
28import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement;
29import org.openstreetmap.josm.gui.mappaint.styleelement.NodeElement;
30import org.openstreetmap.josm.gui.mappaint.styleelement.RepeatImageElement;
31import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
32import org.openstreetmap.josm.gui.mappaint.styleelement.TextElement;
33import org.openstreetmap.josm.gui.mappaint.styleelement.TextLabel;
34import org.openstreetmap.josm.gui.util.GuiHelper;
35import org.openstreetmap.josm.tools.Pair;
36import org.openstreetmap.josm.tools.Utils;
37
38/**
39 * Generates a list of {@link StyleElement}s for a primitive, to
40 * be drawn on the map.
41 * There are several steps to derive the list of elements for display:
42 * <ol>
43 * <li>{@link #generateStyles(OsmPrimitive, double, boolean)} applies the
44 * {@link StyleSource}s one after another to get a key-value map of MapCSS
45 * properties. Then a preliminary set of StyleElements is derived from the
46 * properties map.</li>
47 * <li>{@link #getImpl(OsmPrimitive, double, NavigatableComponent)} handles the
48 * different forms of multipolygon tagging.</li>
49 * <li>{@link #getStyleCacheWithRange(OsmPrimitive, double, NavigatableComponent)}
50 * adds a default StyleElement for primitives that would be invisible otherwise.
51 * (For example untagged nodes and ways.)</li>
52 * </ol>
53 * The results are cached with respect to the current scale.
54 *
55 * Use {@link #setStyleSources(Collection)} to select the StyleSources that are applied.
56 */
57public class ElemStyles implements PreferenceChangedListener {
58 private final List<StyleSource> styleSources;
59 private boolean drawMultipolygon;
60
61 private short cacheIdx = 1;
62
63 private boolean defaultNodes;
64 private boolean defaultLines;
65
66 private short defaultNodesIdx;
67 private short defaultLinesIdx;
68
69 private final Map<String, String> preferenceCache = new HashMap<>();
70
71 /**
72 * Constructs a new {@code ElemStyles}.
73 */
74 public ElemStyles() {
75 styleSources = new ArrayList<>();
76 Main.pref.addPreferenceChangeListener(this);
77 }
78
79 /**
80 * Clear the style cache for all primitives of all DataSets.
81 */
82 public void clearCached() {
83 // run in EDT to make sure this isn't called during rendering run
84 GuiHelper.runInEDT(() -> {
85 cacheIdx++;
86 preferenceCache.clear();
87 });
88 }
89
90 /**
91 * Returns the list of style sources.
92 * @return the list of style sources
93 */
94 public List<StyleSource> getStyleSources() {
95 return Collections.<StyleSource>unmodifiableList(styleSources);
96 }
97
98 /**
99 * Create the list of styles for one primitive.
100 *
101 * @param osm the primitive
102 * @param scale the scale (in meters per 100 pixel)
103 * @param nc display component
104 * @return list of styles
105 */
106 public StyleElementList get(OsmPrimitive osm, double scale, NavigatableComponent nc) {
107 return getStyleCacheWithRange(osm, scale, nc).a;
108 }
109
110 /**
111 * Create the list of styles and its valid scale range for one primitive.
112 *
113 * Automatically adds default styles in case no proper style was found.
114 * Uses the cache, if possible, and saves the results to the cache.
115 * @param osm OSM primitive
116 * @param scale scale
117 * @param nc navigatable component
118 * @return pair containing style list and range
119 */
120 public Pair<StyleElementList, Range> getStyleCacheWithRange(OsmPrimitive osm, double scale, NavigatableComponent nc) {
121 if (osm.mappaintStyle == null || osm.getMappaintCacheIdx() != cacheIdx || scale <= 0) {
122 osm.mappaintStyle = StyleCache.EMPTY_STYLECACHE;
123 } else {
124 Pair<StyleElementList, Range> lst = osm.mappaintStyle.getWithRange(scale, osm.isSelected());
125 if (lst.a != null)
126 return lst;
127 }
128 Pair<StyleElementList, Range> p = getImpl(osm, scale, nc);
129 if (osm instanceof Node && isDefaultNodes()) {
130 if (p.a.isEmpty()) {
131 if (TextLabel.AUTO_LABEL_COMPOSITION_STRATEGY.compose(osm) != null) {
132 p.a = NodeElement.DEFAULT_NODE_STYLELIST_TEXT;
133 } else {
134 p.a = NodeElement.DEFAULT_NODE_STYLELIST;
135 }
136 } else {
137 boolean hasNonModifier = false;
138 boolean hasText = false;
139 for (StyleElement s : p.a) {
140 if (s instanceof BoxTextElement) {
141 hasText = true;
142 } else {
143 if (!s.isModifier) {
144 hasNonModifier = true;
145 }
146 }
147 }
148 if (!hasNonModifier) {
149 p.a = new StyleElementList(p.a, NodeElement.SIMPLE_NODE_ELEMSTYLE);
150 if (!hasText && TextLabel.AUTO_LABEL_COMPOSITION_STRATEGY.compose(osm) != null) {
151 p.a = new StyleElementList(p.a, BoxTextElement.SIMPLE_NODE_TEXT_ELEMSTYLE);
152 }
153 }
154 }
155 } else if (osm instanceof Way && isDefaultLines()) {
156 boolean hasProperLineStyle = false;
157 for (StyleElement s : p.a) {
158 if (s.isProperLineStyle()) {
159 hasProperLineStyle = true;
160 break;
161 }
162 }
163 if (!hasProperLineStyle) {
164 AreaElement area = Utils.find(p.a, AreaElement.class);
165 LineElement line = area == null ? LineElement.UNTAGGED_WAY : LineElement.createSimpleLineStyle(area.color, true);
166 p.a = new StyleElementList(p.a, line);
167 }
168 }
169 StyleCache style = osm.mappaintStyle != null ? osm.mappaintStyle : StyleCache.EMPTY_STYLECACHE;
170 try {
171 osm.mappaintStyle = style.put(p.a, p.b, osm.isSelected());
172 } catch (RangeViolatedError e) {
173 throw new AssertionError("Range violated: " + e.getMessage()
174 + " (object: " + osm.getPrimitiveId() + ", current style: "+osm.mappaintStyle
175 + ", scale: " + scale + ", new stylelist: " + p.a + ", new range: " + p.b + ')', e);
176 }
177 osm.setMappaintCacheIdx(cacheIdx);
178 return p;
179 }
180
181 /**
182 * Create the list of styles and its valid scale range for one primitive.
183 *
184 * This method does multipolygon handling.
185 *
186 * There are different tagging styles for multipolygons, that have to be respected:
187 * - tags on the relation
188 * - tags on the outer way (deprecated)
189 *
190 * If the primitive is a way, look for multipolygon parents. In case it
191 * is indeed member of some multipolygon as role "outer", all area styles
192 * are removed. (They apply to the multipolygon area.)
193 * Outer ways can have their own independent line styles, e.g. a road as
194 * boundary of a forest. Otherwise, in case, the way does not have an
195 * independent line style, take a line style from the multipolygon.
196 * If the multipolygon does not have a line style either, at least create a
197 * default line style from the color of the area.
198 *
199 * Now consider the case that the way is not an outer way of any multipolygon,
200 * but is member of a multipolygon as "inner".
201 * First, the style list is regenerated, considering only tags of this way.
202 * Then check, if the way describes something in its own right. (linear feature
203 * or area) If not, add a default line style from the area color of the multipolygon.
204 *
205 * @param osm OSM primitive
206 * @param scale scale
207 * @param nc navigatable component
208 * @return pair containing style list and range
209 */
210 private Pair<StyleElementList, Range> getImpl(OsmPrimitive osm, double scale, NavigatableComponent nc) {
211 if (osm instanceof Node)
212 return generateStyles(osm, scale, false);
213 else if (osm instanceof Way) {
214 Pair<StyleElementList, Range> p = generateStyles(osm, scale, false);
215
216 boolean isOuterWayOfSomeMP = false;
217 Color wayColor = null;
218
219 for (OsmPrimitive referrer : osm.getReferrers()) {
220 Relation r = (Relation) referrer;
221 if (!drawMultipolygon || !r.isMultipolygon() || !r.isUsable()) {
222 continue;
223 }
224 Multipolygon multipolygon = MultipolygonCache.getInstance().get(r);
225
226 if (multipolygon.getOuterWays().contains(osm)) {
227 boolean hasIndependentLineStyle = false;
228 if (!isOuterWayOfSomeMP) { // do this only one time
229 List<StyleElement> tmp = new ArrayList<>(p.a.size());
230 for (StyleElement s : p.a) {
231 if (s instanceof AreaElement) {
232 wayColor = ((AreaElement) s).color;
233 } else {
234 tmp.add(s);
235 if (s.isProperLineStyle()) {
236 hasIndependentLineStyle = true;
237 }
238 }
239 }
240 p.a = new StyleElementList(tmp);
241 isOuterWayOfSomeMP = true;
242 }
243
244 if (!hasIndependentLineStyle) {
245 Pair<StyleElementList, Range> mpElemStyles;
246 synchronized (r) {
247 mpElemStyles = getStyleCacheWithRange(r, scale, nc);
248 }
249 StyleElement mpLine = null;
250 for (StyleElement s : mpElemStyles.a) {
251 if (s.isProperLineStyle()) {
252 mpLine = s;
253 break;
254 }
255 }
256 p.b = Range.cut(p.b, mpElemStyles.b);
257 if (mpLine != null) {
258 p.a = new StyleElementList(p.a, mpLine);
259 break;
260 } else if (wayColor == null && isDefaultLines()) {
261 AreaElement mpArea = Utils.find(mpElemStyles.a, AreaElement.class);
262 if (mpArea != null) {
263 wayColor = mpArea.color;
264 }
265 }
266 }
267 }
268 }
269 if (isOuterWayOfSomeMP) {
270 if (isDefaultLines()) {
271 boolean hasLineStyle = false;
272 for (StyleElement s : p.a) {
273 if (s.isProperLineStyle()) {
274 hasLineStyle = true;
275 break;
276 }
277 }
278 if (!hasLineStyle) {
279 p.a = new StyleElementList(p.a, LineElement.createSimpleLineStyle(wayColor, true));
280 }
281 }
282 return p;
283 }
284
285 if (!isDefaultLines()) return p;
286
287 for (OsmPrimitive referrer : osm.getReferrers()) {
288 Relation ref = (Relation) referrer;
289 if (!drawMultipolygon || !ref.isMultipolygon() || !ref.isUsable()) {
290 continue;
291 }
292 final Multipolygon multipolygon = MultipolygonCache.getInstance().get(ref);
293
294 if (multipolygon.getInnerWays().contains(osm)) {
295 p = generateStyles(osm, scale, false);
296 boolean hasIndependentElemStyle = false;
297 for (StyleElement s : p.a) {
298 if (s.isProperLineStyle() || s instanceof AreaElement) {
299 hasIndependentElemStyle = true;
300 break;
301 }
302 }
303 if (!hasIndependentElemStyle && !multipolygon.getOuterWays().isEmpty()) {
304 Color mpColor = null;
305 StyleElementList mpElemStyles;
306 synchronized (ref) {
307 mpElemStyles = get(ref, scale, nc);
308 }
309 for (StyleElement mpS : mpElemStyles) {
310 if (mpS instanceof AreaElement) {
311 mpColor = ((AreaElement) mpS).color;
312 break;
313 }
314 }
315 p.a = new StyleElementList(p.a, LineElement.createSimpleLineStyle(mpColor, true));
316 }
317 return p;
318 }
319 }
320 return p;
321 } else if (osm instanceof Relation) {
322 Pair<StyleElementList, Range> p = generateStyles(osm, scale, true);
323 if (drawMultipolygon && ((Relation) osm).isMultipolygon()
324 && !Utils.exists(p.a, AreaElement.class) && Main.pref.getBoolean("multipolygon.deprecated.outerstyle", true)) {
325 // look at outer ways to find area style
326 Multipolygon multipolygon = MultipolygonCache.getInstance().get((Relation) osm);
327 for (Way w : multipolygon.getOuterWays()) {
328 Pair<StyleElementList, Range> wayStyles = generateStyles(w, scale, false);
329 p.b = Range.cut(p.b, wayStyles.b);
330 StyleElement area = Utils.find(wayStyles.a, AreaElement.class);
331 if (area != null) {
332 p.a = new StyleElementList(p.a, area);
333 break;
334 }
335 }
336 }
337 return p;
338 }
339 return null;
340 }
341
342 /**
343 * Create the list of styles and its valid scale range for one primitive.
344 *
345 * Loops over the list of style sources, to generate the map of properties.
346 * From these properties, it generates the different types of styles.
347 *
348 * @param osm the primitive to create styles for
349 * @param scale the scale (in meters per 100 px), must be &gt; 0
350 * @param pretendWayIsClosed For styles that require the way to be closed,
351 * we pretend it is. This is useful for generating area styles from the (segmented)
352 * outer ways of a multipolygon.
353 * @return the generated styles and the valid range as a pair
354 */
355 public Pair<StyleElementList, Range> generateStyles(OsmPrimitive osm, double scale, boolean pretendWayIsClosed) {
356
357 List<StyleElement> sl = new ArrayList<>();
358 MultiCascade mc = new MultiCascade();
359 Environment env = new Environment(osm, mc, null, null);
360
361 for (StyleSource s : styleSources) {
362 if (s.active) {
363 s.apply(mc, osm, scale, pretendWayIsClosed);
364 }
365 }
366
367 for (Entry<String, Cascade> e : mc.getLayers()) {
368 if ("*".equals(e.getKey())) {
369 continue;
370 }
371 env.layer = e.getKey();
372 if (osm instanceof Way) {
373 AreaElement areaStyle = AreaElement.create(env);
374 addIfNotNull(sl, areaStyle);
375 addIfNotNull(sl, RepeatImageElement.create(env));
376 addIfNotNull(sl, LineElement.createLine(env));
377 addIfNotNull(sl, LineElement.createLeftCasing(env));
378 addIfNotNull(sl, LineElement.createRightCasing(env));
379 addIfNotNull(sl, LineElement.createCasing(env));
380 addIfNotNull(sl, AreaIconElement.create(env));
381 addIfNotNull(sl, TextElement.create(env));
382 if (areaStyle != null) {
383 //TODO: Warn about this, or even remove it completely
384 addIfNotNull(sl, TextElement.createForContent(env));
385 }
386 } else if (osm instanceof Node) {
387 NodeElement nodeStyle = NodeElement.create(env);
388 if (nodeStyle != null) {
389 sl.add(nodeStyle);
390 addIfNotNull(sl, BoxTextElement.create(env, nodeStyle.getBoxProvider()));
391 } else {
392 addIfNotNull(sl, BoxTextElement.create(env, NodeElement.SIMPLE_NODE_ELEMSTYLE_BOXPROVIDER));
393 }
394 } else if (osm instanceof Relation) {
395 if (((Relation) osm).isMultipolygon()) {
396 AreaElement areaStyle = AreaElement.create(env);
397 addIfNotNull(sl, areaStyle);
398 addIfNotNull(sl, RepeatImageElement.create(env));
399 addIfNotNull(sl, LineElement.createLine(env));
400 addIfNotNull(sl, LineElement.createCasing(env));
401 addIfNotNull(sl, AreaIconElement.create(env));
402 addIfNotNull(sl, TextElement.create(env));
403 if (areaStyle != null) {
404 //TODO: Warn about this, or even remove it completely
405 addIfNotNull(sl, TextElement.createForContent(env));
406 }
407 } else if (osm.hasTag("type", "restriction")) {
408 addIfNotNull(sl, NodeElement.create(env));
409 }
410 }
411 }
412 return new Pair<>(new StyleElementList(sl), mc.range);
413 }
414
415 private static <T> void addIfNotNull(List<T> list, T obj) {
416 if (obj != null) {
417 list.add(obj);
418 }
419 }
420
421 /**
422 * Draw a default node symbol for nodes that have no style?
423 * @return {@code true} if default node symbol must be drawn
424 */
425 private boolean isDefaultNodes() {
426 if (defaultNodesIdx == cacheIdx)
427 return defaultNodes;
428 defaultNodes = fromCanvas("default-points", Boolean.TRUE, Boolean.class);
429 defaultNodesIdx = cacheIdx;
430 return defaultNodes;
431 }
432
433 /**
434 * Draw a default line for ways that do not have an own line style?
435 * @return {@code true} if default line must be drawn
436 */
437 private boolean isDefaultLines() {
438 if (defaultLinesIdx == cacheIdx)
439 return defaultLines;
440 defaultLines = fromCanvas("default-lines", Boolean.TRUE, Boolean.class);
441 defaultLinesIdx = cacheIdx;
442 return defaultLines;
443 }
444
445 private <T> T fromCanvas(String key, T def, Class<T> c) {
446 MultiCascade mc = new MultiCascade();
447 Relation r = new Relation();
448 r.put("#canvas", "query");
449
450 for (StyleSource s : styleSources) {
451 if (s.active) {
452 s.apply(mc, r, 1, false);
453 }
454 }
455 return mc.getCascade("default").get(key, def, c);
456 }
457
458 public boolean isDrawMultipolygon() {
459 return drawMultipolygon;
460 }
461
462 public void setDrawMultipolygon(boolean drawMultipolygon) {
463 this.drawMultipolygon = drawMultipolygon;
464 }
465
466 /**
467 * remove all style sources; only accessed from MapPaintStyles
468 */
469 void clear() {
470 styleSources.clear();
471 }
472
473 /**
474 * add a style source; only accessed from MapPaintStyles
475 * @param style style source to add
476 */
477 void add(StyleSource style) {
478 styleSources.add(style);
479 }
480
481 /**
482 * remove a style source; only accessed from MapPaintStyles
483 * @param style style source to remove
484 * @return {@code true} if this list contained the specified element
485 */
486 boolean remove(StyleSource style) {
487 return styleSources.remove(style);
488 }
489
490 /**
491 * set the style sources; only accessed from MapPaintStyles
492 * @param sources new style sources
493 */
494 void setStyleSources(Collection<StyleSource> sources) {
495 styleSources.clear();
496 styleSources.addAll(sources);
497 }
498
499 /**
500 * Returns the first AreaElement for a given primitive.
501 * @param p the OSM primitive
502 * @param pretendWayIsClosed For styles that require the way to be closed,
503 * we pretend it is. This is useful for generating area styles from the (segmented)
504 * outer ways of a multipolygon.
505 * @return first AreaElement found or {@code null}.
506 */
507 public static AreaElement getAreaElemStyle(OsmPrimitive p, boolean pretendWayIsClosed) {
508 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().lock();
509 try {
510 if (MapPaintStyles.getStyles() == null)
511 return null;
512 for (StyleElement s : MapPaintStyles.getStyles().generateStyles(p, 1.0, pretendWayIsClosed).a) {
513 if (s instanceof AreaElement)
514 return (AreaElement) s;
515 }
516 return null;
517 } finally {
518 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().unlock();
519 }
520 }
521
522 /**
523 * Determines whether primitive has an AreaElement.
524 * @param p the OSM primitive
525 * @param pretendWayIsClosed For styles that require the way to be closed,
526 * we pretend it is. This is useful for generating area styles from the (segmented)
527 * outer ways of a multipolygon.
528 * @return {@code true} if primitive has an AreaElement
529 */
530 public static boolean hasAreaElemStyle(OsmPrimitive p, boolean pretendWayIsClosed) {
531 return getAreaElemStyle(p, pretendWayIsClosed) != null;
532 }
533
534 /**
535 * Determines whether primitive has <b>only</b> an AreaElement.
536 * @param p the OSM primitive
537 * @return {@code true} if primitive has only an AreaElement
538 * @since 7486
539 */
540 public static boolean hasOnlyAreaElemStyle(OsmPrimitive p) {
541 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().lock();
542 try {
543 if (MapPaintStyles.getStyles() == null)
544 return false;
545 StyleElementList styles = MapPaintStyles.getStyles().generateStyles(p, 1.0, false).a;
546 if (styles.isEmpty()) {
547 return false;
548 }
549 for (StyleElement s : styles) {
550 if (!(s instanceof AreaElement)) {
551 return false;
552 }
553 }
554 return true;
555 } finally {
556 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().unlock();
557 }
558 }
559
560 /**
561 * Looks up a preference value and ensures the style cache is invalidated
562 * as soon as this preference value is changed by the user.
563 *
564 * In addition, it adds an intermediate cache for the preference values,
565 * as frequent preference lookup (using <code>Main.pref.get()</code>) for
566 * each primitive can be slow during rendering.
567 *
568 * @param key preference key
569 * @param def default value
570 * @return the corresponding preference value
571 * @see org.openstreetmap.josm.data.Preferences#get(String, String)
572 */
573 public String getPreferenceCached(String key, String def) {
574 String res;
575 if (preferenceCache.containsKey(key)) {
576 res = preferenceCache.get(key);
577 } else {
578 res = Main.pref.get(key, null);
579 preferenceCache.put(key, res);
580 }
581 return res != null ? res : def;
582 }
583
584 @Override
585 public void preferenceChanged(PreferenceChangeEvent e) {
586 if (preferenceCache.containsKey(e.getKey())) {
587 clearCached();
588 }
589 }
590}
Note: See TracBrowser for help on using the repository browser.