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