import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
-import net.sf.openrocket.util.Prefs;
+import net.sf.openrocket.util.BuildProperties;
public class BugReporter extends Communicator {
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
- connection.setRequestProperty("X-OpenRocket-Version", encode(Prefs.getVersion()));
+ connection.setRequestProperty("X-OpenRocket-Version", encode(BuildProperties.getVersion()));
String post;
- post = (VERSION_PARAM + "=" + encode(Prefs.getVersion())
+ post = (VERSION_PARAM + "=" + encode(BuildProperties.getVersion())
+ "&" + BUG_REPORT_PARAM + "=" + encode(report));
OutputStreamWriter wr = null;
import java.util.List;
import net.sf.openrocket.util.ArrayList;
+import net.sf.openrocket.util.BuildProperties;
import net.sf.openrocket.util.ComparablePair;
import net.sf.openrocket.util.Prefs;
public UpdateInfo() {
- this.latestVersion = Prefs.getVersion();
+ this.latestVersion = BuildProperties.getVersion();
this.updates = new ArrayList<ComparablePair<Integer, String>>();
}
import net.sf.openrocket.logging.LogHelper;
import net.sf.openrocket.startup.Application;
+import net.sf.openrocket.util.BuildProperties;
import net.sf.openrocket.util.ComparablePair;
import net.sf.openrocket.util.LimitedInputStream;
-import net.sf.openrocket.util.Prefs;
public class UpdateInfoRetriever {
private static final LogHelper log = Application.getLogger();
private void doConnection() throws IOException {
String url = Communicator.UPDATE_INFO_URL + "?" + Communicator.VERSION_PARAM + "="
- + Communicator.encode(Prefs.getVersion());
+ + Communicator.encode(BuildProperties.getVersion());
HttpURLConnection connection = Communicator.connectionSource.getConnection(url);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setRequestProperty("X-OpenRocket-Version",
- Communicator.encode(Prefs.getVersion() + " " + Prefs.getBuildSource()));
+ Communicator.encode(BuildProperties.getVersion() + " " + BuildProperties.getBuildSource()));
connection.setRequestProperty("X-OpenRocket-ID",
- Communicator.encode(Prefs.getUniqueID()));
+ Communicator.encode(Application.getPreferences().getUniqueID()));
connection.setRequestProperty("X-OpenRocket-OS",
Communicator.encode(System.getProperty("os.name") + " " +
System.getProperty("os.arch")));
// Check version input
if (version == null || version.length() == 0 ||
- version.equalsIgnoreCase(Prefs.getVersion())) {
+ version.equalsIgnoreCase(BuildProperties.getVersion())) {
// Invalid response
log.warn("Invalid version received, ignoring.");
return;
// Add user-defined materials
- for (Material m : Prefs.getUserMaterials()) {
+ for (Material m : ((Prefs) Application.getPreferences()).getUserMaterials()) {
switch (m.getType()) {
case LINE:
LINE_MATERIAL.add(m);
import net.sf.openrocket.simulation.SimulationOptions;
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.util.BugException;
+import net.sf.openrocket.util.BuildProperties;
import net.sf.openrocket.util.MathUtil;
-import net.sf.openrocket.util.Prefs;
import net.sf.openrocket.util.Reflection;
import net.sf.openrocket.util.TextUtil;
writeln("<?xml version='1.0' encoding='utf-8'?>");
writeln("<openrocket version=\"" + fileVersionString + "\" creator=\"OpenRocket "
- + Prefs.getVersion() + "\">");
+ + BuildProperties.getVersion() + "\">");
indent++;
// Recursively save the rocket structure
fieldSeparator = new JComboBox(new String[] { ",", ";", SPACE, TAB });
fieldSeparator.setEditable(true);
- fieldSeparator.setSelectedItem(Prefs.getString(Prefs.EXPORT_FIELD_SEPARATOR, ","));
+ fieldSeparator.setSelectedItem(Application.getPreferences().getString(Prefs.EXPORT_FIELD_SEPARATOR, ","));
fieldSeparator.setToolTipText(tip);
panel.add(fieldSeparator, "growx");
for (int i = 0; i < includeComments.length / 2; i++) {
options[i] = new JCheckBox(includeComments[i * 2]);
options[i].setToolTipText(includeComments[i * 2 + 1]);
- options[i].setSelected(Prefs.getBoolean("csvOptions." + baseClassName + "." + i, true));
+ options[i].setSelected(Application.getPreferences().getBoolean("csvOptions." + baseClassName + "." + i, true));
panel.add(options[i], "wrap");
}
commentCharacter = new JComboBox(new String[] { "#", "%", ";" });
commentCharacter.setEditable(true);
- commentCharacter.setSelectedItem(Prefs.getString(Prefs.EXPORT_COMMENT_CHARACTER, "#"));
+ commentCharacter.setSelectedItem(Application.getPreferences().getString(Prefs.EXPORT_COMMENT_CHARACTER, "#"));
commentCharacter.setToolTipText(tip);
panel.add(commentCharacter, "growx");
* Store the selected options to the user preferences.
*/
public void storePreferences() {
- Prefs.putString(Prefs.EXPORT_FIELD_SEPARATOR, getFieldSeparator());
- Prefs.putString(Prefs.EXPORT_COMMENT_CHARACTER, getCommentCharacter());
+ Application.getPreferences().putString(Prefs.EXPORT_FIELD_SEPARATOR, getFieldSeparator());
+ Application.getPreferences().putString(Prefs.EXPORT_COMMENT_CHARACTER, getCommentCharacter());
for (int i = 0; i < options.length; i++) {
- Prefs.putBoolean("csvOptions." + baseClassName + "." + i, options[i].isSelected());
+ Application.getPreferences().putBoolean("csvOptions." + baseClassName + "." + i, options[i].isSelected());
}
}
selected = new boolean[types.length];
units = new Unit[types.length];
for (int i = 0; i < types.length; i++) {
- selected[i] = Prefs.isExportSelected(types[i]);
+ selected[i] = ((Prefs) Application.getPreferences()).isExportSelected(types[i]);
units[i] = types[i].getUnitGroup().getDefaultUnit();
}
private void doExport() {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(FileHelper.CSV_FILE_FILTER);
- chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
+ chooser.setCurrentDirectory(((Prefs) Application.getPreferences()).getDefaultDirectory());
if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
return;
// Store preferences and export
int n = 0;
- Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
+ ((Prefs) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
for (int i = 0; i < selected.length; i++) {
- Prefs.setExportSelected(types[i], selected[i]);
+ ((Prefs) Application.getPreferences()).setExportSelected(types[i], selected[i]);
if (selected[i])
n++;
}
public void actionPerformed(ActionEvent e) {
Color c = component.getColor();
if (c == null) {
- c = Prefs.getDefaultColor(component.getClass());
+ c = ((Prefs) Application.getPreferences()).getDefaultColor(component.getClass());
}
//// Choose color
if (colorDefault.isSelected())
component.setColor(null);
else
- component.setColor(Prefs.getDefaultColor(component.getClass()));
+ component.setColor(((Prefs) Application.getPreferences()).getDefaultColor(component.getClass()));
}
});
panel.add(colorDefault, "wrap para");
@Override
public void actionPerformed(ActionEvent e) {
if (component.getColor() != null) {
- Prefs.setDefaultColor(component.getClass(), component.getColor());
+ ((Prefs) Application.getPreferences()).setDefaultColor(component.getClass(), component.getColor());
component.setColor(null);
}
if (component.getLineStyle() != null) {
- Prefs.setDefaultLineStyle(component.getClass(), component.getLineStyle());
+ Application.getPreferences().setDefaultLineStyle(component.getClass(), component.getLineStyle());
component.setLineStyle(null);
}
}
private Color getColor() {
Color c = component.getColor();
if (c == null) {
- c = Prefs.getDefaultColor(component.getClass());
+ c = ((Prefs) Application.getPreferences()).getDefaultColor(component.getClass());
}
return c;
}
import net.sf.openrocket.gui.util.Icons;
import net.sf.openrocket.l10n.Translator;
import net.sf.openrocket.startup.Application;
+import net.sf.openrocket.util.BuildProperties;
import net.sf.openrocket.util.Chars;
-import net.sf.openrocket.util.Prefs;
public class AboutDialog extends JDialog {
public AboutDialog(JFrame parent) {
super(parent, true);
- final String version = Prefs.getVersion();
+ final String version = BuildProperties.getVersion();
JPanel panel = new JPanel(new MigLayout("fill"));
JPanel sub;
import net.sf.openrocket.logging.LogLine;
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.util.BugException;
+import net.sf.openrocket.util.BuildProperties;
import net.sf.openrocket.util.JarUtil;
-import net.sf.openrocket.util.Prefs;
public class BugReportDialog extends JDialog {
private static void addSystemInformation(StringBuilder sb) {
- sb.append("OpenRocket version: " + Prefs.getVersion() + "\n");
- sb.append("OpenRocket source: " + Prefs.getBuildSource() + "\n");
+ sb.append("OpenRocket version: " + BuildProperties.getVersion() + "\n");
+ sb.append("OpenRocket source: " + BuildProperties.getBuildSource() + "\n");
sb.append("OpenRocket location: " + JarUtil.getCurrentJarFile() + "\n");
sb.append("Current default locale: " + Locale.getDefault() + "\n");
sb.append("System properties:\n");
try {
text = URLEncoder.encode(text, "UTF-8");
- version = URLEncoder.encode(Prefs.getVersion(), "UTF-8");
+ version = URLEncoder.encode(BuildProperties.getVersion(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new BugException(e);
}
import net.sf.openrocket.unit.UnitGroup;
import net.sf.openrocket.util.Coordinate;
import net.sf.openrocket.util.MathUtil;
-import net.sf.openrocket.util.Prefs;
public class ComponentAnalysisDialog extends JDialog implements ChangeListener {
rocketPanel.setCPAOA(0);
aoa = new DoubleModel(rocketPanel, "CPAOA", UnitGroup.UNITS_ANGLE, 0, Math.PI);
- rocketPanel.setCPMach(Prefs.getDefaultMach());
+ rocketPanel.setCPMach(Application.getPreferences().getDefaultMach());
mach = new DoubleModel(rocketPanel, "CPMach", UnitGroup.UNITS_COEFFICIENT, 0);
rocketPanel.setCPTheta(rocketPanel.getFigure().getRotation());
theta = new DoubleModel(rocketPanel, "CPTheta", UnitGroup.UNITS_ANGLE, 0, 2 * Math.PI);
*/
package net.sf.openrocket.gui.dialogs;
+import java.awt.Color;
import java.awt.Desktop;
import java.awt.Window;
import java.awt.event.ActionEvent;
private JButton saveAsPDF;
private JButton cancel;
+
+ private final static Prefs prefs = (Prefs) Application.getPreferences();
+
/**
* Constructor.
*
settingsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
- PrintSettings settings = Prefs.getPrintSettings();
+ PrintSettings settings = getPrintSettings();
log.debug("settings=" + settings);
PrintSettingsDialog settingsDialog = new PrintSettingsDialog(PrintDialog.this, settings);
settingsDialog.setVisible(true);
- Prefs.setPrintSettings(settings);
+ setPrintSettings(settings);
}
});
panel.add(settingsButton, "wrap para");
private void onPreview() {
if (desktop != null) {
try {
- PrintSettings settings = Prefs.getPrintSettings();
+ PrintSettings settings = getPrintSettings();
// TODO: HIGH: Remove UIManager, and pass settings to the actual printing methods
TemplateProperties.setColors(settings);
File f = generateReport(settings);
dir = dir.getParentFile();
}
if (dir == null) {
- dir = Prefs.getDefaultDirectory();
+ dir = ((Prefs) Application.getPreferences()).getDefaultDirectory();
}
chooser.setCurrentDirectory(dir);
try {
- PrintSettings settings = Prefs.getPrintSettings();
+ PrintSettings settings = getPrintSettings();
// TODO: HIGH: Remove UIManager, and pass settings to the actual printing methods
TemplateProperties.setColors(settings);
generateReport(file, settings);
}
}
+ public PrintSettings getPrintSettings() {
+ PrintSettings settings = new PrintSettings();
+ Color c;
+
+ c = prefs.getColor("print.template.fillColor", (java.awt.Color) null);
+ if (c != null) {
+ settings.setTemplateFillColor(c);
+ }
+
+ c = prefs.getColor("print.template.borderColor", (java.awt.Color) null);
+ if (c != null) {
+ settings.setTemplateBorderColor(c);
+ }
+
+ settings.setPaperSize(prefs.getEnum("print.paper.size", settings.getPaperSize()));
+ settings.setPaperOrientation(prefs.getEnum("print.paper.orientation", settings.getPaperOrientation()));
+
+ return settings;
+ }
+
+ public void setPrintSettings(PrintSettings settings) {
+ prefs.putColor("print.template.fillColor", settings.getTemplateFillColor() );
+ prefs.putColor("print.template.borderColor", settings.getTemplateBorderColor() );
+ prefs.putEnum("print.paper.size", settings.getPaperSize());
+ prefs.putEnum("print.paper.orientation", settings.getPaperOrientation());
+ }
+
}
default:
throw new BugException("Invalid selection mode sel=" + sel);
}
- Prefs.putChoise("MotorDiameterMatch", sel);
+ Application.getPreferences().putChoice("MotorDiameterMatch", sel);
scrollSelectionVisible();
}
});
//// Hide very similar thrust curves
hideSimilarBox = new JCheckBox(trans.get("TCMotorSelPan.checkbox.hideSimilar"));
GUIUtil.changeFontSize(hideSimilarBox, -1);
- hideSimilarBox.setSelected(Prefs.getBoolean(Prefs.MOTOR_HIDE_SIMILAR, true));
+ hideSimilarBox.setSelected(Application.getPreferences().getBoolean(Prefs.MOTOR_HIDE_SIMILAR, true));
hideSimilarBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
- Prefs.putBoolean(Prefs.MOTOR_HIDE_SIMILAR, hideSimilarBox.isSelected());
+ Application.getPreferences().putBoolean(Prefs.MOTOR_HIDE_SIMILAR, hideSimilarBox.isSelected());
updateData();
}
});
// Sets the filter:
- int showMode = Prefs.getChoise(Prefs.MOTOR_DIAMETER_FILTER, SHOW_MAX, SHOW_EXACT);
+ int showMode = Application.getPreferences().getChoice(Prefs.MOTOR_DIAMETER_FILTER, SHOW_MAX, SHOW_EXACT);
filterComboBox.setSelectedIndex(showMode);
}
// Store selected motor in preferences node, set all others to false
- Preferences prefs = Prefs.getNode(Prefs.PREFERRED_THRUST_CURVE_MOTOR_NODE);
+ Preferences prefs = ((Prefs) Application.getPreferences()).getNode(Prefs.PREFERRED_THRUST_CURVE_MOTOR_NODE);
for (ThrustCurveMotor m : set.getMotors()) {
String digest = MotorDigest.digestMotor(m);
prefs.putBoolean(digest, m == motor);
// Find which motor has been used the most recently
List<ThrustCurveMotor> list = set.getMotors();
- Preferences prefs = Prefs.getNode(Prefs.PREFERRED_THRUST_CURVE_MOTOR_NODE);
+ Preferences prefs = ((Prefs) Application.getPreferences()).getNode(Prefs.PREFERRED_THRUST_CURVE_MOTOR_NODE);
for (ThrustCurveMotor m : list) {
String digest = MotorDigest.digestMotor(m);
if (prefs.getBoolean(digest, false)) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(FileHelper.CSV_FILE_FILTER);
- chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
+ chooser.setCurrentDirectory(((Prefs) Application.getPreferences()).getDefaultDirectory());
chooser.setAccessory(csvOptions);
if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
import net.sf.openrocket.gui.dialogs.UpdateInfoDialog;
import net.sf.openrocket.gui.util.GUIUtil;
import net.sf.openrocket.gui.util.SimpleFileFilter;
+import net.sf.openrocket.l10n.L10N;
import net.sf.openrocket.l10n.Translator;
import net.sf.openrocket.logging.LogHelper;
import net.sf.openrocket.startup.Application;
+import net.sf.openrocket.startup.Preferences;
import net.sf.openrocket.unit.Unit;
import net.sf.openrocket.unit.UnitGroup;
+import net.sf.openrocket.util.BuildProperties;
import net.sf.openrocket.util.Named;
import net.sf.openrocket.util.Prefs;
import net.sf.openrocket.util.Utils;
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
- Prefs.storeDefaultUnits();
+ ((Prefs) Application.getPreferences()).storeDefaultUnits();
}
});
//// Language selector
- Locale userLocale = Prefs.getUserLocale();
+ Locale userLocale = null;
+ {
+ String locale = Application.getPreferences().getString("locale", null);
+ userLocale = L10N.toLocale(locale);
+ }
List<Named<Locale>> locales = new ArrayList<Named<Locale>>();
for (Locale l : Prefs.getSupportedLocales()) {
locales.add(new Named<Locale>(l, l.getDisplayLanguage()));
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
Named<Locale> selection = (Named<Locale>) languageCombo.getSelectedItem();
- Prefs.setUserLocale(selection.get());
+ Locale l = selection.get();
+ Application.getPreferences().putString(Preferences.USER_LOCAL, l == null ? null : l.toString());
}
});
panel.add(new JLabel(trans.get("lbl.language")), "gapright para");
//// User-defined thrust curves:
panel.add(new JLabel(trans.get("pref.dlg.lbl.User-definedthrust")), "spanx, wrap");
final JTextField field = new JTextField();
- List<File> files = Prefs.getUserThrustCurveFiles();
+ List<File> files = ((Prefs) Application.getPreferences()).getUserThrustCurveFiles();
String str = "";
for (File file : files) {
if (str.length() > 0) {
list.add(new File(s));
}
}
- Prefs.setUserThrustCurveFiles(list);
+ ((Prefs) Application.getPreferences()).setUserThrustCurveFiles(list);
}
});
panel.add(field, "w 100px, gapright unrel, spanx, growx, split");
@Override
public void actionPerformed(ActionEvent e) {
// First one sets to the default, but does not un-set the pref
- field.setText(Prefs.getDefaultUserThrustCurveFile().getAbsolutePath());
- Prefs.setUserThrustCurveFiles(null);
+ field.setText(((Prefs)Application.getPreferences()).getDefaultUserThrustCurveFile().getAbsolutePath());
+ ((Prefs) Application.getPreferences()).setUserThrustCurveFiles(null);
}
});
panel.add(button, "wrap");
//// Check for software updates at startup
final JCheckBox softwareUpdateBox =
new JCheckBox(trans.get("pref.dlg.checkbox.Checkupdates"));
- softwareUpdateBox.setSelected(Prefs.getCheckUpdates());
+ softwareUpdateBox.setSelected( Application.getPreferences().getCheckUpdates());
softwareUpdateBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
- Prefs.setCheckUpdates(softwareUpdateBox.isSelected());
+ Application.getPreferences().setCheckUpdates(softwareUpdateBox.isSelected());
}
});
panel.add(softwareUpdateBox);
@Override
public Object getSelectedItem() {
- return descriptions[Prefs.getChoise(preference, descriptions.length, 0)];
+ return descriptions[Application.getPreferences().getChoice(preference, descriptions.length, 0)];
}
@Override
throw new IllegalArgumentException("Illegal argument " + item);
}
- Prefs.putChoise(preference, index);
+ Application.getPreferences().putChoice(preference, index);
}
@Override
@Override
public Object getSelectedItem() {
- if (Prefs.getBoolean(preference, def)) {
+ if (Application.getPreferences().getBoolean(preference, def)) {
return trueDesc;
} else {
return falseDesc;
}
if (trueDesc.equals(item)) {
- Prefs.putBoolean(preference, true);
+ Application.getPreferences().putBoolean(preference, true);
} else if (falseDesc.equals(item)) {
- Prefs.putBoolean(preference, false);
+ Application.getPreferences().putBoolean(preference, false);
} else {
throw new IllegalArgumentException("Illegal argument " + item);
}
trans.get("pref.dlg.lbl.msg2"), JOptionPane.WARNING_MESSAGE, null);
} else if (info.getLatestVersion() == null ||
info.getLatestVersion().equals("") ||
- Prefs.getVersion().equalsIgnoreCase(info.getLatestVersion())) {
+ BuildProperties.getVersion().equalsIgnoreCase(info.getLatestVersion())) {
JOptionPane.showMessageDialog(this,
//// You are running the latest version of OpenRocket.
trans.get("pref.dlg.lbl.msg3"),
UpdateInfoDialog infoDialog = new UpdateInfoDialog(info);
infoDialog.setVisible(true);
if (infoDialog.isReminderSelected()) {
- Prefs.putString(Prefs.LAST_UPDATE, "");
+ Application.getPreferences().putString(Prefs.LAST_UPDATE, "");
} else {
- Prefs.putString(Prefs.LAST_UPDATE, info.getLatestVersion());
+ Application.getPreferences().putString(Prefs.LAST_UPDATE, info.getLatestVersion());
}
}
package net.sf.openrocket.gui.figureelements;
+import static net.sf.openrocket.util.Chars.ALPHA;
+import static net.sf.openrocket.util.Chars.THETA;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics2D;
+import java.awt.Rectangle;
+import java.awt.font.GlyphVector;
+import java.awt.geom.Rectangle2D;
+
import net.sf.openrocket.aerodynamics.Warning;
import net.sf.openrocket.aerodynamics.WarningSet;
import net.sf.openrocket.l10n.Translator;
import net.sf.openrocket.unit.Unit;
import net.sf.openrocket.unit.UnitGroup;
import net.sf.openrocket.util.MathUtil;
-import net.sf.openrocket.util.Prefs;
-
-import java.awt.Color;
-import java.awt.Font;
-import java.awt.Graphics2D;
-import java.awt.Rectangle;
-import java.awt.font.GlyphVector;
-import java.awt.geom.Rectangle2D;
-
-import static net.sf.openrocket.util.Chars.ALPHA;
-import static net.sf.openrocket.util.Chars.THETA;
/**
private double cg = 0, cp = 0;
private double length = 0, diameter = 0;
private double mass = 0;
- private double aoa = Double.NaN, theta = Double.NaN, mach = Prefs.getDefaultMach();
+ private double aoa = Double.NaN, theta = Double.NaN, mach = Application.getPreferences().getDefaultMach();
private WarningSet warnings = null;
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(true);
- chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
+ chooser.setCurrentDirectory(((Prefs) Application.getPreferences()).getDefaultDirectory());
int option = chooser.showOpenDialog(this);
if (option != JFileChooser.APPROVE_OPTION) {
log.user("Decided not to open files, option=" + option);
return;
}
- Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
+ ((Prefs) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
File[] files = chooser.getSelectedFiles();
log.user("Opening files " + Arrays.toString(files));
new StorageOptionChooser(document, document.getDefaultStorageOptions());
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(FileHelper.OPENROCKET_DESIGN_FILTER);
- chooser.setCurrentDirectory(Prefs.getDefaultDirectory());
+ chooser.setCurrentDirectory(((Prefs) Application.getPreferences()).getDefaultDirectory());
chooser.setAccessory(storageChooser);
if (document.getFile() != null)
chooser.setSelectedFile(document.getFile());
return false;
}
- Prefs.setDefaultDirectory(chooser.getCurrentDirectory());
+ ((Prefs) Application.getPreferences()).setDefaultDirectory(chooser.getCurrentDirectory());
storageChooser.storeOptions(document.getDefaultStorageOptions());
file = FileHelper.ensureExtension(file, "ork");
// Check whether to insert between or at the end.
// 0 = ask, 1 = in between, 2 = at the end
- int pos = Prefs.getChoise(Prefs.BODY_COMPONENT_INSERT_POSITION_KEY, 2, 0);
+ int pos = Application.getPreferences().getChoice(Prefs.BODY_COMPONENT_INSERT_POSITION_KEY, 2, 0);
if (pos == 0) {
if (parent.getChildPosition(c) == parent.getChildCount() - 1)
pos = 2; // Selected component is the last component
if (check.isSelected()) {
// Save the preference
- Prefs.putInt(Prefs.BODY_COMPONENT_INSERT_POSITION_KEY, sel);
+ Application.getPreferences().putInt(Prefs.BODY_COMPONENT_INSERT_POSITION_KEY, sel);
}
return sel;
}
private boolean verifyDeleteSimulation() {
- boolean verify = Prefs.getBoolean(Prefs.CONFIRM_DELETE_SIMULATION, true);
+ boolean verify = Application.getPreferences().getBoolean(Prefs.CONFIRM_DELETE_SIMULATION, true);
if (verify) {
JPanel panel = new JPanel(new MigLayout());
//// Do not ask me again
return false;
if (dontAsk.isSelected()) {
- Prefs.putBoolean(Prefs.CONFIRM_DELETE_SIMULATION, false);
+ Application.getPreferences().putBoolean(Prefs.CONFIRM_DELETE_SIMULATION, false);
}
}
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
- String previous = Prefs.getString("previousListenerName", "");
+ String previous = Application.getPreferences().getString("previousListenerName", "");
String input = (String) JOptionPane.showInputDialog(SimulationEditDialog.this,
new Object[] {
//// Type the full Java class name of the simulation listener, for example:
if (input == null || input.equals(""))
return;
- Prefs.putString("previousListenerName", input);
+ Application.getPreferences().putString("previousListenerName", input);
simulation.getSimulationListeners().add(input);
listenerModel.fireContentsChanged();
}
return; // TODO: LOW: "None selected" dialog
// Verify deletion
- boolean verify = Prefs.getBoolean(Prefs.CONFIRM_DELETE_SIMULATION, true);
+ boolean verify = Application.getPreferences().getBoolean(Prefs.CONFIRM_DELETE_SIMULATION, true);
if (verify) {
JPanel panel = new JPanel(new MigLayout());
return;
if (dontAsk.isSelected()) {
- Prefs.putBoolean(Prefs.CONFIRM_DELETE_SIMULATION, false);
+ Application.getPreferences().putBoolean(Prefs.CONFIRM_DELETE_SIMULATION, false);
}
}
import java.awt.font.GlyphVector;
import java.awt.geom.Rectangle2D;
-import net.sf.openrocket.util.Prefs;
+import net.sf.openrocket.util.BuildProperties;
/**
* Helper methods for manipulating the Java runtime splash screen.
private static void drawVersionNumber(Graphics2D g2) {
- String text = "Version " + Prefs.getVersion();
+ String text = "Version " + BuildProperties.getVersion();
GlyphVector gv = VERSION_FONT.createGlyphVector(g2.getFontRenderContext(), text);
Rectangle2D rect = gv.getVisualBounds();
super(parent, trans.get("PlotDialog.title.Flightdataplot"));
this.setModalityType(ModalityType.DOCUMENT_MODAL);
- final boolean initialShowPoints = Prefs.getBoolean(Prefs.PLOT_SHOW_POINTS, false);
+ final boolean initialShowPoints = Application.getPreferences().getBoolean(Prefs.PLOT_SHOW_POINTS, false);
// Fill the auto-selections
@Override
public void actionPerformed(ActionEvent e) {
boolean show = check.isSelected();
- Prefs.putBoolean(Prefs.PLOT_SHOW_POINTS, show);
+ Application.getPreferences().putBoolean(Prefs.PLOT_SHOW_POINTS, show);
for (ModifiedXYItemRenderer r : renderers) {
r.setBaseShapesVisible(show);
}
Rocket duplicate = theRocket.copyWithOriginalID();
FlightData flight = null;
try {
- Simulation simulation = Prefs.getBackgroundSimulation(duplicate);
+ Simulation simulation = ((Prefs)Application.getPreferences()).getBackgroundSimulation(duplicate);
simulation.getOptions().setMotorConfigurationID(motorId);
simulation.simulate();
flight = simulation.getSimulatedData();
import net.sf.openrocket.rocketcomponent.Configuration;
import net.sf.openrocket.rocketcomponent.MotorMount;
import net.sf.openrocket.rocketcomponent.RocketComponent;
+import net.sf.openrocket.startup.Application;
import net.sf.openrocket.util.BugException;
import net.sf.openrocket.util.Coordinate;
import net.sf.openrocket.util.LineStyle;
// Set component color and line style
Color color = c.getColor();
if (color == null) {
- color = Prefs.getDefaultColor(c.getClass());
+ color = ((Prefs) Application.getPreferences()).getDefaultColor(c.getClass());
}
g2.setColor(color);
LineStyle style = c.getLineStyle();
if (style == null)
- style = Prefs.getDefaultLineStyle(c.getClass());
+ style = Application.getPreferences().getDefaultLineStyle(c.getClass());
float[] dashes = style.getDashes();
for (int j = 0; j < dashes.length; j++) {
// Draw motors
String motorID = configuration.getMotorConfigurationID();
- Color fillColor = Prefs.getMotorFillColor();
- Color borderColor = Prefs.getMotorBorderColor();
+ Color fillColor = ((Prefs)Application.getPreferences()).getMotorFillColor();
+ Color borderColor = ((Prefs)Application.getPreferences()).getMotorBorderColor();
Iterator<MotorMount> iterator = configuration.motorIterator();
while (iterator.hasNext()) {
MotorMount mount = iterator.next();
conditions.setMach(cpMach);
extraText.setMach(cpMach);
} else {
- conditions.setMach(Prefs.getDefaultMach());
- extraText.setMach(Prefs.getDefaultMach());
+ conditions.setMach(Application.getPreferences().getDefaultMach());
+ extraText.setMach(Application.getPreferences().getDefaultMach());
}
if (!Double.isNaN(cpAOA)) {
//////// Flight simulation in background
// Check whether to compute or not
- if (!Prefs.computeFlightInBackground()) {
+ if (!((Prefs) Application.getPreferences()).computeFlightInBackground()) {
extraText.setFlightData(null);
extraText.setCalculatingData(false);
stopBackgroundSimulation();
extraText.setCalculatingData(true);
Rocket duplicate = (Rocket) configuration.getRocket().copy();
- Simulation simulation = Prefs.getBackgroundSimulation(duplicate);
+ Simulation simulation = ((Prefs)Application.getPreferences()).getBackgroundSimulation(duplicate);
simulation.getOptions().setMotorConfigurationID(
configuration.getMotorConfigurationID());
--- /dev/null
+package net.sf.openrocket.gui.util;\r
+\r
+public class ColorConversion {\r
+\r
+ public static java.awt.Color toAwtColor( net.sf.openrocket.util.Color c ) {\r
+ if ( c == null ) {\r
+ return null;\r
+ }\r
+ return new java.awt.Color(c.getRed(),c.getGreen(),c.getBlue(),c.getAlpha());\r
+ }\r
+ \r
+ public static net.sf.openrocket.util.Color fromAwtColor( java.awt.Color c ) {\r
+ if ( c == null ) {\r
+ return null;\r
+ }\r
+ return new net.sf.openrocket.util.Color( c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());\r
+ }\r
+}\r
* @return the DPI setting to use.
*/
public static double getDPI() {
- int dpi = Prefs.getInt("DPI", 0); // Tenths of a dpi
+ int dpi = Application.getPreferences().getInt("DPI", 0); // Tenths of a dpi
if (dpi < 10) {
dpi = Toolkit.getDefaultToolkit().getScreenResolution() * 10;
@Override
public void componentResized(ComponentEvent e) {
log.debug("Storing size of " + window.getClass().getName() + ": " + window.getSize());
- Prefs.setWindowSize(window.getClass(), window.getSize());
+ ((Prefs) Application.getPreferences()).setWindowSize(window.getClass(), window.getSize());
if (window instanceof JFrame) {
if ((((JFrame) window).getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH) {
log.debug("Storing maximized state of " + window.getClass().getName());
- Prefs.setWindowMaximized(window.getClass());
+ ((Prefs) Application.getPreferences()).setWindowMaximized(window.getClass());
}
}
}
});
- if (Prefs.isWindowMaximized(window.getClass())) {
+ if (((Prefs) Application.getPreferences()).isWindowMaximized(window.getClass())) {
if (window instanceof JFrame) {
((JFrame) window).setExtendedState(JFrame.MAXIMIZED_BOTH);
}
} else {
- Dimension dim = Prefs.getWindowSize(window.getClass());
+ Dimension dim = ((Prefs) Application.getPreferences()).getWindowSize(window.getClass());
if (dim != null) {
window.setSize(dim);
}
window.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
- Prefs.setWindowPosition(window.getClass(), window.getLocation());
+ ((Prefs) Application.getPreferences()).setWindowPosition(window.getClass(), window.getLocation());
}
});
// Set window position according to preferences, and set prefs when moving
- Point position = Prefs.getWindowPosition(window.getClass());
+ Point position = ((Prefs) Application.getPreferences()).getWindowPosition(window.getClass());
if (position != null) {
window.setLocationByPlatform(false);
window.setLocation(position);
import net.sf.openrocket.database.Database;
import net.sf.openrocket.database.DatabaseListener;
+import net.sf.openrocket.startup.Application;
import net.sf.openrocket.util.Prefs;
/**
@Override
public void elementAdded(Material material, Database<Material> source) {
if (material.isUserDefined()) {
- Prefs.addUserMaterial(material);
+ ((Prefs) Application.getPreferences()).addUserMaterial(material);
}
}
@Override
public void elementRemoved(Material material, Database<Material> source) {
- Prefs.removeUserMaterial(material);
+ ((Prefs) Application.getPreferences()).removeUserMaterial(material);
}
}
* another rocket instance (e.g. the same modification on another rocket component that
* has the same component ID).
*/
- @Override
public boolean equals(Object obj);
}
import net.sf.openrocket.rocketcomponent.Configuration;
import net.sf.openrocket.rocketcomponent.RocketComponent;
import net.sf.openrocket.rocketcomponent.SymmetricComponent;
+import net.sf.openrocket.startup.Application;
import net.sf.openrocket.unit.UnitGroup;
import net.sf.openrocket.unit.Value;
import net.sf.openrocket.util.Coordinate;
import net.sf.openrocket.util.MathUtil;
import net.sf.openrocket.util.Pair;
-import net.sf.openrocket.util.Prefs;
/**
* A simulation domain that limits the required stability of the rocket.
Configuration configuration = simulation.getConfiguration();
FlightConditions conditions = new FlightConditions(configuration);
- conditions.setMach(Prefs.getDefaultMach());
+ conditions.setMach(Application.getPreferences().getDefaultMach());
conditions.setAOA(0);
conditions.setRollRate(0);
import net.sf.openrocket.unit.UnitGroup;
import net.sf.openrocket.util.Coordinate;
import net.sf.openrocket.util.MathUtil;
-import net.sf.openrocket.util.Prefs;
/**
* An optimization parameter that computes either the absolute or relative stability of a rocket.
Configuration configuration = simulation.getConfiguration();
FlightConditions conditions = new FlightConditions(configuration);
- conditions.setMach(Prefs.getDefaultMach());
+ conditions.setMach(Application.getPreferences().getDefaultMach());
conditions.setAOA(0);
conditions.setRollRate(0);
import net.sf.openrocket.material.Material.Type;
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.unit.UnitGroup;
-import net.sf.openrocket.util.Prefs;
/**
* Class of components with well-defined physical appearance and which have an effect on
*/
public ExternalComponent(RocketComponent.Position relativePosition) {
super(relativePosition);
- this.material = Prefs.getDefaultComponentMaterial(this.getClass(), Material.Type.BULK);
+ this.material = Application.getPreferences().getDefaultComponentMaterial(this.getClass(), Material.Type.BULK);
}
/**
import net.sf.openrocket.material.Material;
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.util.MathUtil;
-import net.sf.openrocket.util.Prefs;
public class Parachute extends RecoveryDevice {
private static final Translator trans = Application.getTranslator();
public Parachute() {
this.diameter = 0.3;
- this.lineMaterial = Prefs.getDefaultComponentMaterial(Parachute.class, Material.Type.LINE);
+ this.lineMaterial = Application.getPreferences().getDefaultComponentMaterial(Parachute.class, Material.Type.LINE);
this.lineLength = 0.3;
}
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.util.MathUtil;
import net.sf.openrocket.util.Pair;
-import net.sf.openrocket.util.Prefs;
/**
public RecoveryDevice() {
- this(Prefs.getDefaultComponentMaterial(RecoveryDevice.class, Material.Type.SURFACE));
+ this(Application.getPreferences().getDefaultComponentMaterial(RecoveryDevice.class, Material.Type.SURFACE));
}
public RecoveryDevice(Material material) {
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.util.BugException;
import net.sf.openrocket.util.MathUtil;
-import net.sf.openrocket.util.Prefs;
public class ShockCord extends MassObject {
private static final Translator trans = Application.getTranslator();
private double cordLength;
public ShockCord() {
- material = Prefs.getDefaultComponentMaterial(ShockCord.class, Material.Type.LINE);
+ material = Application.getPreferences().getDefaultComponentMaterial(ShockCord.class, Material.Type.LINE);
cordLength = 0.4;
}
package net.sf.openrocket.rocketcomponent;
import net.sf.openrocket.material.Material;
-import net.sf.openrocket.util.Prefs;
+import net.sf.openrocket.startup.Application;
public abstract class StructuralComponent extends InternalComponent {
public StructuralComponent() {
super();
- material = Prefs.getDefaultComponentMaterial(this.getClass(), Material.Type.BULK);
+ material = Application.getPreferences().getDefaultComponentMaterial(this.getClass(), Material.Type.BULK);
}
private static Translator baseTranslator = new DebugTranslator(null);
private static ThrustCurveMotorSetDatabase motorSetDatabase;
-
+
+ private static Preferences preferences;
// Initialize the logger to something sane for testing without executing Startup
static {
Application.baseTranslator = translator;
}
-
+
+ /**
+ * @return the preferences
+ */
+ public static Preferences getPreferences() {
+ return preferences;
+ }
+
+ /**
+ * @param preferences the preferences to set
+ */
+ public static void setPreferences(Preferences preferences) {
+ Application.preferences = preferences;
+ }
/**
* Return the database of all thrust curves loaded into the system.
--- /dev/null
+package net.sf.openrocket.startup;\r
+\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+\r
+import net.sf.openrocket.database.Databases;\r
+import net.sf.openrocket.l10n.Translator;\r
+import net.sf.openrocket.material.Material;\r
+import net.sf.openrocket.rocketcomponent.MassObject;\r
+import net.sf.openrocket.rocketcomponent.RocketComponent;\r
+import net.sf.openrocket.util.BugException;\r
+import net.sf.openrocket.util.BuildProperties;\r
+import net.sf.openrocket.util.Color;\r
+import net.sf.openrocket.util.LineStyle;\r
+import net.sf.openrocket.util.MathUtil;\r
+import net.sf.openrocket.util.UniqueID;\r
+\r
+public abstract class Preferences {\r
+\r
+ /*\r
+ * Well known string keys to preferences.\r
+ * There are other strings out there in the source as well.\r
+ */\r
+ public static final String BODY_COMPONENT_INSERT_POSITION_KEY = "BodyComponentInsertPosition";\r
+ public static final String USER_THRUST_CURVES_KEY = "UserThrustCurves";\r
+ public static final String CONFIRM_DELETE_SIMULATION = "ConfirmDeleteSimulation";\r
+ // Preferences related to data export\r
+ public static final String EXPORT_FIELD_SEPARATOR = "ExportFieldSeparator";\r
+ public static final String EXPORT_SIMULATION_COMMENT = "ExportSimulationComment";\r
+ public static final String EXPORT_FIELD_NAME_COMMENT = "ExportFieldDescriptionComment";\r
+ public static final String EXPORT_EVENT_COMMENTS = "ExportEventComments";\r
+ public static final String EXPORT_COMMENT_CHARACTER = "ExportCommentCharacter";\r
+ public static final String USER_LOCAL = "locale";\r
+ \r
+ public static final String PLOT_SHOW_POINTS = "ShowPlotPoints";\r
+ \r
+ private static final String CHECK_UPDATES = "CheckUpdates";\r
+ public static final String LAST_UPDATE = "LastUpdateVersion";\r
+ \r
+ public static final String MOTOR_DIAMETER_FILTER = "MotorDiameterMatch";\r
+ public static final String MOTOR_HIDE_SIMILAR = "MotorHideSimilar";\r
+\r
+ // Node names\r
+ public static final String PREFERRED_THRUST_CURVE_MOTOR_NODE = "preferredThrustCurveMotors";\r
+\r
+ /*\r
+ * ******************************************************************************************\r
+ * \r
+ * Abstract methods which must be implemented by any derived class.\r
+ */\r
+ public abstract boolean getBoolean( String key, boolean defaultValue );\r
+ public abstract void putBoolean( String key, boolean value );\r
+\r
+ public abstract int getInt( String key, int defaultValue);\r
+ public abstract void putInt( String key, int value );\r
+\r
+ public abstract double getDouble( String key, double defaultValue );\r
+ public abstract void putDouble( String key, double value );\r
+\r
+ public abstract String getString( String key, String defaultValue );\r
+ public abstract void putString( String key, String value );\r
+ \r
+ /**\r
+ * Directory represents a way to collect multiple keys together. Implementors may\r
+ * choose to concatenate the directory with the key using some special character.\r
+ * @param directory\r
+ * @param key\r
+ * @param defaultValue\r
+ * @return\r
+ */\r
+ public abstract String getString( String directory, String key, String defaultValue);\r
+\r
+ public abstract void putString( String directory, String key, String value );\r
+\r
+ /*\r
+ * ******************************************************************************************\r
+ */\r
+ public final boolean getCheckUpdates() {\r
+ return this.getBoolean(CHECK_UPDATES, BuildProperties.getDefaultCheckUpdates());\r
+ }\r
+ \r
+ public final void setCheckUpdates(boolean check) {\r
+ this.putBoolean(CHECK_UPDATES, check);\r
+ }\r
+ \r
+ public final double getDefaultMach() {\r
+ // TODO: HIGH: implement custom default mach number\r
+ return 0.3;\r
+ }\r
+ \r
+ /**\r
+ * Return the OpenRocket unique ID.\r
+ * \r
+ * @return a random ID string that stays constant between OpenRocket executions\r
+ */\r
+ public final String getUniqueID() {\r
+ String id = this.getString("id", null);\r
+ if (id == null) {\r
+ id = UniqueID.uuid();\r
+ this.putString("id", id);\r
+ }\r
+ return id;\r
+ }\r
+ \r
+ /**\r
+ * Returns a limited-range integer value from the preferences. If the value \r
+ * in the preferences is negative or greater than max, then the default value \r
+ * is returned.\r
+ * \r
+ * @param key The preference to retrieve.\r
+ * @param max Maximum allowed value for the choice.\r
+ * @param def Default value.\r
+ * @return The preference value.\r
+ */\r
+ public final int getChoice(String key, int max, int def) {\r
+ int v = this.getInt(key, def);\r
+ if ((v < 0) || (v > max))\r
+ return def;\r
+ return v;\r
+ }\r
+ \r
+ /**\r
+ * Helper method that puts an integer choice value into the preferences.\r
+ * \r
+ * @param key the preference key.\r
+ * @param value the value to store.\r
+ */\r
+ public final void putChoice(String key, int value) {\r
+ this.putInt(key, value);\r
+ }\r
+ \r
+ /**\r
+ * Retrieve an enum value from the user preferences.\r
+ * \r
+ * @param <T> the enum type\r
+ * @param key the key\r
+ * @param def the default value, cannot be null\r
+ * @return the value in the preferences, or the default value\r
+ */\r
+ public final <T extends Enum<T>> T getEnum(String key, T def) {\r
+ if (def == null) {\r
+ throw new BugException("Default value cannot be null");\r
+ }\r
+ \r
+ String value = getString(key, null);\r
+ if (value == null) {\r
+ return def;\r
+ }\r
+ \r
+ try {\r
+ return Enum.valueOf(def.getDeclaringClass(), value);\r
+ } catch (IllegalArgumentException e) {\r
+ return def;\r
+ }\r
+ }\r
+ \r
+ /**\r
+ * Store an enum value to the user preferences.\r
+ * \r
+ * @param key the key\r
+ * @param value the value to store, or null to remove the value\r
+ */\r
+ public final void putEnum(String key, Enum<?> value) {\r
+ if (value == null) {\r
+ putString(key, null);\r
+ } else {\r
+ putString(key, value.name());\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Retrieve a Line style for the given component.\r
+ * @param c\r
+ * @return\r
+ */\r
+ public final LineStyle getDefaultLineStyle(Class<? extends RocketComponent> c) {\r
+ String value = get("componentStyle", c, DEFAULT_LINE_STYLES);\r
+ try {\r
+ return LineStyle.valueOf(value);\r
+ } catch (Exception e) {\r
+ return LineStyle.SOLID;\r
+ }\r
+ }\r
+ \r
+ /**\r
+ * Set a default line style for the given component.\r
+ * @param c\r
+ * @param style\r
+ */\r
+ public final void setDefaultLineStyle(Class<? extends RocketComponent> c,\r
+ LineStyle style) {\r
+ if (style == null)\r
+ return;\r
+ putString("componentStyle", c.getSimpleName(), style.name());\r
+ }\r
+ \r
+ /**\r
+ * Get the default material type for the given component.\r
+ * @param componentClass\r
+ * @param type the Material.Type to return.\r
+ * @return\r
+ */\r
+ public Material getDefaultComponentMaterial(\r
+ Class<? extends RocketComponent> componentClass,\r
+ Material.Type type) {\r
+ \r
+ String material = get("componentMaterials", componentClass, null);\r
+ if (material != null) {\r
+ try {\r
+ Material m = Material.fromStorableString(material, false);\r
+ if (m.getType() == type)\r
+ return m;\r
+ } catch (IllegalArgumentException ignore) {\r
+ }\r
+ }\r
+ \r
+ switch (type) {\r
+ case LINE:\r
+ return DefaultMaterialHolder.DEFAULT_LINE_MATERIAL;\r
+ case SURFACE:\r
+ return DefaultMaterialHolder.DEFAULT_SURFACE_MATERIAL;\r
+ case BULK:\r
+ return DefaultMaterialHolder.DEFAULT_BULK_MATERIAL;\r
+ }\r
+ throw new IllegalArgumentException("Unknown material type: " + type);\r
+ }\r
+ \r
+ /**\r
+ * Set the default material for a component type.\r
+ * @param componentClass\r
+ * @param material\r
+ */\r
+ public void setDefaultComponentMaterial(\r
+ Class<? extends RocketComponent> componentClass, Material material) {\r
+ \r
+ putString("componentMaterials", componentClass.getSimpleName(),\r
+ material == null ? null : material.toStorableString());\r
+ }\r
+\r
+ /**\r
+ * get a net.sf.openrocket.util.Color object for the given key.\r
+ * @param key\r
+ * @param defaultValue\r
+ * @return\r
+ */\r
+ public final Color getColor( String key, Color defaultValue ) {\r
+ Color c = parseColor( getString(key,null) );\r
+ if ( c == null ) {\r
+ return defaultValue;\r
+ }\r
+ return c;\r
+ }\r
+ \r
+ /**\r
+ * set a net.sf.openrocket.util.Color preference value for the given key.\r
+ * @param key\r
+ * @param value\r
+ */\r
+ public final void putColor( String key, Color value ) {\r
+ putString( key, stringifyColor(value) );\r
+ }\r
+\r
+ /**\r
+ * Helper function to convert a string representation into a net.sf.openrocket.util.Color object.\r
+ * @param color\r
+ * @return\r
+ */\r
+ protected static Color parseColor(String color) {\r
+ if (color == null) {\r
+ return null;\r
+ }\r
+ \r
+ String[] rgb = color.split(",");\r
+ if (rgb.length == 3) {\r
+ try {\r
+ int red = MathUtil.clamp(Integer.parseInt(rgb[0]), 0, 255);\r
+ int green = MathUtil.clamp(Integer.parseInt(rgb[1]), 0, 255);\r
+ int blue = MathUtil.clamp(Integer.parseInt(rgb[2]), 0, 255);\r
+ return new Color(red, green, blue);\r
+ } catch (NumberFormatException ignore) {\r
+ }\r
+ }\r
+ return null;\r
+ }\r
+ \r
+ /**\r
+ * Helper function to convert a net.sf.openrocket.util.Color object into a\r
+ * String before storing in a preference.\r
+ * @param color\r
+ * @return\r
+ */\r
+ protected static String stringifyColor(Color color) {\r
+ String string = color.getRed() + "," + color.getGreen() + "," + color.getBlue();\r
+ return string;\r
+ }\r
+\r
+ /**\r
+ * Special helper function which allows for a map of default values.\r
+ * \r
+ * First getString(directory,componentClass.getSimpleName(), null) is invoked,\r
+ * if the returned value is null, the defaultMap is consulted for a value.\r
+ * \r
+ * @param directory\r
+ * @param componentClass\r
+ * @param defaultMap\r
+ * @return\r
+ */\r
+ protected String get(String directory,\r
+ Class<? extends RocketComponent> componentClass,\r
+ Map<Class<?>, String> defaultMap) {\r
+ \r
+ // Search preferences\r
+ Class<?> c = componentClass;\r
+ while (c != null && RocketComponent.class.isAssignableFrom(c)) {\r
+ String value = this.getString(directory, c.getSimpleName(), null);\r
+ if (value != null)\r
+ return value;\r
+ c = c.getSuperclass();\r
+ }\r
+ \r
+ if (defaultMap == null)\r
+ return null;\r
+ \r
+ // Search defaults\r
+ c = componentClass;\r
+ while (RocketComponent.class.isAssignableFrom(c)) {\r
+ String value = defaultMap.get(c);\r
+ if (value != null)\r
+ return value;\r
+ c = c.getSuperclass();\r
+ }\r
+ \r
+ return null;\r
+ }\r
+\r
+ /*\r
+ * Map of default line styles\r
+ */\r
+ private static final HashMap<Class<?>, String> DEFAULT_LINE_STYLES =\r
+ new HashMap<Class<?>, String>();\r
+ static {\r
+ DEFAULT_LINE_STYLES.put(RocketComponent.class, LineStyle.SOLID.name());\r
+ DEFAULT_LINE_STYLES.put(MassObject.class, LineStyle.DASHED.name());\r
+ }\r
+ \r
+ /*\r
+ * Within a holder class so they will load only when needed.\r
+ */\r
+ private static class DefaultMaterialHolder {\r
+ private static final Translator trans = Application.getTranslator();\r
+ \r
+ //// Elastic cord (round 2mm, 1/16 in)\r
+ private static final Material DEFAULT_LINE_MATERIAL =\r
+ Databases.findMaterial(Material.Type.LINE, trans.get("Databases.materials.Elasticcordround2mm"),\r
+ 0.0018, false);\r
+ //// Ripstop nylon\r
+ private static final Material DEFAULT_SURFACE_MATERIAL =\r
+ Databases.findMaterial(Material.Type.SURFACE, trans.get("Databases.materials.Ripstopnylon"), 0.067, false);\r
+ //// Cardboard\r
+ private static final Material DEFAULT_BULK_MATERIAL =\r
+ Databases.findMaterial(Material.Type.BULK, trans.get("Databases.materials.Cardboard"), 680, false);\r
+ }\r
+ \r
+\r
+\r
+}\r
import net.sf.openrocket.logging.LogLevel;
import net.sf.openrocket.logging.LogLevelBufferLogger;
import net.sf.openrocket.logging.PrintStreamLogger;
+import net.sf.openrocket.util.Prefs;
/**
// Initialize logging first so we can use it
initializeLogging();
+ Application.setPreferences( new Prefs() );
+
// Setup the translations
initializeL10n();
import net.sf.openrocket.logging.LogHelper;
import net.sf.openrocket.motor.Motor;
import net.sf.openrocket.motor.ThrustCurveMotor;
+import net.sf.openrocket.util.BuildProperties;
import net.sf.openrocket.util.Prefs;
/**
*/
static void runMain(final String[] args) throws Exception {
- log.info("Starting up OpenRocket version " + Prefs.getVersion());
+ log.info("Starting up OpenRocket version " + BuildProperties.getVersion());
// Check that we're not running headless
log.info("Checking for graphics head");
// Start update info fetching
final UpdateInfoRetriever updateInfo;
- if (Prefs.getCheckUpdates()) {
+ if ( Application.getPreferences().getCheckUpdates()) {
log.info("Starting update check");
updateInfo = new UpdateInfoRetriever();
updateInfo.start();
ToolTipManager.sharedInstance().setDismissDelay(30000);
// Load defaults
- Prefs.loadDefaultUnits();
+ ((Prefs) Application.getPreferences()).loadDefaultUnits();
// Load motors etc.
log.info("Loading databases");
thrustCurveCount = list.size();
// Load the user-defined thrust curves
- for (File file : Prefs.getUserThrustCurveFiles()) {
+ for (File file : ((Prefs) Application.getPreferences()).getUserThrustCurveFiles()) {
log.info("Loading motors from " + file);
list = MotorLoaderHelper.load(file);
for (Motor m : list) {
if (!updateInfo.isRunning()) {
timer.stop();
- String current = Prefs.getVersion();
- String last = Prefs.getString(Prefs.LAST_UPDATE, "");
+ String current = BuildProperties.getVersion();
+ String last = Application.getPreferences().getString(Prefs.LAST_UPDATE, "");
UpdateInfo info = updateInfo.getUpdateInfo();
if (info != null && info.getLatestVersion() != null &&
UpdateInfoDialog infoDialog = new UpdateInfoDialog(info);
infoDialog.setVisible(true);
if (infoDialog.isReminderSelected()) {
- Prefs.putString(Prefs.LAST_UPDATE, "");
+ Application.getPreferences().putString(Prefs.LAST_UPDATE, "");
} else {
- Prefs.putString(Prefs.LAST_UPDATE, info.getLatestVersion());
+ Application.getPreferences().putString(Prefs.LAST_UPDATE, info.getLatestVersion());
}
}
}
--- /dev/null
+package net.sf.openrocket.util;\r
+\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.util.MissingResourceException;\r
+import java.util.Properties;\r
+\r
+public class BuildProperties {\r
+\r
+ private static final Properties PROPERTIES;\r
+ private static final String BUILD_VERSION;\r
+ private static final String BUILD_SOURCE;\r
+ private static final boolean DEFAULT_CHECK_UPDATES;\r
+ \r
+ /**\r
+ * Return the OpenRocket version number.\r
+ */\r
+ public static String getVersion() {\r
+ return BUILD_VERSION;\r
+ }\r
+ \r
+ /**\r
+ * Return the OpenRocket build source (e.g. "default" or "Debian")\r
+ */\r
+ public static String getBuildSource() {\r
+ return BUILD_SOURCE;\r
+ }\r
+ \r
+ public static boolean getDefaultCheckUpdates() {\r
+ return DEFAULT_CHECK_UPDATES;\r
+ }\r
+ \r
+ static {\r
+ try {\r
+ InputStream is = ClassLoader.getSystemResourceAsStream("build.properties");\r
+ if (is == null) {\r
+ throw new MissingResourceException(\r
+ "build.properties not found, distribution built wrong" +\r
+ " classpath:" + System.getProperty("java.class.path"),\r
+ "build.properties", "build.version");\r
+ }\r
+ \r
+ PROPERTIES = new Properties();\r
+ PROPERTIES.load(is);\r
+ is.close();\r
+ \r
+ String version = PROPERTIES.getProperty("build.version");\r
+ if (version == null) {\r
+ throw new MissingResourceException(\r
+ "build.version not found in property file",\r
+ "build.properties", "build.version");\r
+ }\r
+ BUILD_VERSION = version.trim();\r
+ \r
+ BUILD_SOURCE = PROPERTIES.getProperty("build.source");\r
+ if (BUILD_SOURCE == null) {\r
+ throw new MissingResourceException(\r
+ "build.source not found in property file",\r
+ "build.properties", "build.source");\r
+ }\r
+ \r
+ String value = PROPERTIES.getProperty("build.checkupdates");\r
+ if (value != null)\r
+ DEFAULT_CHECK_UPDATES = Boolean.parseBoolean(value);\r
+ else\r
+ DEFAULT_CHECK_UPDATES = true;\r
+ \r
+ } catch (IOException e) {\r
+ throw new MissingResourceException(\r
+ "Error reading build.properties",\r
+ "build.properties", "build.version");\r
+ }\r
+ }\r
+\r
+}\r
--- /dev/null
+package net.sf.openrocket.util;\r
+\r
+public class Color {\r
+\r
+ public static Color BLACK = new Color(255,255,255);\r
+ \r
+ private int red;\r
+ private int green;\r
+ private int blue;\r
+ private int alpha;\r
+ \r
+ public Color( int red, int green, int blue ) {\r
+ this.red = red;\r
+ this.green = green;\r
+ this.blue = blue;\r
+ this.alpha = 255;\r
+ }\r
+\r
+ public Color( int red, int green, int blue, int alpha ) {\r
+ this.red = red;\r
+ this.green = green;\r
+ this.blue = blue;\r
+ this.alpha = alpha;\r
+ }\r
+\r
+ public int getRed() {\r
+ return red;\r
+ }\r
+\r
+ public void setRed(int red) {\r
+ this.red = red;\r
+ }\r
+\r
+ public int getGreen() {\r
+ return green;\r
+ }\r
+\r
+ public void setGreen(int green) {\r
+ this.green = green;\r
+ }\r
+\r
+ public int getBlue() {\r
+ return blue;\r
+ }\r
+\r
+ public void setBlue(int blue) {\r
+ this.blue = blue;\r
+ }\r
+\r
+ public int getAlpha() {\r
+ return alpha;\r
+ }\r
+\r
+ public void setAlpha(int alpha) {\r
+ this.alpha = alpha;\r
+ }\r
+ \r
+}\r
import java.awt.Dimension;
import java.awt.Point;
import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
-import java.util.Map;
-import java.util.MissingResourceException;
-import java.util.Properties;
import java.util.Set;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import net.sf.openrocket.arch.SystemInfo;
-import net.sf.openrocket.database.Databases;
import net.sf.openrocket.document.Simulation;
import net.sf.openrocket.gui.main.ExceptionHandler;
-import net.sf.openrocket.gui.print.PrintSettings;
-import net.sf.openrocket.l10n.L10N;
-import net.sf.openrocket.l10n.Translator;
+import net.sf.openrocket.gui.util.ColorConversion;
import net.sf.openrocket.logging.LogHelper;
import net.sf.openrocket.material.Material;
import net.sf.openrocket.rocketcomponent.BodyComponent;
import net.sf.openrocket.unit.UnitGroup;
-public class Prefs {
+public class Prefs extends net.sf.openrocket.startup.Preferences {
private static final LogHelper log = Application.getLogger();
private static final String SPLIT_CHARACTER = "|";
*/
private static final String NODENAME = (DEBUG ? "OpenRocket-debug" : "OpenRocket");
-
- /*
- * Load property file only when necessary.
+ /**
+ * Return whether to use additional safety code checks.
*/
- private static class BuildPropertyHolder {
-
- public static final Properties PROPERTIES;
- public static final String BUILD_VERSION;
- public static final String BUILD_SOURCE;
- public static final boolean DEFAULT_CHECK_UPDATES;
-
- static {
- try {
- InputStream is = ClassLoader.getSystemResourceAsStream("build.properties");
- if (is == null) {
- throw new MissingResourceException(
- "build.properties not found, distribution built wrong" +
- " classpath:" + System.getProperty("java.class.path"),
- "build.properties", "build.version");
- }
-
- PROPERTIES = new Properties();
- PROPERTIES.load(is);
- is.close();
-
- String version = PROPERTIES.getProperty("build.version");
- if (version == null) {
- throw new MissingResourceException(
- "build.version not found in property file",
- "build.properties", "build.version");
- }
- BUILD_VERSION = version.trim();
-
- BUILD_SOURCE = PROPERTIES.getProperty("build.source");
- if (BUILD_SOURCE == null) {
- throw new MissingResourceException(
- "build.source not found in property file",
- "build.properties", "build.source");
- }
-
- String value = PROPERTIES.getProperty("build.checkupdates");
- if (value != null)
- DEFAULT_CHECK_UPDATES = Boolean.parseBoolean(value);
- else
- DEFAULT_CHECK_UPDATES = true;
-
- } catch (IOException e) {
- throw new MissingResourceException(
- "Error reading build.properties",
- "build.properties", "build.version");
- }
+ public static boolean useSafetyChecks() {
+ // Currently default to false unless openrocket.debug.safetycheck is defined
+ String s = System.getProperty("openrocket.debug.safetycheck");
+ if (s != null && !(s.equalsIgnoreCase("false") || s.equalsIgnoreCase("off"))) {
+ return true;
}
+ return false;
}
- public static final String BODY_COMPONENT_INSERT_POSITION_KEY = "BodyComponentInsertPosition";
-
- public static final String USER_THRUST_CURVES_KEY = "UserThrustCurves";
-
- public static final String CONFIRM_DELETE_SIMULATION = "ConfirmDeleteSimulation";
-
- // Preferences related to data export
- public static final String EXPORT_FIELD_SEPARATOR = "ExportFieldSeparator";
- public static final String EXPORT_SIMULATION_COMMENT = "ExportSimulationComment";
- public static final String EXPORT_FIELD_NAME_COMMENT = "ExportFieldDescriptionComment";
- public static final String EXPORT_EVENT_COMMENTS = "ExportEventComments";
- public static final String EXPORT_COMMENT_CHARACTER = "ExportCommentCharacter";
-
- public static final String PLOT_SHOW_POINTS = "ShowPlotPoints";
-
- private static final String CHECK_UPDATES = "CheckUpdates";
- public static final String LAST_UPDATE = "LastUpdateVersion";
-
- public static final String MOTOR_DIAMETER_FILTER = "MotorDiameterMatch";
- public static final String MOTOR_HIDE_SIMILAR = "MotorHideSimilar";
+ private final Preferences PREFNODE;
- // Node names
- public static final String PREFERRED_THRUST_CURVE_MOTOR_NODE = "preferredThrustCurveMotors";
-
-
- private static final Preferences PREFNODE;
-
-
- // Clear the preferences if debug mode and clearprefs is defined
- static {
+ public Prefs() {
Preferences root = Preferences.userRoot();
if (DEBUG && CLEARPREFS) {
try {
}
-
-
- ///////// Default component attributes
-
private static final HashMap<Class<?>, String> DEFAULT_COLORS =
new HashMap<Class<?>, String>();
static {
}
- private static final HashMap<Class<?>, String> DEFAULT_LINE_STYLES =
- new HashMap<Class<?>, String>();
- static {
- DEFAULT_LINE_STYLES.put(RocketComponent.class, LineStyle.SOLID.name());
- DEFAULT_LINE_STYLES.put(MassObject.class, LineStyle.DASHED.name());
- }
-
-
- /*
- * Within a holder class so they will load only when needed.
- */
- private static class DefaultMaterialHolder {
- private static final Translator trans = Application.getTranslator();
-
- //// Elastic cord (round 2mm, 1/16 in)
- private static final Material DEFAULT_LINE_MATERIAL =
- Databases.findMaterial(Material.Type.LINE, trans.get("Databases.materials.Elasticcordround2mm"),
- 0.0018, false);
- //// Ripstop nylon
- private static final Material DEFAULT_SURFACE_MATERIAL =
- Databases.findMaterial(Material.Type.SURFACE, trans.get("Databases.materials.Ripstopnylon"), 0.067, false);
- //// Cardboard
- private static final Material DEFAULT_BULK_MATERIAL =
- Databases.findMaterial(Material.Type.BULK, trans.get("Databases.materials.Cardboard"), 680, false);
- }
//////////////////////
- /**
- * Return the OpenRocket version number.
- */
- public static String getVersion() {
- return BuildPropertyHolder.BUILD_VERSION;
- }
-
-
- /**
- * Return the OpenRocket build source (e.g. "default" or "Debian")
- */
- public static String getBuildSource() {
- return BuildPropertyHolder.BUILD_SOURCE;
- }
-
-
- /**
- * Return the OpenRocket unique ID.
- *
- * @return a random ID string that stays constant between OpenRocket executions
- */
- public static String getUniqueID() {
- String id = PREFNODE.get("id", null);
- if (id == null) {
- id = UniqueID.uuid();
- PREFNODE.put("id", id);
- }
- return id;
- }
-
-
/**
* Store the current OpenRocket version into the preferences to allow for preferences migration.
*/
- private static void storeVersion() {
- PREFNODE.put("OpenRocketVersion", getVersion());
- }
-
-
- /**
- * Returns a limited-range integer value from the preferences. If the value
- * in the preferences is negative or greater than max, then the default value
- * is returned.
- *
- * @param key The preference to retrieve.
- * @param max Maximum allowed value for the choice.
- * @param def Default value.
- * @return The preference value.
- */
- public static int getChoise(String key, int max, int def) {
- int v = PREFNODE.getInt(key, def);
- if ((v < 0) || (v > max))
- return def;
- return v;
+ private void storeVersion() {
+ PREFNODE.put("OpenRocketVersion", BuildProperties.getVersion());
}
-
- /**
- * Helper method that puts an integer choice value into the preferences.
- *
- * @param key the preference key.
- * @param value the value to store.
- */
- public static void putChoise(String key, int value) {
- PREFNODE.putInt(key, value);
- storeVersion();
- }
-
-
/**
* Return a string preference.
*
* @param def the default if no preference is stored
* @return the preference value
*/
- public static String getString(String key, String def) {
+ @Override
+ public String getString(String key, String def) {
return PREFNODE.get(key, def);
}
+ @Override
+ public String getString( String directory, String key, String defaultValue ) {
+ Preferences p = PREFNODE.node(directory);
+ return p.get(key,defaultValue);
+ }
+
/**
* Set a string preference.
*
* @param key the preference key
* @param value the value to set, or <code>null</code> to remove the key
*/
- public static void putString(String key, String value) {
+ @Override
+ public void putString(String key, String value) {
if (value == null) {
PREFNODE.remove(key);
- return;
+ } else {
+ PREFNODE.put(key, value);
}
- PREFNODE.put(key, value);
storeVersion();
}
-
- /**
- * Retrieve an enum value from the user preferences.
- *
- * @param <T> the enum type
- * @param key the key
- * @param def the default value, cannot be null
- * @return the value in the preferences, or the default value
- */
- public static <T extends Enum<T>> T getEnum(String key, T def) {
- if (def == null) {
- throw new BugException("Default value cannot be null");
- }
-
- String value = getString(key, null);
- if (value == null) {
- return def;
- }
-
- try {
- return Enum.valueOf(def.getDeclaringClass(), value);
- } catch (IllegalArgumentException e) {
- return def;
- }
- }
-
- /**
- * Store an enum value to the user preferences.
- *
- * @param key the key
- * @param value the value to store, or null to remove the value
- */
- public static void putEnum(String key, Enum<?> value) {
- if (value == null) {
- putString(key, null);
+ @Override
+ public void putString(String directory, String key, String value ) {
+ Preferences p = PREFNODE.node(directory);
+ if ( value == null ) {
+ p.remove(key);
} else {
- putString(key, value.name());
+ p.put(key,value);
}
+ storeVersion();
}
-
/**
* Return a boolean preference.
*
* @param def the default if no preference is stored
* @return the preference value
*/
- public static boolean getBoolean(String key, boolean def) {
+ @Override
+ public boolean getBoolean(String key, boolean def) {
return PREFNODE.getBoolean(key, def);
}
* @param key the preference key
* @param value the value to set
*/
- public static void putBoolean(String key, boolean value) {
+ @Override
+ public void putBoolean(String key, boolean value) {
PREFNODE.putBoolean(key, value);
storeVersion();
}
- public static int getInt( String key, int defaultValue ) {
+ @Override
+ public int getInt( String key, int defaultValue ) {
return PREFNODE.getInt(key, defaultValue);
}
- public static void putInt( String key , int value ) {
+ @Override
+ public void putInt( String key , int value ) {
PREFNODE.putInt(key, value );
+ storeVersion();
+ }
+
+ @Override
+ public double getDouble(String key, double defaultValue) {
+ return PREFNODE.getDouble(key, defaultValue );
}
+ @Override
+ public void putDouble(String key, double value) {
+ PREFNODE.putDouble(key,value);
+ storeVersion();
+ }
+
+
+
/**
* Return a preferences object for the specified node name.
*
* @param nodeName the node name
* @return the preferences object for that node
*/
- public static Preferences getNode(String nodeName) {
+ public Preferences getNode(String nodeName) {
return PREFNODE.node(nodeName);
}
return SUPPORTED_LOCALES;
}
- public static Locale getUserLocale() {
- String locale = getString("locale", null);
- return L10N.toLocale(locale);
- }
-
- public static void setUserLocale(Locale l) {
- if (l == null) {
- putString("locale", null);
- } else {
- putString("locale", l.toString());
- }
- }
-
-
-
- public static boolean getCheckUpdates() {
- return PREFNODE.getBoolean(CHECK_UPDATES, BuildPropertyHolder.DEFAULT_CHECK_UPDATES);
- }
-
- public static void setCheckUpdates(boolean check) {
- PREFNODE.putBoolean(CHECK_UPDATES, check);
- storeVersion();
- }
-
- public static File getDefaultDirectory() {
- String file = PREFNODE.get("defaultDirectory", null);
+ public File getDefaultDirectory() {
+ String file = getString("defaultDirectory", null);
if (file == null)
return null;
return new File(file);
}
- public static void setDefaultDirectory(File dir) {
+ public void setDefaultDirectory(File dir) {
String d;
if (dir == null) {
d = null;
} else {
d = dir.getAbsolutePath();
}
- PREFNODE.put("defaultDirectory", d);
+ putString("defaultDirectory", d);
storeVersion();
}
*
* @return a list of files to load as thrust curves.
*/
- public static List<File> getUserThrustCurveFiles() {
+ public List<File> getUserThrustCurveFiles() {
List<File> list = new ArrayList<File>();
String files = getString(USER_THRUST_CURVES_KEY, null);
return list;
}
- public static File getDefaultUserThrustCurveFile() {
+ public File getDefaultUserThrustCurveFile() {
File appdir = SystemInfo.getUserApplicationDirectory();
File tcdir = new File(appdir, "ThrustCurves");
return tcdir;
*
* @param files the files to load, or <code>null</code> to reset to default value.
*/
- public static void setUserThrustCurveFiles(List<File> files) {
+ public void setUserThrustCurveFiles(List<File> files) {
if (files == null) {
putString(USER_THRUST_CURVES_KEY, null);
return;
putString(USER_THRUST_CURVES_KEY, str);
}
+ public Color getMotorBorderColor() {
+ // TODO: MEDIUM: Motor color (settable?)
+ return new Color(0, 0, 0, 200);
+ }
-
-
-
- public static Color getDefaultColor(Class<? extends RocketComponent> c) {
+
+ public Color getMotorFillColor() {
+ // TODO: MEDIUM: Motor fill color (settable?)
+ return new Color(0, 0, 0, 100);
+ }
+
+ public Color getDefaultColor(Class<? extends RocketComponent> c) {
String color = get("componentColors", c, DEFAULT_COLORS);
if (color == null)
return Color.BLACK;
- Color clr = parseColor(color);
+ net.sf.openrocket.util.Color clr = parseColor(color);
if (clr != null) {
- return clr;
+ return ColorConversion.toAwtColor(clr);
} else {
return Color.BLACK;
}
}
- public static void setDefaultColor(Class<? extends RocketComponent> c, Color color) {
+ public final void setDefaultColor(Class<? extends RocketComponent> c, Color color) {
if (color == null)
return;
- set("componentColors", c, stringifyColor(color));
- }
-
-
- private static Color parseColor(String color) {
- if (color == null) {
- return null;
- }
-
- String[] rgb = color.split(",");
- if (rgb.length == 3) {
- try {
- int red = MathUtil.clamp(Integer.parseInt(rgb[0]), 0, 255);
- int green = MathUtil.clamp(Integer.parseInt(rgb[1]), 0, 255);
- int blue = MathUtil.clamp(Integer.parseInt(rgb[2]), 0, 255);
- return new Color(red, green, blue);
- } catch (NumberFormatException ignore) {
- }
- }
- return null;
- }
-
-
- private static String stringifyColor(Color color) {
- String string = color.getRed() + "," + color.getGreen() + "," + color.getBlue();
- return string;
+ putString("componentColors", c.getSimpleName(), stringifyColor(ColorConversion.fromAwtColor(color)));
}
-
-
- public static Color getMotorBorderColor() {
- // TODO: MEDIUM: Motor color (settable?)
- return new Color(0, 0, 0, 200);
- }
-
-
- public static Color getMotorFillColor() {
- // TODO: MEDIUM: Motor fill color (settable?)
- return new Color(0, 0, 0, 100);
- }
-
-
- public static LineStyle getDefaultLineStyle(Class<? extends RocketComponent> c) {
- String value = get("componentStyle", c, DEFAULT_LINE_STYLES);
- try {
- return LineStyle.valueOf(value);
- } catch (Exception e) {
- return LineStyle.SOLID;
- }
- }
-
- public static void setDefaultLineStyle(Class<? extends RocketComponent> c,
- LineStyle style) {
- if (style == null)
- return;
- set("componentStyle", c, style.name());
- }
-
-
- public static double getDefaultMach() {
- // TODO: HIGH: implement custom default mach number
- return 0.3;
- }
-
- public static Material getDefaultComponentMaterial(
- Class<? extends RocketComponent> componentClass,
- Material.Type type) {
-
- String material = get("componentMaterials", componentClass, null);
- if (material != null) {
- try {
- Material m = Material.fromStorableString(material, false);
- if (m.getType() == type)
- return m;
- } catch (IllegalArgumentException ignore) {
- }
- }
-
- switch (type) {
- case LINE:
- return DefaultMaterialHolder.DEFAULT_LINE_MATERIAL;
- case SURFACE:
- return DefaultMaterialHolder.DEFAULT_SURFACE_MATERIAL;
- case BULK:
- return DefaultMaterialHolder.DEFAULT_BULK_MATERIAL;
- }
- throw new IllegalArgumentException("Unknown material type: " + type);
- }
-
- public static void setDefaultComponentMaterial(
- Class<? extends RocketComponent> componentClass, Material material) {
-
- set("componentMaterials", componentClass,
- material == null ? null : material.toStorableString());
- }
public static int getMaxThreadCount() {
}
- /**
- * Return whether to use additional safety code checks.
- */
- public static boolean useSafetyChecks() {
- // Currently default to false unless openrocket.debug.safetycheck is defined
- String s = System.getProperty("openrocket.debug.safetycheck");
- if (s != null && !(s.equalsIgnoreCase("false") || s.equalsIgnoreCase("off"))) {
- return true;
- }
- return false;
- }
-
- public static Point getWindowPosition(Class<?> c) {
+ public Point getWindowPosition(Class<?> c) {
int x, y;
String pref = PREFNODE.node("windows").get("position." + c.getCanonicalName(), null);
return new Point(x, y);
}
- public static void setWindowPosition(Class<?> c, Point p) {
+ public void setWindowPosition(Class<?> c, Point p) {
PREFNODE.node("windows").put("position." + c.getCanonicalName(), "" + p.x + "," + p.y);
storeVersion();
}
- public static Dimension getWindowSize(Class<?> c) {
+ public Dimension getWindowSize(Class<?> c) {
int x, y;
String pref = PREFNODE.node("windows").get("size." + c.getCanonicalName(), null);
}
- public static boolean isWindowMaximized(Class<?> c) {
+ public boolean isWindowMaximized(Class<?> c) {
String pref = PREFNODE.node("windows").get("size." + c.getCanonicalName(), null);
return "max".equals(pref);
}
- public static void setWindowSize(Class<?> c, Dimension d) {
+ public void setWindowSize(Class<?> c, Dimension d) {
PREFNODE.node("windows").put("size." + c.getCanonicalName(), "" + d.width + "," + d.height);
storeVersion();
}
- public static void setWindowMaximized(Class<?> c) {
+ public void setWindowMaximized(Class<?> c) {
PREFNODE.node("windows").put("size." + c.getCanonicalName(), "max");
storeVersion();
}
-
- //// Printing
-
- public static PrintSettings getPrintSettings() {
- PrintSettings settings = new PrintSettings();
- Color c;
-
- c = parseColor(getString("print.template.fillColor", null));
- if (c != null) {
- settings.setTemplateFillColor(c);
- }
-
- c = parseColor(getString("print.template.borderColor", null));
- if (c != null) {
- settings.setTemplateBorderColor(c);
+ /**
+ * this class returns a java.awt.Color object for the specified key.
+ * you can pass (java.awt.Color) null to the second argument to
+ * disambiguate
+ */
+ public Color getColor( String key, Color defaultValue ) {
+ net.sf.openrocket.util.Color c = super.getColor(key, (net.sf.openrocket.util.Color) null);
+ if ( c == null ) {
+ return defaultValue;
}
-
- settings.setPaperSize(getEnum("print.paper.size", settings.getPaperSize()));
- settings.setPaperOrientation(getEnum("print.paper.orientation", settings.getPaperOrientation()));
-
- return settings;
+ return ColorConversion.toAwtColor(c);
}
- public static void setPrintSettings(PrintSettings settings) {
- putString("print.template.fillColor", stringifyColor(settings.getTemplateFillColor()));
- putString("print.template.borderColor", stringifyColor(settings.getTemplateBorderColor()));
- putEnum("print.paper.size", settings.getPaperSize());
- putEnum("print.paper.orientation", settings.getPaperOrientation());
+ /**
+ *
+ */
+ public void putColor( String key, Color value ) {
+ net.sf.openrocket.util.Color c = ColorConversion.fromAwtColor(value);
+ super.putColor(key, c);
}
+ //// Printing
+
+
//// Background flight data computation
- public static boolean computeFlightInBackground() {
+ public boolean computeFlightInBackground() {
return PREFNODE.getBoolean("backgroundFlight", true);
}
- public static Simulation getBackgroundSimulation(Rocket rocket) {
+ public Simulation getBackgroundSimulation(Rocket rocket) {
Simulation s = new Simulation(rocket);
SimulationOptions cond = s.getOptions();
///////// Export variables
- public static boolean isExportSelected(FlightDataType type) {
+ public boolean isExportSelected(FlightDataType type) {
Preferences prefs = PREFNODE.node("exports");
return prefs.getBoolean(type.getName(), false);
}
- public static void setExportSelected(FlightDataType type, boolean selected) {
+ public void setExportSelected(FlightDataType type, boolean selected) {
Preferences prefs = PREFNODE.node("exports");
prefs.putBoolean(type.getName(), selected);
}
///////// Default unit storage
- public static void loadDefaultUnits() {
+ public void loadDefaultUnits() {
Preferences prefs = PREFNODE.node("units");
try {
}
}
- public static void storeDefaultUnits() {
+ public void storeDefaultUnits() {
Preferences prefs = PREFNODE.node("units");
for (String key : UnitGroup.UNITS.keySet()) {
*
* @param m the material to add.
*/
- public static void addUserMaterial(Material m) {
+ public void addUserMaterial(Material m) {
Preferences prefs = PREFNODE.node("userMaterials");
*
* @param m the material to remove.
*/
- public static void removeUserMaterial(Material m) {
+ public void removeUserMaterial(Material m) {
Preferences prefs = PREFNODE.node("userMaterials");
try {
*
* @return a set of all user-defined materials.
*/
- public static Set<Material> getUserMaterials() {
+ public Set<Material> getUserMaterials() {
Preferences prefs = PREFNODE.node("userMaterials");
HashSet<Material> materials = new HashSet<Material>();
//// Helper methods
- private static String get(String directory,
- Class<? extends RocketComponent> componentClass,
- Map<Class<?>, String> defaultMap) {
-
- // Search preferences
- Class<?> c = componentClass;
- Preferences prefs = PREFNODE.node(directory);
- while (c != null && RocketComponent.class.isAssignableFrom(c)) {
- String value = prefs.get(c.getSimpleName(), null);
- if (value != null)
- return value;
- c = c.getSuperclass();
- }
-
- if (defaultMap == null)
- return null;
-
- // Search defaults
- c = componentClass;
- while (RocketComponent.class.isAssignableFrom(c)) {
- String value = defaultMap.get(c);
- if (value != null)
- return value;
- c = c.getSuperclass();
- }
-
- return null;
- }
-
-
- private static void set(String directory, Class<? extends RocketComponent> componentClass,
- String value) {
- Preferences prefs = PREFNODE.node(directory);
- if (value == null)
- prefs.remove(componentClass.getSimpleName());
- else
- prefs.put(componentClass.getSimpleName(), value);
- storeVersion();
- }
-
}
}
}
-
/**
* Verify that this mutex is unlocked, but don't lock it. This has the same effect
package net.sf.openrocket.util;
+import java.awt.Color;
+import java.util.Random;
+
import net.sf.openrocket.material.Material;
import net.sf.openrocket.material.Material.Type;
import net.sf.openrocket.motor.Motor;
import net.sf.openrocket.rocketcomponent.TubeCoupler;
import net.sf.openrocket.startup.Application;
-import java.awt.Color;
-import java.util.Random;
-
public class TestRockets {
private final String key;
bodytube.addChild(finset);
- Material material = Prefs.getDefaultComponentMaterial(null, Material.Type.BULK);
+ Material material = Application.getPreferences().getDefaultComponentMaterial(null, Material.Type.BULK);
nosecone.setMaterial(material);
bodytube.setMaterial(material);
finset.setMaterial(material);
package net.sf.openrocket;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.awt.event.ActionEvent;
import java.io.IOException;
import net.sf.openrocket.simulation.exception.SimulationException;
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.util.Coordinate;
+import net.sf.openrocket.util.BaseTestCase.BaseTestCase;
import org.junit.BeforeClass;
import org.junit.Test;
* This class contains various integration tests that simulate user actions that
* might be performed.
*/
-public class IntegrationTest {
+public class IntegrationTest extends BaseTestCase {
private OpenRocketDocument document;
private Action undoAction, redoAction;
package net.sf.openrocket.communication;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
+import net.sf.openrocket.util.BuildProperties;
import net.sf.openrocket.util.Prefs;
import org.junit.Test;
private void check(HttpURLConnectionMock connection) {
assertEquals(Communicator.BUG_REPORT_URL, connection.getTrueUrl());
assertTrue(connection.getConnectTimeout() > 0);
- assertEquals(Prefs.getVersion(), connection.getRequestProperty("X-OpenRocket-Version"));
+ assertEquals(BuildProperties.getVersion(), connection.getRequestProperty("X-OpenRocket-Version"));
assertTrue(connection.getInstanceFollowRedirects());
assertEquals("POST", connection.getRequestMethod());
assertFalse(connection.getUseCaches());
check(connection);
String msg = connection.getOutputStreamString();
- assertTrue(msg.indexOf("version=" + Prefs.getVersion()) >= 0);
+ assertTrue(msg.indexOf("version=" + BuildProperties.getVersion()) >= 0);
assertTrue(msg.indexOf(Communicator.encode(message)) >= 0);
}
package net.sf.openrocket.communication;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Random;
+import net.sf.openrocket.util.BuildProperties;
import net.sf.openrocket.util.ComparablePair;
import net.sf.openrocket.util.Prefs;
+import net.sf.openrocket.util.BaseTestCase.BaseTestCase;
import org.junit.Test;
-public class UpdateInfoTest {
+public class UpdateInfoTest extends BaseTestCase {
/** The connection delay */
private static final int DELAY = 100;
}
private void check(HttpURLConnectionMock connection) {
- assertEquals(Communicator.UPDATE_INFO_URL + "?version=" + Prefs.getVersion(),
+ assertEquals(Communicator.UPDATE_INFO_URL + "?version=" + BuildProperties.getVersion(),
connection.getTrueUrl());
assertTrue(connection.getConnectTimeout() > 0);
- assertEquals(Prefs.getVersion() + "+" + Prefs.getBuildSource(),
+ assertEquals(BuildProperties.getVersion() + "+" + BuildProperties.getBuildSource(),
connection.getRequestProperty("X-OpenRocket-Version"));
assertNotNull(connection.getRequestProperty("X-OpenRocket-Country"));
assertNotNull(connection.getRequestProperty("X-OpenRocket-ID"));
check(connection);
- assertEquals(Prefs.getVersion(), info.getLatestVersion());
+ assertEquals(BuildProperties.getVersion(), info.getLatestVersion());
assertEquals(0, info.getUpdates().size());
}
import junit.framework.TestCase;
import net.sf.openrocket.rocketcomponent.RocketComponent;
+import net.sf.openrocket.startup.Application;
+import net.sf.openrocket.util.Prefs;
/**
* A base class for the Rocksim tests. Includes code from the junitx.addons project.
super(name);
}
+
+ /* (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ Application.setPreferences( new Prefs() );
+ }
+
+
public void assertContains(RocketComponent child, List<RocketComponent> components) {
assertTrue("Components did not contain child", components.contains(child));
}
package net.sf.openrocket.gui.configdialog;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
import net.sf.openrocket.gui.adaptors.DoubleModel;
import net.sf.openrocket.rocketcomponent.BodyTube;
import net.sf.openrocket.rocketcomponent.CenteringRing;
import net.sf.openrocket.rocketcomponent.RocketComponent;
+import net.sf.openrocket.util.BaseTestCase.BaseTestCase;
+
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-
-public class FinSetConfigTest {
+public class FinSetConfigTest extends BaseTestCase {
static Method method;
package net.sf.openrocket.rocketcomponent;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.awt.Color;
import net.sf.openrocket.rocketcomponent.FinSet.TabRelativePosition;
import net.sf.openrocket.rocketcomponent.RocketComponent.Position;
import net.sf.openrocket.util.LineStyle;
+import net.sf.openrocket.util.BaseTestCase.BaseTestCase;
import org.junit.Test;
-public class FinSetTest {
+public class FinSetTest extends BaseTestCase {
@Test
package net.sf.openrocket.rocketcomponent;
+import net.sf.openrocket.util.BaseTestCase.BaseTestCase;
+
import org.junit.Test;
-public class RocketTest {
+public class RocketTest extends BaseTestCase {
@Test
public void testCopyFrom() {
--- /dev/null
+package net.sf.openrocket.util.BaseTestCase;\r
+\r
+import net.sf.openrocket.startup.Application;\r
+import net.sf.openrocket.util.Prefs;\r
+\r
+import org.junit.BeforeClass;\r
+\r
+public class BaseTestCase {\r
+\r
+ @BeforeClass\r
+ public static void setUpApplication () {\r
+ \r
+ Application.setPreferences( new Prefs() );\r
+ \r
+ }\r
+}\r