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

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

see #6536 - Refactor crossing way test in order to decrease memory footprint

Drop data structure ExtendedSegment and obtain needed values on demand
from the way tags.

  • Property svn:eol-style set to native
File size: 59.2 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.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<String, Setting>();
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<String, Setting>();
102 // maps color keys to human readable color name
103 protected final SortedMap<String, String> colornames = new TreeMap<String, String>();
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 abstract public 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<String>(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<List<String>>(value.size());
279 for (Collection<String> lst : value) {
280 valueList.add(new ArrayList<String>(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<List<String>>(value.size());
301 for (Collection<String> lst : value) {
302 List<String> lstCopy = new ArrayList<String>(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<Map<String, String>>(value.size());
362 for (Map<String, String> map : value) {
363 Map<String, String> mapCopy = new LinkedHashMap<String,String>(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<PreferenceChangedListener>();
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<String>();
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 synchronized public 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 synchronized public String get(final String key, final String def) {
592 return getSetting(key, new StringSetting(def), StringSetting.class).getValue();
593 }
594
595 synchronized public Map<String, String> getAllPrefix(final String prefix) {
596 final Map<String,String> all = new TreeMap<String,String>();
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 synchronized public List<String> getAllPrefixCollectionKeys(final String prefix) {
606 final List<String> all = new LinkedList<String>();
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 synchronized public Map<String, String> getAllColors() {
616 final Map<String,String> all = new TreeMap<String,String>();
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 synchronized public boolean getBoolean(final String key) {
634 String s = get(key, null);
635 return s == null ? false : Boolean.parseBoolean(s);
636 }
637
638 synchronized public boolean getBoolean(final String key, final boolean def) {
639 return Boolean.parseBoolean(get(key, Boolean.toString(def)));
640 }
641
642 synchronized public 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 if(Main.applet)
692 return;
693
694 File prefFile = getPreferenceFile();
695 File backupFile = new File(prefFile + "_backup");
696
697 // Backup old preferences if there are old preferences
698 if (prefFile.exists()) {
699 Utils.copyFile(prefFile, backupFile);
700 }
701
702 final PrintWriter out = new PrintWriter(new OutputStreamWriter(
703 new FileOutputStream(prefFile + "_tmp"), Utils.UTF_8), false);
704 out.print(toXML(false));
705 Utils.close(out);
706
707 File tmpFile = new File(prefFile + "_tmp");
708 Utils.copyFile(tmpFile, prefFile);
709 tmpFile.delete();
710
711 setCorrectPermissions(prefFile);
712 setCorrectPermissions(backupFile);
713 }
714
715
716 private void setCorrectPermissions(File file) {
717 file.setReadable(false, false);
718 file.setWritable(false, false);
719 file.setExecutable(false, false);
720 file.setReadable(true, true);
721 file.setWritable(true, true);
722 }
723
724 public void load() throws Exception {
725 settingsMap.clear();
726 if (!Main.applet) {
727 File pref = getPreferenceFile();
728 BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8));
729 try {
730 validateXML(in);
731 Utils.close(in);
732 in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8));
733 fromXML(in);
734 } finally {
735 Utils.close(in);
736 }
737 }
738 updateSystemProperties();
739 removeObsolete();
740 }
741
742 public void init(boolean reset){
743 if(Main.applet)
744 return;
745 // get the preferences.
746 File prefDir = getPreferencesDirFile();
747 if (prefDir.exists()) {
748 if(!prefDir.isDirectory()) {
749 Main.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.", prefDir.getAbsoluteFile()));
750 JOptionPane.showMessageDialog(
751 Main.parent,
752 tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>", prefDir.getAbsoluteFile()),
753 tr("Error"),
754 JOptionPane.ERROR_MESSAGE
755 );
756 return;
757 }
758 } else {
759 if (! prefDir.mkdirs()) {
760 Main.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}", prefDir.getAbsoluteFile()));
761 JOptionPane.showMessageDialog(
762 Main.parent,
763 tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>",prefDir.getAbsoluteFile()),
764 tr("Error"),
765 JOptionPane.ERROR_MESSAGE
766 );
767 return;
768 }
769 }
770
771 File preferenceFile = getPreferenceFile();
772 try {
773 if (!preferenceFile.exists()) {
774 Main.info(tr("Missing preference file ''{0}''. Creating a default preference file.", preferenceFile.getAbsoluteFile()));
775 resetToDefault();
776 save();
777 } else if (reset) {
778 Main.warn(tr("Replacing existing preference file ''{0}'' with default preference file.", preferenceFile.getAbsoluteFile()));
779 resetToDefault();
780 save();
781 }
782 } catch(IOException e) {
783 e.printStackTrace();
784 JOptionPane.showMessageDialog(
785 Main.parent,
786 tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>",getPreferenceFile().getAbsoluteFile()),
787 tr("Error"),
788 JOptionPane.ERROR_MESSAGE
789 );
790 return;
791 }
792 try {
793 load();
794 } catch (Exception e) {
795 e.printStackTrace();
796 File backupFile = new File(prefDir,"preferences.xml.bak");
797 JOptionPane.showMessageDialog(
798 Main.parent,
799 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()),
800 tr("Error"),
801 JOptionPane.ERROR_MESSAGE
802 );
803 Main.platform.rename(preferenceFile, backupFile);
804 try {
805 resetToDefault();
806 save();
807 } catch(IOException e1) {
808 e1.printStackTrace();
809 Main.warn(tr("Failed to initialize preferences. Failed to reset preference file to default: {0}", getPreferenceFile()));
810 }
811 }
812 }
813
814 public final void resetToDefault(){
815 settingsMap.clear();
816 }
817
818 /**
819 * Convenience method for accessing colour preferences.
820 *
821 * @param colName name of the colour
822 * @param def default value
823 * @return a Color object for the configured colour, or the default value if none configured.
824 */
825 synchronized public Color getColor(String colName, Color def) {
826 return getColor(colName, null, def);
827 }
828
829 synchronized public Color getUIColor(String colName) {
830 return UIManager.getColor(colName);
831 }
832
833 /* only for preferences */
834 synchronized public String getColorName(String o) {
835 try {
836 Matcher m = Pattern.compile("mappaint\\.(.+?)\\.(.+)").matcher(o);
837 if (m.matches()) {
838 return tr("Paint style {0}: {1}", tr(m.group(1)), tr(m.group(2)));
839 }
840 } catch (Exception e) {
841 Main.warn(e);
842 }
843 try {
844 Matcher m = Pattern.compile("layer (.+)").matcher(o);
845 if (m.matches()) {
846 return tr("Layer: {0}", tr(m.group(1)));
847 }
848 } catch (Exception e) {
849 Main.warn(e);
850 }
851 return tr(colornames.containsKey(o) ? colornames.get(o) : o);
852 }
853
854 public Color getColor(ColorKey key) {
855 return getColor(key.getColorName(), key.getSpecialName(), key.getDefaultValue());
856 }
857
858 /**
859 * Convenience method for accessing colour preferences.
860 *
861 * @param colName name of the colour
862 * @param specName name of the special colour settings
863 * @param def default value
864 * @return a Color object for the configured colour, or the default value if none configured.
865 */
866 synchronized public Color getColor(String colName, String specName, Color def) {
867 String colKey = ColorProperty.getColorKey(colName);
868 if(!colKey.equals(colName)) {
869 colornames.put(colKey, colName);
870 }
871 String colStr = specName != null ? get("color."+specName) : "";
872 if(colStr.isEmpty()) {
873 colStr = get("color." + colKey, "");
874 }
875 return colStr.isEmpty() ? def : ColorHelper.html2color(colStr);
876 }
877
878 synchronized public Color getDefaultColor(String colKey) {
879 StringSetting col = Utils.cast(defaultsMap.get("color."+colKey), StringSetting.class);
880 String colStr = col == null ? null : col.getValue();
881 return colStr == null || colStr.isEmpty() ? null : ColorHelper.html2color(colStr);
882 }
883
884 synchronized public boolean putColor(String colKey, Color val) {
885 return put("color."+colKey, val != null ? ColorHelper.color2html(val) : null);
886 }
887
888 synchronized public int getInteger(String key, int def) {
889 String v = get(key, Integer.toString(def));
890 if(v.isEmpty())
891 return def;
892
893 try {
894 return Integer.parseInt(v);
895 } catch(NumberFormatException e) {
896 // fall out
897 }
898 return def;
899 }
900
901 synchronized public int getInteger(String key, String specName, int def) {
902 String v = get(key+"."+specName);
903 if(v.isEmpty())
904 v = get(key,Integer.toString(def));
905 if(v.isEmpty())
906 return def;
907
908 try {
909 return Integer.parseInt(v);
910 } catch(NumberFormatException e) {
911 // fall out
912 }
913 return def;
914 }
915
916 synchronized public long getLong(String key, long def) {
917 String v = get(key, Long.toString(def));
918 if(null == v)
919 return def;
920
921 try {
922 return Long.parseLong(v);
923 } catch(NumberFormatException e) {
924 // fall out
925 }
926 return def;
927 }
928
929 synchronized public double getDouble(String key, double def) {
930 String v = get(key, Double.toString(def));
931 if(null == v)
932 return def;
933
934 try {
935 return Double.parseDouble(v);
936 } catch(NumberFormatException e) {
937 // fall out
938 }
939 return def;
940 }
941
942 /**
943 * Get a list of values for a certain key
944 * @param key the identifier for the setting
945 * @param def the default value.
946 * @return the corresponding value if the property has been set before,
947 * def otherwise
948 */
949 public Collection<String> getCollection(String key, Collection<String> def) {
950 return getSetting(key, ListSetting.create(def), ListSetting.class).getValue();
951 }
952
953 /**
954 * Get a list of values for a certain key
955 * @param key the identifier for the setting
956 * @return the corresponding value if the property has been set before,
957 * an empty Collection otherwise.
958 */
959 public Collection<String> getCollection(String key) {
960 Collection<String> val = getCollection(key, null);
961 return val == null ? Collections.<String>emptyList() : val;
962 }
963
964 synchronized public void removeFromCollection(String key, String value) {
965 List<String> a = new ArrayList<String>(getCollection(key, Collections.<String>emptyList()));
966 a.remove(value);
967 putCollection(key, a);
968 }
969
970 /**
971 * Set a value for a certain setting. The changed setting is saved
972 * to the preference file immediately. Due to caching mechanisms on modern
973 * operating systems and hardware, this shouldn't be a performance problem.
974 * @param key the unique identifier for the setting
975 * @param setting the value of the setting. In case it is null, the key-value
976 * entry will be removed.
977 * @return true, if something has changed (i.e. value is different than before)
978 */
979 public boolean putSetting(final String key, Setting setting) {
980 CheckParameterUtil.ensureParameterNotNull(key);
981 if (setting != null && setting.getValue() == null)
982 throw new IllegalArgumentException("setting argument must not have null value");
983 Setting settingOld;
984 Setting settingCopy = null;
985 synchronized (this) {
986 if (setting == null) {
987 settingOld = settingsMap.remove(key);
988 if (settingOld == null)
989 return false;
990 } else {
991 settingOld = settingsMap.get(key);
992 if (setting.equals(settingOld))
993 return false;
994 if (settingOld == null && setting.equals(defaultsMap.get(key)))
995 return false;
996 settingCopy = setting.copy();
997 settingsMap.put(key, settingCopy);
998 }
999 try {
1000 save();
1001 } catch (IOException e){
1002 Main.warn(tr("Failed to persist preferences to ''{0}''", getPreferenceFile().getAbsoluteFile()));
1003 }
1004 }
1005 // Call outside of synchronized section in case some listener wait for other thread that wait for preference lock
1006 firePreferenceChanged(key, settingOld, settingCopy);
1007 return true;
1008 }
1009
1010 synchronized public Setting getSetting(String key, Setting def) {
1011 return getSetting(key, def, Setting.class);
1012 }
1013
1014 /**
1015 * Get settings value for a certain key and provide default a value.
1016 * @param <T> the setting type
1017 * @param key the identifier for the setting
1018 * @param def the default value. For each call of getSetting() with a given
1019 * key, the default value must be the same. <code>def</code> must not be
1020 * null, but the value of <code>def</code> can be null.
1021 * @param klass the setting type (same as T)
1022 * @return the corresponding value if the property has been set before,
1023 * def otherwise
1024 */
1025 synchronized public <T extends Setting> T getSetting(String key, T def, Class<T> klass) {
1026 CheckParameterUtil.ensureParameterNotNull(key);
1027 CheckParameterUtil.ensureParameterNotNull(def);
1028 if (defaultsMap.containsKey(key) && !def.equals(defaultsMap.get(key))) {
1029 Main.info("Defaults for " + key + " differ: " + def + " != " + defaultsMap.get(key));
1030 }
1031 defaultsMap.put(key, def.copy());
1032 Setting prop = settingsMap.get(key);
1033 if (klass.isInstance(prop)) {
1034 @SuppressWarnings("unchecked")
1035 T prop_cast = (T) prop;
1036 return prop_cast;
1037 } else {
1038 return def;
1039 }
1040 }
1041
1042 public boolean putCollection(String key, Collection<String> value) {
1043 return putSetting(key, value == null ? null : ListSetting.create(value));
1044 }
1045
1046 /**
1047 * Saves at most {@code maxsize} items of collection {@code val}.
1048 */
1049 public boolean putCollectionBounded(String key, int maxsize, Collection<String> val) {
1050 Collection<String> newCollection = new ArrayList<String>(Math.min(maxsize, val.size()));
1051 for (String i : val) {
1052 if (newCollection.size() >= maxsize) {
1053 break;
1054 }
1055 newCollection.add(i);
1056 }
1057 return putCollection(key, newCollection);
1058 }
1059
1060 /**
1061 * Used to read a 2-dimensional array of strings from the preference file.
1062 * If not a single entry could be found, <code>def</code> is returned.
1063 */
1064 synchronized public Collection<Collection<String>> getArray(String key, Collection<Collection<String>> def) {
1065 ListListSetting val = getSetting(key, ListListSetting.create(def), ListListSetting.class);
1066 @SuppressWarnings({ "unchecked", "rawtypes" })
1067 Collection<Collection<String>> val_cast = (Collection) val.getValue();
1068 return val_cast;
1069 }
1070
1071 public Collection<Collection<String>> getArray(String key) {
1072 Collection<Collection<String>> res = getArray(key, null);
1073 return res == null ? Collections.<Collection<String>>emptyList() : res;
1074 }
1075
1076 public boolean putArray(String key, Collection<Collection<String>> value) {
1077 return putSetting(key, value == null ? null : ListListSetting.create(value));
1078 }
1079
1080 public Collection<Map<String, String>> getListOfStructs(String key, Collection<Map<String, String>> def) {
1081 return getSetting(key, new MapListSetting(def == null ? null : new ArrayList<Map<String, String>>(def)), MapListSetting.class).getValue();
1082 }
1083
1084 public boolean putListOfStructs(String key, Collection<Map<String, String>> value) {
1085 return putSetting(key, value == null ? null : new MapListSetting(new ArrayList<Map<String, String>>(value)));
1086 }
1087
1088 @Retention(RetentionPolicy.RUNTIME) public @interface pref { }
1089 @Retention(RetentionPolicy.RUNTIME) public @interface writeExplicitly { }
1090
1091 /**
1092 * Get a list of hashes which are represented by a struct-like class.
1093 * Possible properties are given by fields of the class klass that have
1094 * the @pref annotation.
1095 * Default constructor is used to initialize the struct objects, properties
1096 * then override some of these default values.
1097 * @param key main preference key
1098 * @param klass The struct class
1099 * @return a list of objects of type T or an empty list if nothing was found
1100 */
1101 public <T> List<T> getListOfStructs(String key, Class<T> klass) {
1102 List<T> r = getListOfStructs(key, null, klass);
1103 if (r == null)
1104 return Collections.emptyList();
1105 else
1106 return r;
1107 }
1108
1109 /**
1110 * same as above, but returns def if nothing was found
1111 */
1112 public <T> List<T> getListOfStructs(String key, Collection<T> def, Class<T> klass) {
1113 Collection<Map<String,String>> prop =
1114 getListOfStructs(key, def == null ? null : serializeListOfStructs(def, klass));
1115 if (prop == null)
1116 return def == null ? null : new ArrayList<T>(def);
1117 List<T> lst = new ArrayList<T>();
1118 for (Map<String,String> entries : prop) {
1119 T struct = deserializeStruct(entries, klass);
1120 lst.add(struct);
1121 }
1122 return lst;
1123 }
1124
1125 /**
1126 * Save a list of hashes represented by a struct-like class.
1127 * Considers only fields that have the @pref annotation.
1128 * In addition it does not write fields with null values. (Thus they are cleared)
1129 * Default values are given by the field values after default constructor has
1130 * been called.
1131 * Fields equal to the default value are not written unless the field has
1132 * the @writeExplicitly annotation.
1133 * @param key main preference key
1134 * @param val the list that is supposed to be saved
1135 * @param klass The struct class
1136 * @return true if something has changed
1137 */
1138 public <T> boolean putListOfStructs(String key, Collection<T> val, Class<T> klass) {
1139 return putListOfStructs(key, serializeListOfStructs(val, klass));
1140 }
1141
1142 private <T> Collection<Map<String,String>> serializeListOfStructs(Collection<T> l, Class<T> klass) {
1143 if (l == null)
1144 return null;
1145 Collection<Map<String,String>> vals = new ArrayList<Map<String,String>>();
1146 for (T struct : l) {
1147 if (struct == null) {
1148 continue;
1149 }
1150 vals.add(serializeStruct(struct, klass));
1151 }
1152 return vals;
1153 }
1154
1155 public static <T> Map<String,String> serializeStruct(T struct, Class<T> klass) {
1156 T structPrototype;
1157 try {
1158 structPrototype = klass.newInstance();
1159 } catch (InstantiationException ex) {
1160 throw new RuntimeException(ex);
1161 } catch (IllegalAccessException ex) {
1162 throw new RuntimeException(ex);
1163 }
1164
1165 Map<String,String> hash = new LinkedHashMap<String,String>();
1166 for (Field f : klass.getDeclaredFields()) {
1167 if (f.getAnnotation(pref.class) == null) {
1168 continue;
1169 }
1170 f.setAccessible(true);
1171 try {
1172 Object fieldValue = f.get(struct);
1173 Object defaultFieldValue = f.get(structPrototype);
1174 if (fieldValue != null) {
1175 if (f.getAnnotation(writeExplicitly.class) != null || !Utils.equal(fieldValue, defaultFieldValue)) {
1176 hash.put(f.getName().replace("_", "-"), fieldValue.toString());
1177 }
1178 }
1179 } catch (IllegalArgumentException ex) {
1180 throw new RuntimeException();
1181 } catch (IllegalAccessException ex) {
1182 throw new RuntimeException();
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 ex) {
1193 throw new RuntimeException();
1194 } catch (IllegalAccessException ex) {
1195 throw new RuntimeException();
1196 }
1197 for (Entry<String,String> key_value : hash.entrySet()) {
1198 Object value = null;
1199 Field f;
1200 try {
1201 f = klass.getDeclaredField(key_value.getKey().replace("-", "_"));
1202 } catch (NoSuchFieldException ex) {
1203 continue;
1204 } catch (SecurityException ex) {
1205 throw new RuntimeException();
1206 }
1207 if (f.getAnnotation(pref.class) == null) {
1208 continue;
1209 }
1210 f.setAccessible(true);
1211 if (f.getType() == Boolean.class || f.getType() == boolean.class) {
1212 value = Boolean.parseBoolean(key_value.getValue());
1213 } else if (f.getType() == Integer.class || f.getType() == int.class) {
1214 try {
1215 value = Integer.parseInt(key_value.getValue());
1216 } catch (NumberFormatException nfe) {
1217 continue;
1218 }
1219 } else if (f.getType() == Double.class || f.getType() == double.class) {
1220 try {
1221 value = Double.parseDouble(key_value.getValue());
1222 } catch (NumberFormatException nfe) {
1223 continue;
1224 }
1225 } else if (f.getType() == String.class) {
1226 value = key_value.getValue();
1227 } else
1228 throw new RuntimeException("unsupported preference primitive type");
1229
1230 try {
1231 f.set(struct, value);
1232 } catch (IllegalArgumentException ex) {
1233 throw new AssertionError();
1234 } catch (IllegalAccessException ex) {
1235 throw new RuntimeException();
1236 }
1237 }
1238 return struct;
1239 }
1240
1241 public Map<String, Setting> getAllSettings() {
1242 return new TreeMap<String, Setting>(settingsMap);
1243 }
1244
1245 public Map<String, Setting> getAllDefaults() {
1246 return new TreeMap<String, Setting>(defaultsMap);
1247 }
1248
1249 /**
1250 * Updates system properties with the current values in the preferences.
1251 *
1252 */
1253 public void updateSystemProperties() {
1254 if(getBoolean("prefer.ipv6", false)) {
1255 // never set this to false, only true!
1256 updateSystemProperty("java.net.preferIPv6Addresses", "true");
1257 }
1258 updateSystemProperty("http.agent", Version.getInstance().getAgentString());
1259 updateSystemProperty("user.language", get("language"));
1260 // Workaround to fix a Java bug.
1261 // Force AWT toolkit to update its internal preferences (fix #3645).
1262 // This ugly hack comes from Sun bug database: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6292739
1263 try {
1264 Field field = Toolkit.class.getDeclaredField("resources");
1265 field.setAccessible(true);
1266 field.set(null, ResourceBundle.getBundle("sun.awt.resources.awt"));
1267 } catch (Exception e) {
1268 // Ignore all exceptions
1269 }
1270 // Workaround to fix another Java bug
1271 // Force Java 7 to use old sorting algorithm of Arrays.sort (fix #8712).
1272 // See Oracle bug database: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7075600
1273 // and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6923200
1274 if (Main.pref.getBoolean("jdk.Arrays.useLegacyMergeSort", !Version.getInstance().isLocalBuild())) {
1275 updateSystemProperty("java.util.Arrays.useLegacyMergeSort", "true");
1276 }
1277 }
1278
1279 private void updateSystemProperty(String key, String value) {
1280 if (value != null) {
1281 System.setProperty(key, value);
1282 }
1283 }
1284
1285 /**
1286 * The default plugin site
1287 */
1288 private final static String[] DEFAULT_PLUGIN_SITE = {
1289 Main.JOSM_WEBSITE+"/plugin%<?plugins=>"};
1290
1291 /**
1292 * Replies the collection of plugin site URLs from where plugin lists can be downloaded
1293 */
1294 public Collection<String> getPluginSites() {
1295 return getCollection("pluginmanager.sites", Arrays.asList(DEFAULT_PLUGIN_SITE));
1296 }
1297
1298 /**
1299 * Sets the collection of plugin site URLs.
1300 *
1301 * @param sites the site URLs
1302 */
1303 public void setPluginSites(Collection<String> sites) {
1304 putCollection("pluginmanager.sites", sites);
1305 }
1306
1307 protected XMLStreamReader parser;
1308
1309 public void validateXML(Reader in) throws Exception {
1310 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
1311 Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream("resource://data/preferences.xsd")));
1312 Validator validator = schema.newValidator();
1313 validator.validate(new StreamSource(in));
1314 }
1315
1316 public void fromXML(Reader in) throws XMLStreamException {
1317 XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(in);
1318 this.parser = parser;
1319 parse();
1320 }
1321
1322 public void parse() throws XMLStreamException {
1323 int event = parser.getEventType();
1324 while (true) {
1325 if (event == XMLStreamConstants.START_ELEMENT) {
1326 parseRoot();
1327 } else if (event == XMLStreamConstants.END_ELEMENT) {
1328 return;
1329 }
1330 if (parser.hasNext()) {
1331 event = parser.next();
1332 } else {
1333 break;
1334 }
1335 }
1336 parser.close();
1337 }
1338
1339 public void parseRoot() throws XMLStreamException {
1340 while (true) {
1341 int event = parser.next();
1342 if (event == XMLStreamConstants.START_ELEMENT) {
1343 if (parser.getLocalName().equals("tag")) {
1344 settingsMap.put(parser.getAttributeValue(null, "key"), new StringSetting(parser.getAttributeValue(null, "value")));
1345 jumpToEnd();
1346 } else if (parser.getLocalName().equals("list") ||
1347 parser.getLocalName().equals("collection") ||
1348 parser.getLocalName().equals("lists") ||
1349 parser.getLocalName().equals("maps")
1350 ) {
1351 parseToplevelList();
1352 } else {
1353 throwException("Unexpected element: "+parser.getLocalName());
1354 }
1355 } else if (event == XMLStreamConstants.END_ELEMENT) {
1356 return;
1357 }
1358 }
1359 }
1360
1361 private void jumpToEnd() throws XMLStreamException {
1362 while (true) {
1363 int event = parser.next();
1364 if (event == XMLStreamConstants.START_ELEMENT) {
1365 jumpToEnd();
1366 } else if (event == XMLStreamConstants.END_ELEMENT) {
1367 return;
1368 }
1369 }
1370 }
1371
1372 protected void parseToplevelList() throws XMLStreamException {
1373 String key = parser.getAttributeValue(null, "key");
1374 String name = parser.getLocalName();
1375
1376 List<String> entries = null;
1377 List<List<String>> lists = null;
1378 List<Map<String, String>> maps = null;
1379 while (true) {
1380 int event = parser.next();
1381 if (event == XMLStreamConstants.START_ELEMENT) {
1382 if (parser.getLocalName().equals("entry")) {
1383 if (entries == null) {
1384 entries = new ArrayList<String>();
1385 }
1386 entries.add(parser.getAttributeValue(null, "value"));
1387 jumpToEnd();
1388 } else if (parser.getLocalName().equals("list")) {
1389 if (lists == null) {
1390 lists = new ArrayList<List<String>>();
1391 }
1392 lists.add(parseInnerList());
1393 } else if (parser.getLocalName().equals("map")) {
1394 if (maps == null) {
1395 maps = new ArrayList<Map<String, String>>();
1396 }
1397 maps.add(parseMap());
1398 } else {
1399 throwException("Unexpected element: "+parser.getLocalName());
1400 }
1401 } else if (event == XMLStreamConstants.END_ELEMENT) {
1402 break;
1403 }
1404 }
1405 if (entries != null) {
1406 settingsMap.put(key, new ListSetting(Collections.unmodifiableList(entries)));
1407 } else if (lists != null) {
1408 settingsMap.put(key, new ListListSetting(Collections.unmodifiableList(lists)));
1409 } else if (maps != null) {
1410 settingsMap.put(key, new MapListSetting(Collections.unmodifiableList(maps)));
1411 } else {
1412 if (name.equals("lists")) {
1413 settingsMap.put(key, new ListListSetting(Collections.<List<String>>emptyList()));
1414 } else if (name.equals("maps")) {
1415 settingsMap.put(key, new MapListSetting(Collections.<Map<String, String>>emptyList()));
1416 } else {
1417 settingsMap.put(key, new ListSetting(Collections.<String>emptyList()));
1418 }
1419 }
1420 }
1421
1422 protected List<String> parseInnerList() throws XMLStreamException {
1423 List<String> entries = new ArrayList<String>();
1424 while (true) {
1425 int event = parser.next();
1426 if (event == XMLStreamConstants.START_ELEMENT) {
1427 if (parser.getLocalName().equals("entry")) {
1428 entries.add(parser.getAttributeValue(null, "value"));
1429 jumpToEnd();
1430 } else {
1431 throwException("Unexpected element: "+parser.getLocalName());
1432 }
1433 } else if (event == XMLStreamConstants.END_ELEMENT) {
1434 break;
1435 }
1436 }
1437 return Collections.unmodifiableList(entries);
1438 }
1439
1440 protected Map<String, String> parseMap() throws XMLStreamException {
1441 Map<String, String> map = new LinkedHashMap<String, String>();
1442 while (true) {
1443 int event = parser.next();
1444 if (event == XMLStreamConstants.START_ELEMENT) {
1445 if (parser.getLocalName().equals("tag")) {
1446 map.put(parser.getAttributeValue(null, "key"), parser.getAttributeValue(null, "value"));
1447 jumpToEnd();
1448 } else {
1449 throwException("Unexpected element: "+parser.getLocalName());
1450 }
1451 } else if (event == XMLStreamConstants.END_ELEMENT) {
1452 break;
1453 }
1454 }
1455 return Collections.unmodifiableMap(map);
1456 }
1457
1458 protected void throwException(String msg) {
1459 throw new RuntimeException(msg + tr(" (at line {0}, column {1})", parser.getLocation().getLineNumber(), parser.getLocation().getColumnNumber()));
1460 }
1461
1462 private class SettingToXml implements SettingVisitor {
1463 private StringBuilder b;
1464 private boolean noPassword;
1465 private String key;
1466
1467 public SettingToXml(StringBuilder b, boolean noPassword) {
1468 this.b = b;
1469 this.noPassword = noPassword;
1470 }
1471
1472 public void setKey(String key) {
1473 this.key = key;
1474 }
1475
1476 @Override
1477 public void visit(StringSetting setting) {
1478 if (noPassword && key.equals("osm-server.password"))
1479 return; // do not store plain password.
1480 /* don't save default values */
1481 if (setting.equals(defaultsMap.get(key)))
1482 return;
1483 b.append(" <tag key='");
1484 b.append(XmlWriter.encode(key));
1485 b.append("' value='");
1486 b.append(XmlWriter.encode(setting.getValue()));
1487 b.append("'/>\n");
1488 }
1489
1490 @Override
1491 public void visit(ListSetting setting) {
1492 b.append(" <list key='").append(XmlWriter.encode(key)).append("'>\n");
1493 for (String s : setting.getValue()) {
1494 b.append(" <entry value='").append(XmlWriter.encode(s)).append("'/>\n");
1495 }
1496 b.append(" </list>\n");
1497 }
1498
1499 @Override
1500 public void visit(ListListSetting setting) {
1501 b.append(" <lists key='").append(XmlWriter.encode(key)).append("'>\n");
1502 for (List<String> list : setting.getValue()) {
1503 b.append(" <list>\n");
1504 for (String s : list) {
1505 b.append(" <entry value='").append(XmlWriter.encode(s)).append("'/>\n");
1506 }
1507 b.append(" </list>\n");
1508 }
1509 b.append(" </lists>\n");
1510 }
1511
1512 @Override
1513 public void visit(MapListSetting setting) {
1514 b.append(" <maps key='").append(XmlWriter.encode(key)).append("'>\n");
1515 for (Map<String, String> struct : setting.getValue()) {
1516 b.append(" <map>\n");
1517 for (Entry<String, String> e : struct.entrySet()) {
1518 b.append(" <tag key='").append(XmlWriter.encode(e.getKey())).append("' value='").append(XmlWriter.encode(e.getValue())).append("'/>\n");
1519 }
1520 b.append(" </map>\n");
1521 }
1522 b.append(" </maps>\n");
1523 }
1524 }
1525
1526 public String toXML(boolean nopass) {
1527 StringBuilder b = new StringBuilder(
1528 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
1529 "<preferences xmlns=\""+Main.JOSM_WEBSITE+"/preferences-1.0\" version=\""+
1530 Version.getInstance().getVersion() + "\">\n");
1531 SettingToXml toXml = new SettingToXml(b, nopass);
1532 for (Entry<String, Setting> e : settingsMap.entrySet()) {
1533 toXml.setKey(e.getKey());
1534 e.getValue().visit(toXml);
1535 }
1536 b.append("</preferences>\n");
1537 return b.toString();
1538 }
1539
1540 /**
1541 * Removes obsolete preference settings. If you throw out a once-used preference
1542 * setting, add it to the list here with an expiry date (written as comment). If you
1543 * see something with an expiry date in the past, remove it from the list.
1544 */
1545 public void removeObsolete() {
1546 /* update the data with old consumer key*/
1547 if(getInteger("josm.version", Version.getInstance().getVersion()) < 6076) {
1548 if(!get("oauth.access-token.key").isEmpty() && get("oauth.settings.consumer-key").isEmpty()) {
1549 put("oauth.settings.consumer-key", "AdCRxTpvnbmfV8aPqrTLyA");
1550 put("oauth.settings.consumer-secret", "XmYOiGY9hApytcBC3xCec3e28QBqOWz5g6DSb5UpE");
1551 }
1552 }
1553
1554 String[] obsolete = {
1555 "downloadAlong.downloadAlongTrack.distance", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongWay.distance
1556 "downloadAlong.downloadAlongTrack.area", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongWay.area
1557 "gpxLayer.downloadAlongTrack.distance", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.distance
1558 "gpxLayer.downloadAlongTrack.area", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.area
1559 "gpxLayer.downloadAlongTrack.near", // 07/2013 - can be removed mid-2014. Replaced by downloadAlongTrack.near
1560 };
1561 for (String key : obsolete) {
1562 if (settingsMap.containsKey(key)) {
1563 settingsMap.remove(key);
1564 Main.info(tr("Preference setting {0} has been removed since it is no longer used.", key));
1565 }
1566 }
1567 }
1568
1569 public static boolean isEqual(Setting a, Setting b) {
1570 if (a == null) return b == null;
1571 return a.equals(b);
1572 }
1573
1574}
Note: See TracBrowser for help on using the repository browser.