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

Last change on this file since 10721 was 10611, checked in by Don-vip, 8 years ago

see #11390 - sonar - squid:S1604 - Java 8: Anonymous inner classes containing only one method should become lambdas

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