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

Last change on this file since 6054 was 6054, checked in by Don-vip, 11 years ago

see #2283 - download GPX data along a track + code refactorization to simplify download_along plugin as well

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