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