1 package net.sf.openrocket.gui.adaptors;
3 import java.awt.event.ActionEvent;
4 import java.beans.PropertyChangeEvent;
5 import java.beans.PropertyChangeListener;
6 import java.lang.reflect.InvocationTargetException;
7 import java.lang.reflect.Method;
8 import java.util.ArrayList;
9 import java.util.EventListener;
10 import java.util.EventObject;
12 import javax.swing.AbstractAction;
13 import javax.swing.AbstractSpinnerModel;
14 import javax.swing.Action;
15 import javax.swing.BoundedRangeModel;
16 import javax.swing.SpinnerModel;
17 import javax.swing.event.ChangeEvent;
18 import javax.swing.event.ChangeListener;
20 import net.sf.openrocket.logging.LogHelper;
21 import net.sf.openrocket.startup.Application;
22 import net.sf.openrocket.unit.Unit;
23 import net.sf.openrocket.unit.UnitGroup;
24 import net.sf.openrocket.util.BugException;
25 import net.sf.openrocket.util.ChangeSource;
26 import net.sf.openrocket.util.FractionUtil;
27 import net.sf.openrocket.util.Invalidatable;
28 import net.sf.openrocket.util.Invalidator;
29 import net.sf.openrocket.util.MathUtil;
30 import net.sf.openrocket.util.MemoryManagement;
31 import net.sf.openrocket.util.Reflection;
32 import net.sf.openrocket.util.StateChangeListener;
36 * A model connector that can read and modify any value of any ChangeSource that
37 * has the appropriate get/set methods defined.
39 * The variable is defined in the constructor by providing the variable name as a string
40 * (e.g. "Radius" -> getRadius()/setRadius()). Additional scaling may be applied, e.g. a
41 * DoubleModel for the diameter can be defined by the variable "Radius" and a multiplier of 2.
43 * Sub-models suitable for JSpinners and other components are available from the appropriate
46 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
49 public class DoubleModel implements StateChangeListener, ChangeSource, Invalidatable {
50 private static final LogHelper log = Application.getLogger();
53 public static final DoubleModel ZERO = new DoubleModel(0);
55 //////////// JSpinner Model ////////////
58 * Model suitable for JSpinner using JSpinner.NumberEditor. It extends SpinnerNumberModel
59 * to be compatible with the NumberEditor, but only has the necessary methods defined.
61 public class ValueSpinnerModel extends AbstractSpinnerModel implements Invalidatable {
64 public Object getValue() {
65 return currentUnit.toString(DoubleModel.this.getValue());
69 public void setValue(Object value) {
71 // Ignore, if called when model is sending events
72 log.verbose("Ignoring call to SpinnerModel setValue for " + DoubleModel.this.toString() +
73 " value=" + value + ", currently firing events");
77 if ( value instanceof Number ) {
79 } else if ( value instanceof String ) {
81 String newValString = (String)value;
82 num = FractionUtil.parseFraction(newValString);
84 catch ( java.lang.NumberFormatException nfex ) {
89 double newValue = num.doubleValue();
90 double converted = currentUnit.fromUnit(newValue);
92 log.user("SpinnerModel setValue called for " + DoubleModel.this.toString() + " newValue=" + newValue +
93 " converted=" + converted);
94 DoubleModel.this.setValue(converted);
99 public Object getNextValue() {
100 double d = currentUnit.toUnit(DoubleModel.this.getValue());
101 double max = currentUnit.toUnit(maxValue);
102 if (MathUtil.equals(d, max))
104 d = currentUnit.getNextValue(d);
111 public Object getPreviousValue() {
112 double d = currentUnit.toUnit(DoubleModel.this.getValue());
113 double min = currentUnit.toUnit(minValue);
114 if (MathUtil.equals(d, min))
116 d = currentUnit.getPreviousValue(d);
123 public void addChangeListener(ChangeListener l) {
124 DoubleModel.this.addChangeListener(l);
128 public void removeChangeListener(ChangeListener l) {
129 DoubleModel.this.removeChangeListener(l);
133 public void invalidate() {
134 DoubleModel.this.invalidate();
139 * Returns a new SpinnerModel with the same base as the DoubleModel.
140 * The values given to the JSpinner are in the currently selected units.
142 * @return A compatibility layer for a SpinnerModel.
144 public SpinnerModel getSpinnerModel() {
145 return new ValueSpinnerModel();
148 //////////// JSlider model ////////////
150 private class ValueSliderModel implements BoundedRangeModel, StateChangeListener, Invalidatable {
151 private static final int MAX = 1000;
154 * Use linear scale value = linear1 * x + linear0 when x < linearPosition
155 * Use quadratic scale value = quad2 * x^2 + quad1 * x + quad0 otherwise
157 private final boolean islinear;
159 // Linear in range x <= linearPosition
160 private final double linearPosition;
162 // May be changing DoubleModels when using linear model
163 private final DoubleModel min, mid, max;
165 // Linear multiplier and constant
166 //private final double linear1;
167 //private final double linear0;
169 // Non-linear multiplier, exponent and constant
170 private double quad2, quad1, quad0;
172 public ValueSliderModel(DoubleModel min, DoubleModel max) {
173 this.islinear = true;
174 linearPosition = 1.0;
177 this.mid = max; // Never use exponential scale
180 min.addChangeListener(this);
181 max.addChangeListener(this);
183 quad2 = quad1 = quad0 = 0; // Not used
189 * Generate a linear model from min to max.
191 public ValueSliderModel(double min, double max) {
192 this.islinear = true;
193 linearPosition = 1.0;
195 this.min = new DoubleModel(min);
196 this.mid = new DoubleModel(max); // Never use exponential scale
197 this.max = new DoubleModel(max);
199 quad2 = quad1 = quad0 = 0; // Not used
202 public ValueSliderModel(double min, double mid, double max) {
203 this(min, 0.5, mid, max);
206 public ValueSliderModel(double min, double mid, DoubleModel max) {
207 this(min, 0.5, mid, max);
211 * v(x) = mul * x^exp + add
213 * v(pos) = mul * pos^exp + add = mid
214 * v(1) = mul + add = max
215 * v'(pos) = mul*exp * pos^(exp-1) = linearMul
217 public ValueSliderModel(double min, double pos, double mid, double max ) {
218 this(min, pos, mid, new DoubleModel(max));
220 public ValueSliderModel(double min, double pos, double mid, DoubleModel max) {
221 this.min = new DoubleModel(min);
222 this.mid = new DoubleModel(mid);
225 this.islinear = false;
227 max.addChangeListener(this);
229 linearPosition = pos;
231 //linear1 = (mid-min)/pos;
233 if (!(min < mid && mid <= max.getValue() && 0 < pos && pos < 1)) {
234 throw new IllegalArgumentException("Bad arguments for ValueSliderModel " +
235 "min=" + min + " mid=" + mid + " max=" + max + " pos=" + pos);
238 updateExponentialParameters();
242 private void updateExponentialParameters() {
243 double pos = this.linearPosition;
244 double minValue = this.min.getValue();
245 double midValue = this.mid.getValue();
246 double maxValue = this.max.getValue();
248 * quad2..0 are calculated such that
249 * f(pos) = mid - continuity
250 * f(1) = max - end point
251 * f'(pos) = linear1 - continuity of derivative
253 double delta = (midValue - minValue) / pos;
254 quad2 = (maxValue - midValue - delta + delta * pos) / pow2(pos - 1);
255 quad1 = (delta + 2 * (midValue - maxValue) * pos - delta * pos * pos) / pow2(pos - 1);
256 quad0 = (midValue - (2 * midValue + delta) * pos + (maxValue + delta) * pos * pos) / pow2(pos - 1);
259 private double pow2(double x) {
264 public int getValue() {
265 double value = DoubleModel.this.getValue();
266 if (value <= min.getValue())
268 if (value >= max.getValue())
272 if (value <= mid.getValue()) {
275 //linear1 = (mid-min)/pos;
277 x = (value - min.getValue()) * linearPosition / (mid.getValue() - min.getValue());
279 // Use quadratic scale
280 // Further solution of the quadratic equation
281 // a*x^2 + b*x + c-value == 0
282 x = (MathUtil.safeSqrt(quad1 * quad1 - 4 * quad2 * (quad0 - value)) - quad1) / (2 * quad2);
284 return (int) (x * MAX);
289 public void setValue(int newValue) {
292 log.verbose("Ignoring call to SliderModel setValue for " + DoubleModel.this.toString() +
293 " value=" + newValue + ", currently firing events");
297 double x = (double) newValue / MAX;
300 if (x <= linearPosition) {
303 //linear1 = (mid-min)/pos;
305 scaledValue = (mid.getValue() - min.getValue()) / linearPosition * x + min.getValue();
307 // Use quadratic scale
308 scaledValue = quad2 * x * x + quad1 * x + quad0;
311 double converted = currentUnit.fromUnit(currentUnit.round(currentUnit.toUnit(scaledValue)));
312 log.user("SliderModel setValue called for " + DoubleModel.this.toString() + " newValue=" + newValue +
313 " scaledValue=" + scaledValue + " converted=" + converted);
314 DoubleModel.this.setValue(converted);
318 // Static get-methods
319 private boolean isAdjusting;
322 public int getExtent() {
327 public int getMaximum() {
332 public int getMinimum() {
337 public boolean getValueIsAdjusting() {
343 public void setExtent(int newExtent) {
347 public void setMaximum(int newMaximum) {
351 public void setMinimum(int newMinimum) {
355 public void setValueIsAdjusting(boolean b) {
360 public void setRangeProperties(int value, int extent, int min, int max, boolean adjusting) {
361 setValueIsAdjusting(adjusting);
365 // Pass change listeners to the underlying model
367 public void addChangeListener(ChangeListener l) {
368 DoubleModel.this.addChangeListener(l);
372 public void removeChangeListener(ChangeListener l) {
373 DoubleModel.this.removeChangeListener(l);
377 public void invalidate() {
378 DoubleModel.this.invalidate();
382 public void stateChanged(EventObject e) {
383 // Min or max range has changed.
385 double midValue = (max.getValue() - min.getValue()) /3.0;
386 mid.setValue(midValue);
387 updateExponentialParameters();
389 // Fire if not already firing
396 public BoundedRangeModel getSliderModel(DoubleModel min, DoubleModel max) {
397 return new ValueSliderModel(min, max);
400 public BoundedRangeModel getSliderModel(double min, double max) {
401 return new ValueSliderModel(min, max);
404 public BoundedRangeModel getSliderModel(double min, double mid, double max) {
405 return new ValueSliderModel(min, mid, max);
408 public BoundedRangeModel getSliderModel(double min, double mid, DoubleModel max) {
409 return new ValueSliderModel(min, mid, max);
412 public BoundedRangeModel getSliderModel(double min, double pos, double mid, double max) {
413 return new ValueSliderModel(min, pos, mid, max);
420 //////////// Action model ////////////
422 private class AutomaticActionModel extends AbstractAction implements StateChangeListener, Invalidatable {
423 private boolean oldValue = false;
425 public AutomaticActionModel() {
426 oldValue = isAutomatic();
427 addChangeListener(this);
432 public boolean isEnabled() {
433 return isAutomaticAvailable();
437 public Object getValue(String key) {
438 if (key.equals(Action.SELECTED_KEY)) {
439 oldValue = isAutomatic();
442 return super.getValue(key);
446 public void putValue(String key, Object value) {
448 log.verbose("Ignoring call to ActionModel putValue for " + DoubleModel.this.toString() +
449 " key=" + key + " value=" + value + ", currently firing events");
452 if (key.equals(Action.SELECTED_KEY) && (value instanceof Boolean)) {
453 log.user("ActionModel putValue called for " + DoubleModel.this.toString() +
454 " key=" + key + " value=" + value);
455 oldValue = (Boolean) value;
456 setAutomatic((Boolean) value);
458 log.debug("Passing ActionModel putValue call to supermethod for " + DoubleModel.this.toString() +
459 " key=" + key + " value=" + value);
460 super.putValue(key, value);
464 // Implement a wrapper to the ChangeListeners
465 ArrayList<PropertyChangeListener> propertyChangeListeners =
466 new ArrayList<PropertyChangeListener>();
469 public void addPropertyChangeListener(PropertyChangeListener listener) {
470 propertyChangeListeners.add(listener);
471 DoubleModel.this.addChangeListener(this);
475 public void removePropertyChangeListener(PropertyChangeListener listener) {
476 propertyChangeListeners.remove(listener);
477 if (propertyChangeListeners.isEmpty())
478 DoubleModel.this.removeChangeListener(this);
481 // If the value has changed, generate an event to the listeners
483 public void stateChanged(EventObject e) {
484 boolean newValue = isAutomatic();
485 if (oldValue == newValue)
487 PropertyChangeEvent event = new PropertyChangeEvent(this, Action.SELECTED_KEY,
490 Object[] l = propertyChangeListeners.toArray();
491 for (int i = 0; i < l.length; i++) {
492 ((PropertyChangeListener) l[i]).propertyChange(event);
497 public void actionPerformed(ActionEvent e) {
498 // Setting performed in putValue
502 public void invalidate() {
503 DoubleModel.this.invalidate();
508 * Returns a new Action corresponding to the changes of the automatic setting
509 * property of the value model. This may be used directly with e.g. check buttons.
511 * @return A compatibility layer for an Action.
513 public Action getAutomaticAction() {
514 return new AutomaticActionModel();
521 //////////// Main model /////////////
524 * The main model handles all values in SI units, i.e. no conversion is made within the model.
527 private final ChangeSource source;
528 private final String valueName;
529 private final double multiplier;
531 private final Method getMethod;
532 private final Method setMethod;
534 private final Method getAutoMethod;
535 private final Method setAutoMethod;
537 private final ArrayList<EventListener> listeners = new ArrayList<EventListener>();
539 private final UnitGroup units;
540 private Unit currentUnit;
542 private final double minValue;
543 private double maxValue;
545 private String toString = null;
548 private int firing = 0; // >0 when model itself is sending events
551 // Used to differentiate changes in valueName and other changes in the component:
552 private double lastValue = 0;
553 private boolean lastAutomatic = false;
555 private Invalidator invalidator = new Invalidator(this);
559 * Generate a DoubleModel that contains an internal double value.
561 * @param value the initial value.
563 public DoubleModel(double value) {
564 this(value, UnitGroup.UNITS_NONE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
568 * Generate a DoubleModel that contains an internal double value.
570 * @param value the initial value.
571 * @param unit the unit for the value.
573 public DoubleModel(double value, UnitGroup unit) {
574 this(value, unit, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
578 * Generate a DoubleModel that contains an internal double value.
580 * @param value the initial value.
581 * @param unit the unit for the value.
582 * @param min minimum value.
584 public DoubleModel(double value, UnitGroup unit, double min) {
585 this(value, unit, min, Double.POSITIVE_INFINITY);
589 * Generate a DoubleModel that contains an internal double value.
591 * @param value the initial value.
592 * @param unit the unit for the value.
593 * @param min minimum value.
594 * @param max maximum value.
596 public DoubleModel(double value, UnitGroup unit, double min, double max) {
597 this.lastValue = value;
602 valueName = "Constant value";
605 getMethod = setMethod = null;
606 getAutoMethod = setAutoMethod = null;
608 currentUnit = units.getDefaultUnit();
613 * Generates a new DoubleModel that changes the values of the specified component.
614 * The double value is read and written using the methods "get"/"set" + valueName.
616 * @param source Component whose parameter to use.
617 * @param valueName Name of methods used to get/set the parameter.
618 * @param multiplier Value shown by the model is the value from component.getXXX * multiplier
619 * @param min Minimum value allowed (in SI units)
620 * @param max Maximum value allowed (in SI units)
622 public DoubleModel(ChangeSource source, String valueName, double multiplier, UnitGroup unit,
623 double min, double max) {
624 this.source = source;
625 this.valueName = valueName;
626 this.multiplier = multiplier;
629 currentUnit = units.getDefaultUnit();
635 getMethod = source.getClass().getMethod("get" + valueName);
636 } catch (NoSuchMethodException e) {
637 throw new IllegalArgumentException("get method for value '" + valueName +
638 "' not present in class " + source.getClass().getCanonicalName());
643 s = source.getClass().getMethod("set" + valueName, double.class);
644 } catch (NoSuchMethodException e1) {
648 // Automatic selection methods
650 Method set = null, get = null;
653 get = source.getClass().getMethod("is" + valueName + "Automatic");
654 set = source.getClass().getMethod("set" + valueName + "Automatic", boolean.class);
655 } catch (NoSuchMethodException e) {
658 if (set != null && get != null) {
662 getAutoMethod = null;
663 setAutoMethod = null;
668 public DoubleModel(ChangeSource source, String valueName, double multiplier, UnitGroup unit,
670 this(source, valueName, multiplier, unit, min, Double.POSITIVE_INFINITY);
673 public DoubleModel(ChangeSource source, String valueName, double multiplier, UnitGroup unit) {
674 this(source, valueName, multiplier, unit, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
677 public DoubleModel(ChangeSource source, String valueName, UnitGroup unit,
678 double min, double max) {
679 this(source, valueName, 1.0, unit, min, max);
682 public DoubleModel(ChangeSource source, String valueName, UnitGroup unit, double min) {
683 this(source, valueName, 1.0, unit, min, Double.POSITIVE_INFINITY);
686 public DoubleModel(ChangeSource source, String valueName, UnitGroup unit) {
687 this(source, valueName, 1.0, unit, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
690 public DoubleModel(ChangeSource source, String valueName) {
691 this(source, valueName, 1.0, UnitGroup.UNITS_NONE,
692 Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
695 public DoubleModel(ChangeSource source, String valueName, double min) {
696 this(source, valueName, 1.0, UnitGroup.UNITS_NONE, min, Double.POSITIVE_INFINITY);
699 public DoubleModel(ChangeSource source, String valueName, double min, double max) {
700 this(source, valueName, 1.0, UnitGroup.UNITS_NONE, min, max);
706 * Returns the value of the variable (in SI units).
708 public double getValue() {
709 if (getMethod == null) // Constant value
713 return (Double) getMethod.invoke(source) * multiplier;
714 } catch (IllegalArgumentException e) {
715 throw new BugException("Unable to invoke getMethod of " + this, e);
716 } catch (IllegalAccessException e) {
717 throw new BugException("Unable to invoke getMethod of " + this, e);
718 } catch (InvocationTargetException e) {
719 throw Reflection.handleWrappedException(e);
724 * Sets the value of the variable.
725 * @param v New value for parameter in SI units.
727 public void setValue(double v) {
730 log.debug("Setting value " + v + " for " + this);
731 if (setMethod == null) {
732 if (getMethod != null) {
733 throw new BugException("setMethod not available for variable '" + valueName +
734 "' in class " + source.getClass().getCanonicalName());
742 setMethod.invoke(source, v / multiplier);
743 } catch (IllegalArgumentException e) {
744 throw new BugException("Unable to invoke setMethod of " + this, e);
745 } catch (IllegalAccessException e) {
746 throw new BugException("Unable to invoke setMethod of " + this, e);
747 } catch (InvocationTargetException e) {
748 throw Reflection.handleWrappedException(e);
753 * Returns whether setting the value automatically is available.
755 public boolean isAutomaticAvailable() {
756 return (getAutoMethod != null) && (setAutoMethod != null);
760 * Returns whether the value is currently being set automatically.
761 * Returns false if automatic setting is not available at all.
763 public boolean isAutomatic() {
764 if (getAutoMethod == null)
768 return (Boolean) getAutoMethod.invoke(source);
769 } catch (IllegalArgumentException e) {
770 throw new BugException("Method call failed", e);
771 } catch (IllegalAccessException e) {
772 throw new BugException("Method call failed", e);
773 } catch (InvocationTargetException e) {
774 throw Reflection.handleWrappedException(e);
779 * Sets whether the value should be set automatically. Simply fires a
780 * state change event if automatic setting is not available.
782 public void setAutomatic(boolean auto) {
785 if (setAutoMethod == null) {
786 log.debug("Setting automatic to " + auto + " for " + this + ", automatic not available");
787 fireStateChanged(); // in case something is out-of-sync
791 log.debug("Setting automatic to " + auto + " for " + this);
792 lastAutomatic = auto;
794 setAutoMethod.invoke(source, auto);
795 } catch (IllegalArgumentException e) {
796 throw new BugException(e);
797 } catch (IllegalAccessException e) {
798 throw new BugException(e);
799 } catch (InvocationTargetException e) {
800 throw Reflection.handleWrappedException(e);
806 * Returns the current Unit. At the beginning it is the default unit of the UnitGroup.
807 * @return The most recently set unit.
809 public Unit getCurrentUnit() {
814 * Sets the current Unit. The unit must be one of those included in the UnitGroup.
815 * @param u The unit to set active.
817 public void setCurrentUnit(Unit u) {
819 if (currentUnit == u)
821 log.debug("Setting unit for " + this + " to '" + u + "'");
828 * Returns the UnitGroup associated with the parameter value.
830 * @return The UnitGroup given to the constructor.
832 public UnitGroup getUnitGroup() {
839 * Add a listener to the model. Adds the model as a listener to the value source if this
840 * is the first listener.
841 * @param l Listener to add.
844 public void addChangeListener(EventListener l) {
847 if (listeners.isEmpty()) {
848 if (source != null) {
849 source.addChangeListener(this);
850 lastValue = getValue();
851 lastAutomatic = isAutomatic();
856 log.verbose(this + " adding listener (total " + listeners.size() + "): " + l);
860 * Remove a listener from the model. Removes the model from being a listener to the Component
861 * if this was the last listener of the model.
862 * @param l Listener to remove.
865 public void removeChangeListener(EventListener l) {
869 if (listeners.isEmpty() && source != null) {
870 source.removeChangeListener(this);
872 log.verbose(this + " removing listener (total " + listeners.size() + "): " + l);
877 * Invalidates this model by removing all listeners and removing this from
878 * listening to the source. After invalidation no listeners can be added to this
879 * model and the value cannot be set.
882 public void invalidate() {
883 log.verbose("Invalidating " + this);
884 invalidator.invalidate();
886 if (!listeners.isEmpty()) {
887 log.warn("Invalidating " + this + " while still having listeners " + listeners);
890 if (source != null) {
891 source.removeChangeListener(this);
893 MemoryManagement.collectable(this);
897 private void checkState(boolean error) {
898 invalidator.check(error);
903 protected void finalize() throws Throwable {
905 if (!listeners.isEmpty()) {
906 log.warn(this + " being garbage-collected while having listeners " + listeners);
912 * Fire a ChangeEvent to all listeners.
914 protected void fireStateChanged() {
917 EventObject event = new EventObject(this);
918 ChangeEvent cevent = new ChangeEvent(this);
920 // Copy the list before iterating to prevent concurrent modification exceptions.
921 EventListener[] ls = listeners.toArray(new EventListener[0]);
922 for (EventListener l : ls) {
923 if ( l instanceof StateChangeListener ) {
924 ((StateChangeListener)l).stateChanged(event);
925 } else if ( l instanceof ChangeListener ) {
926 ((ChangeListener)l).stateChanged(cevent);
933 * Called when the component changes. Checks whether the modeled value has changed, and if
934 * it has, updates lastValue and generates ChangeEvents for all listeners of the model.
937 public void stateChanged(EventObject e) {
940 double v = getValue();
941 boolean b = isAutomatic();
942 if (lastValue == v && lastAutomatic == b)
951 * Explain the DoubleModel as a String.
954 public String toString() {
955 if (toString == null) {
956 if (source == null) {
957 toString = "DoubleModel[constant=" + lastValue + "]";
959 toString = "DoubleModel[" + source.getClass().getSimpleName() + ":" + valueName + "]";