Undo/redo system enhancements, DnD for component tree, bug fixes
[debian/openrocket] / src / net / sf / openrocket / gui / plot / PlotDialog.java
1 package net.sf.openrocket.gui.plot;
2
3 import java.awt.AlphaComposite;
4 import java.awt.BasicStroke;
5 import java.awt.Color;
6 import java.awt.Composite;
7 import java.awt.Font;
8 import java.awt.Graphics2D;
9 import java.awt.Image;
10 import java.awt.Window;
11 import java.awt.event.ActionEvent;
12 import java.awt.event.ActionListener;
13 import java.awt.geom.Line2D;
14 import java.awt.geom.Point2D;
15 import java.awt.geom.Rectangle2D;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Map;
24
25 import javax.imageio.ImageIO;
26 import javax.swing.BorderFactory;
27 import javax.swing.JButton;
28 import javax.swing.JCheckBox;
29 import javax.swing.JDialog;
30 import javax.swing.JPanel;
31
32 import net.miginfocom.swing.MigLayout;
33 import net.sf.openrocket.document.Simulation;
34 import net.sf.openrocket.simulation.FlightDataBranch;
35 import net.sf.openrocket.simulation.FlightDataType;
36 import net.sf.openrocket.simulation.FlightEvent;
37 import net.sf.openrocket.unit.Unit;
38 import net.sf.openrocket.unit.UnitGroup;
39 import net.sf.openrocket.util.BugException;
40 import net.sf.openrocket.util.GUIUtil;
41 import net.sf.openrocket.util.MathUtil;
42 import net.sf.openrocket.util.Prefs;
43
44 import org.jfree.chart.ChartFactory;
45 import org.jfree.chart.ChartPanel;
46 import org.jfree.chart.JFreeChart;
47 import org.jfree.chart.annotations.XYImageAnnotation;
48 import org.jfree.chart.axis.NumberAxis;
49 import org.jfree.chart.axis.ValueAxis;
50 import org.jfree.chart.plot.Marker;
51 import org.jfree.chart.plot.PlotOrientation;
52 import org.jfree.chart.plot.ValueMarker;
53 import org.jfree.chart.plot.XYPlot;
54 import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
55 import org.jfree.chart.title.TextTitle;
56 import org.jfree.data.Range;
57 import org.jfree.data.xy.XYSeries;
58 import org.jfree.data.xy.XYSeriesCollection;
59 import org.jfree.text.TextUtilities;
60 import org.jfree.ui.LengthAdjustmentType;
61 import org.jfree.ui.RectangleAnchor;
62 import org.jfree.ui.TextAnchor;
63
64 public class PlotDialog extends JDialog {
65         
66         private static final float PLOT_STROKE_WIDTH = 1.5f;
67         
68         private static final Color DEFAULT_EVENT_COLOR = new Color(0, 0, 0);
69         private static final Map<FlightEvent.Type, Color> EVENT_COLORS =
70                         new HashMap<FlightEvent.Type, Color>();
71         static {
72                 EVENT_COLORS.put(FlightEvent.Type.LAUNCH, new Color(255, 0, 0));
73                 EVENT_COLORS.put(FlightEvent.Type.LIFTOFF, new Color(0, 80, 196));
74                 EVENT_COLORS.put(FlightEvent.Type.LAUNCHROD, new Color(0, 100, 80));
75                 EVENT_COLORS.put(FlightEvent.Type.IGNITION, new Color(230, 130, 15));
76                 EVENT_COLORS.put(FlightEvent.Type.BURNOUT, new Color(80, 55, 40));
77                 EVENT_COLORS.put(FlightEvent.Type.EJECTION_CHARGE, new Color(80, 55, 40));
78                 EVENT_COLORS.put(FlightEvent.Type.STAGE_SEPARATION, new Color(80, 55, 40));
79                 EVENT_COLORS.put(FlightEvent.Type.APOGEE, new Color(15, 120, 15));
80                 EVENT_COLORS.put(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, new Color(0, 0, 128));
81                 EVENT_COLORS.put(FlightEvent.Type.GROUND_HIT, new Color(0, 0, 0));
82                 EVENT_COLORS.put(FlightEvent.Type.SIMULATION_END, new Color(128, 0, 0));
83         }
84         
85         private static final Map<FlightEvent.Type, Image> EVENT_IMAGES =
86                         new HashMap<FlightEvent.Type, Image>();
87         static {
88                 loadImage(FlightEvent.Type.LAUNCH, "pix/eventicons/event-launch.png");
89                 loadImage(FlightEvent.Type.LIFTOFF, "pix/eventicons/event-liftoff.png");
90                 loadImage(FlightEvent.Type.LAUNCHROD, "pix/eventicons/event-launchrod.png");
91                 loadImage(FlightEvent.Type.IGNITION, "pix/eventicons/event-ignition.png");
92                 loadImage(FlightEvent.Type.BURNOUT, "pix/eventicons/event-burnout.png");
93                 loadImage(FlightEvent.Type.EJECTION_CHARGE, "pix/eventicons/event-ejection-charge.png");
94                 loadImage(FlightEvent.Type.STAGE_SEPARATION,
95                                 "pix/eventicons/event-stage-separation.png");
96                 loadImage(FlightEvent.Type.APOGEE, "pix/eventicons/event-apogee.png");
97                 loadImage(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT,
98                                 "pix/eventicons/event-recovery-device-deployment.png");
99                 loadImage(FlightEvent.Type.GROUND_HIT, "pix/eventicons/event-ground-hit.png");
100                 loadImage(FlightEvent.Type.SIMULATION_END, "pix/eventicons/event-simulation-end.png");
101         }
102         
103         private static void loadImage(FlightEvent.Type type, String file) {
104                 InputStream is;
105                 
106                 is = ClassLoader.getSystemResourceAsStream(file);
107                 if (is == null) {
108                         System.out.println("ERROR: File " + file + " not found!");
109                         return;
110                 }
111                 
112                 try {
113                         Image image = ImageIO.read(is);
114                         EVENT_IMAGES.put(type, image);
115                 } catch (IOException ignore) {
116                         ignore.printStackTrace();
117                 }
118         }
119         
120         
121
122
123         private final List<ModifiedXYItemRenderer> renderers =
124                         new ArrayList<ModifiedXYItemRenderer>();
125         
126         private PlotDialog(Window parent, Simulation simulation, PlotConfiguration config) {
127                 super(parent, "Flight data plot");
128                 this.setModalityType(ModalityType.DOCUMENT_MODAL);
129                 
130                 final boolean initialShowPoints = Prefs.getBoolean(Prefs.PLOT_SHOW_POINTS, false);
131                 
132
133                 // Fill the auto-selections
134                 FlightDataBranch branch = simulation.getSimulatedData().getBranch(0);
135                 PlotConfiguration filled = config.fillAutoAxes(branch);
136                 List<Axis> axes = filled.getAllAxes();
137                 
138
139                 // Create the data series for both axes
140                 XYSeriesCollection[] data = new XYSeriesCollection[2];
141                 data[0] = new XYSeriesCollection();
142                 data[1] = new XYSeriesCollection();
143                 
144
145                 // Get the domain axis type
146                 final FlightDataType domainType = filled.getDomainAxisType();
147                 final Unit domainUnit = filled.getDomainAxisUnit();
148                 if (domainType == null) {
149                         throw new IllegalArgumentException("Domain axis type not specified.");
150                 }
151                 List<Double> x = branch.get(domainType);
152                 
153
154                 // Get plot length (ignore trailing NaN's)
155                 int typeCount = filled.getTypeCount();
156                 int dataLength = 0;
157                 for (int i = 0; i < typeCount; i++) {
158                         FlightDataType type = filled.getType(i);
159                         List<Double> y = branch.get(type);
160                         
161                         for (int j = dataLength; j < y.size(); j++) {
162                                 if (!Double.isNaN(y.get(j)) && !Double.isInfinite(y.get(j)))
163                                         dataLength = j;
164                         }
165                 }
166                 dataLength = Math.min(dataLength, x.size());
167                 
168
169                 // Create the XYSeries objects from the flight data and store into the collections
170                 String[] axisLabel = new String[2];
171                 for (int i = 0; i < typeCount; i++) {
172                         // Get info
173                         FlightDataType type = filled.getType(i);
174                         Unit unit = filled.getUnit(i);
175                         int axis = filled.getAxis(i);
176                         String name = getLabel(type, unit);
177                         
178                         // Store data in provided units
179                         List<Double> y = branch.get(type);
180                         XYSeries series = new XYSeries(name, false, true);
181                         for (int j = 0; j < dataLength; j++) {
182                                 series.add(domainUnit.toUnit(x.get(j)), unit.toUnit(y.get(j)));
183                         }
184                         data[axis].addSeries(series);
185                         
186                         // Update axis label
187                         if (axisLabel[axis] == null)
188                                 axisLabel[axis] = type.getName();
189                         else
190                                 axisLabel[axis] += "; " + type.getName();
191                 }
192                 
193
194                 // Create the chart using the factory to get all default settings
195                 JFreeChart chart = ChartFactory.createXYLineChart(
196                                 "Simulated flight",
197                                 null,
198                                 null,
199                                 null,
200                                 PlotOrientation.VERTICAL,
201                                 true,
202                                 true,
203                                 false
204                                 );
205                 
206                 chart.addSubtitle(new TextTitle(config.getName()));
207                 
208                 // Add the data and formatting to the plot
209                 XYPlot plot = chart.getXYPlot();
210                 int axisno = 0;
211                 for (int i = 0; i < 2; i++) {
212                         // Check whether axis has any data
213                         if (data[i].getSeriesCount() > 0) {
214                                 // Create and set axis
215                                 double min = axes.get(i).getMinValue();
216                                 double max = axes.get(i).getMaxValue();
217                                 NumberAxis axis = new PresetNumberAxis(min, max);
218                                 axis.setLabel(axisLabel[i]);
219                                 //                              axis.setRange(axes.get(i).getMinValue(), axes.get(i).getMaxValue());
220                                 plot.setRangeAxis(axisno, axis);
221                                 
222                                 // Add data and map to the axis
223                                 plot.setDataset(axisno, data[i]);
224                                 ModifiedXYItemRenderer r = new ModifiedXYItemRenderer();
225                                 r.setBaseShapesVisible(initialShowPoints);
226                                 r.setBaseShapesFilled(true);
227                                 for (int j = 0; j < data[i].getSeriesCount(); j++) {
228                                         r.setSeriesStroke(j, new BasicStroke(PLOT_STROKE_WIDTH));
229                                 }
230                                 renderers.add(r);
231                                 plot.setRenderer(axisno, r);
232                                 plot.mapDatasetToRangeAxis(axisno, axisno);
233                                 axisno++;
234                         }
235                 }
236                 
237                 plot.getDomainAxis().setLabel(getLabel(domainType, domainUnit));
238                 plot.addDomainMarker(new ValueMarker(0));
239                 plot.addRangeMarker(new ValueMarker(0));
240                 
241
242
243                 // Create list of events to show (combine event too close to each other)
244                 ArrayList<Double> timeList = new ArrayList<Double>();
245                 ArrayList<String> eventList = new ArrayList<String>();
246                 ArrayList<Color> colorList = new ArrayList<Color>();
247                 ArrayList<Image> imageList = new ArrayList<Image>();
248                 
249                 HashSet<FlightEvent.Type> typeSet = new HashSet<FlightEvent.Type>();
250                 
251                 double prevTime = -100;
252                 String text = null;
253                 Color color = null;
254                 Image image = null;
255                 
256                 List<FlightEvent> events = branch.getEvents();
257                 for (int i = 0; i < events.size(); i++) {
258                         FlightEvent event = events.get(i);
259                         double t = event.getTime();
260                         FlightEvent.Type type = event.getType();
261                         
262                         if (type != FlightEvent.Type.ALTITUDE && config.isEventActive(type)) {
263                                 if (Math.abs(t - prevTime) <= 0.01) {
264                                         
265                                         if (!typeSet.contains(type)) {
266                                                 text = text + ", " + type.toString();
267                                                 color = getEventColor(type);
268                                                 image = EVENT_IMAGES.get(type);
269                                                 typeSet.add(type);
270                                         }
271                                         
272                                 } else {
273                                         
274                                         if (text != null) {
275                                                 timeList.add(prevTime);
276                                                 eventList.add(text);
277                                                 colorList.add(color);
278                                                 imageList.add(image);
279                                         }
280                                         prevTime = t;
281                                         text = type.toString();
282                                         color = getEventColor(type);
283                                         image = EVENT_IMAGES.get(type);
284                                         typeSet.clear();
285                                         typeSet.add(type);
286                                         
287                                 }
288                         }
289                 }
290                 if (text != null) {
291                         timeList.add(prevTime);
292                         eventList.add(text);
293                         colorList.add(color);
294                         imageList.add(image);
295                 }
296                 
297
298                 // Create the event markers
299                 
300                 if (config.getDomainAxisType() == FlightDataType.TYPE_TIME) {
301                         
302                         // Domain time is plotted as vertical markers
303                         for (int i = 0; i < eventList.size(); i++) {
304                                 double t = timeList.get(i);
305                                 String event = eventList.get(i);
306                                 color = colorList.get(i);
307                                 
308                                 ValueMarker m = new ValueMarker(t);
309                                 m.setLabel(event);
310                                 m.setPaint(color);
311                                 m.setLabelPaint(color);
312                                 m.setAlpha(0.7f);
313                                 plot.addDomainMarker(m);
314                         }
315                         
316                 } else {
317                         
318                         // Other domains are plotted as image annotations
319                         List<Double> time = branch.get(FlightDataType.TYPE_TIME);
320                         List<Double> domain = branch.get(config.getDomainAxisType());
321                         
322                         for (int i = 0; i < eventList.size(); i++) {
323                                 final double t = timeList.get(i);
324                                 String event = eventList.get(i);
325                                 image = imageList.get(i);
326                                 
327                                 if (image == null)
328                                         continue;
329                                 
330                                 // Calculate index and interpolation position a
331                                 final double a;
332                                 int tindex = Collections.binarySearch(time, t);
333                                 if (tindex < 0) {
334                                         tindex = -tindex - 1;
335                                 }
336                                 if (tindex >= time.size()) {
337                                         // index greater than largest value in time list
338                                         tindex = time.size() - 1;
339                                         a = 0;
340                                 } else if (tindex <= 0) {
341                                         // index smaller than smallest value in time list
342                                         tindex = 0;
343                                         a = 0;
344                                 } else {
345                                         tindex--;
346                                         double t1 = time.get(tindex);
347                                         double t2 = time.get(tindex + 1);
348                                         
349                                         if ((t1 > t) || (t2 < t)) {
350                                                 throw new BugException("t1=" + t1 + " t2=" + t2 + " t=" + t);
351                                         }
352                                         
353                                         if (MathUtil.equals(t1, t2)) {
354                                                 a = 0;
355                                         } else {
356                                                 a = 1 - (t - t1) / (t2 - t1);
357                                         }
358                                 }
359                                 
360                                 final double xcoord;
361                                 if (a == 0) {
362                                         xcoord = domain.get(tindex);
363                                 } else {
364                                         xcoord = a * domain.get(tindex) + (1 - a) * domain.get(tindex + 1);
365                                 }
366                                 
367                                 for (int index = 0; index < config.getTypeCount(); index++) {
368                                         FlightDataType type = config.getType(index);
369                                         List<Double> range = branch.get(type);
370                                         
371                                         final double ycoord;
372                                         if (a == 0) {
373                                                 ycoord = range.get(tindex);
374                                         } else {
375                                                 ycoord = a * range.get(tindex) + (1 - a) * range.get(tindex + 1);
376                                         }
377                                         
378                                         XYImageAnnotation annotation =
379                                                         new XYImageAnnotation(xcoord, ycoord, image, RectangleAnchor.CENTER);
380                                         annotation.setToolTipText(event);
381                                         plot.addAnnotation(annotation);
382                                 }
383                         }
384                 }
385                 
386
387                 // Create the dialog
388                 
389                 JPanel panel = new JPanel(new MigLayout("fill"));
390                 this.add(panel);
391                 
392                 ChartPanel chartPanel = new ChartPanel(chart,
393                                 false, // properties
394                                 true, // save
395                                 false, // print
396                                 true, // zoom
397                                 true); // tooltips
398                 chartPanel.setMouseWheelEnabled(true);
399                 chartPanel.setEnforceFileExtensions(true);
400                 chartPanel.setInitialDelay(500);
401                 
402                 chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
403                 
404                 panel.add(chartPanel, "grow, wrap 20lp");
405                 
406                 final JCheckBox check = new JCheckBox("Show data points");
407                 check.setSelected(initialShowPoints);
408                 check.addActionListener(new ActionListener() {
409                         @Override
410                         public void actionPerformed(ActionEvent e) {
411                                 boolean show = check.isSelected();
412                                 Prefs.putBoolean(Prefs.PLOT_SHOW_POINTS, show);
413                                 for (ModifiedXYItemRenderer r : renderers) {
414                                         r.setBaseShapesVisible(show);
415                                 }
416                         }
417                 });
418                 panel.add(check, "split, left");
419                 
420                 panel.add(new JPanel(), "growx");
421                 
422                 JButton button = new JButton("Close");
423                 button.addActionListener(new ActionListener() {
424                         @Override
425                         public void actionPerformed(ActionEvent e) {
426                                 PlotDialog.this.dispose();
427                         }
428                 });
429                 panel.add(button, "right");
430                 
431                 this.setLocationByPlatform(true);
432                 this.pack();
433                 
434                 GUIUtil.setDisposableDialogOptions(this, button);
435         }
436         
437         
438         private String getLabel(FlightDataType type, Unit unit) {
439                 String name = type.getName();
440                 if (unit != null && !UnitGroup.UNITS_NONE.contains(unit) &&
441                                 !UnitGroup.UNITS_COEFFICIENT.contains(unit) && unit.getUnit().length() > 0)
442                         name += " (" + unit.getUnit() + ")";
443                 return name;
444         }
445         
446         
447
448         private class PresetNumberAxis extends NumberAxis {
449                 private final double min;
450                 private final double max;
451                 
452                 public PresetNumberAxis(double min, double max) {
453                         this.min = min;
454                         this.max = max;
455                         autoAdjustRange();
456                 }
457                 
458                 @Override
459                 protected void autoAdjustRange() {
460                         this.setRange(min, max);
461                 }
462         }
463         
464         
465         /**
466          * Static method that shows a plot with the specified parameters.
467          * 
468          * @param parent                the parent window, which will be blocked.
469          * @param simulation    the simulation to plot.
470          * @param config                the configuration of the plot.
471          */
472         public static void showPlot(Window parent, Simulation simulation, PlotConfiguration config) {
473                 new PlotDialog(parent, simulation, config).setVisible(true);
474         }
475         
476         
477
478         private static Color getEventColor(FlightEvent.Type type) {
479                 Color c = EVENT_COLORS.get(type);
480                 if (c != null)
481                         return c;
482                 return DEFAULT_EVENT_COLOR;
483         }
484         
485         
486
487
488
489         /**
490          * A modification to the standard renderer that renders the domain marker
491          * labels vertically instead of horizontally.
492          */
493         private static class ModifiedXYItemRenderer extends StandardXYItemRenderer {
494                 
495                 @Override
496                 public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis domainAxis,
497                                 Marker marker, Rectangle2D dataArea) {
498                         
499                         if (!(marker instanceof ValueMarker)) {
500                                 // Use parent for all others
501                                 super.drawDomainMarker(g2, plot, domainAxis, marker, dataArea);
502                                 return;
503                         }
504                         
505                         /*
506                          * Draw the normal marker, but with rotated text.
507                          * Copied from the overridden method.
508                          */
509                         ValueMarker vm = (ValueMarker) marker;
510                         double value = vm.getValue();
511                         Range range = domainAxis.getRange();
512                         if (!range.contains(value)) {
513                                 return;
514                         }
515                         
516                         double v = domainAxis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge());
517                         
518                         PlotOrientation orientation = plot.getOrientation();
519                         Line2D line = null;
520                         if (orientation == PlotOrientation.HORIZONTAL) {
521                                 line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v);
522                         } else {
523                                 line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY());
524                         }
525                         
526                         final Composite originalComposite = g2.getComposite();
527                         g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, marker
528                                         .getAlpha()));
529                         g2.setPaint(marker.getPaint());
530                         g2.setStroke(marker.getStroke());
531                         g2.draw(line);
532                         
533                         String label = marker.getLabel();
534                         RectangleAnchor anchor = marker.getLabelAnchor();
535                         if (label != null) {
536                                 Font labelFont = marker.getLabelFont();
537                                 g2.setFont(labelFont);
538                                 g2.setPaint(marker.getLabelPaint());
539                                 Point2D coordinates = calculateDomainMarkerTextAnchorPoint(g2,
540                                                 orientation, dataArea, line.getBounds2D(), marker
541                                                                 .getLabelOffset(), LengthAdjustmentType.EXPAND, anchor);
542                                 
543                                 // Changed:
544                                 TextAnchor textAnchor = TextAnchor.TOP_RIGHT;
545                                 TextUtilities.drawRotatedString(label, g2, (float) coordinates.getX() + 2,
546                                                 (float) coordinates.getY(), textAnchor,
547                                                 -Math.PI / 2, textAnchor);
548                         }
549                         g2.setComposite(originalComposite);
550                 }
551                 
552         }
553         
554 }