001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005import static org.openstreetmap.josm.tools.Utils.getSystemEnv;
006import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
007
008import java.awt.GraphicsEnvironment;
009import java.io.File;
010import java.io.IOException;
011import java.io.PrintWriter;
012import java.io.Reader;
013import java.io.StringWriter;
014import java.nio.charset.StandardCharsets;
015import java.nio.file.Files;
016import java.nio.file.InvalidPathException;
017import java.nio.file.StandardCopyOption;
018import java.util.ArrayList;
019import java.util.Arrays;
020import java.util.Collection;
021import java.util.Collections;
022import java.util.HashMap;
023import java.util.HashSet;
024import java.util.List;
025import java.util.Map;
026import java.util.Map.Entry;
027import java.util.Optional;
028import java.util.Set;
029import java.util.SortedMap;
030import java.util.TreeMap;
031import java.util.concurrent.TimeUnit;
032import java.util.stream.Collectors;
033import java.util.stream.Stream;
034
035import javax.swing.JOptionPane;
036import javax.xml.stream.XMLStreamException;
037
038import org.openstreetmap.josm.data.preferences.ColorInfo;
039import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
040import org.openstreetmap.josm.data.preferences.JosmUrls;
041import org.openstreetmap.josm.data.preferences.NamedColorProperty;
042import org.openstreetmap.josm.data.preferences.PreferencesReader;
043import org.openstreetmap.josm.data.preferences.PreferencesWriter;
044import org.openstreetmap.josm.gui.MainApplication;
045import org.openstreetmap.josm.io.NetworkManager;
046import org.openstreetmap.josm.io.OsmApi;
047import org.openstreetmap.josm.spi.preferences.AbstractPreferences;
048import org.openstreetmap.josm.spi.preferences.Config;
049import org.openstreetmap.josm.spi.preferences.DefaultPreferenceChangeEvent;
050import org.openstreetmap.josm.spi.preferences.IBaseDirectories;
051import org.openstreetmap.josm.spi.preferences.ListSetting;
052import org.openstreetmap.josm.spi.preferences.PreferenceChangeEvent;
053import org.openstreetmap.josm.spi.preferences.Setting;
054import org.openstreetmap.josm.tools.CheckParameterUtil;
055import org.openstreetmap.josm.tools.ListenerList;
056import org.openstreetmap.josm.tools.Logging;
057import org.openstreetmap.josm.tools.PlatformManager;
058import org.openstreetmap.josm.tools.ReflectionUtils;
059import org.openstreetmap.josm.tools.Utils;
060import org.xml.sax.SAXException;
061
062/**
063 * This class holds all preferences for JOSM.
064 *
065 * Other classes can register their beloved properties here. All properties will be
066 * saved upon set-access.
067 *
068 * Each property is a key=setting pair, where key is a String and setting can be one of
069 * 4 types:
070 *     string, list, list of lists and list of maps.
071 * In addition, each key has a unique default value that is set when the value is first
072 * accessed using one of the get...() methods. You can use the same preference
073 * key in different parts of the code, but the default value must be the same
074 * everywhere. A default value of null means, the setting has been requested, but
075 * no default value was set. This is used in advanced preferences to present a list
076 * off all possible settings.
077 *
078 * At the moment, you cannot put the empty string for string properties.
079 * put(key, "") means, the property is removed.
080 *
081 * @author imi
082 * @since 74
083 */
084public class Preferences extends AbstractPreferences {
085
086    /** remove if key equals */
087    private static final String[] OBSOLETE_PREF_KEYS = {
088        "oauth.access-token.key", // OAuth 1.0a token, unused since OAuth 1.0a was removed (#22810). To remove end of 2027
089        "oauth.access-token.secret", // OAuth 1.0a token, unused since OAuth 1.0a was removed (#22810). To remove end of 2027
090    };
091
092    /** remove if key starts with */
093    private static final String[] OBSOLETE_PREF_KEYS_START = {
094        // nothing ATM
095    };
096
097    /** keep subkey even if it starts with any of {@link #OBSOLETE_PREF_KEYS_START} */
098    private static final List<String> KEEP_PREF_KEYS = Arrays.asList(
099    // nothing ATM
100    );
101
102    /** rename keys that equal */
103    private static final Map<String, String> UPDATE_PREF_KEYS = getUpdatePrefKeys();
104
105    private static Map<String, String> getUpdatePrefKeys() {
106        HashMap<String, String> m = new HashMap<>();
107        m.put("hdop.color.alpha", "circle.color.alpha");
108        m.put("points.hdopcircle", "points.circle");
109        return Collections.unmodifiableMap(m);
110    }
111
112    private static final long MAX_AGE_DEFAULT_PREFERENCES = TimeUnit.DAYS.toSeconds(50);
113
114    private final IBaseDirectories dirs;
115    boolean modifiedDefault;
116
117    /**
118     * Determines if preferences file is saved each time a property is changed.
119     */
120    private boolean saveOnPut = true;
121
122    /**
123     * Maps the setting name to the current value of the setting.
124     * The map must not contain null as key or value. The mapped setting objects
125     * must not have a null value.
126     */
127    protected final SortedMap<String, Setting<?>> settingsMap = new TreeMap<>();
128
129    /**
130     * Maps the setting name to the default value of the setting.
131     * The map must not contain null as key or value. The value of the mapped
132     * setting objects can be null.
133     */
134    protected final SortedMap<String, Setting<?>> defaultsMap = new TreeMap<>();
135
136    /**
137     * Indicates whether {@link #init(boolean)} completed successfully.
138     * Used to decide whether to write backup preference file in {@link #save()}
139     */
140    protected boolean initSuccessful;
141
142    private final ListenerList<org.openstreetmap.josm.spi.preferences.PreferenceChangedListener> listeners = ListenerList.create();
143
144    private final HashMap<String, ListenerList<org.openstreetmap.josm.spi.preferences.PreferenceChangedListener>> keyListeners = new HashMap<>();
145
146    private static final Preferences defaultInstance = new Preferences(JosmBaseDirectories.getInstance());
147
148    /**
149     * Preferences classes calling directly the method {@link #putSetting(String, Setting)}.
150     * This collection allows us to exclude them when searching the business class who set a preference.
151     * The found class is used as event source when notifying event listeners.
152     */
153    private static final Collection<Class<?>> preferencesClasses = Arrays.asList(
154            Preferences.class, PreferencesUtils.class, AbstractPreferences.class);
155
156    /**
157     * Constructs a new {@code Preferences}.
158     */
159    public Preferences() {
160        this.dirs = Config.getDirs();
161    }
162
163    /**
164     * Constructs a new {@code Preferences}.
165     *
166     * @param dirs the directories to use for saving the preferences
167     */
168    public Preferences(IBaseDirectories dirs) {
169        this.dirs = dirs;
170    }
171
172    /**
173     * Constructs a new {@code Preferences} from an existing instance.
174     * @param pref existing preferences to copy
175     * @since 12634
176     */
177    public Preferences(Preferences pref) {
178        this(pref.dirs);
179        settingsMap.putAll(pref.settingsMap);
180        defaultsMap.putAll(pref.defaultsMap);
181    }
182
183    /**
184     * Returns the main (default) preferences instance.
185     * @return the main (default) preferences instance
186     * @since 14149
187     */
188    public static Preferences main() {
189        return defaultInstance;
190    }
191
192    /**
193     * Adds a new preferences listener.
194     * @param listener The listener to add
195     * @since 12881
196     */
197    @Override
198    public void addPreferenceChangeListener(org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
199        if (listener != null) {
200            listeners.addListener(listener);
201        }
202    }
203
204    /**
205     * Removes a preferences listener.
206     * @param listener The listener to remove
207     * @since 12881
208     */
209    @Override
210    public void removePreferenceChangeListener(org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
211        listeners.removeListener(listener);
212    }
213
214    /**
215     * Adds a listener that only listens to changes in one preference
216     * @param key The preference key to listen to
217     * @param listener The listener to add.
218     * @since 12881
219     */
220    @Override
221    public void addKeyPreferenceChangeListener(String key, org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
222        listenersForKey(key).addListener(listener);
223    }
224
225    /**
226     * Adds a weak listener that only listens to changes in one preference
227     * @param key The preference key to listen to
228     * @param listener The listener to add.
229     * @since 10824
230     */
231    public void addWeakKeyPreferenceChangeListener(String key, org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
232        listenersForKey(key).addWeakListener(listener);
233    }
234
235    private ListenerList<org.openstreetmap.josm.spi.preferences.PreferenceChangedListener> listenersForKey(String key) {
236        return keyListeners.computeIfAbsent(key, k -> ListenerList.create());
237    }
238
239    /**
240     * Removes a listener that only listens to changes in one preference
241     * @param key The preference key to listen to
242     * @param listener The listener to add.
243     * @since 12881
244     */
245    @Override
246    public void removeKeyPreferenceChangeListener(String key, org.openstreetmap.josm.spi.preferences.PreferenceChangedListener listener) {
247        Optional.ofNullable(keyListeners.get(key)).orElseThrow(
248                () -> new IllegalArgumentException("There are no listeners registered for " + key))
249        .removeListener(listener);
250    }
251
252    protected void firePreferenceChanged(String key, Setting<?> oldValue, Setting<?> newValue) {
253        final Class<?> source = ReflectionUtils.findCallerClass(preferencesClasses);
254        final PreferenceChangeEvent evt =
255                new DefaultPreferenceChangeEvent(source != null ? source : getClass(), key, oldValue, newValue);
256        listeners.fireEvent(listener -> listener.preferenceChanged(evt));
257
258        ListenerList<org.openstreetmap.josm.spi.preferences.PreferenceChangedListener> forKey = keyListeners.get(key);
259        if (forKey != null) {
260            forKey.fireEvent(listener -> listener.preferenceChanged(evt));
261        }
262    }
263
264    /**
265     * Get the base name of the JOSM directories for preferences, cache and user data.
266     * Default value is "JOSM", unless overridden by system property "josm.dir.name".
267     * @return the base name of the JOSM directories for preferences, cache and user data
268     */
269    public static String getJOSMDirectoryBaseName() {
270        String name = getSystemProperty("josm.dir.name");
271        if (name != null)
272            return name;
273        else
274            return "JOSM";
275    }
276
277    /**
278     * Get the base directories associated with this preference instance.
279     * @return the base directories
280     */
281    public IBaseDirectories getDirs() {
282        return dirs;
283    }
284
285    /**
286     * Returns the user preferences file (preferences.xml).
287     * @return The user preferences file (preferences.xml)
288     */
289    public File getPreferenceFile() {
290        return new File(dirs.getPreferencesDirectory(false), "preferences.xml");
291    }
292
293    /**
294     * Returns the cache file for default preferences.
295     * @return the cache file for default preferences
296     */
297    public File getDefaultsCacheFile() {
298        return new File(dirs.getCacheDirectory(true), "default_preferences.xml");
299    }
300
301    /**
302     * Returns the user plugin directory.
303     * @return The user plugin directory
304     */
305    public File getPluginsDirectory() {
306        return new File(dirs.getUserDataDirectory(false), "plugins");
307    }
308
309    private static void addPossibleResourceDir(Set<String> locations, String s) {
310        if (s != null) {
311            if (!s.endsWith(File.separator)) {
312                s += File.separator;
313            }
314            locations.add(s);
315        }
316    }
317
318    /**
319     * Returns a set of all existing directories where resources could be stored.
320     * @return A set of all existing directories where resources could be stored.
321     */
322    public static Collection<String> getAllPossiblePreferenceDirs() {
323        Set<String> locations = new HashSet<>();
324        addPossibleResourceDir(locations, defaultInstance.dirs.getPreferencesDirectory(false).getPath());
325        addPossibleResourceDir(locations, defaultInstance.dirs.getUserDataDirectory(false).getPath());
326        addPossibleResourceDir(locations, getSystemEnv("JOSM_RESOURCES"));
327        addPossibleResourceDir(locations, getSystemProperty("josm.resources"));
328        locations.addAll(PlatformManager.getPlatform().getPossiblePreferenceDirs());
329        return locations;
330    }
331
332    /**
333     * Get all named colors, including customized and the default ones.
334     * @return a map of all named colors (maps preference key to {@link ColorInfo})
335     */
336    public synchronized Map<String, ColorInfo> getAllNamedColors() {
337        final Map<String, ColorInfo> all = new TreeMap<>();
338        for (final Entry<String, Setting<?>> e : settingsMap.entrySet()) {
339            if (!e.getKey().startsWith(NamedColorProperty.NAMED_COLOR_PREFIX))
340                continue;
341            Utils.instanceOfAndCast(e.getValue(), ListSetting.class)
342                    .map(ListSetting::getValue)
343                    .map(lst -> ColorInfo.fromPref(lst, false))
344                    .ifPresent(info -> all.put(e.getKey(), info));
345        }
346        for (final Entry<String, Setting<?>> e : defaultsMap.entrySet()) {
347            if (!e.getKey().startsWith(NamedColorProperty.NAMED_COLOR_PREFIX))
348                continue;
349            Utils.instanceOfAndCast(e.getValue(), ListSetting.class)
350                    .map(ListSetting::getValue)
351                    .map(lst -> ColorInfo.fromPref(lst, true))
352                    .ifPresent(infoDef -> {
353                        ColorInfo info = all.get(e.getKey());
354                        if (info == null) {
355                            all.put(e.getKey(), infoDef);
356                        } else {
357                            info.setDefaultValue(infoDef.getDefaultValue());
358                        }
359                    });
360        }
361        return all;
362    }
363
364    /**
365     * Called after every put. In case of a problem, do nothing but output the error in log.
366     * @throws IOException if any I/O error occurs
367     */
368    public synchronized void save() throws IOException {
369        save(getPreferenceFile(), settingsMap.entrySet().stream().filter(e -> !e.getValue().equals(defaultsMap.get(e.getKey()))), false);
370    }
371
372    /**
373     * Stores the defaults to the defaults file
374     * @throws IOException If the file could not be saved
375     */
376    public synchronized void saveDefaults() throws IOException {
377        save(getDefaultsCacheFile(), defaultsMap.entrySet().stream(), true);
378    }
379
380    protected void save(File prefFile, Stream<Entry<String, Setting<?>>> settings, boolean defaults) throws IOException {
381        if (!defaults) {
382            /* currently unused, but may help to fix configuration issues in future */
383            putInt("josm.version", Version.getInstance().getVersion());
384        }
385
386        File backupFile = new File(prefFile + "_backup");
387
388        // Backup old preferences if there are old preferences
389        if (initSuccessful && prefFile.exists() && prefFile.length() > 0) {
390            checkFileValidity(prefFile, defaults, f -> Utils.copyFile(f, backupFile));
391        }
392
393        try (PreferencesWriter writer = new PreferencesWriter(
394                new PrintWriter(prefFile + "_tmp", StandardCharsets.UTF_8), false, defaults)) {
395            writer.write(settings);
396        } catch (SecurityException e) {
397            throw new IOException(e);
398        }
399
400        File tmpFile = new File(prefFile + "_tmp");
401        // Only replace the pref file if the _tmp file is valid
402        checkFileValidity(tmpFile, defaults, f -> Files.move(f.toPath(), prefFile.toPath(), StandardCopyOption.REPLACE_EXISTING));
403
404        setCorrectPermissions(prefFile);
405        setCorrectPermissions(backupFile);
406    }
407
408    /**
409     * Ensure that a preferences file is "ok" before copying/moving it over another preferences file
410     * @param file The file to check
411     * @param defaults {@code true} if the file is the cache file for default preferences
412     * @param consumer The consumer that will perform the copy/move action
413     * @throws IOException If there is an issue reading/writing the file
414     */
415    private static void checkFileValidity(File file, boolean defaults, ThrowingConsumer<File, IOException> consumer) throws IOException {
416        try {
417            // But don't back up if the current preferences are invalid.
418            // The validations are expensive (~2/3 CPU, ~1/3 memory), but this isn't a "hot" method
419            PreferencesReader.validateXML(file);
420            PreferencesReader reader = new PreferencesReader(file, defaults);
421            reader.parse();
422            consumer.accept(file);
423        } catch (SAXException | XMLStreamException e) {
424            Logging.trace(e);
425            Logging.debug("Invalid preferences file (" + file + ") due to: " + e.getMessage());
426        }
427    }
428
429    private static void setCorrectPermissions(File file) {
430        if (!file.setReadable(false, false) && Logging.isTraceEnabled()) {
431            Logging.trace(tr("Unable to set file non-readable {0}", file.getAbsolutePath()));
432        }
433        if (!file.setWritable(false, false) && Logging.isTraceEnabled()) {
434            Logging.trace(tr("Unable to set file non-writable {0}", file.getAbsolutePath()));
435        }
436        if (!file.setExecutable(false, false) && Logging.isTraceEnabled()) {
437            Logging.trace(tr("Unable to set file non-executable {0}", file.getAbsolutePath()));
438        }
439        if (!file.setReadable(true, true) && Logging.isTraceEnabled()) {
440            Logging.trace(tr("Unable to set file readable {0}", file.getAbsolutePath()));
441        }
442        if (!file.setWritable(true, true) && Logging.isTraceEnabled()) {
443            Logging.trace(tr("Unable to set file writable {0}", file.getAbsolutePath()));
444        }
445    }
446
447    /**
448     * Loads preferences from settings file.
449     * @throws IOException if any I/O error occurs while reading the file
450     * @throws SAXException if the settings file does not contain valid XML
451     * @throws XMLStreamException if an XML error occurs while parsing the file (after validation)
452     */
453    protected void load() throws IOException, SAXException, XMLStreamException {
454        File pref = getPreferenceFile();
455        PreferencesReader.validateXML(pref);
456        PreferencesReader reader = new PreferencesReader(pref, false);
457        reader.parse();
458        settingsMap.clear();
459        settingsMap.putAll(reader.getSettings());
460        removeAndUpdateObsolete(reader.getVersion());
461    }
462
463    /**
464     * Loads default preferences from default settings cache file.
465     *
466     * Discards entries older than {@link #MAX_AGE_DEFAULT_PREFERENCES}.
467     *
468     * @throws IOException if any I/O error occurs while reading the file
469     * @throws SAXException if the settings file does not contain valid XML
470     * @throws XMLStreamException if an XML error occurs while parsing the file (after validation)
471     */
472    protected void loadDefaults() throws IOException, XMLStreamException, SAXException {
473        File def = getDefaultsCacheFile();
474        PreferencesReader.validateXML(def);
475        PreferencesReader reader = new PreferencesReader(def, true);
476        reader.parse();
477        defaultsMap.clear();
478        long minTime = System.currentTimeMillis() / 1000 - MAX_AGE_DEFAULT_PREFERENCES;
479        for (Entry<String, Setting<?>> e : reader.getSettings().entrySet()) {
480            if (e.getValue().getTime() >= minTime) {
481                defaultsMap.put(e.getKey(), e.getValue());
482            }
483        }
484    }
485
486    /**
487     * Loads preferences from XML reader.
488     * @param in XML reader
489     * @throws XMLStreamException if any XML stream error occurs
490     * @throws IOException if any I/O error occurs
491     */
492    public synchronized void fromXML(Reader in) throws XMLStreamException, IOException {
493        PreferencesReader reader = new PreferencesReader(in, false);
494        reader.parse();
495        settingsMap.clear();
496        settingsMap.putAll(reader.getSettings());
497    }
498
499    /**
500     * Initializes preferences.
501     * @param reset if {@code true}, current settings file is replaced by the default one
502     */
503    public synchronized void init(boolean reset) {
504        initSuccessful = false;
505        // get the preferences.
506        File prefDir = dirs.getPreferencesDirectory(false);
507        if (prefDir.exists()) {
508            if (!prefDir.isDirectory()) {
509                Logging.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.",
510                        prefDir.getAbsoluteFile()));
511                if (!GraphicsEnvironment.isHeadless()) {
512                    JOptionPane.showMessageDialog(
513                            MainApplication.getMainFrame(),
514                            tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>",
515                                    prefDir.getAbsoluteFile()),
516                            tr("Error"),
517                            JOptionPane.ERROR_MESSAGE
518                    );
519                }
520                return;
521            }
522        } else {
523            if (!prefDir.mkdirs()) {
524                Logging.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}",
525                        prefDir.getAbsoluteFile()));
526                if (!GraphicsEnvironment.isHeadless()) {
527                    JOptionPane.showMessageDialog(
528                            MainApplication.getMainFrame(),
529                            tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>",
530                                    prefDir.getAbsoluteFile()),
531                            tr("Error"),
532                            JOptionPane.ERROR_MESSAGE
533                    );
534                }
535                return;
536            }
537        }
538
539        File preferenceFile = getPreferenceFile();
540        try {
541            if (!preferenceFile.exists()) {
542                Logging.info(tr("Missing preference file ''{0}''. Creating a default preference file.", preferenceFile.getAbsoluteFile()));
543                resetToDefault();
544                save();
545            } else if (reset) {
546                File backupFile = new File(prefDir, "preferences.xml.bak");
547                PlatformManager.getPlatform().rename(preferenceFile, backupFile);
548                Logging.warn(tr("Replacing existing preference file ''{0}'' with default preference file.", preferenceFile.getAbsoluteFile()));
549                resetToDefault();
550                save();
551            }
552        } catch (IOException | InvalidPathException e) {
553            Logging.error(e);
554            if (!GraphicsEnvironment.isHeadless()) {
555                JOptionPane.showMessageDialog(
556                        MainApplication.getMainFrame(),
557                        tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>",
558                                getPreferenceFile().getAbsoluteFile()),
559                        tr("Error"),
560                        JOptionPane.ERROR_MESSAGE
561                );
562            }
563            return;
564        }
565        File def = getDefaultsCacheFile();
566        if (def.exists()) {
567            try {
568                loadDefaults();
569            } catch (IOException | XMLStreamException | SAXException e) {
570                Logging.error(e);
571                Logging.warn(tr("Failed to load defaults cache file: {0}", def));
572                defaultsMap.clear();
573                if (!def.delete()) {
574                    Logging.warn(tr("Failed to delete faulty defaults cache file: {0}", def));
575                }
576            }
577        }
578        File possiblyGoodBackupFile = new File(prefDir, "preferences.xml_backup");
579        try {
580            load();
581            initSuccessful = true;
582        } catch (IOException | SAXException | XMLStreamException e) {
583            Logging.error(e);
584            File backupFile = new File(prefDir, "preferences.xml.bak");
585            if (!GraphicsEnvironment.isHeadless()) {
586                JOptionPane.showMessageDialog(
587                        MainApplication.getMainFrame(),
588                        tr("<html>Preferences file had errors.<br> Making backup of old one to <br>{0}<br> " +
589                                "and trying to read last good preference file <br>{1}<br>.</html>",
590                                backupFile.getAbsoluteFile(), possiblyGoodBackupFile.getAbsoluteFile()),
591                        tr("Error"),
592                        JOptionPane.ERROR_MESSAGE
593                );
594            }
595            PlatformManager.getPlatform().rename(preferenceFile, backupFile);
596        }
597        if (!initSuccessful) {
598            try {
599                if (possiblyGoodBackupFile.exists() && possiblyGoodBackupFile.length() > 0) {
600                    Utils.copyFile(possiblyGoodBackupFile, preferenceFile);
601                }
602
603                load();
604                initSuccessful = true;
605            } catch (IOException | SAXException | XMLStreamException e) {
606                Logging.error(e);
607                Logging.warn(tr("Failed to initialize preferences. Failed to reset preference file to default: {0}", getPreferenceFile()));
608            }
609        }
610        if (!initSuccessful) {
611            try {
612                if (!GraphicsEnvironment.isHeadless()) {
613                    JOptionPane.showMessageDialog(
614                            MainApplication.getMainFrame(),
615                            tr("<html>Preferences file had errors.<br> Creating a new default preference file.</html>"),
616                             tr("Error"),
617                            JOptionPane.ERROR_MESSAGE
618                    );
619                }
620                resetToDefault();
621                save();
622            } catch (IOException e1) {
623                Logging.error(e1);
624                Logging.warn(tr("Failed to initialize preferences. Failed to reset preference file to default: {0}", getPreferenceFile()));
625            }
626        }
627    }
628
629    /**
630     * Resets the preferences to their initial state. This resets all values and file associations.
631     * The default values and listeners are not removed.
632     * <p>
633     * It is meant to be called before {@link #init(boolean)}
634     * @since 10876
635     */
636    public void resetToInitialState() {
637        resetToDefault();
638        saveOnPut = true;
639        initSuccessful = false;
640    }
641
642    /**
643     * Reset all values stored in this map to the default values. This clears the preferences.
644     */
645    public final synchronized void resetToDefault() {
646        settingsMap.clear();
647    }
648
649    /**
650     * Set a value for a certain setting. The changed setting is saved to the preference file immediately.
651     * Due to caching mechanisms on modern operating systems and hardware, this shouldn't be a performance problem.
652     * @param key the unique identifier for the setting
653     * @param setting the value of the setting. In case it is null, the key-value entry will be removed.
654     * @return {@code true}, if something has changed (i.e. value is different than before)
655     */
656    @Override
657    public boolean putSetting(final String key, Setting<?> setting) {
658        CheckParameterUtil.ensureParameterNotNull(key);
659        if (setting != null && setting.getValue() == null)
660            throw new IllegalArgumentException("setting argument must not have null value");
661        Setting<?> settingOld;
662        Setting<?> settingCopy = null;
663        synchronized (this) {
664            if (setting == null) {
665                settingOld = settingsMap.remove(key);
666                if (settingOld == null)
667                    return false;
668            } else {
669                settingOld = settingsMap.get(key);
670                if (setting.equals(settingOld))
671                    return false;
672                if (settingOld == null && setting.equals(defaultsMap.get(key)))
673                    return false;
674                settingCopy = setting.copy();
675                settingsMap.put(key, settingCopy);
676            }
677            if (saveOnPut) {
678                try {
679                    save();
680                } catch (IOException | InvalidPathException e) {
681                    File file = getPreferenceFile();
682                    try {
683                        file = file.getAbsoluteFile();
684                    } catch (SecurityException ex) {
685                        Logging.trace(ex);
686                    }
687                    Logging.log(Logging.LEVEL_WARN, tr("Failed to persist preferences to ''{0}''", file), e);
688                }
689            }
690        }
691        // Call outside of synchronized section in case some listener wait for other thread that wait for preference lock
692        firePreferenceChanged(key, settingOld, settingCopy);
693        return true;
694    }
695
696    /**
697     * Get a setting of any type
698     * @param key The key for the setting
699     * @param def The default value to use if it was not found
700     * @return The setting
701     */
702    public synchronized Setting<?> getSetting(String key, Setting<?> def) {
703        return getSetting(key, def, Setting.class);
704    }
705
706    /**
707     * Get settings value for a certain key and provide default a value.
708     * @param <T> the setting type
709     * @param key the identifier for the setting
710     * @param def the default value. For each call of getSetting() with a given key, the default value must be the same.
711     * <code>def</code> must not be null, but the value of <code>def</code> can be null.
712     * @param klass the setting type (same as T)
713     * @return the corresponding value if the property has been set before, {@code def} otherwise
714     */
715    @SuppressWarnings("unchecked")
716    @Override
717    public synchronized <T extends Setting<?>> T getSetting(String key, T def, Class<T> klass) {
718        CheckParameterUtil.ensureParameterNotNull(key);
719        CheckParameterUtil.ensureParameterNotNull(def);
720        Setting<?> oldDef = defaultsMap.get(key);
721        if (oldDef != null && oldDef.isNew() && oldDef.getValue() != null && def.getValue() != null && !def.equals(oldDef)) {
722            Logging.info("Defaults for " + key + " differ: " + def + " != " + defaultsMap.get(key));
723        }
724        if (def.getValue() != null || oldDef == null) {
725            Setting<?> defCopy = def.copy();
726            defCopy.setTime(System.currentTimeMillis() / 1000);
727            defCopy.setNew(true);
728            defaultsMap.put(key, defCopy);
729        }
730        Setting<?> prop = settingsMap.get(key);
731        if (klass.isInstance(prop)) {
732            return (T) prop;
733        } else {
734            return def;
735        }
736    }
737
738    @Override
739    public Set<String> getKeySet() {
740        return Collections.unmodifiableSet(settingsMap.keySet());
741    }
742
743    @Override
744    public Map<String, Setting<?>> getAllSettings() {
745        return new TreeMap<>(settingsMap);
746    }
747
748    /**
749     * Gets a map of all currently known defaults
750     * @return The map (key/setting)
751     */
752    public Map<String, Setting<?>> getAllDefaults() {
753        return new TreeMap<>(defaultsMap);
754    }
755
756    /**
757     * Replies the collection of plugin site URLs from where plugin lists can be downloaded.
758     * @return the collection of plugin site URLs
759     * @see #getOnlinePluginSites
760     */
761    public Collection<String> getPluginSites() {
762        return getList("pluginmanager.sites", Collections.singletonList(Config.getUrls().getJOSMWebsite()+"/pluginicons%<?plugins=>"));
763    }
764
765    /**
766     * Returns the list of plugin sites available according to offline mode settings.
767     * @return the list of available plugin sites
768     * @since 8471
769     */
770    public Collection<String> getOnlinePluginSites() {
771        Collection<String> pluginSites = new ArrayList<>(getPluginSites());
772        pluginSites.removeIf(NetworkManager::isOffline);
773        return pluginSites;
774    }
775
776    /**
777     * Sets the collection of plugin site URLs.
778     *
779     * @param sites the site URLs
780     */
781    public void setPluginSites(Collection<String> sites) {
782        putList("pluginmanager.sites", new ArrayList<>(sites));
783    }
784
785    /**
786     * Returns XML describing these preferences.
787     * @param nopass if password must be excluded
788     * @return XML
789     */
790    public synchronized String toXML(boolean nopass) {
791        return toXML(settingsMap.entrySet(), nopass, false);
792    }
793
794    /**
795     * Returns XML describing the given preferences.
796     * @param settings preferences settings
797     * @param nopass if password must be excluded
798     * @param defaults true, if default values are converted to XML, false for
799     * regular preferences
800     * @return XML
801     */
802    public String toXML(Collection<Entry<String, Setting<?>>> settings, boolean nopass, boolean defaults) {
803        try (
804            StringWriter sw = new StringWriter();
805            PreferencesWriter prefWriter = new PreferencesWriter(new PrintWriter(sw), nopass, defaults)
806        ) {
807            prefWriter.write(settings);
808            sw.flush();
809            return sw.toString();
810        } catch (IOException e) {
811            Logging.error(e);
812            return null;
813        }
814    }
815
816    /**
817     * Removes and updates obsolete preference settings. If you throw out a once-used preference
818     * setting, add it to the list here with an expiry date (written as comment). If you
819     * see something with an expiry date in the past, remove it from the list.
820     * @param loadedVersion JOSM version when the preferences file was written
821     */
822    private void removeAndUpdateObsolete(int loadedVersion) {
823        Logging.trace("Update obsolete preference keys for version {0}", Integer.toString(loadedVersion));
824        for (Entry<String, String> e : UPDATE_PREF_KEYS.entrySet()) {
825            String oldkey = e.getKey();
826            String newkey = e.getValue();
827            if (settingsMap.containsKey(oldkey)) {
828                Setting<?> value = settingsMap.remove(oldkey);
829                settingsMap.putIfAbsent(newkey, value);
830                Logging.info(tr("Updated preference setting {0} to {1}", oldkey, newkey));
831            }
832        }
833
834        Logging.trace("Remove obsolete preferences for version {0}", Integer.toString(loadedVersion));
835        for (String key : OBSOLETE_PREF_KEYS) {
836            if (settingsMap.containsKey(key)) {
837                settingsMap.remove(key);
838                Logging.info(tr("Removed preference setting {0} since it is no longer used", key));
839            }
840            if (defaultsMap.containsKey(key)) {
841                defaultsMap.remove(key);
842                Logging.info(tr("Removed preference default {0} since it is no longer used", key));
843                modifiedDefault = true;
844            }
845        }
846        for (String key : OBSOLETE_PREF_KEYS_START) {
847            settingsMap.entrySet().stream()
848            .filter(e -> e.getKey().startsWith(key))
849            .collect(Collectors.toSet())
850            .forEach(e -> {
851                String k = e.getKey();
852                if (!KEEP_PREF_KEYS.contains(k)) {
853                    settingsMap.remove(k);
854                    Logging.info(tr("Removed preference setting {0} since it is no longer used", k));
855                }
856            });
857            defaultsMap.entrySet().stream()
858            .filter(e -> e.getKey().startsWith(key))
859            .collect(Collectors.toSet())
860            .forEach(e -> {
861                String k = e.getKey();
862                if (!KEEP_PREF_KEYS.contains(k)) {
863                    defaultsMap.remove(k);
864                    Logging.info(tr("Removed preference default {0} since it is no longer used", k));
865                    modifiedDefault = true;
866                }
867            });
868        }
869        if (!getBoolean("preferences.reset.draw.rawgps.lines")) {
870            // see #18444
871            // add "preferences.reset.draw.rawgps.lines" to OBSOLETE_PREF_KEYS when removing
872            putBoolean("preferences.reset.draw.rawgps.lines", true);
873            putInt("draw.rawgps.lines", -1);
874        }
875        updateMapPaintKnownDefaults();
876        if (modifiedDefault) {
877            try {
878                saveDefaults();
879                Logging.info(tr("Saved updated default preferences."));
880            } catch (IOException ex) {
881                Logging.log(Logging.LEVEL_WARN, tr("Failed to save default preferences."), ex);
882            }
883            modifiedDefault = false;
884        }
885        // As of June 1st, 2024, the OSM.org instance no longer allows basic authentication.
886        if (JosmUrls.getInstance().getDefaultOsmApiUrl().equals(OsmApi.getOsmApi().getServerUrl()) && "basic".equals(OsmApi.getAuthMethod())) {
887            put("osm-server.auth-method", null);
888            put("osm-server.username", null);
889            put("osm-server.password", null);
890        }
891    }
892
893    /**
894     * Update the known defaults for the map paintstyles.
895     * This should be removed sometime after 2024-06-01.
896     */
897    private void updateMapPaintKnownDefaults() {
898        final String mapPaintStyleEntriesPrefEntry = "mappaint.style.entries";
899        final String url = "url";
900        final String active = "active";
901        final String potlatch2 = "resource://styles/standard/potlatch2.mapcss";
902        final String remotePotlatch2 = "https://josm.openstreetmap.de/josmfile?page=Styles/Potlatch2&zip=1";
903
904        // Remove potlatch2 from the known defaults
905        final List<String> knownDefaults = new ArrayList<>(getList("mappaint.style.known-defaults"));
906        // See #18866: Potlatch 2 internal theme removed in favor of remote theme by Stereo
907        knownDefaults.removeIf(potlatch2::equals);
908
909        // Moved from MapPaintPrefHelper for consistency
910        // XML style is not bundled anymore
911        knownDefaults.removeIf("resource://styles/standard/elemstyles.xml"::equals);
912        putList("mappaint.style.known-defaults", knownDefaults);
913
914        // If the user hasn't set the entries, don't go through the removal process for potlatch 2. There is an issue
915        // where it may clear all paintstyles (done when the user has never touched the style settings).
916        if (!this.settingsMap.containsKey(mapPaintStyleEntriesPrefEntry)) {
917            return;
918        }
919        // Replace potlatch2 in the current style entries, but only if it is enabled. Otherwise, remove it.
920        final List<Map<String, String>> styleEntries = new ArrayList<>(getListOfMaps(mapPaintStyleEntriesPrefEntry));
921        final boolean potlatchEnabled = styleEntries.stream().filter(map -> potlatch2.equals(map.get(url)))
922                .anyMatch(map -> Boolean.parseBoolean(map.get(active)));
923        final boolean remotePotlatch2Present = styleEntries.stream().anyMatch(map -> remotePotlatch2.equals(map.get(url)));
924        // Remove potlatch2 if it is not enabled _or_ the remote potlatch2 version is present
925        styleEntries.removeIf(map -> (!potlatchEnabled || remotePotlatch2Present) && potlatch2.equals(map.get(url)));
926        styleEntries.replaceAll(HashMap::new); // The maps are initially immutable.
927        for (Map<String, String> map : styleEntries) {
928            if (potlatch2.equals(map.get(url))) {
929                map.put(url, remotePotlatch2);
930            }
931        }
932        putListOfMaps(mapPaintStyleEntriesPrefEntry, styleEntries);
933    }
934
935    /**
936     * Enables or not the preferences file auto-save mechanism (save each time a setting is changed).
937     * This behaviour is enabled by default.
938     * @param enable if {@code true}, makes JOSM save preferences file each time a setting is changed
939     * @since 7085
940     */
941    public final void enableSaveOnPut(boolean enable) {
942        synchronized (this) {
943            saveOnPut = enable;
944        }
945    }
946
947    /**
948     * A consumer that can throw an exception
949     * @param <T> The object type to accept
950     * @param <E> The throwable type
951     */
952    @FunctionalInterface
953    private interface ThrowingConsumer<T, E extends Throwable> {
954        /**
955         * Accept an object
956         * @param object The object to accept
957         * @throws E The exception that can be thrown
958         */
959        void accept(T object) throws E;
960    }
961}