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

Last change on this file since 7026 was 7026, checked in by stoecker, 10 years ago

fix #3142 - drop applet code finally

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