    001    /* ===========================================================
    002     * JFreeChart : a free chart library for the Java(tm) platform
    003     * ===========================================================
    004     *
    005     * (C) Copyright 2000-2011, 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     * [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
    025     * Other names may be trademarks of their respective owners.]
    026     *
    027     * ---------------------------
    028     * SamplingXYLineRenderer.java
    029     * ---------------------------
    030     * (C) Copyright 2008, 2009, by Object Refinery Limited.
    031     *
    032     * Original Author:  David Gilbert (for Object Refinery Limited);
    033     * Contributor(s):   -;
    034     *
    035     * Changes:
    036     * --------
    037     * 02-Oct-2008 : Version 1 (DG);
    038     * 28-Apr-2009 : Fixed bug in legend shape display, and deprecated
    039     *               getLegendLine() and setLegendLine() - these methods
    040     *               are unnecessary because a mechanism already exists in the
    041     *               superclass for specifying a custom legend shape (DG);
    042     *
    043     */
    044
    045    package org.jfree.chart.renderer.xy;
    046
    047    import java.awt.Graphics2D;
    048    import java.awt.Shape;
    049    import java.awt.geom.GeneralPath;
    050    import java.awt.geom.Line2D;
    051    import java.awt.geom.PathIterator;
    052    import java.awt.geom.Rectangle2D;
    053    import java.io.IOException;
    054    import java.io.ObjectInputStream;
    055    import java.io.ObjectOutputStream;
    056    import java.io.Serializable;
    057
    058    import org.jfree.chart.axis.ValueAxis;
    059    import org.jfree.chart.event.RendererChangeEvent;
    060    import org.jfree.chart.plot.CrosshairState;
    061    import org.jfree.chart.plot.PlotOrientation;
    062    import org.jfree.chart.plot.PlotRenderingInfo;
    063    import org.jfree.chart.plot.XYPlot;
    064    import org.jfree.data.xy.XYDataset;
    065    import org.jfree.io.SerialUtilities;
    066    import org.jfree.ui.RectangleEdge;
    067    import org.jfree.util.PublicCloneable;
    068    import org.jfree.util.ShapeUtilities;
    069
    070    /**
    071     * A renderer that draws line charts.  The renderer doesn't necessarily plot
    072     * every data item - instead, it tries to plot only those data items that
    073     * make a difference to the visual output (the other data items are skipped).
    074     * This renderer is designed for use with the {@link XYPlot} class.
    075     *
    076     * @since 1.0.13
    077     */
    078    public class SamplingXYLineRenderer extends AbstractXYItemRenderer
    079            implements XYItemRenderer, Cloneable, PublicCloneable, Serializable {
    080
    081        /** The shape that is used to represent a line in the legend. */
    082        private transient Shape legendLine;
    083
    084        /**
    085         * Creates a new renderer.
    086         */
    087        public SamplingXYLineRenderer() {
    088            this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0);
    089            setBaseLegendShape(this.legendLine);
    090            setTreatLegendShapeAsLine(true);
    091        }
    092
    093        /**
    094         * Returns the shape used to represent a line in the legend.
    095         *
    096         * @return The legend line (never <code>null</code>).
    097         *
    098         * @see #setLegendLine(Shape)
    099         *
    100         * @deprecated As of version 1.0.14, this method is deprecated.  You
    101         * should use the {@link #getBaseLegendShape()} method instead.
    102         */
    103        public Shape getLegendLine() {
    104            return this.legendLine;
    105        }
    106
    107        /**
    108         * Sets the shape used as a line in each legend item and sends a
    109         * {@link RendererChangeEvent} to all registered listeners.
    110         *
    111         * @param line  the line (<code>null</code> not permitted).
    112         *
    113         * @see #getLegendLine()
    114         *
    115         * @deprecated As of version 1.0.14, this method is deprecated.  You should
    116         * use the {@link #setBaseLegendShape(java.awt.Shape)} method instead.
    117         */
    118        public void setLegendLine(Shape line) {
    119            if (line == null) {
    120                throw new IllegalArgumentException("Null 'line' argument.");
    121            }
    122            this.legendLine = line;
    123            fireChangeEvent();
    124        }
    125
    126        /**
    127         * Returns the number of passes through the data that the renderer requires
    128         * in order to draw the chart.  Most charts will require a single pass, but
    129         * some require two passes.
    130         *
    131         * @return The pass count.
    132         */
    133        public int getPassCount() {
    134            return 1;
    135        }
    136
    137        /**
    138         * Records the state for the renderer.  This is used to preserve state
    139         * information between calls to the drawItem() method for a single chart
    140         * drawing.
    141         */
    142        public static class State extends XYItemRendererState {
    143
    144            /** The path for the current series. */
    145            GeneralPath seriesPath;
    146
    147            /**
    148             * A second path that draws vertical intervals to cover any extreme
    149             * values.
    150             */
    151            GeneralPath intervalPath;
    152
    153            /**
    154             * The minimum change in the x-value needed to trigger an update to
    155             * the seriesPath.
    156             */
    157            double dX = 1.0;
    158
    159            /** The last x-coordinate visited by the seriesPath. */
    160            double lastX;
    161
    162            /** The initial y-coordinate for the current x-coordinate. */
    163            double openY = 0.0;
    164
    165            /** The highest y-coordinate for the current x-coordinate. */
    166            double highY = 0.0;
    167
    168            /** The lowest y-coordinate for the current x-coordinate. */
    169            double lowY = 0.0;
    170
    171            /** The final y-coordinate for the current x-coordinate. */
    172            double closeY = 0.0;
    173
    174            /**
    175             * A flag that indicates if the last (x, y) point was 'good'
    176             * (non-null).
    177             */
    178            boolean lastPointGood;
    179
    180            /**
    181             * Creates a new state instance.
    182             *
    183             * @param info  the plot rendering info.
    184             */
    185            public State(PlotRenderingInfo info) {
    186                super(info);
    187            }
    188
    189            /**
    190             * This method is called by the {@link XYPlot} at the start of each
    191             * series pass.  We reset the state for the current series.
    192             *
    193             * @param dataset  the dataset.
    194             * @param series  the series index.
    195             * @param firstItem  the first item index for this pass.
    196             * @param lastItem  the last item index for this pass.
    197             * @param pass  the current pass index.
    198             * @param passCount  the number of passes.
    199             */
    200            public void startSeriesPass(XYDataset dataset, int series,
    201                    int firstItem, int lastItem, int pass, int passCount) {
    202                this.seriesPath.reset();
    203                this.intervalPath.reset();
    204                this.lastPointGood = false;
    205                super.startSeriesPass(dataset, series, firstItem, lastItem, pass,
    206                        passCount);
    207            }
    208
    209        }
    210
    211        /**
    212         * Initialises the renderer.
    213         * <P>
    214         * This method will be called before the first item is rendered, giving the
    215         * renderer an opportunity to initialise any state information it wants to
    216         * maintain.  The renderer can do nothing if it chooses.
    217         *
    218         * @param g2  the graphics device.
    219         * @param dataArea  the area inside the axes.
    220         * @param plot  the plot.
    221         * @param data  the data.
    222         * @param info  an optional info collection object to return data back to
    223         *              the caller.
    224         *
    225         * @return The renderer state.
    226         */
    227        public XYItemRendererState initialise(Graphics2D g2,
    228                Rectangle2D dataArea, XYPlot plot, XYDataset data,
    229                PlotRenderingInfo info) {
    230
    231            double dpi = 72;
    232        //        Integer dpiVal = (Integer) g2.getRenderingHint(HintKey.DPI);
    233        //        if (dpiVal != null) {
    234        //            dpi = dpiVal.intValue();
    235        //        }
    236            State state = new State(info);
    237            state.seriesPath = new GeneralPath();
    238            state.intervalPath = new GeneralPath();
    239            state.dX = 72.0 / dpi;
    240            return state;
    241        }
    242
    243        /**
    244         * Draws the visual representation of a single data item.
    245         *
    246         * @param g2  the graphics device.
    247         * @param state  the renderer state.
    248         * @param dataArea  the area within which the data is being drawn.
    249         * @param info  collects information about the drawing.
    250         * @param plot  the plot (can be used to obtain standard color
    251         *              information etc).
    252         * @param domainAxis  the domain axis.
    253         * @param rangeAxis  the range axis.
    254         * @param dataset  the dataset.
    255         * @param series  the series index (zero-based).
    256         * @param item  the item index (zero-based).
    257         * @param crosshairState  crosshair information for the plot
    258         *                        (<code>null</code> permitted).
    259         * @param pass  the pass index.
    260         */
    261        public void drawItem(Graphics2D g2,
    262                             XYItemRendererState state,
    263                             Rectangle2D dataArea,
    264                             PlotRenderingInfo info,
    265                             XYPlot plot,
    266                             ValueAxis domainAxis,
    267                             ValueAxis rangeAxis,
    268                             XYDataset dataset,
    269                             int series,
    270                             int item,
    271                             CrosshairState crosshairState,
    272                             int pass) {
    273
    274            // do nothing if item is not visible
    275            if (!getItemVisible(series, item)) {
    276                return;
    277            }
    278            RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    279            RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    280
    281            // get the data point...
    282            double x1 = dataset.getXValue(series, item);
    283            double y1 = dataset.getYValue(series, item);
    284            double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
    285            double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);
    286
    287            State s = (State) state;
    288            // update path to reflect latest point
    289            if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) {
    290                float x = (float) transX1;
    291                float y = (float) transY1;
    292                PlotOrientation orientation = plot.getOrientation();
    293                if (orientation == PlotOrientation.HORIZONTAL) {
    294                    x = (float) transY1;
    295                    y = (float) transX1;
    296                }
    297                if (s.lastPointGood) {
    298                    if ((Math.abs(x - s.lastX) > s.dX)) {
    299                        s.seriesPath.lineTo(x, y);
    300                        if (s.lowY < s.highY) {
    301                            s.intervalPath.moveTo((float) s.lastX, (float) s.lowY);
    302                            s.intervalPath.lineTo((float) s.lastX, (float) s.highY);
    303                        }
    304                        s.lastX = x;
    305                        s.openY = y;
    306                        s.highY = y;
    307                        s.lowY = y;
    308                        s.closeY = y;
    309                    }
    310                    else {
    311                        s.highY = Math.max(s.highY, y);
    312                        s.lowY = Math.min(s.lowY, y);
    313                        s.closeY = y;
    314                    }
    315                }
    316                else {
    317                    s.seriesPath.moveTo(x, y);
    318                    s.lastX = x;
    319                    s.openY = y;
    320                    s.highY = y;
    321                    s.lowY = y;
    322                    s.closeY = y;
    323                }
    324                s.lastPointGood = true;
    325            }
    326            else {
    327                s.lastPointGood = false;
    328            }
    329            // if this is the last item, draw the path ...
    330            if (item == s.getLastItemIndex()) {
    331                // draw path
    332                PathIterator pi = s.seriesPath.getPathIterator(null);
    333                int count = 0;
    334                while (!pi.isDone()) {
    335                    count++;
    336                    pi.next();
    337                }
    338                g2.setStroke(getItemStroke(series, item));
    339                g2.setPaint(getItemPaint(series, item));
    340                g2.draw(s.seriesPath);
    341                g2.draw(s.intervalPath);
    342            }
    343        }
    344
    345        /**
    346         * Returns a clone of the renderer.
    347         *
    348         * @return A clone.
    349         *
    350         * @throws CloneNotSupportedException if the clone cannot be created.
    351         */
    352        public Object clone() throws CloneNotSupportedException {
    353            SamplingXYLineRenderer clone = (SamplingXYLineRenderer) super.clone();
    354            if (this.legendLine != null) {
    355                clone.legendLine = ShapeUtilities.clone(this.legendLine);
    356            }
    357            return clone;
    358        }
    359
    360        /**
    361         * Tests this renderer for equality with an arbitrary object.
    362         *
    363         * @param obj  the object (<code>null</code> permitted).
    364         *
    365         * @return <code>true</code> or <code>false</code>.
    366         */
    367        public boolean equals(Object obj) {
    368            if (obj == this) {
    369                return true;
    370            }
    371            if (!(obj instanceof SamplingXYLineRenderer)) {
    372                return false;
    373            }
    374            if (!super.equals(obj)) {
    375                return false;
    376            }
    377            SamplingXYLineRenderer that = (SamplingXYLineRenderer) obj;
    378            if (!ShapeUtilities.equal(this.legendLine, that.legendLine)) {
    379                return false;
    380            }
    381            return true;
    382        }
    383
    384        /**
    385         * Provides serialization support.
    386         *
    387         * @param stream  the input stream.
    388         *
    389         * @throws IOException  if there is an I/O error.
    390         * @throws ClassNotFoundException  if there is a classpath problem.
    391         */
    392        private void readObject(ObjectInputStream stream)
    393                throws IOException, ClassNotFoundException {
    394            stream.defaultReadObject();
    395            this.legendLine = SerialUtilities.readShape(stream);
    396        }
    397
    398        /**
    399         * Provides serialization support.
    400         *
    401         * @param stream  the output stream.
    402         *
    403         * @throws IOException  if there is an I/O error.
    404         */
    405        private void writeObject(ObjectOutputStream stream) throws IOException {
    406            stream.defaultWriteObject();
    407            SerialUtilities.writeShape(this.legendLine, stream);
    408        }
    409
    410    }