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

Last change on this file since 1065 was 1065, checked in by stoecker, 15 years ago

language handling fixed

  • Property svn:eol-style set to native
File size: 13.9 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.data;
3
4import java.awt.Color;
5import java.io.BufferedReader;
6import java.io.File;
7import java.io.FileReader;
8import java.io.FileWriter;
9import java.io.IOException;
10import java.io.PrintWriter;
11import java.util.ArrayList;
12import java.util.Arrays;
13import java.util.Collection;
14import java.util.LinkedList;
15import java.util.Map;
16import java.util.Properties;
17import java.util.SortedMap;
18import java.util.StringTokenizer;
19import java.util.TreeMap;
20import java.util.Map.Entry;
21
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.gui.preferences.ProxyPreferences;
24import org.openstreetmap.josm.tools.ColorHelper;
25
26/**
27 * This class holds all preferences for JOSM.
28 *
29 * Other classes can register their beloved properties here. All properties will be
30 * saved upon set-access.
31 *
32 * @author imi
33 */
34public class Preferences {
35
36 /**
37 * Internal storage for the preferenced directory.
38 * Do not access this variable directly!
39 * @see #getPreferencesDirFile()
40 */
41 private File preferencesDirFile = null;
42
43 public static interface PreferenceChangedListener {
44 void preferenceChanged(String key, String newValue);
45 }
46
47 /**
48 * Class holding one bookmarkentry.
49 * @author imi
50 */
51 public static class Bookmark {
52 public String name;
53 public double[] latlon = new double[4]; // minlat, minlon, maxlat, maxlon
54 @Override public String toString() {
55 return name;
56 }
57 }
58
59 public final ArrayList<PreferenceChangedListener> listener = new ArrayList<PreferenceChangedListener>();
60
61 /**
62 * Map the property name to the property object.
63 */
64 protected final SortedMap<String, String> properties = new TreeMap<String, String>();
65 protected final SortedMap<String, String> defaults = new TreeMap<String, String>();
66
67 /**
68 * Override some values on read. This is intended to be used for technology previews
69 * where we want to temporarily modify things without changing the user's preferences
70 * file.
71 */
72 protected static final SortedMap<String, String> override = new TreeMap<String, String>();
73 static {
74 //override.put("osm-server.version", "0.5");
75 //override.put("osm-server.additional-versions", "");
76 //override.put("osm-server.url", "http://openstreetmap.gryph.de/api");
77 //override.put("plugins", null);
78 }
79
80 /**
81 * Return the location of the user defined preferences file
82 */
83 public String getPreferencesDir() {
84 final String path = getPreferencesDirFile().getPath();
85 if (path.endsWith(File.separator))
86 return path;
87 return path + File.separator;
88 }
89
90 public File getPreferencesDirFile() {
91 if (preferencesDirFile != null)
92 return preferencesDirFile;
93 String path;
94 path = System.getProperty("josm.home");
95 if (path != null) {
96 preferencesDirFile = new File(path);
97 } else {
98 path = System.getenv("APPDATA");
99 if (path != null) {
100 preferencesDirFile = new File(path, "JOSM");
101 } else {
102 preferencesDirFile = new File(System.getProperty("user.home"), ".josm");
103 }
104 }
105 return preferencesDirFile;
106 }
107
108 public File getPluginsDirFile() {
109 return new File(getPreferencesDirFile(), "plugins");
110 }
111
112 /**
113 * @return A list of all existing directories where resources could be stored.
114 */
115 public Collection<String> getAllPossiblePreferenceDirs() {
116 LinkedList<String> locations = new LinkedList<String>();
117 locations.add(Main.pref.getPreferencesDir());
118 String s;
119 if ((s = System.getenv("JOSM_RESOURCES")) != null) {
120 if (!s.endsWith(File.separator))
121 s = s + File.separator;
122 locations.add(s);
123 }
124 if ((s = System.getProperty("josm.resources")) != null) {
125 if (!s.endsWith(File.separator))
126 s = s + File.separator;
127 locations.add(s);
128 }
129 String appdata = System.getenv("APPDATA");
130 if (System.getenv("ALLUSERSPROFILE") != null && appdata != null
131 && appdata.lastIndexOf(File.separator) != -1) {
132 appdata = appdata.substring(appdata.lastIndexOf(File.separator));
133 locations.add(new File(new File(System.getenv("ALLUSERSPROFILE"),
134 appdata), "JOSM").getPath());
135 }
136 locations.add("/usr/local/share/josm/");
137 locations.add("/usr/local/lib/josm/");
138 locations.add("/usr/share/josm/");
139 locations.add("/usr/lib/josm/");
140 return locations;
141 }
142
143 synchronized public boolean hasKey(final String key) {
144 return override.containsKey(key) ? override.get(key) != null : properties.containsKey(key);
145 }
146
147 synchronized public String get(final String key) {
148 putDefault(key, null);
149 if (override.containsKey(key))
150 return override.get(key);
151 if (!properties.containsKey(key))
152 return "";
153 return properties.get(key);
154 }
155
156 synchronized public String get(final String key, final String def) {
157 putDefault(key, def);
158 if (override.containsKey(key))
159 return override.get(key);
160 final String prop = properties.get(key);
161 if (prop == null || prop.equals(""))
162 return def;
163 return prop;
164 }
165
166 synchronized public Map<String, String> getAllPrefix(final String prefix) {
167 final Map<String,String> all = new TreeMap<String,String>();
168 for (final Entry<String,String> e : properties.entrySet())
169 if (e.getKey().startsWith(prefix))
170 all.put(e.getKey(), e.getValue());
171 for (final Entry<String,String> e : override.entrySet())
172 if (e.getKey().startsWith(prefix))
173 if (e.getValue() == null)
174 all.remove(e.getKey());
175 else
176 all.put(e.getKey(), e.getValue());
177 return all;
178 }
179
180 synchronized public Map<String, String> getDefaults()
181 {
182 return defaults;
183 }
184
185 synchronized public void putDefault(final String key, final String def) {
186 if(!defaults.containsKey(key) || defaults.get(key) == null)
187 defaults.put(key, def);
188 else if(def != null && !defaults.get(key).equals(def))
189 System.out.println("Defaults for " + key + " differ: " + def + " != " + defaults.get(key));
190 }
191
192 synchronized public boolean getBoolean(final String key) {
193 putDefault(key, null);
194 if (override.containsKey(key))
195 return override.get(key) == null ? false : Boolean.parseBoolean(override.get(key));
196 return properties.containsKey(key) ? Boolean.parseBoolean(properties.get(key)) : false;
197 }
198
199 synchronized public boolean getBoolean(final String key, final boolean def) {
200 putDefault(key, Boolean.toString(def));
201 if (override.containsKey(key))
202 return override.get(key) == null ? def : Boolean.parseBoolean(override.get(key));
203 return properties.containsKey(key) ? Boolean.parseBoolean(properties.get(key)) : def;
204 }
205
206 synchronized public void put(final String key, String value) {
207 String oldvalue = properties.get(key);
208 if(value != null && value.length() == 0)
209 value = null;
210 if(!((oldvalue == null && value == null) || (value != null
211 && oldvalue != null && oldvalue.equals(value))))
212 {
213 if (value == null)
214 properties.remove(key);
215 else
216 properties.put(key, value);
217 save();
218 firePreferenceChanged(key, value);
219 }
220 }
221
222 synchronized public void put(final String key, final boolean value) {
223 put(key, Boolean.toString(value));
224 }
225
226 private final void firePreferenceChanged(final String key, final String value) {
227 for (final PreferenceChangedListener l : listener)
228 l.preferenceChanged(key, value);
229 }
230
231 /**
232 * Called after every put. In case of a problem, do nothing but output the error
233 * in log.
234 */
235 public void save() {
236 try {
237 setSystemProperties();
238 final PrintWriter out = new PrintWriter(new FileWriter(getPreferencesDir() + "preferences"), false);
239 for (final Entry<String, String> e : properties.entrySet()) {
240 out.println(e.getKey() + "=" + e.getValue());
241 }
242 out.close();
243 } catch (final IOException e) {
244 e.printStackTrace();
245 // do not message anything, since this can be called from strange
246 // places.
247 }
248 }
249
250 public void load() throws IOException {
251 properties.clear();
252 final BufferedReader in = new BufferedReader(new FileReader(getPreferencesDir()+"preferences"));
253 int lineNumber = 0;
254 ArrayList<Integer> errLines = new ArrayList<Integer>();
255 for (String line = in.readLine(); line != null; line = in.readLine(), lineNumber++) {
256 final int i = line.indexOf('=');
257 if (i == -1 || i == 0) {
258 errLines.add(lineNumber);
259 continue;
260 }
261 properties.put(line.substring(0,i), line.substring(i+1));
262 }
263 if (!errLines.isEmpty()) {
264 throw new IOException("Malformed config file at lines " + errLines);
265 }
266 setSystemProperties();
267 }
268
269 public final void resetToDefault() {
270 properties.clear();
271 properties.put("projection", "org.openstreetmap.josm.data.projection.Epsg4326");
272 properties.put("draw.segment.direction", "true");
273 properties.put("draw.wireframe", "false");
274 properties.put("layerlist.visible", "true");
275 properties.put("propertiesdialog.visible", "true");
276 properties.put("selectionlist.visible", "true");
277 properties.put("commandstack.visible", "true");
278 properties.put("osm-server.url", "http://www.openstreetmap.org/api");
279 if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") == -1) {
280 properties.put("laf", "javax.swing.plaf.metal.MetalLookAndFeel");
281 } else {
282 properties.put("laf", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
283 }
284 save();
285 }
286
287 public Collection<Bookmark> loadBookmarks() throws IOException {
288 File bookmarkFile = new File(getPreferencesDir()+"bookmarks");
289 if (!bookmarkFile.exists())
290 bookmarkFile.createNewFile();
291 BufferedReader in = new BufferedReader(new FileReader(bookmarkFile));
292
293 Collection<Bookmark> bookmarks = new LinkedList<Bookmark>();
294 for (String line = in.readLine(); line != null; line = in.readLine()) {
295 StringTokenizer st = new StringTokenizer(line, ",");
296 if (st.countTokens() < 5)
297 continue;
298 Bookmark b = new Bookmark();
299 b.name = st.nextToken();
300 try {
301 for (int i = 0; i < b.latlon.length; ++i)
302 b.latlon[i] = Double.parseDouble(st.nextToken());
303 bookmarks.add(b);
304 } catch (NumberFormatException x) {
305 // line not parsed
306 }
307 }
308 in.close();
309 return bookmarks;
310 }
311
312 public void saveBookmarks(Collection<Bookmark> bookmarks) throws IOException {
313 File bookmarkFile = new File(Main.pref.getPreferencesDir()+"bookmarks");
314 if (!bookmarkFile.exists())
315 bookmarkFile.createNewFile();
316 PrintWriter out = new PrintWriter(new FileWriter(bookmarkFile));
317 for (Bookmark b : bookmarks) {
318 b.name = b.name.replace(',', '_');
319 out.print(b.name+",");
320 for (int i = 0; i < b.latlon.length; ++i)
321 out.print(b.latlon[i]+(i<b.latlon.length-1?",":""));
322 out.println();
323 }
324 out.close();
325 }
326
327 /**
328 * Convenience method for accessing colour preferences.
329 *
330 * @param colName name of the colour
331 * @param def default value
332 * @return a Color object for the configured colour, or the default value if none configured.
333 */
334 synchronized public Color getColor(String colName, Color def) {
335 String colStr = get("color."+colName);
336 if (colStr.equals("")) {
337 put("color."+colName, ColorHelper.color2html(def));
338 return def;
339 }
340 return ColorHelper.html2color(colStr);
341 }
342
343 // only for compatibility. Don't use any more.
344 @Deprecated
345 public static Color getPreferencesColor(String colName, Color def)
346 {
347 return Main.pref.getColor(colName, def);
348 }
349
350 /**
351 * Convenience method for accessing colour preferences.
352 *
353 * @param colName name of the colour
354 * @param specName name of the special colour settings
355 * @param def default value
356 * @return a Color object for the configured colour, or the default value if none configured.
357 */
358 synchronized public Color getColor(String colName, String specName, Color def) {
359 String colStr = get("color."+specName);
360 if(colStr.equals(""))
361 {
362 colStr = get("color."+colName);
363 if (colStr.equals("")) {
364 put("color."+colName, ColorHelper.color2html(def));
365 return def;
366 }
367 }
368 putDefault("color."+colName, ColorHelper.color2html(def));
369 return ColorHelper.html2color(colStr);
370 }
371
372 synchronized public void putColor(String colName, Color val) {
373 put("color."+colName, val != null ? ColorHelper.color2html(val) : null);
374 }
375
376 synchronized public int getInteger(String key, int def) {
377 putDefault(key, Integer.toString(def));
378 String v = get(key);
379 if(null == v)
380 return def;
381
382 try {
383 return Integer.parseInt(v);
384 } catch(NumberFormatException e) {
385 // fall out
386 }
387 return def;
388 }
389
390 synchronized public double getDouble(String key, double def) {
391 putDefault(key, Double.toString(def));
392 String v = get(key);
393 if(null == v)
394 return def;
395
396 try {
397 return Double.parseDouble(v);
398 } catch(NumberFormatException e) {
399 // fall out
400 }
401 return def;
402 }
403
404 synchronized public Collection<String> getCollection(String key, Collection<String> def) {
405 String s = get(key);
406 if(s != null && s.length() != 0)
407 {
408 /* handle old comma separated stuff - remove in future */
409 if(s.indexOf(',') >= 0)
410 return Arrays.asList(s.split(","));
411 else
412 return Arrays.asList(s.split(";"));
413 }
414 else if(def != null)
415 return def;
416 return null;
417 }
418 synchronized public void removeFromCollection(String key, String value) {
419 ArrayList<String> a = new ArrayList<String>(getCollection(key, null));
420 if(a != null)
421 {
422 a.remove(value);
423 putCollection(key, a);
424 }
425 }
426 synchronized public void putCollection(String key, Collection<String> val) {
427 String s = null;
428 if(val != null)
429 {
430 for(String a : val)
431 {
432 if(s != null)
433 s += ";" + a;
434 else
435 s = a;
436 }
437 }
438
439 put(key, s);
440 }
441
442 private void setSystemProperties() {
443 Properties sysProp = System.getProperties();
444 if (getBoolean(ProxyPreferences.PROXY_ENABLE)) {
445 sysProp.put("proxySet", "true");
446 sysProp.put("http.proxyHost", get(ProxyPreferences.PROXY_HOST));
447 sysProp.put("proxyPort", get(ProxyPreferences.PROXY_PORT));
448 if (!getBoolean(ProxyPreferences.PROXY_ANONYMOUS)) {
449 sysProp.put("proxyUser", get(ProxyPreferences.PROXY_USER));
450 sysProp.put("proxyPassword", get(ProxyPreferences.PROXY_PASS));
451 }
452 } else {
453 sysProp.put("proxySet", "false");
454 sysProp.remove("http.proxyHost");
455 sysProp.remove("proxyPort");
456 sysProp.remove("proxyUser");
457 sysProp.remove("proxyPassword");
458 }
459 System.setProperties(sysProp);
460 }
461}
Note: See TracBrowser for help on using the repository browser.