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

Last change on this file since 7122 was 7085, checked in by Don-vip, 10 years ago

allow to disable auto-save of preferences file for unit tests (ant chmod does not seem to work from Jenkins)

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