source: josm/trunk/src/org/openstreetmap/josm/gui/mappaint/MapPaintStyles.java@ 10611

Last change on this file since 10611 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: 18.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.mappaint;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.File;
7import java.io.IOException;
8import java.io.InputStreamReader;
9import java.nio.charset.StandardCharsets;
10import java.util.ArrayList;
11import java.util.Arrays;
12import java.util.Collection;
13import java.util.HashSet;
14import java.util.LinkedList;
15import java.util.List;
16import java.util.Set;
17import java.util.concurrent.CopyOnWriteArrayList;
18
19import javax.swing.ImageIcon;
20import javax.swing.JOptionPane;
21import javax.swing.SwingUtilities;
22
23import org.openstreetmap.josm.Main;
24import org.openstreetmap.josm.data.coor.LatLon;
25import org.openstreetmap.josm.data.osm.DataSet;
26import org.openstreetmap.josm.data.osm.Node;
27import org.openstreetmap.josm.data.osm.Tag;
28import org.openstreetmap.josm.gui.HelpAwareOptionPane;
29import org.openstreetmap.josm.gui.PleaseWaitRunnable;
30import org.openstreetmap.josm.gui.help.HelpUtil;
31import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
32import org.openstreetmap.josm.gui.mappaint.styleelement.MapImage;
33import org.openstreetmap.josm.gui.mappaint.styleelement.NodeElement;
34import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
35import org.openstreetmap.josm.gui.preferences.SourceEntry;
36import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference.MapPaintPrefHelper;
37import org.openstreetmap.josm.gui.progress.ProgressMonitor;
38import org.openstreetmap.josm.io.CachedFile;
39import org.openstreetmap.josm.io.IllegalDataException;
40import org.openstreetmap.josm.tools.ImageProvider;
41import org.openstreetmap.josm.tools.Utils;
42
43/**
44 * This class manages the ElemStyles instance. The object you get with
45 * getStyles() is read only, any manipulation happens via one of
46 * the wrapper methods here. (readFromPreferences, moveStyles, ...)
47 *
48 * On change, mapPaintSylesUpdated() is fired for all listeners.
49 */
50public final class MapPaintStyles {
51
52 /** To remove in November 2016 */
53 private static final String XML_STYLE_MIME_TYPES =
54 "application/xml, text/xml, text/plain; q=0.8, application/zip, application/octet-stream; q=0.5";
55
56 private static ElemStyles styles = new ElemStyles();
57
58 /**
59 * Returns the {@link ElemStyles} instance.
60 * @return the {@code ElemStyles} instance
61 */
62 public static ElemStyles getStyles() {
63 return styles;
64 }
65
66 private MapPaintStyles() {
67 // Hide default constructor for utils classes
68 }
69
70 /**
71 * Value holder for a reference to a tag name. A style instruction
72 * <pre>
73 * text: a_tag_name;
74 * </pre>
75 * results in a tag reference for the tag <tt>a_tag_name</tt> in the
76 * style cascade.
77 */
78 public static class TagKeyReference {
79 public final String key;
80
81 public TagKeyReference(String key) {
82 this.key = key;
83 }
84
85 @Override
86 public String toString() {
87 return "TagKeyReference{" + "key='" + key + "'}";
88 }
89 }
90
91 /**
92 * IconReference is used to remember the associated style source for each icon URL.
93 * This is necessary because image URLs can be paths relative
94 * to the source file and we have cascading of properties from different source files.
95 */
96 public static class IconReference {
97
98 public final String iconName;
99 public final StyleSource source;
100
101 public IconReference(String iconName, StyleSource source) {
102 this.iconName = iconName;
103 this.source = source;
104 }
105
106 @Override
107 public String toString() {
108 return "IconReference{" + "iconName='" + iconName + "' source='" + source.getDisplayString() + "'}";
109 }
110 }
111
112 /**
113 * Image provider for icon. Note that this is a provider only. A @link{ImageProvider#get()} call may still fail!
114 *
115 * @param ref reference to the requested icon
116 * @param test if <code>true</code> than the icon is request is tested
117 * @return image provider for icon (can be <code>null</code> when <code>test</code> is <code>true</code>).
118 * @see #getIcon(IconReference, int,int)
119 * @since 8097
120 */
121 public static ImageProvider getIconProvider(IconReference ref, boolean test) {
122 final String namespace = ref.source.getPrefName();
123 ImageProvider i = new ImageProvider(ref.iconName)
124 .setDirs(getIconSourceDirs(ref.source))
125 .setId("mappaint."+namespace)
126 .setArchive(ref.source.zipIcons)
127 .setInArchiveDir(ref.source.getZipEntryDirName())
128 .setOptional(true);
129 if (test && i.get() == null) {
130 String msg = "Mappaint style \""+namespace+"\" ("+ref.source.getDisplayString()+") icon \"" + ref.iconName + "\" not found.";
131 ref.source.logWarning(msg);
132 Main.warn(msg);
133 return null;
134 }
135 return i;
136 }
137
138 /**
139 * Return scaled icon.
140 *
141 * @param ref reference to the requested icon
142 * @param width icon width or -1 for autoscale
143 * @param height icon height or -1 for autoscale
144 * @return image icon or <code>null</code>.
145 * @see #getIconProvider(IconReference, boolean)
146 */
147 public static ImageIcon getIcon(IconReference ref, int width, int height) {
148 final String namespace = ref.source.getPrefName();
149 ImageIcon i = getIconProvider(ref, false).setSize(width, height).get();
150 if (i == null) {
151 Main.warn("Mappaint style \""+namespace+"\" ("+ref.source.getDisplayString()+") icon \"" + ref.iconName + "\" not found.");
152 return null;
153 }
154 return i;
155 }
156
157 /**
158 * No icon with the given name was found, show a dummy icon instead
159 * @param source style source
160 * @return the icon misc/no_icon.png, in descending priority:
161 * - relative to source file
162 * - from user icon paths
163 * - josm's default icon
164 * can be null if the defaults are turned off by user
165 */
166 public static ImageIcon getNoIcon_Icon(StyleSource source) {
167 return new ImageProvider("presets/misc/no_icon")
168 .setDirs(getIconSourceDirs(source))
169 .setId("mappaint."+source.getPrefName())
170 .setArchive(source.zipIcons)
171 .setInArchiveDir(source.getZipEntryDirName())
172 .setOptional(true).get();
173 }
174
175 public static ImageIcon getNodeIcon(Tag tag) {
176 return getNodeIcon(tag, true);
177 }
178
179 /**
180 * Returns the node icon that would be displayed for the given tag.
181 * @param tag The tag to look an icon for
182 * @param includeDeprecatedIcon if {@code true}, the special deprecated icon will be returned if applicable
183 * @return {@code null} if no icon found, or if the icon is deprecated and not wanted
184 */
185 public static ImageIcon getNodeIcon(Tag tag, boolean includeDeprecatedIcon) {
186 if (tag != null) {
187 DataSet ds = new DataSet();
188 Node virtualNode = new Node(LatLon.ZERO);
189 virtualNode.put(tag.getKey(), tag.getValue());
190 StyleElementList styleList;
191 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().lock();
192 try {
193 // Add primitive to dataset to avoid DataIntegrityProblemException when evaluating selectors
194 ds.addPrimitive(virtualNode);
195 styleList = getStyles().generateStyles(virtualNode, 0.5, false).a;
196 ds.removePrimitive(virtualNode);
197 } finally {
198 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().unlock();
199 }
200 if (styleList != null) {
201 for (StyleElement style : styleList) {
202 if (style instanceof NodeElement) {
203 MapImage mapImage = ((NodeElement) style).mapImage;
204 if (mapImage != null) {
205 if (includeDeprecatedIcon || mapImage.name == null || !"misc/deprecated.png".equals(mapImage.name)) {
206 return new ImageIcon(mapImage.getImage(false));
207 } else {
208 return null; // Deprecated icon found but not wanted
209 }
210 }
211 }
212 }
213 }
214 }
215 return null;
216 }
217
218 public static List<String> getIconSourceDirs(StyleSource source) {
219 List<String> dirs = new LinkedList<>();
220
221 File sourceDir = source.getLocalSourceDir();
222 if (sourceDir != null) {
223 dirs.add(sourceDir.getPath());
224 }
225
226 Collection<String> prefIconDirs = Main.pref.getCollection("mappaint.icon.sources");
227 for (String fileset : prefIconDirs) {
228 String[] a;
229 if (fileset.indexOf('=') >= 0) {
230 a = fileset.split("=", 2);
231 } else {
232 a = new String[] {"", fileset};
233 }
234
235 /* non-prefixed path is generic path, always take it */
236 if (a[0].isEmpty() || source.getPrefName().equals(a[0])) {
237 dirs.add(a[1]);
238 }
239 }
240
241 if (Main.pref.getBoolean("mappaint.icon.enable-defaults", true)) {
242 /* don't prefix icon path, as it should be generic */
243 dirs.add("resource://images/");
244 }
245
246 return dirs;
247 }
248
249 public static void readFromPreferences() {
250 styles.clear();
251
252 Collection<? extends SourceEntry> sourceEntries = MapPaintPrefHelper.INSTANCE.get();
253
254 for (SourceEntry entry : sourceEntries) {
255 StyleSource source = fromSourceEntry(entry);
256 if (source != null) {
257 styles.add(source);
258 }
259 }
260 for (StyleSource source : styles.getStyleSources()) {
261 loadStyleForFirstTime(source);
262 }
263 fireMapPaintSylesUpdated();
264 }
265
266 private static void loadStyleForFirstTime(StyleSource source) {
267 final long startTime = System.currentTimeMillis();
268 source.loadStyleSource();
269 if (Main.pref.getBoolean("mappaint.auto_reload_local_styles", true) && source.isLocal()) {
270 try {
271 Main.fileWatcher.registerStyleSource(source);
272 } catch (IOException e) {
273 Main.error(e);
274 }
275 }
276 if (Main.isDebugEnabled() || !source.isValid()) {
277 final long elapsedTime = System.currentTimeMillis() - startTime;
278 String message = "Initializing map style " + source.url + " completed in " + Utils.getDurationString(elapsedTime);
279 if (!source.isValid()) {
280 Main.warn(message + " (" + source.getErrors().size() + " errors, " + source.getWarnings().size() + " warnings)");
281 } else {
282 Main.debug(message);
283 }
284 }
285 }
286
287 private static StyleSource fromSourceEntry(SourceEntry entry) {
288 // TODO: Method to clean up in November 2016: remove XML detection completely
289 Set<String> mimes = new HashSet<>(Arrays.asList(MapCSSStyleSource.MAPCSS_STYLE_MIME_TYPES.split(", ")));
290 mimes.addAll(Arrays.asList(XML_STYLE_MIME_TYPES.split(", ")));
291 try (CachedFile cf = new CachedFile(entry.url).setHttpAccept(Utils.join(", ", mimes))) {
292 String zipEntryPath = cf.findZipEntryPath("mapcss", "style");
293 if (zipEntryPath != null) {
294 entry.isZip = true;
295 entry.zipEntryPath = zipEntryPath;
296 return new MapCSSStyleSource(entry);
297 }
298 zipEntryPath = cf.findZipEntryPath("xml", "style");
299 if (zipEntryPath != null || Utils.hasExtension(entry.url, "xml"))
300 throw new IllegalDataException("XML style");
301 if (Utils.hasExtension(entry.url, "mapcss"))
302 return new MapCSSStyleSource(entry);
303 try (InputStreamReader reader = new InputStreamReader(cf.getInputStream(), StandardCharsets.UTF_8)) {
304 WHILE: while (true) {
305 int c = reader.read();
306 switch (c) {
307 case -1:
308 break WHILE;
309 case ' ':
310 case '\t':
311 case '\n':
312 case '\r':
313 continue;
314 case '<':
315 throw new IllegalDataException("XML style");
316 default:
317 return new MapCSSStyleSource(entry);
318 }
319 }
320 }
321 Main.warn("Could not detect style type. Using default (mapcss).");
322 return new MapCSSStyleSource(entry);
323 } catch (IOException e) {
324 Main.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", entry.url, e.toString()));
325 Main.error(e);
326 } catch (IllegalDataException e) {
327 String msg = tr("JOSM does no longer support mappaint styles written in the old XML format.\nPlease update ''{0}'' to MapCSS",
328 entry.url);
329 Main.error(msg);
330 Main.debug(e);
331 HelpAwareOptionPane.showOptionDialog(Main.parent, msg, tr("Warning"), JOptionPane.WARNING_MESSAGE,
332 HelpUtil.ht("/Styles/MapCSSImplementation"));
333 }
334 return null;
335 }
336
337 /**
338 * reload styles
339 * preferences are the same, but the file source may have changed
340 * @param sel the indices of styles to reload
341 */
342 public static void reloadStyles(final int... sel) {
343 List<StyleSource> toReload = new ArrayList<>();
344 List<StyleSource> data = styles.getStyleSources();
345 for (int i : sel) {
346 toReload.add(data.get(i));
347 }
348 Main.worker.submit(new MapPaintStyleLoader(toReload));
349 }
350
351 public static class MapPaintStyleLoader extends PleaseWaitRunnable {
352 private boolean canceled;
353 private final Collection<StyleSource> sources;
354
355 public MapPaintStyleLoader(Collection<StyleSource> sources) {
356 super(tr("Reloading style sources"));
357 this.sources = sources;
358 }
359
360 @Override
361 protected void cancel() {
362 canceled = true;
363 }
364
365 @Override
366 protected void finish() {
367 SwingUtilities.invokeLater(() -> {
368 fireMapPaintSylesUpdated();
369 styles.clearCached();
370 if (Main.isDisplayingMapView()) {
371 Main.map.mapView.preferenceChanged(null);
372 Main.map.mapView.repaint();
373 }
374 });
375 }
376
377 @Override
378 protected void realRun() {
379 ProgressMonitor monitor = getProgressMonitor();
380 monitor.setTicksCount(sources.size());
381 for (StyleSource s : sources) {
382 if (canceled)
383 return;
384 monitor.subTask(tr("loading style ''{0}''...", s.getDisplayString()));
385 s.loadStyleSource();
386 monitor.worked(1);
387 }
388 }
389 }
390
391 /**
392 * Move position of entries in the current list of StyleSources
393 * @param sel The indices of styles to be moved.
394 * @param delta The number of lines it should move. positive int moves
395 * down and negative moves up.
396 */
397 public static void moveStyles(int[] sel, int delta) {
398 if (!canMoveStyles(sel, delta))
399 return;
400 int[] selSorted = Utils.copyArray(sel);
401 Arrays.sort(selSorted);
402 List<StyleSource> data = new ArrayList<>(styles.getStyleSources());
403 for (int row: selSorted) {
404 StyleSource t1 = data.get(row);
405 StyleSource t2 = data.get(row + delta);
406 data.set(row, t2);
407 data.set(row + delta, t1);
408 }
409 styles.setStyleSources(data);
410 MapPaintPrefHelper.INSTANCE.put(data);
411 fireMapPaintSylesUpdated();
412 styles.clearCached();
413 Main.map.mapView.repaint();
414 }
415
416 public static boolean canMoveStyles(int[] sel, int i) {
417 if (sel.length == 0)
418 return false;
419 int[] selSorted = Utils.copyArray(sel);
420 Arrays.sort(selSorted);
421
422 if (i < 0) // Up
423 return selSorted[0] >= -i;
424 else if (i > 0) // Down
425 return selSorted[selSorted.length-1] <= styles.getStyleSources().size() - 1 - i;
426 else
427 return true;
428 }
429
430 public static void toggleStyleActive(int... sel) {
431 List<StyleSource> data = styles.getStyleSources();
432 for (int p : sel) {
433 StyleSource s = data.get(p);
434 s.active = !s.active;
435 }
436 MapPaintPrefHelper.INSTANCE.put(data);
437 if (sel.length == 1) {
438 fireMapPaintStyleEntryUpdated(sel[0]);
439 } else {
440 fireMapPaintSylesUpdated();
441 }
442 styles.clearCached();
443 Main.map.mapView.repaint();
444 }
445
446 /**
447 * Add a new map paint style.
448 * @param entry map paint style
449 * @return loaded style source, or {@code null}
450 */
451 public static StyleSource addStyle(SourceEntry entry) {
452 StyleSource source = fromSourceEntry(entry);
453 if (source != null) {
454 styles.add(source);
455 loadStyleForFirstTime(source);
456 MapPaintPrefHelper.INSTANCE.put(styles.getStyleSources());
457 fireMapPaintSylesUpdated();
458 styles.clearCached();
459 if (Main.isDisplayingMapView()) {
460 Main.map.mapView.repaint();
461 }
462 }
463 return source;
464 }
465
466 /***********************************
467 * MapPaintSylesUpdateListener &amp; related code
468 * (get informed when the list of MapPaint StyleSources changes)
469 */
470
471 public interface MapPaintSylesUpdateListener {
472 void mapPaintStylesUpdated();
473
474 void mapPaintStyleEntryUpdated(int idx);
475 }
476
477 private static final CopyOnWriteArrayList<MapPaintSylesUpdateListener> listeners
478 = new CopyOnWriteArrayList<>();
479
480 public static void addMapPaintSylesUpdateListener(MapPaintSylesUpdateListener listener) {
481 if (listener != null) {
482 listeners.addIfAbsent(listener);
483 }
484 }
485
486 public static void removeMapPaintSylesUpdateListener(MapPaintSylesUpdateListener listener) {
487 listeners.remove(listener);
488 }
489
490 public static void fireMapPaintSylesUpdated() {
491 for (MapPaintSylesUpdateListener l : listeners) {
492 l.mapPaintStylesUpdated();
493 }
494 }
495
496 public static void fireMapPaintStyleEntryUpdated(int idx) {
497 for (MapPaintSylesUpdateListener l : listeners) {
498 l.mapPaintStyleEntryUpdated(idx);
499 }
500 }
501}
Note: See TracBrowser for help on using the repository browser.