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

Last change on this file since 6774 was 6774, checked in by simon04, 10 years ago

fix #9633 - MapCSS: allow (named) colours with alpha

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