001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.mappaint;
003
004import java.io.File;
005import java.io.IOException;
006import java.util.ArrayList;
007import java.util.Arrays;
008import java.util.Collection;
009import java.util.LinkedList;
010import java.util.List;
011
012import javax.swing.ImageIcon;
013import javax.swing.SwingUtilities;
014
015import org.openstreetmap.josm.data.preferences.sources.MapPaintPrefHelper;
016import org.openstreetmap.josm.data.preferences.sources.SourceEntry;
017import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
018import org.openstreetmap.josm.io.CachedFile;
019import org.openstreetmap.josm.io.FileWatcher;
020import org.openstreetmap.josm.spi.preferences.Config;
021import org.openstreetmap.josm.spi.preferences.IPreferences;
022import org.openstreetmap.josm.spi.preferences.PreferenceChangeEvent;
023import org.openstreetmap.josm.spi.preferences.PreferenceChangedListener;
024import org.openstreetmap.josm.tools.ImageProvider;
025import org.openstreetmap.josm.tools.ListenerList;
026import org.openstreetmap.josm.tools.Logging;
027import org.openstreetmap.josm.tools.Stopwatch;
028import org.openstreetmap.josm.tools.Utils;
029
030/**
031 * This class manages the list of available map paint styles and gives access to
032 * the ElemStyles singleton.
033 *
034 * On change, {@link MapPaintStylesUpdateListener#mapPaintStylesUpdated()} is fired
035 * for all listeners.
036 */
037public final class MapPaintStyles {
038
039    private static final Collection<String> DEPRECATED_IMAGE_NAMES = Arrays.asList(
040            "presets/misc/deprecated.svg",
041            "misc/deprecated.png");
042
043    private static final ListenerList<MapPaintStylesUpdateListener> listeners = ListenerList.createUnchecked();
044
045    private static final class MapPaintStylesPreferenceListener implements PreferenceChangedListener {
046        private final IPreferences pref;
047        /** Preferences to ignore (i.e., if they change, don't reload) */
048        private final List<String> preferenceIgnoreList;
049
050        MapPaintStylesPreferenceListener(IPreferences pref) {
051            this.pref = pref;
052            this.preferenceIgnoreList = Arrays.asList("mappaint.style.entries", "mappaint.style.known-defaults",
053                    "mappaint.renderer-class-name");
054        }
055
056        @Override
057        public void preferenceChanged(PreferenceChangeEvent e) {
058            if (e.getKey().contains("mappaint") && !this.preferenceIgnoreList.contains(e.getKey())) {
059                // We need to remove this from the listeners, so that we don't recursively call ourselves.
060                pref.removePreferenceChangeListener(this);
061                MapPaintStyles.readFromPreferences();
062                pref.addPreferenceChangeListener(this);
063            }
064        }
065    }
066
067    static {
068        listeners.addListener(new MapPaintStylesUpdateListener() {
069            @Override
070            public void mapPaintStylesUpdated() {
071                SwingUtilities.invokeLater(styles::clearCached);
072            }
073
074            @Override
075            public void mapPaintStyleEntryUpdated(int index) {
076                mapPaintStylesUpdated();
077            }
078        });
079        Config.getPref().addPreferenceChangeListener(new MapPaintStylesPreferenceListener(Config.getPref()));
080    }
081
082    private static final ElemStyles styles = new ElemStyles();
083
084    /**
085     * Returns the {@link ElemStyles} singleton instance.
086     *
087     * The returned object is read only, any manipulation happens via one of
088     * the other wrapper methods in this class. ({@link #readFromPreferences},
089     * {@link #moveStyles}, ...)
090     * @return the {@code ElemStyles} singleton instance
091     */
092    public static ElemStyles getStyles() {
093        return styles;
094    }
095
096    private MapPaintStyles() {
097        // Hide default constructor for utils classes
098    }
099
100    /**
101     * Value holder for a reference to a tag name. A style instruction
102     * <pre>
103     *    text: a_tag_name;
104     * </pre>
105     * results in a tag reference for the tag <code>a_tag_name</code> in the
106     * style cascade.
107     */
108    public static class TagKeyReference {
109        /**
110         * The tag name
111         */
112        public final String key;
113
114        /**
115         * Create a new {@link TagKeyReference}
116         * @param key The tag name
117         */
118        public TagKeyReference(String key) {
119            this.key = key.intern();
120        }
121
122        @Override
123        public String toString() {
124            return "TagKeyReference{" + "key='" + key + "'}";
125        }
126    }
127
128    /**
129     * IconReference is used to remember the associated style source for each icon URL.
130     * This is necessary because image URLs can be paths relative
131     * to the source file and we have cascading of properties from different source files.
132     */
133    public static class IconReference {
134
135        /**
136         * The name of the icon
137         */
138        public final String iconName;
139        /**
140         * The style source this reference occurred in
141         */
142        public final StyleSource source;
143
144        /**
145         * Create a new {@link IconReference}
146         * @param iconName The icon name
147         * @param source The current style source
148         */
149        public IconReference(String iconName, StyleSource source) {
150            this.iconName = iconName;
151            this.source = source;
152        }
153
154        @Override
155        public String toString() {
156            return "IconReference{" + "iconName='" + iconName + "' source='" + source.getDisplayString() + "'}";
157        }
158
159        /**
160         * Determines whether this icon represents a deprecated icon
161         * @return whether this icon represents a deprecated icon
162         * @since 10927
163         */
164        public boolean isDeprecatedIcon() {
165            return DEPRECATED_IMAGE_NAMES.contains(iconName);
166        }
167    }
168
169    /**
170     * Image provider for icon. Note that this is a provider only. A {@link ImageProvider#get()} call may still fail!
171     *
172     * @param ref reference to the requested icon
173     * @param test if <code>true</code> than the icon is request is tested
174     * @return image provider for icon (can be <code>null</code> when <code>test</code> is <code>true</code>).
175     * @see #getIcon(IconReference, int,int)
176     * @since 8097
177     */
178    public static ImageProvider getIconProvider(IconReference ref, boolean test) {
179        final String namespace = ref.source.getPrefName();
180        ImageProvider i = new ImageProvider(ref.iconName)
181                .setDirs(getIconSourceDirs(ref.source))
182                .setId("mappaint."+namespace)
183                .setArchive(ref.source.zipIcons)
184                .setInArchiveDir(ref.source.getZipEntryDirName())
185                .setOptional(true);
186        if (test && i.get() == null) {
187            String msg = "Mappaint style \""+namespace+"\" ("+ref.source.getDisplayString()+") icon \"" + ref.iconName + "\" not found.";
188            ref.source.logWarning(msg);
189            Logging.warn(msg);
190            return null;
191        }
192        return i;
193    }
194
195    /**
196     * Return scaled icon.
197     *
198     * @param ref reference to the requested icon
199     * @param width icon width or -1 for autoscale
200     * @param height icon height or -1 for autoscale
201     * @return image icon or <code>null</code>.
202     * @see #getIconProvider(IconReference, boolean)
203     */
204    public static ImageIcon getIcon(IconReference ref, int width, int height) {
205        final String namespace = ref.source.getPrefName();
206        ImageIcon i = getIconProvider(ref, false).setSize(width, height).get();
207        if (i == null) {
208            Logging.warn("Mappaint style \""+namespace+"\" ("+ref.source.getDisplayString()+") icon \"" + ref.iconName + "\" not found.");
209            return null;
210        }
211        return i;
212    }
213
214    /**
215     * No icon with the given name was found, show a dummy icon instead
216     * @param source style source
217     * @return the icon misc/no_icon.png, in descending priority:
218     *   - relative to source file
219     *   - from user icon paths
220     *   - josm's default icon
221     *  can be null if the defaults are turned off by user
222     */
223    public static ImageIcon getNoIconIcon(StyleSource source) {
224        return new ImageProvider("presets/misc/no_icon")
225                .setDirs(getIconSourceDirs(source))
226                .setId("mappaint."+source.getPrefName())
227                .setArchive(source.zipIcons)
228                .setInArchiveDir(source.getZipEntryDirName())
229                .setOptional(true).get();
230    }
231
232    /**
233     * Gets the directories that should be searched for icons
234     * @param source The style source the icon is from
235     * @return A list of directory names
236     */
237    public static List<String> getIconSourceDirs(StyleSource source) {
238        List<String> dirs = new LinkedList<>();
239
240        File sourceDir = source.getLocalSourceDir();
241        if (sourceDir != null) {
242            dirs.add(sourceDir.getPath());
243        }
244
245        Collection<String> prefIconDirs = Config.getPref().getList("mappaint.icon.sources");
246        for (String fileset : prefIconDirs) {
247            String[] a;
248            if (fileset.indexOf('=') >= 0) {
249                a = fileset.split("=", 2);
250            } else {
251                a = new String[] {"", fileset};
252            }
253
254            /* non-prefixed path is generic path, always take it */
255            if (a[0].isEmpty() || source.getPrefName().equals(a[0])) {
256                dirs.add(a[1]);
257            }
258        }
259
260        if (Config.getPref().getBoolean("mappaint.icon.enable-defaults", true)) {
261            /* don't prefix icon path, as it should be generic */
262            dirs.add("resource://images/");
263        }
264
265        return dirs;
266    }
267
268    /**
269     * Reloads all styles from the preferences.
270     */
271    public static void readFromPreferences() {
272        styles.clear();
273
274        Collection<? extends SourceEntry> sourceEntries = MapPaintPrefHelper.INSTANCE.get();
275
276        for (SourceEntry entry : sourceEntries) {
277            try {
278                styles.add(fromSourceEntry(entry));
279            } catch (IllegalArgumentException e) {
280                Logging.error("Failed to load map paint style {0}", entry);
281                Logging.error(e);
282            }
283        }
284        for (StyleSource source : styles.getStyleSources()) {
285            if (source.active) {
286                loadStyleForFirstTime(source);
287            } else {
288                source.loadStyleSource(true);
289            }
290        }
291        fireMapPaintStylesUpdated();
292    }
293
294    private static void loadStyleForFirstTime(StyleSource source) {
295        final Stopwatch stopwatch = Stopwatch.createStarted();
296        source.loadStyleSource();
297        if (Config.getPref().getBoolean("mappaint.auto_reload_local_styles", true) && source.isLocal()) {
298            try {
299                FileWatcher.getDefaultInstance().registerSource(source);
300            } catch (IOException | IllegalStateException | IllegalArgumentException e) {
301                Logging.error(e);
302            }
303        }
304        if (Logging.isDebugEnabled() || !source.isValid()) {
305            String message = stopwatch.toString("Initializing map style " + source.url);
306            if (!source.isValid()) {
307                Logging.warn(message + " (" + source.getErrors().size() + " errors, " + source.getWarnings().size() + " warnings)");
308            } else {
309                Logging.debug(message);
310            }
311        }
312    }
313
314    private static StyleSource fromSourceEntry(SourceEntry entry) {
315        if (entry.url == null && entry instanceof MapCSSStyleSource) {
316            return (MapCSSStyleSource) entry;
317        }
318        try (CachedFile cf = new CachedFile(entry.url).setHttpAccept(MapCSSStyleSource.MAPCSS_STYLE_MIME_TYPES)) {
319            String zipEntryPath = cf.findZipEntryPath("mapcss", "style");
320            if (zipEntryPath != null) {
321                entry.isZip = true;
322                entry.zipEntryPath = zipEntryPath;
323            }
324            return new MapCSSStyleSource(entry);
325        }
326    }
327
328    /**
329     * Move position of entries in the current list of StyleSources
330     * @param sel The indices of styles to be moved.
331     * @param delta The number of lines it should move. positive int moves
332     *      down and negative moves up.
333     */
334    public static void moveStyles(int[] sel, int delta) {
335        if (!canMoveStyles(sel, delta))
336            return;
337        int[] selSorted = Utils.copyArray(sel);
338        Arrays.sort(selSorted);
339        List<StyleSource> data = new ArrayList<>(styles.getStyleSources());
340        for (int row: selSorted) {
341            StyleSource t1 = data.get(row);
342            StyleSource t2 = data.get(row + delta);
343            data.set(row, t2);
344            data.set(row + delta, t1);
345        }
346        styles.setStyleSources(data);
347        MapPaintPrefHelper.INSTANCE.put(data);
348        fireMapPaintStylesUpdated();
349    }
350
351    /**
352     * Check if the styles can be moved
353     * @param sel The indexes of the selected styles
354     * @param i The number of places to move the styles
355     * @return <code>true</code> if that movement is possible
356     */
357    public static boolean canMoveStyles(int[] sel, int i) {
358        if (sel.length == 0)
359            return false;
360        int[] selSorted = Utils.copyArray(sel);
361        Arrays.sort(selSorted);
362
363        if (i < 0) // Up
364            return selSorted[0] >= -i;
365        else if (i > 0) // Down
366            return selSorted[selSorted.length-1] <= styles.getStyleSources().size() - 1 - i;
367        else
368            return true;
369    }
370
371    /**
372     * Toggles the active state of several styles
373     * @param sel The style indexes
374     */
375    public static void toggleStyleActive(int... sel) {
376        List<StyleSource> data = styles.getStyleSources();
377        for (int p : sel) {
378            StyleSource s = data.get(p);
379            s.active = !s.active;
380            if (s.active && !s.isLoaded()) {
381                loadStyleForFirstTime(s);
382            }
383        }
384        MapPaintPrefHelper.INSTANCE.put(data);
385        if (sel.length == 1) {
386            fireMapPaintStyleEntryUpdated(sel[0]);
387        } else {
388            fireMapPaintStylesUpdated();
389        }
390    }
391
392    /**
393     * Add a new map paint style.
394     * @param entry map paint style
395     * @return loaded style source
396     */
397    public static StyleSource addStyle(SourceEntry entry) {
398        StyleSource source = fromSourceEntry(entry);
399        styles.add(source);
400        loadStyleForFirstTime(source);
401        refreshStyles();
402        return source;
403    }
404
405    /**
406     * Remove a map paint style.
407     * @param entry map paint style
408     * @since 11493
409     */
410    public static void removeStyle(SourceEntry entry) {
411        StyleSource source = fromSourceEntry(entry);
412        if (styles.remove(source)) {
413            refreshStyles();
414        }
415    }
416
417    private static void refreshStyles() {
418        MapPaintPrefHelper.INSTANCE.put(styles.getStyleSources());
419        fireMapPaintStylesUpdated();
420    }
421
422    /***********************************
423     * MapPaintStylesUpdateListener &amp; related code
424     *  (get informed when the list of MapPaint StyleSources changes)
425     */
426    public interface MapPaintStylesUpdateListener {
427        /**
428         * Called on any style source changes that are not handled by {@link #mapPaintStyleEntryUpdated(int)}
429         */
430        void mapPaintStylesUpdated();
431
432        /**
433         * Called whenever a single style source entry was changed.
434         * @param index The index of the entry.
435         */
436        void mapPaintStyleEntryUpdated(int index);
437    }
438
439    /**
440     * Add a listener that listens to global style changes.
441     * @param listener The listener
442     */
443    public static void addMapPaintStylesUpdateListener(MapPaintStylesUpdateListener listener) {
444        listeners.addListener(listener);
445    }
446
447    /**
448     * Removes a listener that listens to global style changes.
449     * @param listener The listener
450     */
451    public static void removeMapPaintStylesUpdateListener(MapPaintStylesUpdateListener listener) {
452        listeners.removeListener(listener);
453    }
454
455    /**
456     * Notifies all listeners that there was any update to the map paint styles
457     */
458    public static void fireMapPaintStylesUpdated() {
459        listeners.fireEvent(MapPaintStylesUpdateListener::mapPaintStylesUpdated);
460    }
461
462    /**
463     * Notifies all listeners that there was an update to a specific map paint style
464     * @param index The style index
465     */
466    public static void fireMapPaintStyleEntryUpdated(int index) {
467        listeners.fireEvent(l -> l.mapPaintStyleEntryUpdated(index));
468    }
469}