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

Last change on this file since 9114 was 9114, checked in by bastiK, 8 years ago

mapcss: make partial fill threshold an advanced preference option (see #12104)

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