001    /* ===========================================================
002     * JFreeChart : a free chart library for the Java(tm) platform
003     * ===========================================================
004     *
005     * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors.
006     *
007     * Project Info:  http://www.jfree.org/jfreechart/index.html
008     *
009     * This library is free software; you can redistribute it and/or modify it 
010     * under the terms of the GNU Lesser General Public License as published by 
011     * the Free Software Foundation; either version 2.1 of the License, or 
012     * (at your option) any later version.
013     *
014     * This library is distributed in the hope that it will be useful, but 
015     * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
016     * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
017     * License for more details.
018     *
019     * You should have received a copy of the GNU Lesser General Public
020     * License along with this library; if not, write to the Free Software
021     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
022     * USA.  
023     *
024     * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
025     * in the United States and other countries.]
026     *
027     * -------------------
028     * XYAreaRenderer.java
029     * -------------------
030     * (C) Copyright 2002-2007, by Hari and Contributors.
031     *
032     * Original Author:  Hari (ourhari@hotmail.com);
033     * Contributor(s):   David Gilbert (for Object Refinery Limited);
034     *                   Richard Atkinson;
035     *                   Christian W. Zuckschwerdt;
036     *
037     * $Id: XYAreaRenderer.java,v 1.12.2.11 2007/05/18 10:28:31 mungady Exp $
038     *
039     * Changes:
040     * --------
041     * 03-Apr-2002 : Version 1, contributed by Hari.  This class is based on the 
042     *               StandardXYItemRenderer class (DG);
043     * 09-Apr-2002 : Removed the translated zero from the drawItem method - 
044     *               overridden the initialise() method to calculate it (DG);
045     * 30-May-2002 : Added tool tip generator to constructor to match super 
046     *               class (DG);
047     * 25-Jun-2002 : Removed unnecessary local variable (DG);
048     * 05-Aug-2002 : Small modification to drawItem method to support URLs for HTML
049     *               image maps (RA);
050     * 01-Oct-2002 : Fixed errors reported by Checkstyle (DG);
051     * 07-Nov-2002 : Renamed AreaXYItemRenderer --> XYAreaRenderer (DG);
052     * 25-Mar-2003 : Implemented Serializable (DG);
053     * 01-May-2003 : Modified drawItem() method signature (DG);
054     * 27-Jul-2003 : Made line and polygon properties protected rather than 
055     *               private (RA);
056     * 30-Jul-2003 : Modified entity constructor (CZ);
057     * 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
058     * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
059     * 07-Oct-2003 : Added renderer state (DG);
060     * 08-Dec-2003 : Modified hotspot for chart entity (DG);
061     * 10-Feb-2004 : Changed the drawItem() method to make cut-and-paste overriding
062     *               easier.  Also moved state class into this class (DG);
063     * 25-Feb-2004 : Replaced CrosshairInfo with CrosshairState.  Renamed 
064     *               XYToolTipGenerator --> XYItemLabelGenerator (DG);
065     * 15-Jul-2004 : Switched getX() with getXValue() and getY() with 
066     *               getYValue() (DG);
067     * 11-Nov-2004 : Now uses ShapeUtilities to translate shapes (DG);
068     * 19-Jan-2005 : Now accesses primitives only from dataset (DG);
069     * 21-Mar-2005 : Override getLegendItem() and equals() methods (DG);
070     * 20-Apr-2005 : Use generators for legend tooltips and URLs (DG);
071     * ------------- JFREECHART 1.0.x ---------------------------------------------
072     * 06-Feb-2007 : Fixed bug 1086307, crosshairs with multiple axes (DG);
073     * 14-Feb-2007 : Fixed bug in clone() (DG);
074     * 20-Apr-2007 : Updated getLegendItem() for renderer change (DG);
075     * 04-May-2007 : Set processVisibleItemsOnly flag to false (DG);
076     * 17-May-2007 : Set datasetIndex and seriesIndex in getLegendItem() (DG);
077     * 18-May-2007 : Set dataset and seriesKey for LegendItem (DG);
078     * 
079     */
080    
081    package org.jfree.chart.renderer.xy;
082    
083    import java.awt.Graphics2D;
084    import java.awt.Paint;
085    import java.awt.Polygon;
086    import java.awt.Shape;
087    import java.awt.Stroke;
088    import java.awt.geom.GeneralPath;
089    import java.awt.geom.Line2D;
090    import java.awt.geom.Rectangle2D;
091    import java.io.IOException;
092    import java.io.ObjectInputStream;
093    import java.io.ObjectOutputStream;
094    import java.io.Serializable;
095    
096    import org.jfree.chart.LegendItem;
097    import org.jfree.chart.axis.ValueAxis;
098    import org.jfree.chart.entity.EntityCollection;
099    import org.jfree.chart.entity.XYItemEntity;
100    import org.jfree.chart.event.RendererChangeEvent;
101    import org.jfree.chart.labels.XYSeriesLabelGenerator;
102    import org.jfree.chart.labels.XYToolTipGenerator;
103    import org.jfree.chart.plot.CrosshairState;
104    import org.jfree.chart.plot.PlotOrientation;
105    import org.jfree.chart.plot.PlotRenderingInfo;
106    import org.jfree.chart.plot.XYPlot;
107    import org.jfree.chart.urls.XYURLGenerator;
108    import org.jfree.data.xy.XYDataset;
109    import org.jfree.io.SerialUtilities;
110    import org.jfree.util.PublicCloneable;
111    import org.jfree.util.ShapeUtilities;
112    
113    /**
114     * Area item renderer for an {@link XYPlot}.  This class can draw (a) shapes at
115     * each point, or (b) lines between points, or (c) both shapes and lines, 
116     * or (d) filled areas, or (e) filled areas and shapes.
117     */
118    public class XYAreaRenderer extends AbstractXYItemRenderer 
119                                implements XYItemRenderer, 
120                                           Cloneable,
121                                           PublicCloneable,
122                                           Serializable {
123    
124        /** For serialization. */
125        private static final long serialVersionUID = -4481971353973876747L;
126        
127        /**
128         * A state object used by this renderer.
129         */
130        static class XYAreaRendererState extends XYItemRendererState {
131            
132            /** Working storage for the area under one series. */
133            public Polygon area;
134            
135            /** Working line that can be recycled. */
136            public Line2D line;
137            
138            /**
139             * Creates a new state.
140             * 
141             * @param info  the plot rendering info.
142             */
143            public XYAreaRendererState(PlotRenderingInfo info) {
144                super(info);
145                this.area = new Polygon();
146                this.line = new Line2D.Double();
147            }
148            
149        }
150        
151        /** Useful constant for specifying the type of rendering (shapes only). */
152        public static final int SHAPES = 1;
153    
154        /** Useful constant for specifying the type of rendering (lines only). */
155        public static final int LINES = 2;
156    
157        /** 
158         * Useful constant for specifying the type of rendering (shapes and lines).
159         */
160        public static final int SHAPES_AND_LINES = 3;
161    
162        /** Useful constant for specifying the type of rendering (area only). */
163        public static final int AREA = 4;
164    
165        /** 
166         * Useful constant for specifying the type of rendering (area and shapes). 
167         */
168        public static final int AREA_AND_SHAPES = 5;
169    
170        /** A flag indicating whether or not shapes are drawn at each XY point. */
171        private boolean plotShapes;
172    
173        /** A flag indicating whether or not lines are drawn between XY points. */
174        private boolean plotLines;
175    
176        /** A flag indicating whether or not Area are drawn at each XY point. */
177        private boolean plotArea;
178    
179        /** A flag that controls whether or not the outline is shown. */
180        private boolean showOutline;
181    
182        /** 
183         * The shape used to represent an area in each legend item (this should 
184         * never be <code>null</code>). 
185         */
186        private transient Shape legendArea;
187    
188        /**
189         * Constructs a new renderer.
190         */
191        public XYAreaRenderer() {
192            this(AREA);
193        }
194    
195        /**
196         * Constructs a new renderer.
197         *
198         * @param type  the type of the renderer.
199         */
200        public XYAreaRenderer(int type) {
201            this(type, null, null);
202        }
203    
204        /**
205         * Constructs a new renderer.  To specify the type of renderer, use one of 
206         * the constants: <code>SHAPES</code>, <code>LINES</code>,
207         * <code>SHAPES_AND_LINES</code>, <code>AREA</code> or 
208         * <code>AREA_AND_SHAPES</code>.
209         *
210         * @param type  the type of renderer.
211         * @param toolTipGenerator  the tool tip generator to use 
212         *                          (<code>null</code> permitted).
213         * @param urlGenerator  the URL generator (<code>null</code> permitted).
214         */
215        public XYAreaRenderer(int type, XYToolTipGenerator toolTipGenerator, 
216                              XYURLGenerator urlGenerator) {
217    
218            super();
219            setBaseToolTipGenerator(toolTipGenerator);
220            setURLGenerator(urlGenerator);
221    
222            if (type == SHAPES) {
223                this.plotShapes = true;
224            }
225            if (type == LINES) {
226                this.plotLines = true;
227            }
228            if (type == SHAPES_AND_LINES) {
229                this.plotShapes = true;
230                this.plotLines = true;
231            }
232            if (type == AREA) {
233                this.plotArea = true;
234            }
235            if (type == AREA_AND_SHAPES) {
236                this.plotArea = true;
237                this.plotShapes = true;
238            }
239            this.showOutline = false;
240            GeneralPath area = new GeneralPath();
241            area.moveTo(0.0f, -4.0f);
242            area.lineTo(3.0f, -2.0f);
243            area.lineTo(4.0f, 4.0f);
244            area.lineTo(-4.0f, 4.0f);
245            area.lineTo(-3.0f, -2.0f);
246            area.closePath();
247            this.legendArea = area;
248    
249        }
250    
251        /**
252         * Returns true if shapes are being plotted by the renderer.
253         *
254         * @return <code>true</code> if shapes are being plotted by the renderer.
255         */
256        public boolean getPlotShapes() {
257            return this.plotShapes;
258        }
259    
260        /**
261         * Returns true if lines are being plotted by the renderer.
262         *
263         * @return <code>true</code> if lines are being plotted by the renderer.
264         */
265        public boolean getPlotLines() {
266            return this.plotLines;
267        }
268    
269        /**
270         * Returns true if Area is being plotted by the renderer.
271         *
272         * @return <code>true</code> if Area is being plotted by the renderer.
273         */
274        public boolean getPlotArea() {
275            return this.plotArea;
276        }
277    
278        /**
279         * Returns a flag that controls whether or not outlines of the areas are 
280         * drawn.
281         *
282         * @return The flag.
283         * 
284         * @see #setOutline(boolean)
285         */
286        public boolean isOutline() {
287            return this.showOutline;
288        }
289    
290        /**
291         * Sets a flag that controls whether or not outlines of the areas are drawn
292         * and sends a {@link RendererChangeEvent} to all registered listeners.
293         *
294         * @param show  the flag.
295         * 
296         * @see #isOutline()
297         */
298        public void setOutline(boolean show) {
299            this.showOutline = show;
300            notifyListeners(new RendererChangeEvent(this));
301        }
302    
303        /**
304         * Returns the shape used to represent an area in the legend.
305         * 
306         * @return The legend area (never <code>null</code>).
307         */
308        public Shape getLegendArea() {
309            return this.legendArea;   
310        }
311        
312        /**
313         * Sets the shape used as an area in each legend item and sends a 
314         * {@link RendererChangeEvent} to all registered listeners.
315         * 
316         * @param area  the area (<code>null</code> not permitted).
317         */
318        public void setLegendArea(Shape area) {
319            if (area == null) {
320                throw new IllegalArgumentException("Null 'area' argument.");   
321            }
322            this.legendArea = area;
323            notifyListeners(new RendererChangeEvent(this));
324        }
325    
326        /**
327         * Initialises the renderer and returns a state object that should be 
328         * passed to all subsequent calls to the drawItem() method.
329         *
330         * @param g2  the graphics device.
331         * @param dataArea  the area inside the axes.
332         * @param plot  the plot.
333         * @param data  the data.
334         * @param info  an optional info collection object to return data back to 
335         *              the caller.
336         *
337         * @return A state object for use by the renderer.
338         */
339        public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea,
340                XYPlot plot, XYDataset data, PlotRenderingInfo info) {
341            XYAreaRendererState state = new XYAreaRendererState(info);
342            
343            // in the rendering process, there is special handling for item 
344            // zero, so we can't support processing of visible data items only
345            state.setProcessVisibleItemsOnly(false);
346            return state;
347        }
348    
349        /**
350         * Returns a default legend item for the specified series.  Subclasses 
351         * should override this method to generate customised items.
352         *
353         * @param datasetIndex  the dataset index (zero-based).
354         * @param series  the series index (zero-based).
355         *
356         * @return A legend item for the series.
357         */
358        public LegendItem getLegendItem(int datasetIndex, int series) {
359            LegendItem result = null;
360            XYPlot xyplot = getPlot();
361            if (xyplot != null) {
362                XYDataset dataset = xyplot.getDataset(datasetIndex);
363                if (dataset != null) {
364                    XYSeriesLabelGenerator lg = getLegendItemLabelGenerator();
365                    String label = lg.generateLabel(dataset, series);
366                    String description = label;
367                    String toolTipText = null;
368                    if (getLegendItemToolTipGenerator() != null) {
369                        toolTipText = getLegendItemToolTipGenerator().generateLabel(
370                                dataset, series);
371                    }
372                    String urlText = null;
373                    if (getLegendItemURLGenerator() != null) {
374                        urlText = getLegendItemURLGenerator().generateLabel(
375                                dataset, series);
376                    }
377                    Paint paint = lookupSeriesPaint(series);
378                    result = new LegendItem(label, description, toolTipText, 
379                            urlText, this.legendArea, paint);
380                    result.setDataset(dataset);
381                    result.setDatasetIndex(datasetIndex);
382                    result.setSeriesKey(dataset.getSeriesKey(series));
383                    result.setSeriesIndex(series);
384                }
385            }
386            return result;
387        }
388    
389        /**
390         * Draws the visual representation of a single data item.
391         *
392         * @param g2  the graphics device.
393         * @param state  the renderer state.
394         * @param dataArea  the area within which the data is being drawn.
395         * @param info  collects information about the drawing.
396         * @param plot  the plot (can be used to obtain standard color information 
397         *              etc).
398         * @param domainAxis  the domain axis.
399         * @param rangeAxis  the range axis.
400         * @param dataset  the dataset.
401         * @param series  the series index (zero-based).
402         * @param item  the item index (zero-based).
403         * @param crosshairState  crosshair information for the plot 
404         *                        (<code>null</code> permitted).
405         * @param pass  the pass index.
406         */
407        public void drawItem(Graphics2D g2, XYItemRendererState state,
408                Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot,
409                ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset,
410                int series, int item, CrosshairState crosshairState, int pass) {
411            
412            if (!getItemVisible(series, item)) {
413                return;   
414            }
415            XYAreaRendererState areaState = (XYAreaRendererState) state;
416            
417            // get the data point...
418            double x1 = dataset.getXValue(series, item);
419            double y1 = dataset.getYValue(series, item);
420            if (Double.isNaN(y1)) {
421                y1 = 0.0;
422            }
423            double transX1 = domainAxis.valueToJava2D(x1, dataArea, 
424                    plot.getDomainAxisEdge());
425            double transY1 = rangeAxis.valueToJava2D(y1, dataArea, 
426                    plot.getRangeAxisEdge());
427            
428            // get the previous point and the next point so we can calculate a 
429            // "hot spot" for the area (used by the chart entity)...
430            int itemCount = dataset.getItemCount(series);
431            double x0 = dataset.getXValue(series, Math.max(item - 1, 0));
432            double y0 = dataset.getYValue(series, Math.max(item - 1, 0));
433            if (Double.isNaN(y0)) {
434                y0 = 0.0;
435            }
436            double transX0 = domainAxis.valueToJava2D(x0, dataArea, 
437                    plot.getDomainAxisEdge());
438            double transY0 = rangeAxis.valueToJava2D(y0, dataArea, 
439                    plot.getRangeAxisEdge());
440            
441            double x2 = dataset.getXValue(series, Math.min(item + 1, 
442                    itemCount - 1));
443            double y2 = dataset.getYValue(series, Math.min(item + 1, 
444                    itemCount - 1));
445            if (Double.isNaN(y2)) {
446                y2 = 0.0;
447            }
448            double transX2 = domainAxis.valueToJava2D(x2, dataArea, 
449                    plot.getDomainAxisEdge());
450            double transY2 = rangeAxis.valueToJava2D(y2, dataArea, 
451                    plot.getRangeAxisEdge());
452            
453            double transZero = rangeAxis.valueToJava2D(0.0, dataArea, 
454                    plot.getRangeAxisEdge());
455            Polygon hotspot = null;
456            if (plot.getOrientation() == PlotOrientation.HORIZONTAL) {
457                hotspot = new Polygon();
458                hotspot.addPoint((int) transZero, 
459                        (int) ((transX0 + transX1) / 2.0));
460                hotspot.addPoint((int) ((transY0 + transY1) / 2.0), 
461                        (int) ((transX0 + transX1) / 2.0));
462                hotspot.addPoint((int) transY1, (int) transX1);
463                hotspot.addPoint((int) ((transY1 + transY2) / 2.0), 
464                        (int) ((transX1 + transX2) / 2.0));
465                hotspot.addPoint((int) transZero, 
466                        (int) ((transX1 + transX2) / 2.0));
467            }
468            else {  // vertical orientation
469                hotspot = new Polygon();
470                hotspot.addPoint((int) ((transX0 + transX1) / 2.0), 
471                        (int) transZero);
472                hotspot.addPoint((int) ((transX0 + transX1) / 2.0), 
473                        (int) ((transY0 + transY1) / 2.0));
474                hotspot.addPoint((int) transX1, (int) transY1);
475                hotspot.addPoint((int) ((transX1 + transX2) / 2.0), 
476                        (int) ((transY1 + transY2) / 2.0));
477                hotspot.addPoint((int) ((transX1 + transX2) / 2.0), 
478                        (int) transZero);
479            }
480            
481            if (item == 0) {  // create a new area polygon for the series
482                areaState.area = new Polygon();
483                // the first point is (x, 0)
484                double zero = rangeAxis.valueToJava2D(0.0, dataArea, 
485                        plot.getRangeAxisEdge());
486                if (plot.getOrientation() == PlotOrientation.VERTICAL) {
487                    areaState.area.addPoint((int) transX1, (int) zero);
488                }
489                else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) {
490                    areaState.area.addPoint((int) zero, (int) transX1);
491                }
492            }
493    
494            // Add each point to Area (x, y)
495            if (plot.getOrientation() == PlotOrientation.VERTICAL) {
496                areaState.area.addPoint((int) transX1, (int) transY1);
497            }
498            else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) {
499                areaState.area.addPoint((int) transY1, (int) transX1);
500            }
501            
502            PlotOrientation orientation = plot.getOrientation();
503            Paint paint = getItemPaint(series, item);
504            Stroke stroke = getItemStroke(series, item);
505            g2.setPaint(paint);
506            g2.setStroke(stroke);
507            
508            Shape shape = null;
509            if (getPlotShapes()) {
510                shape = getItemShape(series, item);
511                if (orientation == PlotOrientation.VERTICAL) {
512                    shape = ShapeUtilities.createTranslatedShape(shape, transX1, 
513                            transY1);
514                }
515                else if (orientation == PlotOrientation.HORIZONTAL) {
516                    shape = ShapeUtilities.createTranslatedShape(shape, transY1, 
517                            transX1);
518                }
519                g2.draw(shape);
520            }
521    
522            if (getPlotLines()) {
523                if (item > 0) {
524                    if (plot.getOrientation() == PlotOrientation.VERTICAL) {
525                        areaState.line.setLine(transX0, transY0, transX1, transY1);
526                    }
527                    else if (plot.getOrientation() == PlotOrientation.HORIZONTAL) {
528                        areaState.line.setLine(transY0, transX0, transY1, transX1);
529                    }
530                    g2.draw(areaState.line);
531                }
532            }
533    
534            // Check if the item is the last item for the series.
535            // and number of items > 0.  We can't draw an area for a single point.
536            if (getPlotArea() && item > 0 && item == (itemCount - 1)) {
537    
538                if (orientation == PlotOrientation.VERTICAL) {
539                    // Add the last point (x,0)
540                    areaState.area.addPoint((int) transX1, (int) transZero);
541                }
542                else if (orientation == PlotOrientation.HORIZONTAL) {
543                    // Add the last point (x,0)
544                    areaState.area.addPoint((int) transZero, (int) transX1);
545                }
546    
547                g2.fill(areaState.area);
548    
549                // draw an outline around the Area.
550                if (isOutline()) {
551                    g2.setStroke(getItemOutlineStroke(series, item));
552                    g2.setPaint(getItemOutlinePaint(series, item));
553                    g2.draw(areaState.area);
554                }
555            }
556    
557            int domainAxisIndex = plot.getDomainAxisIndex(domainAxis);
558            int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis);
559            updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, 
560                    rangeAxisIndex, transX1, transY1, orientation);
561            
562            // collect entity and tool tip information...
563            if (state.getInfo() != null) {
564                EntityCollection entities = state.getEntityCollection();
565                if (entities != null && hotspot != null) {
566                    String tip = null;
567                    XYToolTipGenerator generator 
568                        = getToolTipGenerator(series, item);
569                    if (generator != null) {
570                        tip = generator.generateToolTip(dataset, series, item);
571                    }
572                    String url = null;
573                    if (getURLGenerator() != null) {
574                        url = getURLGenerator().generateURL(dataset, series, item);
575                    }
576                    XYItemEntity entity = new XYItemEntity(hotspot, dataset, 
577                            series, item, tip, url);
578                    entities.add(entity);
579                }
580            }
581    
582        }
583    
584        /**
585         * Returns a clone of the renderer.
586         * 
587         * @return A clone.
588         * 
589         * @throws CloneNotSupportedException  if the renderer cannot be cloned.
590         */
591        public Object clone() throws CloneNotSupportedException {
592            XYAreaRenderer clone = (XYAreaRenderer) super.clone();
593            clone.legendArea = ShapeUtilities.clone(this.legendArea);
594            return clone;
595        }
596        
597        /**
598         * Tests this renderer for equality with an arbitrary object.
599         * 
600         * @param obj  the object (<code>null</code> permitted).
601         * 
602         * @return A boolean.
603         */
604        public boolean equals(Object obj) {
605            if (obj == this) {
606                return true;   
607            }
608            if (!(obj instanceof XYAreaRenderer)) {
609                return false;   
610            }
611            XYAreaRenderer that = (XYAreaRenderer) obj;
612            if (this.plotArea != that.plotArea) {
613                return false;   
614            }
615            if (this.plotLines != that.plotLines) {
616                return false;   
617            }
618            if (this.plotShapes != that.plotShapes) {
619                return false;   
620            }
621            if (this.showOutline != that.showOutline) {
622                return false;   
623            }
624            if (!ShapeUtilities.equal(this.legendArea, that.legendArea)) {
625                return false;   
626            }
627            return true;
628        }
629        
630        /**
631         * Provides serialization support.
632         *
633         * @param stream  the input stream.
634         *
635         * @throws IOException  if there is an I/O error.
636         * @throws ClassNotFoundException  if there is a classpath problem.
637         */
638        private void readObject(ObjectInputStream stream) 
639                throws IOException, ClassNotFoundException {
640            stream.defaultReadObject();
641            this.legendArea = SerialUtilities.readShape(stream);
642        }
643        
644        /**
645         * Provides serialization support.
646         *
647         * @param stream  the output stream.
648         *
649         * @throws IOException  if there is an I/O error.
650         */
651        private void writeObject(ObjectOutputStream stream) throws IOException {
652            stream.defaultWriteObject();
653            SerialUtilities.writeShape(this.legendArea, stream);
654        }
655    }