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.material.Material;
22 import net.sf.openrocket.rocketcomponent.BodyComponent;
23 import net.sf.openrocket.rocketcomponent.FinSet;
24 import net.sf.openrocket.rocketcomponent.InternalComponent;
25 import net.sf.openrocket.rocketcomponent.LaunchLug;
26 import net.sf.openrocket.rocketcomponent.MassObject;
27 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
28 import net.sf.openrocket.rocketcomponent.Rocket;
29 import net.sf.openrocket.rocketcomponent.RocketComponent;
30 import net.sf.openrocket.simulation.FlightDataBranch;
31 import net.sf.openrocket.simulation.RK4Simulator;
32 import net.sf.openrocket.simulation.SimulationConditions;
33 import net.sf.openrocket.unit.UnitGroup;
39 * Whether to use the debug-node instead of the normal node.
41 public static final boolean DEBUG = false;
44 * Whether to clear all preferences at application startup. This has an effect only
47 public static final boolean CLEARPREFS = true;
50 * The node name to use in the Java preferences storage.
52 public static final String NODENAME = (DEBUG?"OpenRocket-debug":"OpenRocket");
56 private static final String BUILD_VERSION;
57 private static final String BUILD_SOURCE;
61 InputStream is = ClassLoader.getSystemResourceAsStream("build.properties");
63 throw new MissingResourceException(
64 "build.properties not found, distribution built wrong",
65 "build.properties", "build.version");
68 Properties props = new Properties();
72 BUILD_VERSION = props.getProperty("build.version");
73 if (BUILD_VERSION == null) {
74 throw new MissingResourceException(
75 "build.version not found in property file",
76 "build.properties", "build.version");
79 BUILD_SOURCE = props.getProperty("build.source");
81 } catch (IOException e) {
82 throw new MissingResourceException(
83 "Error reading build.properties",
84 "build.properties", "build.version");
89 public static final String BODY_COMPONENT_INSERT_POSITION_KEY = "BodyComponentInsertPosition";
92 public static final String CONFIRM_DELETE_SIMULATION = "ConfirmDeleteSimulation";
94 // Preferences related to data export
95 public static final String EXPORT_FIELD_SEPARATOR = "ExportFieldSeparator";
96 public static final String EXPORT_SIMULATION_COMMENT = "ExportSimulationComment";
97 public static final String EXPORT_FIELD_NAME_COMMENT = "ExportFieldDescriptionComment";
98 public static final String EXPORT_EVENT_COMMENTS = "ExportEventComments";
99 public static final String EXPORT_COMMENT_CHARACTER = "ExportCommentCharacter";
101 public static final String PLOT_SHOW_POINTS = "ShowPlotPoints";
104 * Node to this application's preferences.
105 * @deprecated Use the static methods instead.
108 public static final Preferences NODE;
109 private static final Preferences PREFNODE;
113 Preferences root = Preferences.userRoot();
114 if (DEBUG && CLEARPREFS) {
116 if (root.nodeExists(NODENAME)) {
117 root.node(NODENAME).removeNode();
119 } catch (BackingStoreException e) {
120 throw new RuntimeException("Unable to clear preference node",e);
123 PREFNODE = root.node(NODENAME);
130 ///////// Default component attributes
132 private static final HashMap<Class<?>,String> DEFAULT_COLORS =
133 new HashMap<Class<?>,String>();
135 DEFAULT_COLORS.put(BodyComponent.class, "0,0,240");
136 DEFAULT_COLORS.put(FinSet.class, "0,0,200");
137 DEFAULT_COLORS.put(LaunchLug.class, "0,0,180");
138 DEFAULT_COLORS.put(InternalComponent.class, "170,0,100");
139 DEFAULT_COLORS.put(MassObject.class, "0,0,0");
140 DEFAULT_COLORS.put(RecoveryDevice.class, "255,0,0");
144 private static final HashMap<Class<?>,String> DEFAULT_LINE_STYLES =
145 new HashMap<Class<?>,String>();
147 DEFAULT_LINE_STYLES.put(RocketComponent.class, LineStyle.SOLID.name());
148 DEFAULT_LINE_STYLES.put(MassObject.class, LineStyle.DASHED.name());
152 private static final Material DEFAULT_LINE_MATERIAL =
153 Databases.findMaterial(Material.Type.LINE, "Elastic cord (round 2mm, 1/16 in)",
155 private static final Material DEFAULT_SURFACE_MATERIAL =
156 Databases.findMaterial(Material.Type.SURFACE, "Ripstop nylon", 0.067, false);
157 private static final Material DEFAULT_BULK_MATERIAL =
158 Databases.findMaterial(Material.Type.BULK, "Cardboard", 680, false);
161 //////////////////////
164 public static String getVersion() {
165 return BUILD_VERSION;
169 public static String getBuildSource() {
175 public static void storeVersion() {
176 PREFNODE.put("OpenRocketVersion", getVersion());
181 * Returns a limited-range integer value from the preferences. If the value
182 * in the preferences is negative or greater than max, then the default value
185 * @param key The preference to retrieve.
186 * @param max Maximum allowed value for the choice.
187 * @param def Default value.
188 * @return The preference value.
190 public static int getChoise(String key, int max, int def) {
191 int v = PREFNODE.getInt(key, def);
192 if ((v<0) || (v>max))
199 * Helper method that puts an integer choice value into the preferences.
201 * @param key the preference key.
202 * @param value the value to store.
204 public static void putChoise(String key, int value) {
205 PREFNODE.putInt(key, value);
211 public static String getString(String key, String def) {
212 return PREFNODE.get(key, def);
215 public static void putString(String key, String value) {
216 PREFNODE.put(key, value);
221 public static boolean getBoolean(String key, boolean def) {
222 return PREFNODE.getBoolean(key, def);
225 public static void putBoolean(String key, boolean value) {
226 PREFNODE.putBoolean(key, value);
234 public static File getDefaultDirectory() {
235 String file = PREFNODE.get("defaultDirectory", null);
238 return new File(file);
241 public static void setDefaultDirectory(File dir) {
246 d = dir.getAbsolutePath();
248 PREFNODE.put("defaultDirectory", d);
254 public static Color getDefaultColor(Class<? extends RocketComponent> c) {
255 String color = get("componentColors", c, DEFAULT_COLORS);
259 String[] rgb = color.split(",");
262 int red = MathUtil.clamp(Integer.parseInt(rgb[0]),0,255);
263 int green = MathUtil.clamp(Integer.parseInt(rgb[1]),0,255);
264 int blue = MathUtil.clamp(Integer.parseInt(rgb[2]),0,255);
265 return new Color(red,green,blue);
266 } catch (NumberFormatException ignore) { }
272 public static void setDefaultColor(Class<? extends RocketComponent> c, Color color) {
275 String string = color.getRed() + "," + color.getGreen() + "," + color.getBlue();
276 set("componentColors", c, string);
279 public static Color getMotorBorderColor() {
280 // TODO: MEDIUM: Motor color (settable?)
281 return new Color(0,0,0,200);
285 public static Color getMotorFillColor() {
286 // TODO: MEDIUM: Motor fill color (settable?)
287 return new Color(0,0,0,100);
291 public static LineStyle getDefaultLineStyle(Class<? extends RocketComponent> c) {
292 String value = get("componentStyle", c, DEFAULT_LINE_STYLES);
294 return LineStyle.valueOf(value);
295 } catch (Exception e) {
296 return LineStyle.SOLID;
300 public static void setDefaultLineStyle(Class<? extends RocketComponent> c,
304 set("componentStyle", c, style.name());
309 * Return the DPI setting of the monitor. This is either the setting provided
310 * by the system or a user-specified DPI setting.
312 * @return the DPI setting to use.
314 public static double getDPI() {
315 int dpi = PREFNODE.getInt("DPI", 0); // Tenths of a dpi
318 dpi = Toolkit.getDefaultToolkit().getScreenResolution()*10;
323 return ((double)dpi)/10.0;
327 public static double getDefaultMach() {
328 // TODO: HIGH: implement custom default mach number
335 public static Material getDefaultComponentMaterial(
336 Class<? extends RocketComponent> componentClass,
337 Material.Type type) {
339 String material = get("componentMaterials", componentClass, null);
340 if (material != null) {
342 Material m = Material.fromStorableString(material, false);
343 if (m.getType() == type)
345 } catch (IllegalArgumentException ignore) { }
350 return DEFAULT_LINE_MATERIAL;
352 return DEFAULT_SURFACE_MATERIAL;
354 return DEFAULT_BULK_MATERIAL;
356 throw new IllegalArgumentException("Unknown material type: "+type);
359 public static void setDefaultComponentMaterial(
360 Class<? extends RocketComponent> componentClass, Material material) {
362 set("componentMaterials", componentClass,
363 material==null ? null : material.toStorableString());
367 public static int getMaxThreadCount() {
368 return Runtime.getRuntime().availableProcessors();
373 public static Point getWindowPosition(Class<?> c) {
375 String pref = PREFNODE.node("windows").get("position." + c.getCanonicalName(), null);
380 if (pref.indexOf(',')<0)
384 x = Integer.parseInt(pref.substring(0,pref.indexOf(',')));
385 y = Integer.parseInt(pref.substring(pref.indexOf(',')+1));
386 } catch (NumberFormatException e) {
389 return new Point(x,y);
392 public static void setWindowPosition(Class<?> c, Point p) {
393 PREFNODE.node("windows").put("position." + c.getCanonicalName(), "" + p.x + "," + p.y);
400 public static Dimension getWindowSize(Class<?> c) {
402 String pref = PREFNODE.node("windows").get("size." + c.getCanonicalName(), null);
407 if (pref.indexOf(',')<0)
411 x = Integer.parseInt(pref.substring(0,pref.indexOf(',')));
412 y = Integer.parseInt(pref.substring(pref.indexOf(',')+1));
413 } catch (NumberFormatException e) {
416 return new Dimension(x,y);
419 public static void setWindowSize(Class<?> c, Dimension d) {
420 PREFNODE.node("windows").put("size." + c.getCanonicalName(), "" + d.width + "," + d.height);
425 //// Background flight data computation
427 public static boolean computeFlightInBackground() {
428 return PREFNODE.getBoolean("backgroundFlight", true);
431 public static Simulation getBackgroundSimulation(Rocket rocket) {
432 Simulation s = new Simulation(rocket);
433 SimulationConditions cond = s.getConditions();
435 cond.setTimeStep(RK4Simulator.RECOMMENDED_TIME_STEP*2);
436 cond.setWindSpeedAverage(1.0);
437 cond.setWindSpeedDeviation(0.1);
438 cond.setLaunchRodLength(5);
444 ///////// Export variables
446 public static boolean isExportSelected(FlightDataBranch.Type type) {
447 Preferences prefs = PREFNODE.node("exports");
448 return prefs.getBoolean(type.getName(), false);
451 public static void setExportSelected(FlightDataBranch.Type type, boolean selected) {
452 Preferences prefs = PREFNODE.node("exports");
453 prefs.putBoolean(type.getName(), selected);
458 ///////// Default unit storage
460 public static void loadDefaultUnits() {
461 Preferences prefs = PREFNODE.node("units");
464 for (String key: prefs.keys()) {
465 UnitGroup group = UnitGroup.UNITS.get(key);
469 group.setDefaultUnit(prefs.get(key, null));
472 } catch (BackingStoreException e) {
473 System.err.println("BackingStoreException:");
478 public static void storeDefaultUnits() {
479 Preferences prefs = PREFNODE.node("units");
481 for (String key: UnitGroup.UNITS.keySet()) {
482 UnitGroup group = UnitGroup.UNITS.get(key);
483 if (group == null || group.getUnitCount() < 2)
486 prefs.put(key, group.getDefaultUnit().getUnit());
492 //// Material storage
496 * Add a user-defined material to the preferences. The preferences are
497 * first checked for an existing material matching the provided one using
498 * {@link Material#equals(Object)}.
500 * @param m the material to add.
502 public static void addUserMaterial(Material m) {
503 Preferences prefs = PREFNODE.node("userMaterials");
506 // Check whether material already exists
507 if (getUserMaterials().contains(m)) {
511 // Add material using next free key (key is not used when loading)
512 String mat = m.toStorableString();
513 for (int i = 0; ; i++) {
514 String key = "material" + i;
515 if (prefs.get(key, null) == null) {
524 * Remove a user-defined material from the preferences. The matching is performed
525 * using {@link Material#equals(Object)}.
527 * @param m the material to remove.
529 public static void removeUserMaterial(Material m) {
530 Preferences prefs = PREFNODE.node("userMaterials");
534 // Iterate through materials and remove all keys with a matching material
535 for (String key: prefs.keys()) {
536 String value = prefs.get(key, null);
539 Material existing = Material.fromStorableString(value, true);
540 if (existing.equals(m)) {
544 } catch (IllegalArgumentException ignore) { }
548 } catch (BackingStoreException e) {
549 throw new IllegalStateException("Cannot read preferences!", e);
555 * Return a set of all user-defined materials in the preferences. The materials
556 * are created marked as user-defined.
558 * @return a set of all user-defined materials.
560 public static Set<Material> getUserMaterials() {
561 Preferences prefs = PREFNODE.node("userMaterials");
563 HashSet<Material> materials = new HashSet<Material>();
566 for (String key: prefs.keys()) {
567 String value = prefs.get(key, null);
570 Material m = Material.fromStorableString(value, true);
573 } catch (IllegalArgumentException e) {
574 System.err.println("Illegal material string " + value);
579 } catch (BackingStoreException e) {
580 throw new IllegalStateException("Cannot read preferences!", e);
589 private static String get(String directory,
590 Class<? extends RocketComponent> componentClass,
591 Map<Class<?>, String> defaultMap) {
593 // Search preferences
594 Class<?> c = componentClass;
595 Preferences prefs = PREFNODE.node(directory);
596 while (c!=null && RocketComponent.class.isAssignableFrom(c)) {
597 String value = prefs.get(c.getSimpleName(), null);
600 c = c.getSuperclass();
603 if (defaultMap == null)
608 while (RocketComponent.class.isAssignableFrom(c)) {
609 String value = defaultMap.get(c);
612 c = c.getSuperclass();
619 private static void set(String directory, Class<? extends RocketComponent> componentClass,
621 Preferences prefs = PREFNODE.node(directory);
623 prefs.remove(componentClass.getSimpleName());
625 prefs.put(componentClass.getSimpleName(), value);