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

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

support rendering of IPrimitive

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