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

Last change on this file since 1023 was 1018, checked in by stoecker, 16 years ago

close bug #1628

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