source: josm/trunk/src/org/openstreetmap/josm/data/Preferences.java@ 10922

Last change on this file since 10922 was 10920, checked in by michael2402, 8 years ago

See #13309: Do not add 'color.' prefix twice in getColor()

  • Property svn:eol-style set to native
File size: 60.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.Color;
8import java.awt.GraphicsEnvironment;
9import java.awt.Toolkit;
10import java.io.File;
11import java.io.FileOutputStream;
12import java.io.IOException;
13import java.io.OutputStreamWriter;
14import java.io.PrintWriter;
15import java.io.Reader;
16import java.io.StringReader;
17import java.io.StringWriter;
18import java.lang.annotation.Retention;
19import java.lang.annotation.RetentionPolicy;
20import java.lang.reflect.Field;
21import java.nio.charset.StandardCharsets;
22import java.util.ArrayList;
23import java.util.Collection;
24import java.util.Collections;
25import java.util.HashMap;
26import java.util.HashSet;
27import java.util.Iterator;
28import java.util.LinkedHashMap;
29import java.util.LinkedList;
30import java.util.List;
31import java.util.Map;
32import java.util.Map.Entry;
33import java.util.MissingResourceException;
34import java.util.Objects;
35import java.util.ResourceBundle;
36import java.util.Set;
37import java.util.SortedMap;
38import java.util.TreeMap;
39import java.util.function.Predicate;
40import java.util.regex.Matcher;
41import java.util.regex.Pattern;
42import java.util.stream.Stream;
43
44import javax.json.Json;
45import javax.json.JsonArray;
46import javax.json.JsonArrayBuilder;
47import javax.json.JsonObject;
48import javax.json.JsonObjectBuilder;
49import javax.json.JsonReader;
50import javax.json.JsonString;
51import javax.json.JsonValue;
52import javax.json.JsonWriter;
53import javax.swing.JOptionPane;
54import javax.xml.stream.XMLStreamException;
55
56import org.openstreetmap.josm.Main;
57import org.openstreetmap.josm.data.preferences.BooleanProperty;
58import org.openstreetmap.josm.data.preferences.ColorProperty;
59import org.openstreetmap.josm.data.preferences.DoubleProperty;
60import org.openstreetmap.josm.data.preferences.IntegerProperty;
61import org.openstreetmap.josm.data.preferences.ListListSetting;
62import org.openstreetmap.josm.data.preferences.ListSetting;
63import org.openstreetmap.josm.data.preferences.LongProperty;
64import org.openstreetmap.josm.data.preferences.MapListSetting;
65import org.openstreetmap.josm.data.preferences.PreferencesReader;
66import org.openstreetmap.josm.data.preferences.PreferencesWriter;
67import org.openstreetmap.josm.data.preferences.Setting;
68import org.openstreetmap.josm.data.preferences.StringSetting;
69import org.openstreetmap.josm.io.OfflineAccessException;
70import org.openstreetmap.josm.io.OnlineResource;
71import org.openstreetmap.josm.tools.CheckParameterUtil;
72import org.openstreetmap.josm.tools.ColorHelper;
73import org.openstreetmap.josm.tools.I18n;
74import org.openstreetmap.josm.tools.ListenerList;
75import org.openstreetmap.josm.tools.MultiMap;
76import org.openstreetmap.josm.tools.Utils;
77import org.xml.sax.SAXException;
78
79/**
80 * This class holds all preferences for JOSM.
81 *
82 * Other classes can register their beloved properties here. All properties will be
83 * saved upon set-access.
84 *
85 * Each property is a key=setting pair, where key is a String and setting can be one of
86 * 4 types:
87 * string, list, list of lists and list of maps.
88 * In addition, each key has a unique default value that is set when the value is first
89 * accessed using one of the get...() methods. You can use the same preference
90 * key in different parts of the code, but the default value must be the same
91 * everywhere. A default value of null means, the setting has been requested, but
92 * no default value was set. This is used in advanced preferences to present a list
93 * off all possible settings.
94 *
95 * At the moment, you cannot put the empty string for string properties.
96 * put(key, "") means, the property is removed.
97 *
98 * @author imi
99 * @since 74
100 */
101public class Preferences {
102
103 private static final String[] OBSOLETE_PREF_KEYS = {
104 };
105
106 private static final long MAX_AGE_DEFAULT_PREFERENCES = 60L * 60L * 24L * 50L; // 50 days (in seconds)
107
108 /**
109 * Internal storage for the preference directory.
110 * Do not access this variable directly!
111 * @see #getPreferencesDirectory()
112 */
113 private File preferencesDir;
114
115 /**
116 * Internal storage for the cache directory.
117 */
118 private File cacheDir;
119
120 /**
121 * Internal storage for the user data directory.
122 */
123 private File userdataDir;
124
125 /**
126 * Determines if preferences file is saved each time a property is changed.
127 */
128 private boolean saveOnPut = true;
129
130 /**
131 * Maps the setting name to the current value of the setting.
132 * The map must not contain null as key or value. The mapped setting objects
133 * must not have a null value.
134 */
135 protected final SortedMap<String, Setting<?>> settingsMap = new TreeMap<>();
136
137 /**
138 * Maps the setting name to the default value of the setting.
139 * The map must not contain null as key or value. The value of the mapped
140 * setting objects can be null.
141 */
142 protected final SortedMap<String, Setting<?>> defaultsMap = new TreeMap<>();
143
144 private final Predicate<Entry<String, Setting<?>>> NO_DEFAULT_SETTINGS_ENTRY =
145 e -> !e.getValue().equals(defaultsMap.get(e.getKey()));
146
147 /**
148 * Maps color keys to human readable color name
149 */
150 protected final SortedMap<String, String> colornames = new TreeMap<>();
151
152 /**
153 * Indicates whether {@link #init(boolean)} completed successfully.
154 * Used to decide whether to write backup preference file in {@link #save()}
155 */
156 protected boolean initSuccessful;
157
158 /**
159 * Event triggered when a preference entry value changes.
160 */
161 public interface PreferenceChangeEvent {
162 /**
163 * Returns the preference key.
164 * @return the preference key
165 */
166 String getKey();
167
168 /**
169 * Returns the old preference value.
170 * @return the old preference value
171 */
172 Setting<?> getOldValue();
173
174 /**
175 * Returns the new preference value.
176 * @return the new preference value
177 */
178 Setting<?> getNewValue();
179 }
180
181 /**
182 * Listener to preference change events.
183 * @since 10600 (functional interface)
184 */
185 @FunctionalInterface
186 public interface PreferenceChangedListener {
187 /**
188 * Trigerred when a preference entry value changes.
189 * @param e the preference change event
190 */
191 void preferenceChanged(PreferenceChangeEvent e);
192 }
193
194 private static class DefaultPreferenceChangeEvent implements PreferenceChangeEvent {
195 private final String key;
196 private final Setting<?> oldValue;
197 private final Setting<?> newValue;
198
199 DefaultPreferenceChangeEvent(String key, Setting<?> oldValue, Setting<?> newValue) {
200 this.key = key;
201 this.oldValue = oldValue;
202 this.newValue = newValue;
203 }
204
205 @Override
206 public String getKey() {
207 return key;
208 }
209
210 @Override
211 public Setting<?> getOldValue() {
212 return oldValue;
213 }
214
215 @Override
216 public Setting<?> getNewValue() {
217 return newValue;
218 }
219 }
220
221 private final ListenerList<PreferenceChangedListener> listeners = ListenerList.create();
222
223 private final HashMap<String, ListenerList<PreferenceChangedListener>> keyListeners = new HashMap<>();
224
225 /**
226 * Adds a new preferences listener.
227 * @param listener The listener to add
228 */
229 public void addPreferenceChangeListener(PreferenceChangedListener listener) {
230 if (listener != null) {
231 listeners.addListener(listener);
232 }
233 }
234
235 /**
236 * Removes a preferences listener.
237 * @param listener The listener to remove
238 */
239 public void removePreferenceChangeListener(PreferenceChangedListener listener) {
240 listeners.removeListener(listener);
241 }
242
243 /**
244 * Adds a listener that only listens to changes in one preference
245 * @param key The preference key to listen to
246 * @param listener The listener to add.
247 * @since 10824
248 */
249 public void addKeyPreferenceChangeListener(String key, PreferenceChangedListener listener) {
250 listenersForKey(key).addListener(listener);
251 }
252
253 /**
254 * Adds a weak listener that only listens to changes in one preference
255 * @param key The preference key to listen to
256 * @param listener The listener to add.
257 * @since 10824
258 */
259 public void addWeakKeyPreferenceChangeListener(String key, PreferenceChangedListener listener) {
260 listenersForKey(key).addWeakListener(listener);
261 }
262
263 private ListenerList<PreferenceChangedListener> listenersForKey(String key) {
264 ListenerList<PreferenceChangedListener> keyListener = keyListeners.get(key);
265 if (keyListener == null) {
266 keyListener = ListenerList.create();
267 keyListeners.put(key, keyListener);
268 }
269 return keyListener;
270 }
271
272 /**
273 * Removes a listener that only listens to changes in one preference
274 * @param key The preference key to listen to
275 * @param listener The listener to add.
276 */
277 public void removeKeyPreferenceChangeListener(String key, PreferenceChangedListener listener) {
278 ListenerList<PreferenceChangedListener> keyListener = keyListeners.get(key);
279 if (keyListener == null) {
280 throw new IllegalArgumentException("There are no listeners registered for " + key);
281 }
282 keyListener.removeListener(listener);
283 }
284
285 protected void firePreferenceChanged(String key, Setting<?> oldValue, Setting<?> newValue) {
286 final PreferenceChangeEvent evt = new DefaultPreferenceChangeEvent(key, oldValue, newValue);
287 listeners.fireEvent(listener -> listener.preferenceChanged(evt));
288
289 ListenerList<PreferenceChangedListener> forKey = keyListeners.get(key);
290 if (forKey != null) {
291 forKey.fireEvent(listener -> listener.preferenceChanged(evt));
292 }
293 }
294
295 /**
296 * Returns the user defined preferences directory, containing the preferences.xml file
297 * @return The user defined preferences directory, containing the preferences.xml file
298 * @since 7834
299 */
300 public File getPreferencesDirectory() {
301 if (preferencesDir != null)
302 return preferencesDir;
303 String path;
304 path = System.getProperty("josm.pref");
305 if (path != null) {
306 preferencesDir = new File(path).getAbsoluteFile();
307 } else {
308 path = System.getProperty("josm.home");
309 if (path != null) {
310 preferencesDir = new File(path).getAbsoluteFile();
311 } else {
312 preferencesDir = Main.platform.getDefaultPrefDirectory();
313 }
314 }
315 return preferencesDir;
316 }
317
318 /**
319 * Returns the user data directory, containing autosave, plugins, etc.
320 * Depending on the OS it may be the same directory as preferences directory.
321 * @return The user data directory, containing autosave, plugins, etc.
322 * @since 7834
323 */
324 public File getUserDataDirectory() {
325 if (userdataDir != null)
326 return userdataDir;
327 String path;
328 path = System.getProperty("josm.userdata");
329 if (path != null) {
330 userdataDir = new File(path).getAbsoluteFile();
331 } else {
332 path = System.getProperty("josm.home");
333 if (path != null) {
334 userdataDir = new File(path).getAbsoluteFile();
335 } else {
336 userdataDir = Main.platform.getDefaultUserDataDirectory();
337 }
338 }
339 return userdataDir;
340 }
341
342 /**
343 * Returns the user preferences file (preferences.xml).
344 * @return The user preferences file (preferences.xml)
345 */
346 public File getPreferenceFile() {
347 return new File(getPreferencesDirectory(), "preferences.xml");
348 }
349
350 /**
351 * Returns the cache file for default preferences.
352 * @return the cache file for default preferences
353 */
354 public File getDefaultsCacheFile() {
355 return new File(getCacheDirectory(), "default_preferences.xml");
356 }
357
358 /**
359 * Returns the user plugin directory.
360 * @return The user plugin directory
361 */
362 public File getPluginsDirectory() {
363 return new File(getUserDataDirectory(), "plugins");
364 }
365
366 /**
367 * Get the directory where cached content of any kind should be stored.
368 *
369 * If the directory doesn't exist on the file system, it will be created by this method.
370 *
371 * @return the cache directory
372 */
373 public File getCacheDirectory() {
374 if (cacheDir != null)
375 return cacheDir;
376 String path = System.getProperty("josm.cache");
377 if (path != null) {
378 cacheDir = new File(path).getAbsoluteFile();
379 } else {
380 path = System.getProperty("josm.home");
381 if (path != null) {
382 cacheDir = new File(path, "cache");
383 } else {
384 path = get("cache.folder", null);
385 if (path != null) {
386 cacheDir = new File(path).getAbsoluteFile();
387 } else {
388 cacheDir = Main.platform.getDefaultCacheDirectory();
389 }
390 }
391 }
392 if (!cacheDir.exists() && !cacheDir.mkdirs()) {
393 Main.warn(tr("Failed to create missing cache directory: {0}", cacheDir.getAbsoluteFile()));
394 JOptionPane.showMessageDialog(
395 Main.parent,
396 tr("<html>Failed to create missing cache directory: {0}</html>", cacheDir.getAbsoluteFile()),
397 tr("Error"),
398 JOptionPane.ERROR_MESSAGE
399 );
400 }
401 return cacheDir;
402 }
403
404 private static void addPossibleResourceDir(Set<String> locations, String s) {
405 if (s != null) {
406 if (!s.endsWith(File.separator)) {
407 s += File.separator;
408 }
409 locations.add(s);
410 }
411 }
412
413 /**
414 * Returns a set of all existing directories where resources could be stored.
415 * @return A set of all existing directories where resources could be stored.
416 */
417 public Collection<String> getAllPossiblePreferenceDirs() {
418 Set<String> locations = new HashSet<>();
419 addPossibleResourceDir(locations, getPreferencesDirectory().getPath());
420 addPossibleResourceDir(locations, getUserDataDirectory().getPath());
421 addPossibleResourceDir(locations, System.getenv("JOSM_RESOURCES"));
422 addPossibleResourceDir(locations, System.getProperty("josm.resources"));
423 if (Main.isPlatformWindows()) {
424 String appdata = System.getenv("APPDATA");
425 if (System.getenv("ALLUSERSPROFILE") != null && appdata != null
426 && appdata.lastIndexOf(File.separator) != -1) {
427 appdata = appdata.substring(appdata.lastIndexOf(File.separator));
428 locations.add(new File(new File(System.getenv("ALLUSERSPROFILE"),
429 appdata), "JOSM").getPath());
430 }
431 } else {
432 locations.add("/usr/local/share/josm/");
433 locations.add("/usr/local/lib/josm/");
434 locations.add("/usr/share/josm/");
435 locations.add("/usr/lib/josm/");
436 }
437 return locations;
438 }
439
440 /**
441 * Get settings value for a certain key.
442 * @param key the identifier for the setting
443 * @return "" if there is nothing set for the preference key, the corresponding value otherwise. The result is not null.
444 */
445 public synchronized String get(final String key) {
446 String value = get(key, null);
447 return value == null ? "" : value;
448 }
449
450 /**
451 * Get settings value for a certain key and provide default a value.
452 * @param key the identifier for the setting
453 * @param def the default value. For each call of get() with a given key, the default value must be the same.
454 * @return the corresponding value if the property has been set before, {@code def} otherwise
455 */
456 public synchronized String get(final String key, final String def) {
457 return getSetting(key, new StringSetting(def), StringSetting.class).getValue();
458 }
459
460 public synchronized Map<String, String> getAllPrefix(final String prefix) {
461 final Map<String, String> all = new TreeMap<>();
462 for (final Entry<String, Setting<?>> e : settingsMap.entrySet()) {
463 if (e.getKey().startsWith(prefix) && (e.getValue() instanceof StringSetting)) {
464 all.put(e.getKey(), ((StringSetting) e.getValue()).getValue());
465 }
466 }
467 return all;
468 }
469
470 public synchronized List<String> getAllPrefixCollectionKeys(final String prefix) {
471 final List<String> all = new LinkedList<>();
472 for (Map.Entry<String, Setting<?>> entry : settingsMap.entrySet()) {
473 if (entry.getKey().startsWith(prefix) && entry.getValue() instanceof ListSetting) {
474 all.add(entry.getKey());
475 }
476 }
477 return all;
478 }
479
480 public synchronized Map<String, String> getAllColors() {
481 final Map<String, String> all = new TreeMap<>();
482 for (final Entry<String, Setting<?>> e : defaultsMap.entrySet()) {
483 if (e.getKey().startsWith("color.") && e.getValue() instanceof StringSetting) {
484 StringSetting d = (StringSetting) e.getValue();
485 if (d.getValue() != null) {
486 all.put(e.getKey().substring(6), d.getValue());
487 }
488 }
489 }
490 for (final Entry<String, Setting<?>> e : settingsMap.entrySet()) {
491 if (e.getKey().startsWith("color.") && (e.getValue() instanceof StringSetting)) {
492 all.put(e.getKey().substring(6), ((StringSetting) e.getValue()).getValue());
493 }
494 }
495 return all;
496 }
497
498 public synchronized boolean getBoolean(final String key) {
499 String s = get(key, null);
500 return s != null && Boolean.parseBoolean(s);
501 }
502
503 public synchronized boolean getBoolean(final String key, final boolean def) {
504 return Boolean.parseBoolean(get(key, Boolean.toString(def)));
505 }
506
507 public synchronized boolean getBoolean(final String key, final String specName, final boolean def) {
508 boolean generic = getBoolean(key, def);
509 String skey = key+'.'+specName;
510 Setting<?> prop = settingsMap.get(skey);
511 if (prop instanceof StringSetting)
512 return Boolean.parseBoolean(((StringSetting) prop).getValue());
513 else
514 return generic;
515 }
516
517 /**
518 * Set a value for a certain setting.
519 * @param key the unique identifier for the setting
520 * @param value the value of the setting. Can be null or "" which both removes the key-value entry.
521 * @return {@code true}, if something has changed (i.e. value is different than before)
522 */
523 public boolean put(final String key, String value) {
524 return putSetting(key, value == null || value.isEmpty() ? null : new StringSetting(value));
525 }
526
527 /**
528 * Set a boolean value for a certain setting.
529 * @param key the unique identifier for the setting
530 * @param value The new value
531 * @return {@code true}, if something has changed (i.e. value is different than before)
532 * @see BooleanProperty
533 */
534 public boolean put(final String key, final boolean value) {
535 return put(key, Boolean.toString(value));
536 }
537
538 /**
539 * Set a boolean value for a certain setting.
540 * @param key the unique identifier for the setting
541 * @param value The new value
542 * @return {@code true}, if something has changed (i.e. value is different than before)
543 * @see IntegerProperty
544 */
545 public boolean putInteger(final String key, final Integer value) {
546 return put(key, Integer.toString(value));
547 }
548
549 /**
550 * Set a boolean value for a certain setting.
551 * @param key the unique identifier for the setting
552 * @param value The new value
553 * @return {@code true}, if something has changed (i.e. value is different than before)
554 * @see DoubleProperty
555 */
556 public boolean putDouble(final String key, final Double value) {
557 return put(key, Double.toString(value));
558 }
559
560 /**
561 * Set a boolean value for a certain setting.
562 * @param key the unique identifier for the setting
563 * @param value The new value
564 * @return {@code true}, if something has changed (i.e. value is different than before)
565 * @see LongProperty
566 */
567 public boolean putLong(final String key, final Long value) {
568 return put(key, Long.toString(value));
569 }
570
571 /**
572 * Called after every put. In case of a problem, do nothing but output the error in log.
573 * @throws IOException if any I/O error occurs
574 */
575 public synchronized void save() throws IOException {
576 save(getPreferenceFile(), settingsMap.entrySet().stream().filter(NO_DEFAULT_SETTINGS_ENTRY), false);
577 }
578
579 public synchronized void saveDefaults() throws IOException {
580 save(getDefaultsCacheFile(), defaultsMap.entrySet().stream(), true);
581 }
582
583 protected void save(File prefFile, Stream<Entry<String, Setting<?>>> settings, boolean defaults) throws IOException {
584 if (!defaults) {
585 /* currently unused, but may help to fix configuration issues in future */
586 putInteger("josm.version", Version.getInstance().getVersion());
587
588 updateSystemProperties();
589 }
590
591 File backupFile = new File(prefFile + "_backup");
592
593 // Backup old preferences if there are old preferences
594 if (prefFile.exists() && prefFile.length() > 0 && initSuccessful) {
595 Utils.copyFile(prefFile, backupFile);
596 }
597
598 try (PrintWriter out = new PrintWriter(new OutputStreamWriter(
599 new FileOutputStream(prefFile + "_tmp"), StandardCharsets.UTF_8), false)) {
600 PreferencesWriter writer = new PreferencesWriter(out, false, defaults);
601 writer.write(settings);
602 }
603
604 File tmpFile = new File(prefFile + "_tmp");
605 Utils.copyFile(tmpFile, prefFile);
606 Utils.deleteFile(tmpFile, marktr("Unable to delete temporary file {0}"));
607
608 setCorrectPermissions(prefFile);
609 setCorrectPermissions(backupFile);
610 }
611
612 private static void setCorrectPermissions(File file) {
613 if (!file.setReadable(false, false) && Main.isDebugEnabled()) {
614 Main.debug(tr("Unable to set file non-readable {0}", file.getAbsolutePath()));
615 }
616 if (!file.setWritable(false, false) && Main.isDebugEnabled()) {
617 Main.debug(tr("Unable to set file non-writable {0}", file.getAbsolutePath()));
618 }
619 if (!file.setExecutable(false, false) && Main.isDebugEnabled()) {
620 Main.debug(tr("Unable to set file non-executable {0}", file.getAbsolutePath()));
621 }
622 if (!file.setReadable(true, true) && Main.isDebugEnabled()) {
623 Main.debug(tr("Unable to set file readable {0}", file.getAbsolutePath()));
624 }
625 if (!file.setWritable(true, true) && Main.isDebugEnabled()) {
626 Main.debug(tr("Unable to set file writable {0}", file.getAbsolutePath()));
627 }
628 }
629
630 /**
631 * Loads preferences from settings file.
632 * @throws IOException if any I/O error occurs while reading the file
633 * @throws SAXException if the settings file does not contain valid XML
634 * @throws XMLStreamException if an XML error occurs while parsing the file (after validation)
635 */
636 protected void load() throws IOException, SAXException, XMLStreamException {
637 File pref = getPreferenceFile();
638 PreferencesReader.validateXML(pref);
639 PreferencesReader reader = new PreferencesReader(pref, false);
640 reader.parse();
641 settingsMap.clear();
642 settingsMap.putAll(reader.getSettings());
643 updateSystemProperties();
644 removeObsolete(reader.getVersion());
645 }
646
647 /**
648 * Loads default preferences from default settings cache file.
649 *
650 * Discards entries older than {@link #MAX_AGE_DEFAULT_PREFERENCES}.
651 *
652 * @throws IOException if any I/O error occurs while reading the file
653 * @throws SAXException if the settings file does not contain valid XML
654 * @throws XMLStreamException if an XML error occurs while parsing the file (after validation)
655 */
656 protected void loadDefaults() throws IOException, XMLStreamException, SAXException {
657 File def = getDefaultsCacheFile();
658 PreferencesReader.validateXML(def);
659 PreferencesReader reader = new PreferencesReader(def, true);
660 reader.parse();
661 defaultsMap.clear();
662 long minTime = System.currentTimeMillis() / 1000 - MAX_AGE_DEFAULT_PREFERENCES;
663 for (Entry<String, Setting<?>> e : reader.getSettings().entrySet()) {
664 if (e.getValue().getTime() >= minTime) {
665 defaultsMap.put(e.getKey(), e.getValue());
666 }
667 }
668 }
669
670 /**
671 * Loads preferences from XML reader.
672 * @param in XML reader
673 * @throws XMLStreamException if any XML stream error occurs
674 * @throws IOException if any I/O error occurs
675 */
676 public void fromXML(Reader in) throws XMLStreamException, IOException {
677 PreferencesReader reader = new PreferencesReader(in, false);
678 reader.parse();
679 settingsMap.clear();
680 settingsMap.putAll(reader.getSettings());
681 }
682
683 /**
684 * Initializes preferences.
685 * @param reset if {@code true}, current settings file is replaced by the default one
686 */
687 public void init(boolean reset) {
688 initSuccessful = false;
689 // get the preferences.
690 File prefDir = getPreferencesDirectory();
691 if (prefDir.exists()) {
692 if (!prefDir.isDirectory()) {
693 Main.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.",
694 prefDir.getAbsoluteFile()));
695 JOptionPane.showMessageDialog(
696 Main.parent,
697 tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>",
698 prefDir.getAbsoluteFile()),
699 tr("Error"),
700 JOptionPane.ERROR_MESSAGE
701 );
702 return;
703 }
704 } else {
705 if (!prefDir.mkdirs()) {
706 Main.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}",
707 prefDir.getAbsoluteFile()));
708 JOptionPane.showMessageDialog(
709 Main.parent,
710 tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>",
711 prefDir.getAbsoluteFile()),
712 tr("Error"),
713 JOptionPane.ERROR_MESSAGE
714 );
715 return;
716 }
717 }
718
719 File preferenceFile = getPreferenceFile();
720 try {
721 if (!preferenceFile.exists()) {
722 Main.info(tr("Missing preference file ''{0}''. Creating a default preference file.", preferenceFile.getAbsoluteFile()));
723 resetToDefault();
724 save();
725 } else if (reset) {
726 File backupFile = new File(prefDir, "preferences.xml.bak");
727 Main.platform.rename(preferenceFile, backupFile);
728 Main.warn(tr("Replacing existing preference file ''{0}'' with default preference file.", preferenceFile.getAbsoluteFile()));
729 resetToDefault();
730 save();
731 }
732 } catch (IOException e) {
733 Main.error(e);
734 JOptionPane.showMessageDialog(
735 Main.parent,
736 tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>",
737 getPreferenceFile().getAbsoluteFile()),
738 tr("Error"),
739 JOptionPane.ERROR_MESSAGE
740 );
741 return;
742 }
743 try {
744 load();
745 initSuccessful = true;
746 } catch (IOException | SAXException | XMLStreamException e) {
747 Main.error(e);
748 File backupFile = new File(prefDir, "preferences.xml.bak");
749 JOptionPane.showMessageDialog(
750 Main.parent,
751 tr("<html>Preferences file had errors.<br> Making backup of old one to <br>{0}<br> " +
752 "and creating a new default preference file.</html>",
753 backupFile.getAbsoluteFile()),
754 tr("Error"),
755 JOptionPane.ERROR_MESSAGE
756 );
757 Main.platform.rename(preferenceFile, backupFile);
758 try {
759 resetToDefault();
760 save();
761 } catch (IOException e1) {
762 Main.error(e1);
763 Main.warn(tr("Failed to initialize preferences. Failed to reset preference file to default: {0}", getPreferenceFile()));
764 }
765 }
766 File def = getDefaultsCacheFile();
767 if (def.exists()) {
768 try {
769 loadDefaults();
770 } catch (IOException | XMLStreamException | SAXException e) {
771 Main.error(e);
772 Main.warn(tr("Failed to load defaults cache file: {0}", def));
773 defaultsMap.clear();
774 if (!def.delete()) {
775 Main.warn(tr("Failed to delete faulty defaults cache file: {0}", def));
776 }
777 }
778 }
779 }
780
781 /**
782 * Resets the preferences to their initial state. This resets all values and file associations.
783 * The default values and listeners are not removed.
784 * <p>
785 * It is meant to be called before {@link #init(boolean)}
786 * @since 10876
787 */
788 public void resetToInitialState() {
789 resetToDefault();
790 preferencesDir = null;
791 cacheDir = null;
792 userdataDir = null;
793 saveOnPut = true;
794 initSuccessful = false;
795 }
796
797 /**
798 * Reset all values stored in this map to the default values. This clears the preferences.
799 */
800 public final void resetToDefault() {
801 settingsMap.clear();
802 }
803
804 /**
805 * Convenience method for accessing colour preferences.
806 * <p>
807 * To be removed: end of 2016
808 *
809 * @param colName name of the colour
810 * @param def default value
811 * @return a Color object for the configured colour, or the default value if none configured.
812 * @deprecated Use a {@link ColorProperty} instead.
813 */
814 @Deprecated
815 public synchronized Color getColor(String colName, Color def) {
816 return getColor(colName, null, def);
817 }
818
819 /* only for preferences */
820 public synchronized String getColorName(String o) {
821 Matcher m = Pattern.compile("mappaint\\.(.+?)\\.(.+)").matcher(o);
822 if (m.matches()) {
823 return tr("Paint style {0}: {1}", tr(I18n.escape(m.group(1))), tr(I18n.escape(m.group(2))));
824 }
825 m = Pattern.compile("layer (.+)").matcher(o);
826 if (m.matches()) {
827 return tr("Layer: {0}", tr(I18n.escape(m.group(1))));
828 }
829 return tr(I18n.escape(colornames.containsKey(o) ? colornames.get(o) : o));
830 }
831
832 /**
833 * Convenience method for accessing colour preferences.
834 * <p>
835 * To be removed: end of 2016
836 * @param colName name of the colour
837 * @param specName name of the special colour settings
838 * @param def default value
839 * @return a Color object for the configured colour, or the default value if none configured.
840 * @deprecated Use a {@link ColorProperty} instead.
841 * You can replace this by: <code>new ColorProperty(colName, def).getChildColor(specName)</code>
842 */
843 @Deprecated
844 public synchronized Color getColor(String colName, String specName, Color def) {
845 String colKey = ColorProperty.getColorKey(colName);
846 registerColor(colKey, colName);
847 String colStr = specName != null ? get("color."+specName) : "";
848 if (colStr.isEmpty()) {
849 colStr = get(colKey, ColorHelper.color2html(def, true));
850 }
851 if (colStr != null && !colStr.isEmpty()) {
852 return ColorHelper.html2color(colStr);
853 } else {
854 return def;
855 }
856 }
857
858 /**
859 * Registers a color name conversion for the global color registry.
860 * @param colKey The key
861 * @param colName The name of the color.
862 * @since 10824
863 */
864 public void registerColor(String colKey, String colName) {
865 if (!colKey.equals(colName)) {
866 colornames.put(colKey, colName);
867 }
868 }
869
870 public synchronized Color getDefaultColor(String colKey) {
871 StringSetting col = Utils.cast(defaultsMap.get("color."+colKey), StringSetting.class);
872 String colStr = col == null ? null : col.getValue();
873 return colStr == null || colStr.isEmpty() ? null : ColorHelper.html2color(colStr);
874 }
875
876 public synchronized boolean putColor(String colKey, Color val) {
877 return put("color."+colKey, val != null ? ColorHelper.color2html(val, true) : null);
878 }
879
880 public synchronized int getInteger(String key, int def) {
881 String v = get(key, Integer.toString(def));
882 if (v.isEmpty())
883 return def;
884
885 try {
886 return Integer.parseInt(v);
887 } catch (NumberFormatException e) {
888 // fall out
889 Main.trace(e);
890 }
891 return def;
892 }
893
894 public synchronized int getInteger(String key, String specName, int def) {
895 String v = get(key+'.'+specName);
896 if (v.isEmpty())
897 v = get(key, Integer.toString(def));
898 if (v.isEmpty())
899 return def;
900
901 try {
902 return Integer.parseInt(v);
903 } catch (NumberFormatException e) {
904 // fall out
905 Main.trace(e);
906 }
907 return def;
908 }
909
910 public synchronized long getLong(String key, long def) {
911 String v = get(key, Long.toString(def));
912 if (null == v)
913 return def;
914
915 try {
916 return Long.parseLong(v);
917 } catch (NumberFormatException e) {
918 // fall out
919 Main.trace(e);
920 }
921 return def;
922 }
923
924 public synchronized double getDouble(String key, double def) {
925 String v = get(key, Double.toString(def));
926 if (null == v)
927 return def;
928
929 try {
930 return Double.parseDouble(v);
931 } catch (NumberFormatException e) {
932 // fall out
933 Main.trace(e);
934 }
935 return def;
936 }
937
938 /**
939 * Get a list of values for a certain key
940 * @param key the identifier for the setting
941 * @param def the default value.
942 * @return the corresponding value if the property has been set before, {@code def} otherwise
943 */
944 public Collection<String> getCollection(String key, Collection<String> def) {
945 return getSetting(key, ListSetting.create(def), ListSetting.class).getValue();
946 }
947
948 /**
949 * Get a list of values for a certain key
950 * @param key the identifier for the setting
951 * @return the corresponding value if the property has been set before, an empty collection otherwise.
952 */
953 public Collection<String> getCollection(String key) {
954 Collection<String> val = getCollection(key, null);
955 return val == null ? Collections.<String>emptyList() : val;
956 }
957
958 public synchronized void removeFromCollection(String key, String value) {
959 List<String> a = new ArrayList<>(getCollection(key, Collections.<String>emptyList()));
960 a.remove(value);
961 putCollection(key, a);
962 }
963
964 /**
965 * Set a value for a certain setting. The changed setting is saved to the preference file immediately.
966 * Due to caching mechanisms on modern operating systems and hardware, this shouldn't be a performance problem.
967 * @param key the unique identifier for the setting
968 * @param setting the value of the setting. In case it is null, the key-value entry will be removed.
969 * @return {@code true}, if something has changed (i.e. value is different than before)
970 */
971 public boolean putSetting(final String key, Setting<?> setting) {
972 CheckParameterUtil.ensureParameterNotNull(key);
973 if (setting != null && setting.getValue() == null)
974 throw new IllegalArgumentException("setting argument must not have null value");
975 Setting<?> settingOld;
976 Setting<?> settingCopy = null;
977 synchronized (this) {
978 if (setting == null) {
979 settingOld = settingsMap.remove(key);
980 if (settingOld == null)
981 return false;
982 } else {
983 settingOld = settingsMap.get(key);
984 if (setting.equals(settingOld))
985 return false;
986 if (settingOld == null && setting.equals(defaultsMap.get(key)))
987 return false;
988 settingCopy = setting.copy();
989 settingsMap.put(key, settingCopy);
990 }
991 if (saveOnPut) {
992 try {
993 save();
994 } catch (IOException e) {
995 Main.warn(e, tr("Failed to persist preferences to ''{0}''", getPreferenceFile().getAbsoluteFile()));
996 }
997 }
998 }
999 // Call outside of synchronized section in case some listener wait for other thread that wait for preference lock
1000 firePreferenceChanged(key, settingOld, settingCopy);
1001 return true;
1002 }
1003
1004 public synchronized Setting<?> getSetting(String key, Setting<?> def) {
1005 return getSetting(key, def, Setting.class);
1006 }
1007
1008 /**
1009 * Get settings value for a certain key and provide default a value.
1010 * @param <T> the setting type
1011 * @param key the identifier for the setting
1012 * @param def the default value. For each call of getSetting() with a given key, the default value must be the same.
1013 * <code>def</code> must not be null, but the value of <code>def</code> can be null.
1014 * @param klass the setting type (same as T)
1015 * @return the corresponding value if the property has been set before, {@code def} otherwise
1016 */
1017 @SuppressWarnings("unchecked")
1018 public synchronized <T extends Setting<?>> T getSetting(String key, T def, Class<T> klass) {
1019 CheckParameterUtil.ensureParameterNotNull(key);
1020 CheckParameterUtil.ensureParameterNotNull(def);
1021 Setting<?> oldDef = defaultsMap.get(key);
1022 if (oldDef != null && oldDef.isNew() && oldDef.getValue() != null && def.getValue() != null && !def.equals(oldDef)) {
1023 Main.info("Defaults for " + key + " differ: " + def + " != " + defaultsMap.get(key));
1024 }
1025 if (def.getValue() != null || oldDef == null) {
1026 Setting<?> defCopy = def.copy();
1027 defCopy.setTime(System.currentTimeMillis() / 1000);
1028 defCopy.setNew(true);
1029 defaultsMap.put(key, defCopy);
1030 }
1031 Setting<?> prop = settingsMap.get(key);
1032 if (klass.isInstance(prop)) {
1033 return (T) prop;
1034 } else {
1035 return def;
1036 }
1037 }
1038
1039 /**
1040 * Put a collection.
1041 * @param key key
1042 * @param value value
1043 * @return {@code true}, if something has changed (i.e. value is different than before)
1044 */
1045 public boolean putCollection(String key, Collection<String> value) {
1046 return putSetting(key, value == null ? null : ListSetting.create(value));
1047 }
1048
1049 /**
1050 * Saves at most {@code maxsize} items of collection {@code val}.
1051 * @param key key
1052 * @param maxsize max number of items to save
1053 * @param val value
1054 * @return {@code true}, if something has changed (i.e. value is different than before)
1055 */
1056 public boolean putCollectionBounded(String key, int maxsize, Collection<String> val) {
1057 Collection<String> newCollection = new ArrayList<>(Math.min(maxsize, val.size()));
1058 for (String i : val) {
1059 if (newCollection.size() >= maxsize) {
1060 break;
1061 }
1062 newCollection.add(i);
1063 }
1064 return putCollection(key, newCollection);
1065 }
1066
1067 /**
1068 * Used to read a 2-dimensional array of strings from the preference file.
1069 * If not a single entry could be found, <code>def</code> is returned.
1070 * @param key preference key
1071 * @param def default array value
1072 * @return array value
1073 */
1074 @SuppressWarnings({ "unchecked", "rawtypes" })
1075 public synchronized Collection<Collection<String>> getArray(String key, Collection<Collection<String>> def) {
1076 ListListSetting val = getSetting(key, ListListSetting.create(def), ListListSetting.class);
1077 return (Collection) val.getValue();
1078 }
1079
1080 public Collection<Collection<String>> getArray(String key) {
1081 Collection<Collection<String>> res = getArray(key, null);
1082 return res == null ? Collections.<Collection<String>>emptyList() : res;
1083 }
1084
1085 /**
1086 * Put an array.
1087 * @param key key
1088 * @param value value
1089 * @return {@code true}, if something has changed (i.e. value is different than before)
1090 */
1091 public boolean putArray(String key, Collection<Collection<String>> value) {
1092 return putSetting(key, value == null ? null : ListListSetting.create(value));
1093 }
1094
1095 public Collection<Map<String, String>> getListOfStructs(String key, Collection<Map<String, String>> def) {
1096 return getSetting(key, new MapListSetting(def == null ? null : new ArrayList<>(def)), MapListSetting.class).getValue();
1097 }
1098
1099 public boolean putListOfStructs(String key, Collection<Map<String, String>> value) {
1100 return putSetting(key, value == null ? null : new MapListSetting(new ArrayList<>(value)));
1101 }
1102
1103 /**
1104 * Annotation used for converting objects to String Maps and vice versa.
1105 * Indicates that a certain field should be considered in the conversion process. Otherwise it is ignored.
1106 *
1107 * @see #serializeStruct(java.lang.Object, java.lang.Class)
1108 * @see #deserializeStruct(java.util.Map, java.lang.Class)
1109 */
1110 @Retention(RetentionPolicy.RUNTIME) // keep annotation at runtime
1111 public @interface pref { }
1112
1113 /**
1114 * Annotation used for converting objects to String Maps.
1115 * Indicates that a certain field should be written to the map, even if the value is the same as the default value.
1116 *
1117 * @see #serializeStruct(java.lang.Object, java.lang.Class)
1118 */
1119 @Retention(RetentionPolicy.RUNTIME) // keep annotation at runtime
1120 public @interface writeExplicitly { }
1121
1122 /**
1123 * Get a list of hashes which are represented by a struct-like class.
1124 * Possible properties are given by fields of the class klass that have the @pref annotation.
1125 * Default constructor is used to initialize the struct objects, properties then override some of these default values.
1126 * @param <T> klass type
1127 * @param key main preference key
1128 * @param klass The struct class
1129 * @return a list of objects of type T or an empty list if nothing was found
1130 */
1131 public <T> List<T> getListOfStructs(String key, Class<T> klass) {
1132 List<T> r = getListOfStructs(key, null, klass);
1133 if (r == null)
1134 return Collections.emptyList();
1135 else
1136 return r;
1137 }
1138
1139 /**
1140 * same as above, but returns def if nothing was found
1141 * @param <T> klass type
1142 * @param key main preference key
1143 * @param def default value
1144 * @param klass The struct class
1145 * @return a list of objects of type T or {@code def} if nothing was found
1146 */
1147 public <T> List<T> getListOfStructs(String key, Collection<T> def, Class<T> klass) {
1148 Collection<Map<String, String>> prop =
1149 getListOfStructs(key, def == null ? null : serializeListOfStructs(def, klass));
1150 if (prop == null)
1151 return def == null ? null : new ArrayList<>(def);
1152 List<T> lst = new ArrayList<>();
1153 for (Map<String, String> entries : prop) {
1154 T struct = deserializeStruct(entries, klass);
1155 lst.add(struct);
1156 }
1157 return lst;
1158 }
1159
1160 /**
1161 * Convenience method that saves a MapListSetting which is provided as a collection of objects.
1162 *
1163 * Each object is converted to a <code>Map&lt;String, String&gt;</code> using the fields with {@link pref} annotation.
1164 * The field name is the key and the value will be converted to a string.
1165 *
1166 * Considers only fields that have the @pref annotation.
1167 * In addition it does not write fields with null values. (Thus they are cleared)
1168 * Default values are given by the field values after default constructor has been called.
1169 * Fields equal to the default value are not written unless the field has the @writeExplicitly annotation.
1170 * @param <T> the class,
1171 * @param key main preference key
1172 * @param val the list that is supposed to be saved
1173 * @param klass The struct class
1174 * @return true if something has changed
1175 */
1176 public <T> boolean putListOfStructs(String key, Collection<T> val, Class<T> klass) {
1177 return putListOfStructs(key, serializeListOfStructs(val, klass));
1178 }
1179
1180 private static <T> Collection<Map<String, String>> serializeListOfStructs(Collection<T> l, Class<T> klass) {
1181 if (l == null)
1182 return null;
1183 Collection<Map<String, String>> vals = new ArrayList<>();
1184 for (T struct : l) {
1185 if (struct == null) {
1186 continue;
1187 }
1188 vals.add(serializeStruct(struct, klass));
1189 }
1190 return vals;
1191 }
1192
1193 @SuppressWarnings("rawtypes")
1194 private static String mapToJson(Map map) {
1195 StringWriter stringWriter = new StringWriter();
1196 try (JsonWriter writer = Json.createWriter(stringWriter)) {
1197 JsonObjectBuilder object = Json.createObjectBuilder();
1198 for (Object o: map.entrySet()) {
1199 Entry e = (Entry) o;
1200 Object evalue = e.getValue();
1201 object.add(e.getKey().toString(), evalue.toString());
1202 }
1203 writer.writeObject(object.build());
1204 }
1205 return stringWriter.toString();
1206 }
1207
1208 @SuppressWarnings({ "rawtypes", "unchecked" })
1209 private static Map mapFromJson(String s) {
1210 Map ret = null;
1211 try (JsonReader reader = Json.createReader(new StringReader(s))) {
1212 JsonObject object = reader.readObject();
1213 ret = new HashMap(object.size());
1214 for (Entry<String, JsonValue> e: object.entrySet()) {
1215 JsonValue value = e.getValue();
1216 if (value instanceof JsonString) {
1217 // in some cases, when JsonValue.toString() is called, then additional quotation marks are left in value
1218 ret.put(e.getKey(), ((JsonString) value).getString());
1219 } else {
1220 ret.put(e.getKey(), e.getValue().toString());
1221 }
1222 }
1223 }
1224 return ret;
1225 }
1226
1227 @SuppressWarnings("rawtypes")
1228 private static String multiMapToJson(MultiMap map) {
1229 StringWriter stringWriter = new StringWriter();
1230 try (JsonWriter writer = Json.createWriter(stringWriter)) {
1231 JsonObjectBuilder object = Json.createObjectBuilder();
1232 for (Object o: map.entrySet()) {
1233 Entry e = (Entry) o;
1234 Set evalue = (Set) e.getValue();
1235 JsonArrayBuilder a = Json.createArrayBuilder();
1236 for (Object evo: evalue) {
1237 a.add(evo.toString());
1238 }
1239 object.add(e.getKey().toString(), a.build());
1240 }
1241 writer.writeObject(object.build());
1242 }
1243 return stringWriter.toString();
1244 }
1245
1246 @SuppressWarnings({ "rawtypes", "unchecked" })
1247 private static MultiMap multiMapFromJson(String s) {
1248 MultiMap ret = null;
1249 try (JsonReader reader = Json.createReader(new StringReader(s))) {
1250 JsonObject object = reader.readObject();
1251 ret = new MultiMap(object.size());
1252 for (Entry<String, JsonValue> e: object.entrySet()) {
1253 JsonValue value = e.getValue();
1254 if (value instanceof JsonArray) {
1255 for (JsonString js: ((JsonArray) value).getValuesAs(JsonString.class)) {
1256 ret.put(e.getKey(), js.getString());
1257 }
1258 } else if (value instanceof JsonString) {
1259 // in some cases, when JsonValue.toString() is called, then additional quotation marks are left in value
1260 ret.put(e.getKey(), ((JsonString) value).getString());
1261 } else {
1262 ret.put(e.getKey(), e.getValue().toString());
1263 }
1264 }
1265 }
1266 return ret;
1267 }
1268
1269 /**
1270 * Convert an object to a String Map, by using field names and values as map key and value.
1271 *
1272 * The field value is converted to a String.
1273 *
1274 * Only fields with annotation {@link pref} are taken into account.
1275 *
1276 * Fields will not be written to the map if the value is null or unchanged
1277 * (compared to an object created with the no-arg-constructor).
1278 * The {@link writeExplicitly} annotation overrides this behavior, i.e. the default value will also be written.
1279 *
1280 * @param <T> the class of the object <code>struct</code>
1281 * @param struct the object to be converted
1282 * @param klass the class T
1283 * @return the resulting map (same data content as <code>struct</code>)
1284 */
1285 public static <T> Map<String, String> serializeStruct(T struct, Class<T> klass) {
1286 T structPrototype;
1287 try {
1288 structPrototype = klass.getConstructor().newInstance();
1289 } catch (ReflectiveOperationException ex) {
1290 throw new IllegalArgumentException(ex);
1291 }
1292
1293 Map<String, String> hash = new LinkedHashMap<>();
1294 for (Field f : klass.getDeclaredFields()) {
1295 if (f.getAnnotation(pref.class) == null) {
1296 continue;
1297 }
1298 Utils.setObjectsAccessible(f);
1299 try {
1300 Object fieldValue = f.get(struct);
1301 Object defaultFieldValue = f.get(structPrototype);
1302 if (fieldValue != null && (f.getAnnotation(writeExplicitly.class) != null || !Objects.equals(fieldValue, defaultFieldValue))) {
1303 String key = f.getName().replace('_', '-');
1304 if (fieldValue instanceof Map) {
1305 hash.put(key, mapToJson((Map<?, ?>) fieldValue));
1306 } else if (fieldValue instanceof MultiMap) {
1307 hash.put(key, multiMapToJson((MultiMap<?, ?>) fieldValue));
1308 } else {
1309 hash.put(key, fieldValue.toString());
1310 }
1311 }
1312 } catch (IllegalAccessException ex) {
1313 throw new RuntimeException(ex);
1314 }
1315 }
1316 return hash;
1317 }
1318
1319 /**
1320 * Converts a String-Map to an object of a certain class, by comparing map keys to field names of the class and assigning
1321 * map values to the corresponding fields.
1322 *
1323 * The map value (a String) is converted to the field type. Supported types are: boolean, Boolean, int, Integer, double,
1324 * Double, String, Map&lt;String, String&gt; and Map&lt;String, List&lt;String&gt;&gt;.
1325 *
1326 * Only fields with annotation {@link pref} are taken into account.
1327 * @param <T> the class
1328 * @param hash the string map with initial values
1329 * @param klass the class T
1330 * @return an object of class T, initialized as described above
1331 */
1332 public static <T> T deserializeStruct(Map<String, String> hash, Class<T> klass) {
1333 T struct = null;
1334 try {
1335 struct = klass.getConstructor().newInstance();
1336 } catch (ReflectiveOperationException ex) {
1337 throw new IllegalArgumentException(ex);
1338 }
1339 for (Entry<String, String> key_value : hash.entrySet()) {
1340 Object value;
1341 Field f;
1342 try {
1343 f = klass.getDeclaredField(key_value.getKey().replace('-', '_'));
1344 } catch (NoSuchFieldException ex) {
1345 Main.trace(ex);
1346 continue;
1347 }
1348 if (f.getAnnotation(pref.class) == null) {
1349 continue;
1350 }
1351 Utils.setObjectsAccessible(f);
1352 if (f.getType() == Boolean.class || f.getType() == boolean.class) {
1353 value = Boolean.valueOf(key_value.getValue());
1354 } else if (f.getType() == Integer.class || f.getType() == int.class) {
1355 try {
1356 value = Integer.valueOf(key_value.getValue());
1357 } catch (NumberFormatException nfe) {
1358 continue;
1359 }
1360 } else if (f.getType() == Double.class || f.getType() == double.class) {
1361 try {
1362 value = Double.valueOf(key_value.getValue());
1363 } catch (NumberFormatException nfe) {
1364 continue;
1365 }
1366 } else if (f.getType() == String.class) {
1367 value = key_value.getValue();
1368 } else if (f.getType().isAssignableFrom(Map.class)) {
1369 value = mapFromJson(key_value.getValue());
1370 } else if (f.getType().isAssignableFrom(MultiMap.class)) {
1371 value = multiMapFromJson(key_value.getValue());
1372 } else
1373 throw new RuntimeException("unsupported preference primitive type");
1374
1375 try {
1376 f.set(struct, value);
1377 } catch (IllegalArgumentException ex) {
1378 throw new AssertionError(ex);
1379 } catch (IllegalAccessException ex) {
1380 throw new RuntimeException(ex);
1381 }
1382 }
1383 return struct;
1384 }
1385
1386 public Map<String, Setting<?>> getAllSettings() {
1387 return new TreeMap<>(settingsMap);
1388 }
1389
1390 public Map<String, Setting<?>> getAllDefaults() {
1391 return new TreeMap<>(defaultsMap);
1392 }
1393
1394 /**
1395 * Updates system properties with the current values in the preferences.
1396 *
1397 */
1398 public void updateSystemProperties() {
1399 if ("true".equals(get("prefer.ipv6", "auto")) && !"true".equals(Utils.updateSystemProperty("java.net.preferIPv6Addresses", "true"))) {
1400 // never set this to false, only true!
1401 Main.info(tr("Try enabling IPv6 network, prefering IPv6 over IPv4 (only works on early startup)."));
1402 }
1403 Utils.updateSystemProperty("http.agent", Version.getInstance().getAgentString());
1404 Utils.updateSystemProperty("user.language", get("language"));
1405 // Workaround to fix a Java bug. This ugly hack comes from Sun bug database: https://bugs.openjdk.java.net/browse/JDK-6292739
1406 // Force AWT toolkit to update its internal preferences (fix #6345).
1407 if (!GraphicsEnvironment.isHeadless()) {
1408 try {
1409 Field field = Toolkit.class.getDeclaredField("resources");
1410 Utils.setObjectsAccessible(field);
1411 field.set(null, ResourceBundle.getBundle("sun.awt.resources.awt"));
1412 } catch (ReflectiveOperationException | MissingResourceException e) {
1413 Main.warn(e);
1414 }
1415 }
1416 // Possibility to disable SNI (not by default) in case of misconfigured https servers
1417 // See #9875 + http://stackoverflow.com/a/14884941/2257172
1418 // then https://josm.openstreetmap.de/ticket/12152#comment:5 for details
1419 if (getBoolean("jdk.tls.disableSNIExtension", false)) {
1420 Utils.updateSystemProperty("jsse.enableSNIExtension", "false");
1421 }
1422 }
1423
1424 /**
1425 * Replies the collection of plugin site URLs from where plugin lists can be downloaded.
1426 * @return the collection of plugin site URLs
1427 * @see #getOnlinePluginSites
1428 */
1429 public Collection<String> getPluginSites() {
1430 return getCollection("pluginmanager.sites", Collections.singleton(Main.getJOSMWebsite()+"/pluginicons%<?plugins=>"));
1431 }
1432
1433 /**
1434 * Returns the list of plugin sites available according to offline mode settings.
1435 * @return the list of available plugin sites
1436 * @since 8471
1437 */
1438 public Collection<String> getOnlinePluginSites() {
1439 Collection<String> pluginSites = new ArrayList<>(getPluginSites());
1440 for (Iterator<String> it = pluginSites.iterator(); it.hasNext();) {
1441 try {
1442 OnlineResource.JOSM_WEBSITE.checkOfflineAccess(it.next(), Main.getJOSMWebsite());
1443 } catch (OfflineAccessException ex) {
1444 Main.warn(ex, false);
1445 it.remove();
1446 }
1447 }
1448 return pluginSites;
1449 }
1450
1451 /**
1452 * Sets the collection of plugin site URLs.
1453 *
1454 * @param sites the site URLs
1455 */
1456 public void setPluginSites(Collection<String> sites) {
1457 putCollection("pluginmanager.sites", sites);
1458 }
1459
1460 /**
1461 * Returns XML describing these preferences.
1462 * @param nopass if password must be excluded
1463 * @return XML
1464 */
1465 public String toXML(boolean nopass) {
1466 return toXML(settingsMap.entrySet(), nopass, false);
1467 }
1468
1469 /**
1470 * Returns XML describing the given preferences.
1471 * @param settings preferences settings
1472 * @param nopass if password must be excluded
1473 * @param defaults true, if default values are converted to XML, false for
1474 * regular preferences
1475 * @return XML
1476 */
1477 public String toXML(Collection<Entry<String, Setting<?>>> settings, boolean nopass, boolean defaults) {
1478 try (
1479 StringWriter sw = new StringWriter();
1480 PreferencesWriter prefWriter = new PreferencesWriter(new PrintWriter(sw), nopass, defaults);
1481 ) {
1482 prefWriter.write(settings);
1483 sw.flush();
1484 return sw.toString();
1485 } catch (IOException e) {
1486 Main.error(e);
1487 return null;
1488 }
1489 }
1490
1491 /**
1492 * Removes obsolete preference settings. If you throw out a once-used preference
1493 * setting, add it to the list here with an expiry date (written as comment). If you
1494 * see something with an expiry date in the past, remove it from the list.
1495 * @param loadedVersion JOSM version when the preferences file was written
1496 */
1497 private void removeObsolete(int loadedVersion) {
1498 /* drop in October 2016 */
1499 if (loadedVersion < 9715) {
1500 Setting<?> setting = settingsMap.get("imagery.entries");
1501 if (setting instanceof MapListSetting) {
1502 List<Map<String, String>> l = new LinkedList<>();
1503 boolean modified = false;
1504 for (Map<String, String> map: ((MapListSetting) setting).getValue()) {
1505 Map<String, String> newMap = new HashMap<>();
1506 for (Entry<String, String> entry: map.entrySet()) {
1507 String value = entry.getValue();
1508 if ("noTileHeaders".equals(entry.getKey())) {
1509 value = value.replaceFirst("\":(\".*\")\\}", "\":[$1]}");
1510 if (!value.equals(entry.getValue())) {
1511 modified = true;
1512 }
1513 }
1514 newMap.put(entry.getKey(), value);
1515 }
1516 l.add(newMap);
1517 }
1518 if (modified) {
1519 putListOfStructs("imagery.entries", l);
1520 }
1521 }
1522 }
1523 // drop in November 2016
1524 removeUrlFromEntries(loadedVersion, 9965,
1525 "mappaint.style.entries",
1526 "josm.openstreetmap.de/josmfile?page=Styles/LegacyStandard");
1527 // drop in December 2016
1528 removeUrlFromEntries(loadedVersion, 10063,
1529 "validator.org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.entries",
1530 "resource://data/validator/power.mapcss");
1531
1532 for (String key : OBSOLETE_PREF_KEYS) {
1533 if (settingsMap.containsKey(key)) {
1534 settingsMap.remove(key);
1535 Main.info(tr("Preference setting {0} has been removed since it is no longer used.", key));
1536 }
1537 }
1538 }
1539
1540 private void removeUrlFromEntries(int loadedVersion, int versionMax, String key, String urlPart) {
1541 if (loadedVersion < versionMax) {
1542 Setting<?> setting = settingsMap.get(key);
1543 if (setting instanceof MapListSetting) {
1544 List<Map<String, String>> l = new LinkedList<>();
1545 boolean modified = false;
1546 for (Map<String, String> map: ((MapListSetting) setting).getValue()) {
1547 String url = map.get("url");
1548 if (url != null && url.contains(urlPart)) {
1549 modified = true;
1550 } else {
1551 l.add(map);
1552 }
1553 }
1554 if (modified) {
1555 putListOfStructs(key, l);
1556 }
1557 }
1558 }
1559 }
1560
1561 /**
1562 * Enables or not the preferences file auto-save mechanism (save each time a setting is changed).
1563 * This behaviour is enabled by default.
1564 * @param enable if {@code true}, makes JOSM save preferences file each time a setting is changed
1565 * @since 7085
1566 */
1567 public final void enableSaveOnPut(boolean enable) {
1568 synchronized (this) {
1569 saveOnPut = enable;
1570 }
1571 }
1572}
Note: See TracBrowser for help on using the repository browser.