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