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.logging.LogHelper;
23 import net.sf.openrocket.material.Material;
24 import net.sf.openrocket.rocketcomponent.BodyComponent;
25 import net.sf.openrocket.rocketcomponent.FinSet;
26 import net.sf.openrocket.rocketcomponent.InternalComponent;
27 import net.sf.openrocket.rocketcomponent.LaunchLug;
28 import net.sf.openrocket.rocketcomponent.MassObject;
29 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
30 import net.sf.openrocket.rocketcomponent.Rocket;
31 import net.sf.openrocket.rocketcomponent.RocketComponent;
32 import net.sf.openrocket.simulation.FlightDataType;
33 import net.sf.openrocket.simulation.GUISimulationConditions;
34 import net.sf.openrocket.simulation.RK4SimulationStepper;
35 import net.sf.openrocket.startup.Application;
36 import net.sf.openrocket.unit.UnitGroup;
40 private static final LogHelper log = Application.getLogger();
43 * Whether to use the debug-node instead of the normal node.
45 public static final boolean DEBUG = false;
48 * Whether to clear all preferences at application startup. This has an effect only
51 public static final boolean CLEARPREFS = true;
54 * The node name to use in the Java preferences storage.
56 public static final String NODENAME = (DEBUG ? "OpenRocket-debug" : "OpenRocket");
59 public static final String DEFAULT_BUILD_SOURCE = "default";
63 * Load property file only when necessary.
65 private static class BuildPropertyHolder {
67 public static final String BUILD_VERSION;
68 public static final String BUILD_SOURCE;
69 public static final boolean DEFAULT_CHECK_UPDATES;
73 InputStream is = ClassLoader.getSystemResourceAsStream("build.properties");
75 throw new MissingResourceException(
76 "build.properties not found, distribution built wrong" +
77 " classpath:" + System.getProperty("java.class.path"),
78 "build.properties", "build.version");
81 Properties props = new Properties();
85 String version = props.getProperty("build.version");
86 if (version == null) {
87 throw new MissingResourceException(
88 "build.version not found in property file",
89 "build.properties", "build.version");
91 BUILD_VERSION = version.trim();
93 BUILD_SOURCE = props.getProperty("build.source");
94 if (BUILD_SOURCE == null) {
95 throw new MissingResourceException(
96 "build.source not found in property file",
97 "build.properties", "build.source");
100 String value = props.getProperty("build.checkupdates");
102 DEFAULT_CHECK_UPDATES = Boolean.parseBoolean(value);
104 DEFAULT_CHECK_UPDATES = true;
106 } catch (IOException e) {
107 throw new MissingResourceException(
108 "Error reading build.properties",
109 "build.properties", "build.version");
114 public static final String BODY_COMPONENT_INSERT_POSITION_KEY = "BodyComponentInsertPosition";
117 public static final String CONFIRM_DELETE_SIMULATION = "ConfirmDeleteSimulation";
119 // Preferences related to data export
120 public static final String EXPORT_FIELD_SEPARATOR = "ExportFieldSeparator";
121 public static final String EXPORT_SIMULATION_COMMENT = "ExportSimulationComment";
122 public static final String EXPORT_FIELD_NAME_COMMENT = "ExportFieldDescriptionComment";
123 public static final String EXPORT_EVENT_COMMENTS = "ExportEventComments";
124 public static final String EXPORT_COMMENT_CHARACTER = "ExportCommentCharacter";
126 public static final String PLOT_SHOW_POINTS = "ShowPlotPoints";
128 private static final String CHECK_UPDATES = "CheckUpdates";
129 public static final String LAST_UPDATE = "LastUpdateVersion";
132 * Node to this application's preferences.
133 * @deprecated Use the static methods instead.
136 public static final Preferences NODE;
137 private static final Preferences PREFNODE;
141 Preferences root = Preferences.userRoot();
142 if (DEBUG && CLEARPREFS) {
144 if (root.nodeExists(NODENAME)) {
145 root.node(NODENAME).removeNode();
147 } catch (BackingStoreException e) {
148 throw new BugException("Unable to clear preference node", e);
151 PREFNODE = root.node(NODENAME);
158 ///////// Default component attributes
160 private static final HashMap<Class<?>, String> DEFAULT_COLORS =
161 new HashMap<Class<?>, String>();
163 DEFAULT_COLORS.put(BodyComponent.class, "0,0,240");
164 DEFAULT_COLORS.put(FinSet.class, "0,0,200");
165 DEFAULT_COLORS.put(LaunchLug.class, "0,0,180");
166 DEFAULT_COLORS.put(InternalComponent.class, "170,0,100");
167 DEFAULT_COLORS.put(MassObject.class, "0,0,0");
168 DEFAULT_COLORS.put(RecoveryDevice.class, "255,0,0");
172 private static final HashMap<Class<?>, String> DEFAULT_LINE_STYLES =
173 new HashMap<Class<?>, String>();
175 DEFAULT_LINE_STYLES.put(RocketComponent.class, LineStyle.SOLID.name());
176 DEFAULT_LINE_STYLES.put(MassObject.class, LineStyle.DASHED.name());
181 * Within a holder class so they will load only when needed.
183 private static class DefaultMaterialHolder {
184 private static final Material DEFAULT_LINE_MATERIAL =
185 Databases.findMaterial(Material.Type.LINE, "Elastic cord (round 2mm, 1/16 in)",
187 private static final Material DEFAULT_SURFACE_MATERIAL =
188 Databases.findMaterial(Material.Type.SURFACE, "Ripstop nylon", 0.067, false);
189 private static final Material DEFAULT_BULK_MATERIAL =
190 Databases.findMaterial(Material.Type.BULK, "Cardboard", 680, false);
193 //////////////////////
196 public static String getVersion() {
197 return BuildPropertyHolder.BUILD_VERSION;
201 public static String getBuildSource() {
202 return BuildPropertyHolder.BUILD_SOURCE;
206 public static String getUniqueID() {
207 String id = PREFNODE.get("id", null);
209 id = UniqueID.uuid();
210 PREFNODE.put("id", id);
217 public static void storeVersion() {
218 PREFNODE.put("OpenRocketVersion", getVersion());
223 * Returns a limited-range integer value from the preferences. If the value
224 * in the preferences is negative or greater than max, then the default value
227 * @param key The preference to retrieve.
228 * @param max Maximum allowed value for the choice.
229 * @param def Default value.
230 * @return The preference value.
232 public static int getChoise(String key, int max, int def) {
233 int v = PREFNODE.getInt(key, def);
234 if ((v < 0) || (v > max))
241 * Helper method that puts an integer choice value into the preferences.
243 * @param key the preference key.
244 * @param value the value to store.
246 public static void putChoise(String key, int value) {
247 PREFNODE.putInt(key, value);
253 public static String getString(String key, String def) {
254 return PREFNODE.get(key, def);
257 public static void putString(String key, String value) {
258 PREFNODE.put(key, value);
263 public static boolean getBoolean(String key, boolean def) {
264 return PREFNODE.getBoolean(key, def);
267 public static void putBoolean(String key, boolean value) {
268 PREFNODE.putBoolean(key, value);
274 public static boolean getCheckUpdates() {
275 return PREFNODE.getBoolean(CHECK_UPDATES, BuildPropertyHolder.DEFAULT_CHECK_UPDATES);
278 public static void setCheckUpdates(boolean check) {
279 PREFNODE.putBoolean(CHECK_UPDATES, check);
286 public static File getDefaultDirectory() {
287 String file = PREFNODE.get("defaultDirectory", null);
290 return new File(file);
293 public static void setDefaultDirectory(File dir) {
298 d = dir.getAbsolutePath();
300 PREFNODE.put("defaultDirectory", d);
306 public static Color getDefaultColor(Class<? extends RocketComponent> c) {
307 String color = get("componentColors", c, DEFAULT_COLORS);
311 String[] rgb = color.split(",");
312 if (rgb.length == 3) {
314 int red = MathUtil.clamp(Integer.parseInt(rgb[0]), 0, 255);
315 int green = MathUtil.clamp(Integer.parseInt(rgb[1]), 0, 255);
316 int blue = MathUtil.clamp(Integer.parseInt(rgb[2]), 0, 255);
317 return new Color(red, green, blue);
318 } catch (NumberFormatException ignore) {
325 public static void setDefaultColor(Class<? extends RocketComponent> c, Color color) {
328 String string = color.getRed() + "," + color.getGreen() + "," + color.getBlue();
329 set("componentColors", c, string);
332 public static Color getMotorBorderColor() {
333 // TODO: MEDIUM: Motor color (settable?)
334 return new Color(0, 0, 0, 200);
338 public static Color getMotorFillColor() {
339 // TODO: MEDIUM: Motor fill color (settable?)
340 return new Color(0, 0, 0, 100);
344 public static LineStyle getDefaultLineStyle(Class<? extends RocketComponent> c) {
345 String value = get("componentStyle", c, DEFAULT_LINE_STYLES);
347 return LineStyle.valueOf(value);
348 } catch (Exception e) {
349 return LineStyle.SOLID;
353 public static void setDefaultLineStyle(Class<? extends RocketComponent> c,
357 set("componentStyle", c, style.name());
362 * Return the DPI setting of the monitor. This is either the setting provided
363 * by the system or a user-specified DPI setting.
365 * @return the DPI setting to use.
367 public static double getDPI() {
368 int dpi = PREFNODE.getInt("DPI", 0); // Tenths of a dpi
371 dpi = Toolkit.getDefaultToolkit().getScreenResolution() * 10;
376 return ((double) dpi) / 10.0;
380 public static double getDefaultMach() {
381 // TODO: HIGH: implement custom default mach number
388 public static Material getDefaultComponentMaterial(
389 Class<? extends RocketComponent> componentClass,
390 Material.Type type) {
392 String material = get("componentMaterials", componentClass, null);
393 if (material != null) {
395 Material m = Material.fromStorableString(material, false);
396 if (m.getType() == type)
398 } catch (IllegalArgumentException ignore) {
404 return DefaultMaterialHolder.DEFAULT_LINE_MATERIAL;
406 return DefaultMaterialHolder.DEFAULT_SURFACE_MATERIAL;
408 return DefaultMaterialHolder.DEFAULT_BULK_MATERIAL;
410 throw new IllegalArgumentException("Unknown material type: " + type);
413 public static void setDefaultComponentMaterial(
414 Class<? extends RocketComponent> componentClass, Material material) {
416 set("componentMaterials", componentClass,
417 material == null ? null : material.toStorableString());
421 public static int getMaxThreadCount() {
422 return Runtime.getRuntime().availableProcessors();
427 public static Point getWindowPosition(Class<?> c) {
429 String pref = PREFNODE.node("windows").get("position." + c.getCanonicalName(), null);
434 if (pref.indexOf(',') < 0)
438 x = Integer.parseInt(pref.substring(0, pref.indexOf(',')));
439 y = Integer.parseInt(pref.substring(pref.indexOf(',') + 1));
440 } catch (NumberFormatException e) {
443 return new Point(x, y);
446 public static void setWindowPosition(Class<?> c, Point p) {
447 PREFNODE.node("windows").put("position." + c.getCanonicalName(), "" + p.x + "," + p.y);
454 public static Dimension getWindowSize(Class<?> c) {
456 String pref = PREFNODE.node("windows").get("size." + c.getCanonicalName(), null);
461 if (pref.indexOf(',') < 0)
465 x = Integer.parseInt(pref.substring(0, pref.indexOf(',')));
466 y = Integer.parseInt(pref.substring(pref.indexOf(',') + 1));
467 } catch (NumberFormatException e) {
470 return new Dimension(x, y);
473 public static void setWindowSize(Class<?> c, Dimension d) {
474 PREFNODE.node("windows").put("size." + c.getCanonicalName(), "" + d.width + "," + d.height);
479 //// Background flight data computation
481 public static boolean computeFlightInBackground() {
482 // TODO: CRITICAL: Revert
484 // return PREFNODE.getBoolean("backgroundFlight", true);
487 public static Simulation getBackgroundSimulation(Rocket rocket) {
488 Simulation s = new Simulation(rocket);
489 GUISimulationConditions cond = s.getConditions();
491 cond.setTimeStep(RK4SimulationStepper.RECOMMENDED_TIME_STEP * 2);
492 cond.setWindSpeedAverage(1.0);
493 cond.setWindSpeedDeviation(0.1);
494 cond.setLaunchRodLength(5);
500 ///////// Export variables
502 public static boolean isExportSelected(FlightDataType type) {
503 Preferences prefs = PREFNODE.node("exports");
504 return prefs.getBoolean(type.getName(), false);
507 public static void setExportSelected(FlightDataType type, boolean selected) {
508 Preferences prefs = PREFNODE.node("exports");
509 prefs.putBoolean(type.getName(), selected);
514 ///////// Default unit storage
516 public static void loadDefaultUnits() {
517 Preferences prefs = PREFNODE.node("units");
520 for (String key : prefs.keys()) {
521 UnitGroup group = UnitGroup.UNITS.get(key);
526 group.setDefaultUnit(prefs.get(key, null));
527 } catch (IllegalArgumentException ignore) {
531 } catch (BackingStoreException e) {
532 ExceptionHandler.handleErrorCondition(e);
536 public static void storeDefaultUnits() {
537 Preferences prefs = PREFNODE.node("units");
539 for (String key : UnitGroup.UNITS.keySet()) {
540 UnitGroup group = UnitGroup.UNITS.get(key);
541 if (group == null || group.getUnitCount() < 2)
544 prefs.put(key, group.getDefaultUnit().getUnit());
550 //// Material storage
554 * Add a user-defined material to the preferences. The preferences are
555 * first checked for an existing material matching the provided one using
556 * {@link Material#equals(Object)}.
558 * @param m the material to add.
560 public static void addUserMaterial(Material m) {
561 Preferences prefs = PREFNODE.node("userMaterials");
564 // Check whether material already exists
565 if (getUserMaterials().contains(m)) {
569 // Add material using next free key (key is not used when loading)
570 String mat = m.toStorableString();
571 for (int i = 0;; i++) {
572 String key = "material" + i;
573 if (prefs.get(key, null) == null) {
582 * Remove a user-defined material from the preferences. The matching is performed
583 * using {@link Material#equals(Object)}.
585 * @param m the material to remove.
587 public static void removeUserMaterial(Material m) {
588 Preferences prefs = PREFNODE.node("userMaterials");
592 // Iterate through materials and remove all keys with a matching material
593 for (String key : prefs.keys()) {
594 String value = prefs.get(key, null);
597 Material existing = Material.fromStorableString(value, true);
598 if (existing.equals(m)) {
602 } catch (IllegalArgumentException ignore) {
607 } catch (BackingStoreException e) {
608 throw new IllegalStateException("Cannot read preferences!", e);
614 * Return a set of all user-defined materials in the preferences. The materials
615 * are created marked as user-defined.
617 * @return a set of all user-defined materials.
619 public static Set<Material> getUserMaterials() {
620 Preferences prefs = PREFNODE.node("userMaterials");
622 HashSet<Material> materials = new HashSet<Material>();
625 for (String key : prefs.keys()) {
626 String value = prefs.get(key, null);
629 Material m = Material.fromStorableString(value, true);
632 } catch (IllegalArgumentException e) {
633 log.warn("Illegal material string " + value);
638 } catch (BackingStoreException e) {
639 throw new IllegalStateException("Cannot read preferences!", e);
648 private static String get(String directory,
649 Class<? extends RocketComponent> componentClass,
650 Map<Class<?>, String> defaultMap) {
652 // Search preferences
653 Class<?> c = componentClass;
654 Preferences prefs = PREFNODE.node(directory);
655 while (c != null && RocketComponent.class.isAssignableFrom(c)) {
656 String value = prefs.get(c.getSimpleName(), null);
659 c = c.getSuperclass();
662 if (defaultMap == null)
667 while (RocketComponent.class.isAssignableFrom(c)) {
668 String value = defaultMap.get(c);
671 c = c.getSuperclass();
678 private static void set(String directory, Class<? extends RocketComponent> componentClass,
680 Preferences prefs = PREFNODE.node(directory);
682 prefs.remove(componentClass.getSimpleName());
684 prefs.put(componentClass.getSimpleName(), value);