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

Last change on this file since 8332 was 8324, checked in by Don-vip, 9 years ago

squid:S1133 - remove deprecated code

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