1 package net.sf.openrocket.util;
4 import java.awt.Dimension;
6 import java.awt.Toolkit;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.util.HashMap;
11 import java.util.HashSet;
13 import java.util.MissingResourceException;
14 import java.util.Properties;
16 import java.util.prefs.BackingStoreException;
17 import java.util.prefs.Preferences;
19 import net.sf.openrocket.database.Databases;
20 import net.sf.openrocket.document.Simulation;
21 import net.sf.openrocket.gui.main.ExceptionHandler;
22 import net.sf.openrocket.material.Material;
23 import net.sf.openrocket.rocketcomponent.BodyComponent;
24 import net.sf.openrocket.rocketcomponent.FinSet;
25 import net.sf.openrocket.rocketcomponent.InternalComponent;
26 import net.sf.openrocket.rocketcomponent.LaunchLug;
27 import net.sf.openrocket.rocketcomponent.MassObject;
28 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
29 import net.sf.openrocket.rocketcomponent.Rocket;
30 import net.sf.openrocket.rocketcomponent.RocketComponent;
31 import net.sf.openrocket.simulation.FlightDataBranch;
32 import net.sf.openrocket.simulation.RK4Simulator;
33 import net.sf.openrocket.simulation.SimulationConditions;
34 import net.sf.openrocket.unit.UnitGroup;
40 * Whether to use the debug-node instead of the normal node.
42 public static final boolean DEBUG = false;
45 * Whether to clear all preferences at application startup. This has an effect only
48 public static final boolean CLEARPREFS = true;
51 * The node name to use in the Java preferences storage.
53 public static final String NODENAME = (DEBUG?"OpenRocket-debug":"OpenRocket");
57 private static final String BUILD_VERSION;
58 private static final String BUILD_SOURCE;
59 public static final String DEFAULT_BUILD_SOURCE = "default";
63 InputStream is = ClassLoader.getSystemResourceAsStream("build.properties");
65 throw new MissingResourceException(
66 "build.properties not found, distribution built wrong" +
67 " path:"+System.getProperty("java.class.path"),
68 "build.properties", "build.version");
71 Properties props = new Properties();
75 BUILD_VERSION = props.getProperty("build.version");
76 if (BUILD_VERSION == null) {
77 throw new MissingResourceException(
78 "build.version not found in property file",
79 "build.properties", "build.version");
82 BUILD_SOURCE = props.getProperty("build.source");
84 } catch (IOException e) {
85 throw new MissingResourceException(
86 "Error reading build.properties",
87 "build.properties", "build.version");
92 public static final String BODY_COMPONENT_INSERT_POSITION_KEY = "BodyComponentInsertPosition";
95 public static final String CONFIRM_DELETE_SIMULATION = "ConfirmDeleteSimulation";
97 // Preferences related to data export
98 public static final String EXPORT_FIELD_SEPARATOR = "ExportFieldSeparator";
99 public static final String EXPORT_SIMULATION_COMMENT = "ExportSimulationComment";
100 public static final String EXPORT_FIELD_NAME_COMMENT = "ExportFieldDescriptionComment";
101 public static final String EXPORT_EVENT_COMMENTS = "ExportEventComments";
102 public static final String EXPORT_COMMENT_CHARACTER = "ExportCommentCharacter";
104 public static final String PLOT_SHOW_POINTS = "ShowPlotPoints";
107 * Node to this application's preferences.
108 * @deprecated Use the static methods instead.
111 public static final Preferences NODE;
112 private static final Preferences PREFNODE;
116 Preferences root = Preferences.userRoot();
117 if (DEBUG && CLEARPREFS) {
119 if (root.nodeExists(NODENAME)) {
120 root.node(NODENAME).removeNode();
122 } catch (BackingStoreException e) {
123 throw new RuntimeException("Unable to clear preference node",e);
126 PREFNODE = root.node(NODENAME);
133 ///////// Default component attributes
135 private static final HashMap<Class<?>,String> DEFAULT_COLORS =
136 new HashMap<Class<?>,String>();
138 DEFAULT_COLORS.put(BodyComponent.class, "0,0,240");
139 DEFAULT_COLORS.put(FinSet.class, "0,0,200");
140 DEFAULT_COLORS.put(LaunchLug.class, "0,0,180");
141 DEFAULT_COLORS.put(InternalComponent.class, "170,0,100");
142 DEFAULT_COLORS.put(MassObject.class, "0,0,0");
143 DEFAULT_COLORS.put(RecoveryDevice.class, "255,0,0");
147 private static final HashMap<Class<?>,String> DEFAULT_LINE_STYLES =
148 new HashMap<Class<?>,String>();
150 DEFAULT_LINE_STYLES.put(RocketComponent.class, LineStyle.SOLID.name());
151 DEFAULT_LINE_STYLES.put(MassObject.class, LineStyle.DASHED.name());
155 private static final Material DEFAULT_LINE_MATERIAL =
156 Databases.findMaterial(Material.Type.LINE, "Elastic cord (round 2mm, 1/16 in)",
158 private static final Material DEFAULT_SURFACE_MATERIAL =
159 Databases.findMaterial(Material.Type.SURFACE, "Ripstop nylon", 0.067, false);
160 private static final Material DEFAULT_BULK_MATERIAL =
161 Databases.findMaterial(Material.Type.BULK, "Cardboard", 680, false);
164 //////////////////////
167 public static String getVersion() {
168 return BUILD_VERSION;
172 public static String getBuildSource() {
177 public static String getUniqueID() {
178 String id = PREFNODE.get("id", null);
180 id = UniqueID.generateHashedID();
181 PREFNODE.put("id", id);
188 public static void storeVersion() {
189 PREFNODE.put("OpenRocketVersion", getVersion());
194 * Returns a limited-range integer value from the preferences. If the value
195 * in the preferences is negative or greater than max, then the default value
198 * @param key The preference to retrieve.
199 * @param max Maximum allowed value for the choice.
200 * @param def Default value.
201 * @return The preference value.
203 public static int getChoise(String key, int max, int def) {
204 int v = PREFNODE.getInt(key, def);
205 if ((v<0) || (v>max))
212 * Helper method that puts an integer choice value into the preferences.
214 * @param key the preference key.
215 * @param value the value to store.
217 public static void putChoise(String key, int value) {
218 PREFNODE.putInt(key, value);
224 public static String getString(String key, String def) {
225 return PREFNODE.get(key, def);
228 public static void putString(String key, String value) {
229 PREFNODE.put(key, value);
234 public static boolean getBoolean(String key, boolean def) {
235 return PREFNODE.getBoolean(key, def);
238 public static void putBoolean(String key, boolean value) {
239 PREFNODE.putBoolean(key, value);
247 public static File getDefaultDirectory() {
248 String file = PREFNODE.get("defaultDirectory", null);
251 return new File(file);
254 public static void setDefaultDirectory(File dir) {
259 d = dir.getAbsolutePath();
261 PREFNODE.put("defaultDirectory", d);
267 public static Color getDefaultColor(Class<? extends RocketComponent> c) {
268 String color = get("componentColors", c, DEFAULT_COLORS);
272 String[] rgb = color.split(",");
275 int red = MathUtil.clamp(Integer.parseInt(rgb[0]),0,255);
276 int green = MathUtil.clamp(Integer.parseInt(rgb[1]),0,255);
277 int blue = MathUtil.clamp(Integer.parseInt(rgb[2]),0,255);
278 return new Color(red,green,blue);
279 } catch (NumberFormatException ignore) { }
285 public static void setDefaultColor(Class<? extends RocketComponent> c, Color color) {
288 String string = color.getRed() + "," + color.getGreen() + "," + color.getBlue();
289 set("componentColors", c, string);
292 public static Color getMotorBorderColor() {
293 // TODO: MEDIUM: Motor color (settable?)
294 return new Color(0,0,0,200);
298 public static Color getMotorFillColor() {
299 // TODO: MEDIUM: Motor fill color (settable?)
300 return new Color(0,0,0,100);
304 public static LineStyle getDefaultLineStyle(Class<? extends RocketComponent> c) {
305 String value = get("componentStyle", c, DEFAULT_LINE_STYLES);
307 return LineStyle.valueOf(value);
308 } catch (Exception e) {
309 return LineStyle.SOLID;
313 public static void setDefaultLineStyle(Class<? extends RocketComponent> c,
317 set("componentStyle", c, style.name());
322 * Return the DPI setting of the monitor. This is either the setting provided
323 * by the system or a user-specified DPI setting.
325 * @return the DPI setting to use.
327 public static double getDPI() {
328 int dpi = PREFNODE.getInt("DPI", 0); // Tenths of a dpi
331 dpi = Toolkit.getDefaultToolkit().getScreenResolution()*10;
336 return ((double)dpi)/10.0;
340 public static double getDefaultMach() {
341 // TODO: HIGH: implement custom default mach number
348 public static Material getDefaultComponentMaterial(
349 Class<? extends RocketComponent> componentClass,
350 Material.Type type) {
352 String material = get("componentMaterials", componentClass, null);
353 if (material != null) {
355 Material m = Material.fromStorableString(material, false);
356 if (m.getType() == type)
358 } catch (IllegalArgumentException ignore) { }
363 return DEFAULT_LINE_MATERIAL;
365 return DEFAULT_SURFACE_MATERIAL;
367 return DEFAULT_BULK_MATERIAL;
369 throw new IllegalArgumentException("Unknown material type: "+type);
372 public static void setDefaultComponentMaterial(
373 Class<? extends RocketComponent> componentClass, Material material) {
375 set("componentMaterials", componentClass,
376 material==null ? null : material.toStorableString());
380 public static int getMaxThreadCount() {
381 return Runtime.getRuntime().availableProcessors();
386 public static Point getWindowPosition(Class<?> c) {
388 String pref = PREFNODE.node("windows").get("position." + c.getCanonicalName(), null);
393 if (pref.indexOf(',')<0)
397 x = Integer.parseInt(pref.substring(0,pref.indexOf(',')));
398 y = Integer.parseInt(pref.substring(pref.indexOf(',')+1));
399 } catch (NumberFormatException e) {
402 return new Point(x,y);
405 public static void setWindowPosition(Class<?> c, Point p) {
406 PREFNODE.node("windows").put("position." + c.getCanonicalName(), "" + p.x + "," + p.y);
413 public static Dimension getWindowSize(Class<?> c) {
415 String pref = PREFNODE.node("windows").get("size." + c.getCanonicalName(), null);
420 if (pref.indexOf(',')<0)
424 x = Integer.parseInt(pref.substring(0,pref.indexOf(',')));
425 y = Integer.parseInt(pref.substring(pref.indexOf(',')+1));
426 } catch (NumberFormatException e) {
429 return new Dimension(x,y);
432 public static void setWindowSize(Class<?> c, Dimension d) {
433 PREFNODE.node("windows").put("size." + c.getCanonicalName(), "" + d.width + "," + d.height);
438 //// Background flight data computation
440 public static boolean computeFlightInBackground() {
441 return PREFNODE.getBoolean("backgroundFlight", true);
444 public static Simulation getBackgroundSimulation(Rocket rocket) {
445 Simulation s = new Simulation(rocket);
446 SimulationConditions cond = s.getConditions();
448 cond.setTimeStep(RK4Simulator.RECOMMENDED_TIME_STEP*2);
449 cond.setWindSpeedAverage(1.0);
450 cond.setWindSpeedDeviation(0.1);
451 cond.setLaunchRodLength(5);
457 ///////// Export variables
459 public static boolean isExportSelected(FlightDataBranch.Type type) {
460 Preferences prefs = PREFNODE.node("exports");
461 return prefs.getBoolean(type.getName(), false);
464 public static void setExportSelected(FlightDataBranch.Type type, boolean selected) {
465 Preferences prefs = PREFNODE.node("exports");
466 prefs.putBoolean(type.getName(), selected);
471 ///////// Default unit storage
473 public static void loadDefaultUnits() {
474 Preferences prefs = PREFNODE.node("units");
477 for (String key: prefs.keys()) {
478 UnitGroup group = UnitGroup.UNITS.get(key);
482 group.setDefaultUnit(prefs.get(key, null));
485 } catch (BackingStoreException e) {
486 ExceptionHandler.handleErrorCondition(e);
490 public static void storeDefaultUnits() {
491 Preferences prefs = PREFNODE.node("units");
493 for (String key: UnitGroup.UNITS.keySet()) {
494 UnitGroup group = UnitGroup.UNITS.get(key);
495 if (group == null || group.getUnitCount() < 2)
498 prefs.put(key, group.getDefaultUnit().getUnit());
504 //// Material storage
508 * Add a user-defined material to the preferences. The preferences are
509 * first checked for an existing material matching the provided one using
510 * {@link Material#equals(Object)}.
512 * @param m the material to add.
514 public static void addUserMaterial(Material m) {
515 Preferences prefs = PREFNODE.node("userMaterials");
518 // Check whether material already exists
519 if (getUserMaterials().contains(m)) {
523 // Add material using next free key (key is not used when loading)
524 String mat = m.toStorableString();
525 for (int i = 0; ; i++) {
526 String key = "material" + i;
527 if (prefs.get(key, null) == null) {
536 * Remove a user-defined material from the preferences. The matching is performed
537 * using {@link Material#equals(Object)}.
539 * @param m the material to remove.
541 public static void removeUserMaterial(Material m) {
542 Preferences prefs = PREFNODE.node("userMaterials");
546 // Iterate through materials and remove all keys with a matching material
547 for (String key: prefs.keys()) {
548 String value = prefs.get(key, null);
551 Material existing = Material.fromStorableString(value, true);
552 if (existing.equals(m)) {
556 } catch (IllegalArgumentException ignore) { }
560 } catch (BackingStoreException e) {
561 throw new IllegalStateException("Cannot read preferences!", e);
567 * Return a set of all user-defined materials in the preferences. The materials
568 * are created marked as user-defined.
570 * @return a set of all user-defined materials.
572 public static Set<Material> getUserMaterials() {
573 Preferences prefs = PREFNODE.node("userMaterials");
575 HashSet<Material> materials = new HashSet<Material>();
578 for (String key: prefs.keys()) {
579 String value = prefs.get(key, null);
582 Material m = Material.fromStorableString(value, true);
585 } catch (IllegalArgumentException e) {
586 System.err.println("Illegal material string " + value);
591 } catch (BackingStoreException e) {
592 throw new IllegalStateException("Cannot read preferences!", e);
601 private static String get(String directory,
602 Class<? extends RocketComponent> componentClass,
603 Map<Class<?>, String> defaultMap) {
605 // Search preferences
606 Class<?> c = componentClass;
607 Preferences prefs = PREFNODE.node(directory);
608 while (c!=null && RocketComponent.class.isAssignableFrom(c)) {
609 String value = prefs.get(c.getSimpleName(), null);
612 c = c.getSuperclass();
615 if (defaultMap == null)
620 while (RocketComponent.class.isAssignableFrom(c)) {
621 String value = defaultMap.get(c);
624 c = c.getSuperclass();
631 private static void set(String directory, Class<? extends RocketComponent> componentClass,
633 Preferences prefs = PREFNODE.node(directory);
635 prefs.remove(componentClass.getSimpleName());
637 prefs.put(componentClass.getSimpleName(), value);