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

Last change on this file since 11730 was 11730, checked in by michael2402, 7 years ago

Add a new style element for area icon styles. Use the same placement algorithm we use for texts. Fixes #10176

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