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

Last change on this file since 9783 was 9781, checked in by bastiK, 8 years ago

whitespace

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