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