001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.layer.imagery;
003
004import java.util.HashMap;
005import java.util.Locale;
006import java.util.Map;
007import java.util.Objects;
008import java.util.concurrent.CopyOnWriteArrayList;
009
010import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
011import org.openstreetmap.josm.data.coor.EastNorth;
012import org.openstreetmap.josm.data.imagery.OffsetBookmark;
013import org.openstreetmap.josm.data.preferences.BooleanProperty;
014import org.openstreetmap.josm.data.projection.ProjectionRegistry;
015import org.openstreetmap.josm.gui.layer.AbstractTileSourceLayer;
016import org.openstreetmap.josm.io.session.SessionAwareReadApply;
017import org.openstreetmap.josm.spi.preferences.Config;
018import org.openstreetmap.josm.tools.CheckParameterUtil;
019import org.openstreetmap.josm.tools.JosmRuntimeException;
020import org.openstreetmap.josm.tools.bugreport.BugReport;
021
022/**
023 * This are the preferences of how to display a {@link TileSource}.
024 * <p>
025 * They have been extracted from the {@link AbstractTileSourceLayer}. Each layer has one set of such settings.
026 * @author michael
027 * @since 10568
028 */
029public class TileSourceDisplaySettings implements SessionAwareReadApply {
030    /**
031     * A string returned by {@link DisplaySettingsChangeEvent#getChangedSetting()} if auto load was changed.
032     * @see TileSourceDisplaySettings#isAutoLoad()
033     */
034    public static final String AUTO_LOAD = "automatic-downloading";
035
036    /**
037     * A string returned by {@link DisplaySettingsChangeEvent#getChangedSetting()} if auto zoom was changed.
038     * @see TileSourceDisplaySettings#isAutoZoom()
039     */
040    public static final String AUTO_ZOOM = "automatically-change-resolution";
041
042    /**
043     * A string returned by {@link DisplaySettingsChangeEvent#getChangedSetting()} if the show errors property was changed.
044     * @see TileSourceDisplaySettings#isShowErrors()
045     */
046    private static final String SHOW_ERRORS = "show-errors";
047
048    private static final String SHOW_TILE_BORDERS = "show-tile-borders";
049
050    private static final String DISPLACEMENT = "displacement";
051
052    private static final String PREFERENCE_PREFIX = "imagery.generic";
053
054    /**
055     * The default auto load property
056     */
057    public static final BooleanProperty PROP_AUTO_LOAD = new BooleanProperty(PREFERENCE_PREFIX + ".default_autoload", true);
058
059    /**
060     * The default auto zoom property
061     */
062    public static final BooleanProperty PROP_AUTO_ZOOM = new BooleanProperty(PREFERENCE_PREFIX + ".default_autozoom", true);
063
064    /**
065     * The default tile borders property, remembered whenever the user toggles them, so that the choice also
066     * applies to layers created later and after a restart
067     * @since 19640
068     */
069    public static final BooleanProperty PROP_SHOW_TILE_BORDERS
070            = new BooleanProperty(PREFERENCE_PREFIX + ".default_showtileborders", false);
071
072
073    /** if layers changes automatically, when user zooms in */
074    private boolean autoZoom;
075    /** if layer automatically loads new tiles */
076    private boolean autoLoad;
077    /** if layer should show errors on tiles */
078    private boolean showErrors;
079    /** if layer should draw a border around each tile */
080    private boolean showTileBorders;
081
082    private OffsetBookmark previousOffsetBookmark;
083    private OffsetBookmark offsetBookmark;
084    /**
085     * the displacement (basically caches the displacement from the offsetBookmark
086     * in the current projection)
087     */
088    private EastNorth displacement = EastNorth.ZERO;
089
090    private final CopyOnWriteArrayList<DisplaySettingsChangeListener> listeners = new CopyOnWriteArrayList<>();
091
092    /**
093     * Create a new {@link TileSourceDisplaySettings}
094     */
095    public TileSourceDisplaySettings() {
096        this(new String[] {PREFERENCE_PREFIX});
097    }
098
099    /**
100     * Create a new {@link TileSourceDisplaySettings}
101     * @param preferencePrefix The additional prefix to scan for preferences.
102     */
103    public TileSourceDisplaySettings(String preferencePrefix) {
104        this(PREFERENCE_PREFIX, preferencePrefix);
105    }
106
107    private TileSourceDisplaySettings(String... prefixes) {
108        autoZoom = getProperty(prefixes, "default_autozoom", PROP_AUTO_ZOOM.getDefaultValue());
109        autoLoad = getProperty(prefixes, "default_autoload", PROP_AUTO_LOAD.getDefaultValue());
110        showErrors = getProperty(prefixes, "default_showerrors", Boolean.TRUE);
111        showTileBorders = getProperty(prefixes, "default_showtileborders", PROP_SHOW_TILE_BORDERS.getDefaultValue());
112    }
113
114    private static boolean getProperty(String[] prefixes, String name, Boolean def) {
115        // iterate through all values to force the preferences to receive the default value
116        boolean value = def;
117        for (String p : prefixes) {
118            String key = p + "." + name;
119            boolean currentValue = Config.getPref().getBoolean(key, def);
120            if (!Config.getPref().get(key, def.toString()).isEmpty()) {
121                value = currentValue;
122            }
123        }
124        return value;
125    }
126
127    /**
128     * Let the layer zoom automatically if the user zooms in
129     * @return auto zoom
130     */
131    public boolean isAutoZoom() {
132        return autoZoom;
133    }
134
135    /**
136     * Sets the auto zoom property
137     * @param autoZoom {@code true} to let the layer zoom automatically if the user zooms in
138     * @see #isAutoZoom()
139     * @see #AUTO_ZOOM
140     */
141    public void setAutoZoom(boolean autoZoom) {
142        this.autoZoom = autoZoom;
143        fireSettingsChange(AUTO_ZOOM);
144    }
145
146    /**
147     * Gets if the layer should automatically load new tiles.
148     * @return <code>true</code> if it should
149     */
150    public boolean isAutoLoad() {
151        return autoLoad;
152    }
153
154    /**
155     * Sets the auto load property
156     * @param autoLoad {@code true} if the layer should automatically load new tiles
157     * @see #isAutoLoad()
158     * @see #AUTO_LOAD
159     */
160    public void setAutoLoad(boolean autoLoad) {
161        this.autoLoad = autoLoad;
162        fireSettingsChange(AUTO_LOAD);
163    }
164
165    /**
166     * If the layer should display the errors it encountered while loading the tiles.
167     * @return <code>true</code> to show errors.
168     */
169    public boolean isShowErrors() {
170        return showErrors;
171    }
172
173    /**
174     * Sets the show errors property. Fires a change event.
175     * @param showErrors {@code true} if the layer should display the errors it encountered while loading the tiles
176     * @see #isShowErrors()
177     * @see #SHOW_ERRORS
178     */
179    public void setShowErrors(boolean showErrors) {
180        this.showErrors = showErrors;
181        fireSettingsChange(SHOW_ERRORS);
182    }
183
184    /**
185     * If the layer should draw a thin border around each tile.
186     * @return <code>true</code> to draw tile borders.
187     * @since 19640
188     */
189    public boolean isShowTileBorders() {
190        return showTileBorders;
191    }
192
193    /**
194     * Sets the show tile borders property. Fires a change event.
195     * @param showTileBorders {@code true} if the layer should draw a thin border around each tile
196     * @see #isShowTileBorders()
197     * @since 19640
198     */
199    public void setShowTileBorders(boolean showTileBorders) {
200        this.showTileBorders = showTileBorders;
201        fireSettingsChange(SHOW_TILE_BORDERS);
202    }
203
204    /**
205     * Gets the displacement in x (east) direction
206     * @return The displacement.
207     * @see #getDisplacement()
208     * @since 10571
209     */
210    public double getDx() {
211        return getDisplacement().east();
212    }
213
214    /**
215     * Gets the displacement in y (north) direction
216     * @return The displacement.
217     * @see #getDisplacement()
218     * @since 10571
219     */
220    public double getDy() {
221        return getDisplacement().north();
222    }
223
224    /**
225     * Gets the displacement of the image
226     * @return The displacement.
227     * @since 10571
228     */
229    public EastNorth getDisplacement() {
230        return displacement;
231    }
232
233    /**
234     * Gets the displacement of the image formatted as a string
235     * @param locale the locale used to format the decimals
236     * @return the displacement string
237     * @see #getDisplacement()
238     * @since 15733
239     */
240    public String getDisplacementString(final Locale locale) {
241        // Support projections with very small numbers (e.g. 4326)
242        int precision = ProjectionRegistry.getProjection().getDefaultZoomInPPD() >= 1.0 ? 2 : 7;
243        return String.format(locale, "%1." + precision + "f; %1." + precision + "f", getDx(), getDy());
244    }
245
246    /**
247     * Sets an offset bookmark to use. Loads the displacement from the bookmark.
248     *
249     * @param offsetBookmark the offset bookmark, may be null
250     */
251    public void setOffsetBookmark(OffsetBookmark offsetBookmark) {
252        if (this.offsetBookmark != null) {
253            this.previousOffsetBookmark = this.offsetBookmark;
254        }
255        this.offsetBookmark = offsetBookmark;
256        if (offsetBookmark == null) {
257            setDisplacement(EastNorth.ZERO);
258        } else {
259            setDisplacement(offsetBookmark.getDisplacement(ProjectionRegistry.getProjection()));
260        }
261    }
262
263    /**
264     * Gets the offset bookmark in use.
265     * @return the offset bookmark, may be null
266     */
267    public OffsetBookmark getOffsetBookmark() {
268        return this.offsetBookmark;
269    }
270
271    /**
272     * Gets the offset bookmark previously in use.
273     * @return the previously used offset bookmark, may be null
274     */
275    public OffsetBookmark getPreviousOffsetBookmark() {
276        return previousOffsetBookmark;
277    }
278
279    private void setDisplacement(EastNorth displacement) {
280        CheckParameterUtil.ensureThat(displacement.isValid(), () -> displacement + " invalid");
281        this.displacement = displacement;
282        fireSettingsChange(DISPLACEMENT);
283    }
284
285    /**
286     * Notifies all listeners that the paint settings have changed
287     * @param changedSetting The setting name
288     */
289    private void fireSettingsChange(String changedSetting) {
290        DisplaySettingsChangeEvent e = new DisplaySettingsChangeEvent(changedSetting);
291        for (DisplaySettingsChangeListener l : listeners) {
292            l.displaySettingsChanged(e);
293        }
294    }
295
296    /**
297     * Add a listener that listens to display settings changes.
298     * @param l The listener
299     */
300    public void addSettingsChangeListener(DisplaySettingsChangeListener l) {
301        listeners.add(l);
302    }
303
304    /**
305     * Remove a listener that listens to display settings changes.
306     * @param l The listener
307     */
308    public void removeSettingsChangeListener(DisplaySettingsChangeListener l) {
309        listeners.remove(l);
310    }
311
312    /**
313     * Stores the current settings object to the given hashmap.
314     * The offset data is not stored and needs to be handled separately.
315     * @see #applyFromPropertiesMap(Map)
316     * @see OffsetBookmark#toPropertiesMap()
317     */
318    @Override
319    public Map<String, String> toPropertiesMap() {
320        Map<String, String> data = new HashMap<>();
321        data.put(AUTO_LOAD, Boolean.toString(autoLoad));
322        data.put(AUTO_ZOOM, Boolean.toString(autoZoom));
323        data.put(SHOW_ERRORS, Boolean.toString(showErrors));
324        data.put(SHOW_TILE_BORDERS, Boolean.toString(showTileBorders));
325        return data;
326    }
327
328    /**
329     * Load the settings from the given data instance.
330     * The offset data is not loaded and needs to be handled separately.
331     * @param data The data
332     * @see #toPropertiesMap()
333     * @see OffsetBookmark#fromPropertiesMap(java.util.Map)
334     */
335    @Override
336    public void applyFromPropertiesMap(Map<String, String> data) {
337        try {
338            String doAutoLoad = data.get(AUTO_LOAD);
339            if (doAutoLoad != null) {
340                setAutoLoad(Boolean.parseBoolean(doAutoLoad));
341            }
342
343            String doAutoZoom = data.get(AUTO_ZOOM);
344            if (doAutoZoom != null) {
345                setAutoZoom(Boolean.parseBoolean(doAutoZoom));
346            }
347
348            String doShowErrors = data.get(SHOW_ERRORS);
349            if (doShowErrors != null) {
350                setShowErrors(Boolean.parseBoolean(doShowErrors));
351            }
352
353            String doShowTileBorders = data.get(SHOW_TILE_BORDERS);
354            if (doShowTileBorders != null) {
355                setShowTileBorders(Boolean.parseBoolean(doShowTileBorders));
356            }
357        } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
358            throw BugReport.intercept(e).put("data", data);
359        }
360    }
361
362    @Override
363    public int hashCode() {
364        return Objects.hash(autoLoad, autoZoom, showErrors, showTileBorders);
365    }
366
367    @Override
368    public boolean equals(Object obj) {
369        if (this == obj)
370            return true;
371        if (obj == null || getClass() != obj.getClass())
372            return false;
373        TileSourceDisplaySettings other = (TileSourceDisplaySettings) obj;
374        return autoLoad == other.autoLoad
375            && autoZoom == other.autoZoom
376            && showErrors == other.showErrors
377            && showTileBorders == other.showTileBorders;
378    }
379
380    @Override
381    public String toString() {
382        return "TileSourceDisplaySettings [autoZoom=" + autoZoom + ", autoLoad=" + autoLoad + ", showErrors="
383                + showErrors + ", showTileBorders=" + showTileBorders + ']';
384    }
385
386    /**
387     * A listener that listens to changes to the {@link TileSourceDisplaySettings} object.
388     * @author Michael Zangl
389     * @since 10600 (functional interface)
390     */
391    @FunctionalInterface
392    public interface DisplaySettingsChangeListener {
393        /**
394         * Called whenever the display settings have changed.
395         * @param e The change event.
396         */
397        void displaySettingsChanged(DisplaySettingsChangeEvent e);
398    }
399
400    /**
401     * An event that is created whenever the display settings change.
402     * @author Michael Zangl
403     */
404    public static final class DisplaySettingsChangeEvent {
405        private final String changedSetting;
406
407        DisplaySettingsChangeEvent(String changedSetting) {
408            this.changedSetting = changedSetting;
409        }
410
411        /**
412         * Gets the setting that was changed
413         * @return The name of the changed setting.
414         */
415        public String getChangedSetting() {
416            return changedSetting;
417        }
418
419        @Override
420        public String toString() {
421            return "DisplaySettingsChangeEvent [changedSetting=" + changedSetting + ']';
422        }
423    }
424}